/** * 生成验证码的逻辑 */ @RequestMapping("verify") private ModelAndView verify(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); response.addHeader("Cache-Control", "post-check=0, pre-check=0"); response.setHeader("Pragma", "no-cache"); response.setContentType("image/jpeg"); String capText = captchaProducer.createText(); session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText); BufferedImage bi = captchaProducer.createImage(capText); ServletOutputStream out = response.getOutputStream(); ImageIO.write(bi, "jpg", out); try { out.flush(); } finally { out.close(); } return null; }
@Override public ServletOutputStream getOutputStream() throws IOException { final ServletOutputStream outputStream = d.getOutputStream(); return new ServletOutputStream() { @Override public void write(int b) throws IOException { respBody.write(b); outputStream.write(b); } @Override public void setWriteListener(WriteListener writeListener) { outputStream.setWriteListener(writeListener); } @Override public boolean isReady() { return outputStream.isReady(); } }; }
private void updateResponse(String requestURI, ContentCachingResponseWrapper responseWrapper) throws IOException { try { HttpServletResponse rawResponse = (HttpServletResponse) responseWrapper.getResponse(); byte[] body = responseWrapper.getContentAsByteArray(); ServletOutputStream outputStream = rawResponse.getOutputStream(); if (rawResponse.isCommitted()) { if (body.length > 0) { StreamUtils.copy(body, outputStream); } } else { if (body.length > 0) { rawResponse.setContentLength(body.length); StreamUtils.copy(body, rawResponse.getOutputStream()); } } finishResponse(outputStream, body); } catch (Exception ex) { logger.error("请求地址为" + requestURI + "的连接返回报文失败,原因是{}", ex.getMessage()); } }
/** * Exports tool results into excel. * * @throws IOException */ private ActionForward exportExcel(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException { initializeScratchieService(); String sessionMapID = request.getParameter(ScratchieConstants.ATTR_SESSION_MAP_ID); SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession() .getAttribute(sessionMapID); Scratchie scratchie = (Scratchie) sessionMap.get(ScratchieConstants.ATTR_SCRATCHIE); LinkedHashMap<String, ExcelCell[][]> dataToExport = service.exportExcel(scratchie.getContentId()); String fileName = "scratchie_export.xlsx"; fileName = FileUtil.encodeFilenameForDownload(request, fileName); response.setContentType("application/x-download"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); // set cookie that will tell JS script that export has been finished String downloadTokenValue = WebUtil.readStrParam(request, "downloadTokenValue"); Cookie fileDownloadTokenCookie = new Cookie("fileDownloadToken", downloadTokenValue); fileDownloadTokenCookie.setPath("/"); response.addCookie(fileDownloadTokenCookie); // Code to generate file and write file contents to response ServletOutputStream out = response.getOutputStream(); ExcelUtil.createExcel(out, dataToExport, null, false); return null; }
/** * Write the given temporary OutputStream to the HTTP response. * @param response current HTTP response * @param baos the temporary OutputStream to write * @throws IOException if writing/flushing failed */ protected void writeToResponse(HttpServletResponse response, ByteArrayOutputStream baos) throws IOException { // Write content type and also length (determined via byte array). response.setContentType(getContentType()); response.setContentLength(baos.size()); // Flush byte array to servlet output stream. ServletOutputStream out = response.getOutputStream(); baos.writeTo(out); out.flush(); }
@RequestMapping("captcha.jpg") public void captcha(HttpServletResponse response) throws ServletException, IOException { response.setHeader("Cache-Control", "no-store, no-cache"); response.setContentType("image/jpeg"); //生成文字验证码 String text = producer.createText(); //生成图片验证码 BufferedImage image = producer.createImage(text); //保存到shiro session ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text); ServletOutputStream out = response.getOutputStream(); ImageIO.write(image, "jpg", out); IOUtils.closeQuietly(out); }
@RequestMapping(value = Mappings.ADMINISTRATION_EXPORT_RESERVATIONS_CSV, method = RequestMethod.GET) public void exportReservationsCsv( @RequestParam("begin") String begin, @RequestParam("end") String end, HttpServletResponse response) throws Exception { Date beginDate = Utils.stringToDate(begin); Date endDate = Utils.stringToDate(end); response.setContentType("text/csv"); response.setHeader("Content-disposition", "attachment; filename=\"export.csv\""); File tempFile = exportService.exportReserationsCsv(beginDate, endDate); try (ServletOutputStream out = response.getOutputStream(); InputStream in = Files.newInputStream(tempFile.toPath())) { IOUtils.copy(in, out); } Files.delete(tempFile.toPath()); }
@SuppressWarnings("deprecation") protected void writeResponse(Response res) throws Exception { response.setStatus(res.getStatusCode(), res.getStatusMessage()); for (HeaderField header : res.getHeader().getAllHeaderFields()) { if (header.getHeaderName().equals(Header.TRANSFER_ENCODING)) continue; response.addHeader(header.getHeaderName().toString(), header.getValue()); } ServletOutputStream out = response.getOutputStream(); res.getBody().write(new PlainBodyTransferrer(out)); out.flush(); response.flushBuffer(); exchange.setTimeResSent(System.currentTimeMillis()); exchange.collectStatistics(); }
/** * Copy the contents of the specified input stream to the specified * output stream, and ensure that both streams are closed before returning * (even in the face of an exception). * * @param istream The input stream to read from * @param ostream The output stream to write to * @return Exception which occurred during processing */ private IOException copyRange(InputStream istream, ServletOutputStream ostream) { // Copy the input stream to the output stream IOException exception = null; byte buffer[] = new byte[input]; int len = buffer.length; while (true) { try { len = istream.read(buffer); if (len == -1) break; ostream.write(buffer, 0, len); } catch (IOException e) { exception = e; len = -1; break; } } return exception; }
@RequestMapping("captcha.jpg") public void captcha(HttpServletResponse response)throws ServletException, IOException { response.setHeader("Cache-Control", "no-store, no-cache"); response.setContentType("image/jpeg"); //生成文字验证码 String text = producer.createText(); //生成图片验证码 BufferedImage image = producer.createImage(text); //保存到shiro session ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text); ServletOutputStream out = response.getOutputStream(); ImageIO.write(image, "jpg", out); IOUtils.closeQuietly(out); }
@RequestMapping(value = "/email/attachment/{id}",method = RequestMethod.GET) public void getAttachmentContent(@PathVariable("id") Long id, HttpServletResponse response) { final AttachmentEntity attachment = attachmentService.findAttachmentById(id); if (attachment != null) { try { ServletOutputStream stream = response.getOutputStream(); OutputStream out = new BufferedOutputStream(stream); response.resetBuffer(); response.setBufferSize(attachment.getAttachmentContent().getData().length); response.setHeader("Content-Length", String.valueOf(attachment. getAttachmentContent().getData().length)); out.write(attachment.getAttachmentContent().getData()); out.close(); stream.close(); } catch (final IOException e) { log.error("Unable to open file", e); } } else { log.error("File does not exist"); } }
@RequestMapping(value="/launchjob") @ResponseBody public void startJob(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { log.info("manual startJob"); try { httpServletResponse.setContentType("text/plain; charset=utf-8"); ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream(); if(scheduleJobs.getJobStatus() == ScheduleJobs.JOB_STATUS_RUNNING) { responseOutputStream.write("Job正在运行。。。".getBytes("utf-8")); responseOutputStream.flush(); responseOutputStream.close(); } else { log.info("scheduleJobs.cronJob() start by controller..."); scheduleJobs.cronJob(); } } catch (Exception e) { log.info("startJob exception e="+e.getMessage()); } }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); resp.setCharacterEncoding("utf-8"); HashMap<String, Object> status = new HashMap<>(); JSONObject object = new JSONObject(); String quizFormName = req.getParameter("name"); // get main data QuizForm qf = allQuizForm.get(quizFormName); // build status status.put("code", String.valueOf(HttpServletResponse.SC_OK)); status.put("message", "query quiz form successful"); status.put("extra", Constant.JSON.EMPTY_OBJECT); status.put("security", Constant.JSON.EMPTY_OBJECT); // build main object object.put("meta", status); object.put("data", qf); // FIXME 非测试时移去注释 (配合Configuration System把这里设计的合理一点 - 磷) // response.setContentType("application/json"); // specific content type try (ServletOutputStream out = resp.getOutputStream()) { out.write(resp.toString().getBytes(StandardCharsets.UTF_8)); out.flush(); } catch (IOException e) { LoggerFactory.getLogger(Counter.class).error("IOException thrown: ", e); } }
/** * 生成验证码 */ static void generate(HttpServletResponse response, String vCode) { BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); response.setHeader("Pragma","no-cache"); response.setHeader("Cache-Control","no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/jpeg"); ServletOutputStream sos = null; try { drawGraphic(image, vCode); sos = response.getOutputStream(); ImageIO.write(image, "JPEG", sos); sos.flush(); } catch (Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(sos); } }
private void doService(HttpMethod method, HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { outputRequestLog(req); InputStream iStream = null; ServletOutputStream oStream = null; try { long threadID = Thread.currentThread().getId(); log.debug("[" + threadID + "] forwarded to " + distributer.getRedirectUrl(req)); HttpClient client = new HttpClient(); log.debug("[" + threadID + "]send request."); int resultCode = client.executeMethod(method); log.debug("[" + threadID + "]got response: result code is " + resultCode); res.setStatus(resultCode); for (Header header : method.getResponseHeaders()) { res.setHeader(header.getName(), header.getValue()); } iStream = method.getResponseBodyAsStream(); oStream = res.getOutputStream(); writeOutputStream(iStream, oStream); log.debug("[" + threadID + "] response sent to client."); } catch (Exception e) { log.error(e.getMessage(), e); throw new ServletException(e.getMessage(), e); } finally { if (iStream != null) { iStream.close(); } if (oStream != null) { oStream.close(); } } }
/** * 验证码 */ @RequestMapping(value = "/captcha", method = RequestMethod.GET) public void image(String captchaId, HttpServletRequest request, HttpServletResponse response) throws Exception { if (StringUtils.isEmpty(captchaId)) { captchaId = request.getSession().getId(); } response.addHeader("vincent.li", "vincent.li"); response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Cache-Control", "no-store"); response.setDateHeader("Expires", 0); response.setContentType("image/jpeg"); ServletOutputStream servletOutputStream = null; try { servletOutputStream = response.getOutputStream(); BufferedImage bufferedImage = (BufferedImage) imageCaptchaService.getChallengeForID(captchaId); ImageIO.write(bufferedImage, "jpg", servletOutputStream); servletOutputStream.flush(); } catch (Exception e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(servletOutputStream); } }
@Override protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception { service.setRemoteHost(request.getRemoteHost()); InputStream inputStream = request.getInputStream(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[65536]; int numberOfBytes; while ((numberOfBytes = inputStream.read(buffer)) > 0) { byteArrayOutputStream.write(buffer, 0, numberOfBytes); } inputStream.close(); String responseBody = service.doRequest(byteArrayOutputStream.toString("UTF-8")); byte[] responseBytes = responseBody.getBytes("UTF-8"); response.setContentType("text/plain; charset=UTF-8"); response.addHeader("Access-Control-Allow-Origin", "*"); ServletOutputStream servletOutputStream = response.getOutputStream(); servletOutputStream.write(responseBytes); servletOutputStream.close(); }
private void viewXml(RenderContext info, HttpServletResponse response) throws IOException { response.setContentType("text/xml"); ServletOutputStream outputStream = response.getOutputStream(); outputStream.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); outputStream.println(itemXsltService.getXmlForXslt(info, AbstractParentViewItemSection.getItemInfo(info)) .toString()); outputStream.flush(); outputStream.close(); }
/** * Plenty attached authority */ @Test public void doFilterAttachedAuthority3() throws Exception { attachRole(DEFAULT_ROLE, "role2"); addSystemAuthorization(HttpMethod.GET, "role2", "^rest/match$"); em.flush(); em.clear(); cacheResource.invalidate("authorizations"); final FilterChain chain = Mockito.mock(FilterChain.class); final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); final ServletContext servletContext = Mockito.mock(ServletContext.class); Mockito.when(servletContext.getContextPath()).thenReturn("/context"); Mockito.when(request.getRequestURI()).thenReturn("/context/rest/match"); Mockito.when(request.getQueryString()).thenReturn("query"); Mockito.when(request.getMethod()).thenReturn("GET"); final ServletOutputStream outputStream = Mockito.mock(ServletOutputStream.class); final HttpServletResponse response = Mockito.mock(HttpServletResponse.class); Mockito.when(response.getOutputStream()).thenReturn(outputStream); authorizingFilter.setServletContext(servletContext); authorizingFilter.doFilter(request, response, chain); Mockito.when(request.getMethod()).thenReturn("HEAD"); authorizingFilter.doFilter(request, response, chain); Mockito.verify(chain, Mockito.atLeastOnce()).doFilter(request, response); Mockito.validateMockitoUsage(); }
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { Center center = ApplicationContextHelper.getBean(Constant.CENTERS_BEAN_NAME, Centers.class) .getCenterBySessionId(req.getParameter("sessionId")); ServletOutputStream out = resp.getOutputStream(); try { // hex to bytes byte[] bytes = CoderUtils.hexStringToByteArray(req.getParameter("data")); // 解密 String text = new String(RsaUtils.decryptByPublicKey(bytes, center.getPublicKey())); // 通过name选取方法并调用 Object result = invokeMethodByName(req.getParameter("name"), text); byte[] respData = JSON.toJSONString(result).getBytes("utf-8"); if (respData.length > center.getLength() - Constant.RSA_RESERVED_LENGTH) { throw new Exception("response data is too big"); } // 返回加密 respData = RsaUtils.encryptByPublicKey(respData, center.getPublicKey()); out.write(respData); } catch (Exception e) { e.printStackTrace(); out.write(500); } finally { out.close(); } }
/** * Return the servlet output stream associated with this Response. * * @exception IllegalStateException if <code>getWriter</code> has * already been called for this response * @exception IOException if an input/output error occurs */ @Override public ServletOutputStream getOutputStream() throws IOException { if (writer != null) throw new IllegalStateException("getWriter() has already been called for this response"); if (stream == null) stream = createOutputStream(); if (debug > 1) { System.out.println("stream is set to "+stream+" in getOutputStream"); } return (stream); }
/** * Copy the contents of the specified input stream to the specified * output stream, and ensure that both streams are closed before returning * (even in the face of an exception). * * @param istream The input stream to read from * @param ostream The output stream to write to * @return Exception which occurred during processing */ protected IOException copyRange(InputStream istream, ServletOutputStream ostream) { // Copy the input stream to the output stream IOException exception = null; byte buffer[] = new byte[input]; int len = buffer.length; while (true) { try { len = istream.read(buffer); if (len == -1) break; ostream.write(buffer, 0, len); } catch (IOException e) { exception = e; len = -1; break; } } return exception; }
@RequestMapping(value = Mappings.ADMINISTRATION_EXPORT_SERVICES_CSV, method = RequestMethod.GET) public void exportServicesCsv( @RequestParam("begin") String begin, @RequestParam("end") String end, HttpServletResponse response) throws Exception { Date beginDate = Utils.stringToDate(begin); Date endDate = Utils.stringToDate(end); response.setContentType("text/csv"); response.setHeader("Content-disposition", "attachment; filename=\"export.csv\""); File tempFile = exportService.exportServicesCsv(beginDate, endDate); try (ServletOutputStream out = response.getOutputStream(); InputStream in = Files.newInputStream(tempFile.toPath())) { IOUtils.copy(in, out); } Files.delete(tempFile.toPath()); }
@RequestMapping(value = "/webservice1_0bs/multimediaImage/null", method = RequestMethod.GET) @ResponseBody public void getNullImage(HttpServletResponse response) { try { byte[] b = new byte[0]; InputStream i = App.retGlobalResource("/src/main/ui/no_image_icon.png").openStream(); response.setHeader("Cache-Control", "no-store"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/" + "png"); ServletOutputStream responseOutputStream = response.getOutputStream(); byte[] bytes = new byte[1024]; int read = 0; while ((read = i.read(bytes)) != -1) { responseOutputStream.write(bytes, 0, read); } responseOutputStream.flush(); responseOutputStream.close(); } catch (IOException e1) { log.error(e1); try { response.sendError(HttpServletResponse.SC_NOT_FOUND); } catch (Exception e) { log.error(e); } } }
@RequestMapping("captcha.jpg") public void captcha(HttpServletResponse response) throws ServletException, IOException { response.setHeader("Cache-Control", "no-store, no-cache"); response.setContentType("image/jpeg"); // 生成文字验证码 String text = producer.createText(); // 生成图片验证码 BufferedImage image = producer.createImage(text); // 保存到shiro session ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text); ServletOutputStream out = response.getOutputStream(); ImageIO.write(image, "jpg", out); }
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); AsyncContext context = request.startAsync(); ServletOutputStream output = response.getOutputStream(); output.setWriteListener(new WritingListener(output, context)); }
/** * Return a OutputStream, throws and exception if a printwriter already * been returned. * * @return a OutputStream object * @exception java.io.IOException * if the printwriter already been called */ @Override public ServletOutputStream getOutputStream() throws java.io.IOException { if (printWriter == null) { if (servletOutputStream == null) { servletOutputStream = captureServletOutputStream; } return servletOutputStream; } throw new IllegalStateException(); }
/** * Create and return a ServletOutputStream to write the content associated * with this Response. * * @exception IOException * if an input/output error occurs */ @Deprecated public ServletOutputStream createOutputStream() throws IOException { // Probably useless if (outputStream == null) { outputStream = new CoyoteOutputStream(outputBuffer); } return outputStream; }
/** * Create and return a ServletOutputStream to write the content * associated with this Response. * * @exception IOException if an input/output error occurs */ @Deprecated public ServletOutputStream createOutputStream() throws IOException { // Probably useless if (outputStream == null) { outputStream = new CoyoteOutputStream(outputBuffer); } return outputStream; }
/** * Verify that the test result can be returned correctly even when the * logic in the method to test takes a long time and thus it verifies that * the test result is only returned after it has been written in the * application scope on the server side. */ public void testLongProcess() throws Exception { ServletOutputStream os = response.getOutputStream(); os.print("<html><head><Long Process></head><body>"); os.flush(); // do some processing that takes a while ... Thread.sleep(3000); os.println("Some data</body></html>"); }
private void writeFileToOutputStream ( HttpServletResponse response, File targetFile ) throws IOException { try (DataInputStream in = new DataInputStream( new FileInputStream( targetFile.getAbsolutePath() ) ); ServletOutputStream servletOutputStream = response.getOutputStream();) { byte[] bbuf = new byte[ BYTE_DOWNLOAD_CHUNK ]; int numBytesRead; long startingMax = targetFile.length(); long totalBytesRead = 0L; // hook for files that are being updated while ((in != null) && ((numBytesRead = in.read( bbuf )) != -1) && (startingMax > totalBytesRead)) { totalBytesRead += numBytesRead; servletOutputStream.write( bbuf, 0, numBytesRead ); servletOutputStream.flush(); } } catch (Exception e) { String reason = CSAP.getCsapFilteredStackTrace( e ); logger.error( "Failed accessing file: {}", reason ); response.getWriter().println( "Failed accessing file: " + targetFile + "\n Validate OS file system permissions" ); } }
/** * Copy the contents of the specified input stream to the specified * output stream, and ensure that both streams are closed before returning * (even in the face of an exception). * * @param cacheEntry The cache entry for the source resource * @param is The input stream to read the source resource from * @param ostream The output stream to write to * * @exception IOException if an input/output error occurs */ protected void copy(CacheEntry cacheEntry, InputStream is, ServletOutputStream ostream) throws IOException { IOException exception = null; InputStream resourceInputStream = null; // Optimization: If the binary content has already been loaded, send // it directly if (cacheEntry.resource != null) { byte buffer[] = cacheEntry.resource.getContent(); if (buffer != null) { ostream.write(buffer, 0, buffer.length); return; } resourceInputStream = cacheEntry.resource.streamContent(); } else { resourceInputStream = is; } InputStream istream = new BufferedInputStream (resourceInputStream, input); // Copy the input stream to the output stream exception = copyRange(istream, ostream); // Clean up the input stream istream.close(); // Rethrow any exception that has occurred if (exception != null) throw exception; }
public XServletOutputStream(ServletOutputStream servletOutputStream, HttpServletRequest request, XHttpServletResponse response) { super(); this.servletOutputStream = servletOutputStream; this.response = response; this.request = request; }
/** * 获取ServletOutputStream对象 * * @return ServletOutputStream对象 * @throws IOException * IO异常 */ public ServletOutputStream getOutputStream() throws IOException { if (writer != null) { throw new IllegalStateException("getWriter() has already been called!"); } if (stream == null) { stream = createOutputStream(); } return (stream); }
@Override public ServletOutputStream getOutputStream() throws IOException { if (servletOutputStream == null) { servletOutputStream = new XServletOutputStream( super.getOutputStream(), request, this); } return servletOutputStream; }
/** * Verify that when big amount of data is returned by the servlet output * stream, it does not io-block. */ public void testLotsOfData() throws Exception { ServletOutputStream os = response.getOutputStream(); os.println("<html><head>Lots of Data</head><body>"); os.flush(); for (int i = 0; i < 5000; i++) { os.println("<p>Lots and lots of data here"); } os.println("</body></html>"); }
public static void writeResponseFromFile(HttpServletResponse response, String filePath) { response.setContentType("application/json"); response.setStatus(HttpServletResponse.SC_OK); try (FileInputStream fis = new FileInputStream(new File(filePath)); ServletOutputStream sos = response.getOutputStream()) { IOUtils.copy(fis, sos); sos.flush(); } catch (IOException e) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
/** * Create and return a ServletOutputStream to write the content * associated with this Response. * * @exception IOException if an input/output error occurs */ public ServletOutputStream createOutputStream() throws IOException { if (debug > 1) { System.out.println("createOutputStream gets called"); } CompressionResponseStream stream = new CompressionResponseStream(origResponse); stream.setDebugLevel(debug); stream.setBuffer(threshold); return stream; }
public String execute() throws Exception { HttpServletRequest request = Struts2Utils.getRequest(); HttpServletResponse response = Struts2Utils.getResponse(); ByteArrayOutputStream out = null; byte[] captchaChallengeAsJpeg = null; // the output stream to render the captcha image as jpeg into ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream(); try { // get the session id that will identify the generated captcha. // the same id must be used to validate the response, the session id // is a good candidate! String captchaId = request.getSession().getId(); // call the ImageCaptchaService getChallenge method BufferedImage challenge = imageCaptchaService.getImageChallengeForID(captchaId, request.getLocale()); // a jpeg encoder /*** jdk1.7之后默认不支持了 **/ // JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(jpegOutputStream); // jpegEncoder.encode(challenge); // 换成新版图片api ImageIO.write(challenge, "jpg", jpegOutputStream); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } captchaChallengeAsJpeg = jpegOutputStream.toByteArray(); // flush it in the response response.setHeader("Cache-Control", "no-store"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/jpeg"); ServletOutputStream responseOutputStream = response.getOutputStream(); responseOutputStream.write(captchaChallengeAsJpeg); responseOutputStream.flush(); responseOutputStream.close(); return null; }