<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>验证码</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <script src="<%=basePath%>js/jquery-1.7.2.min.js" type="text/javascript"></script> <script src="<%=basePath%>js/checkBoxUtil.js" type="text/javascript"></script> <script src="<%=basePath%>js/tableUtil.js" type="text/javascript"></script> <script src="<%=basePath%>plug-in-js/lhgdialog4.2.0/lhgdialog.min.js" type="text/javascript"></script> <script type="text/javascript"> function refresh(){ var src= "<%=basePath%> manage/yzm/createCode.do?number=" + Math.random(); $("#img").attr("src", src); } </script> </head> <body> <img id="img" src="<%=basePath%>manage/yzm/createCode.do" onclick="refresh()"> </body> </html>
package com.xcaj.www.manage.yangTest.util; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.util.Random; public class CaptchaUtil { /** * 图像 */ private BufferedImage image; /** * 验证码 */ private String str; private static char code[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789".toCharArray(); private static final String SESSION_CODE_NAME="code"; private CaptchaUtil(){ init();//初始化属性 } //取得RandomNumUtil实例 public static CaptchaUtil Instance(){ return new CaptchaUtil(); } //取得验证码图片 public BufferedImage getImage(){ return this.image; } //取得图片的验证码 public String getString(){ return this.str; } //给定范围获取随机颜色 private Color getRandColor(int fc,int bc){ Random random = new Random(); if(fc>255){ fc=255; } if(bc>255){ bc=255; } int r = fc+random.nextInt(bc-fc); int g = fc+random.nextInt(bc-fc); int b = fc+random.nextInt(bc-fc); return new Color(r, g, b); } private void init(){ //在内存中创建图像 int width = 85,height = 20; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //获取图形上下文 Graphics g = image.getGraphics(); //生成随机类 Random random = new Random(); //设定背景颜色 g.setColor(getRandColor(200,250)); g.fillRect(0, 0, width, height); //设置字体 g.setFont(new Font("Times New Roman", Font.PLAIN, 18)); //随机产生155条干扰线,使图像中的认证码不易被其他程序 g.setColor(getRandColor(160,200)); for(int i = 0; i < 155; i++){ int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(12); int yl = random.nextInt(12); g.drawLine(x, y, x+xl, y+yl); } //取随机产生的认证码(4位数字) String sRand = ""; for(int i = 0; i < 4; i++){ String rand = String.valueOf(code[random.nextInt(code.length)]); sRand+=rand; //将认证码显示在图片中 g.setColor(new Color(20+random.nextInt(110), 20+random.nextInt(110), 20+random.nextInt(110))); g.drawString(rand, 13*i+6,16); } //赋值验证码 this.str = sRand; //图像生效 g.dispose(); //赋值图像 this.image = image; } }
package com.xcaj.www.manage.yangTest.controller; import java.io.OutputStream; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.xcaj.www.manage.yangTest.util.CaptchaUtil; import com.xcaj.www.util.controller.UtilBaseController; @Controller @RequestMapping("/manage/yzm") public class CreatCodeController extends UtilBaseController{ @RequestMapping("createCode.do") public String createCode(HttpServletRequest request,HttpServletResponse response,Model model){ OutputStream os = null; try { //通知浏览器不要缓存 response.setHeader("Expires", "-1"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "-1"); /*response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0);*/ CaptchaUtil util = CaptchaUtil.Instance(); //将验证码输入到session 中验证 String code = util.getString(); request.getSession().setAttribute("code", code); //输出到页面 os = response.getOutputStream(); ImageIO.write(util.getImage(),"JPEG", os); model.addAttribute("code",code); os.flush(); os.close(); return "/manage/yangTest/yzm"; } catch (Exception e) { e.printStackTrace(); } return ""; } }
这个会报错,response.getOutputStream()和response.getWriter()冲突,没有解决,之后把工具类中的代码写在jsp中不报错 八月 09, 2017 3:38:29 下午 org.apache.catalina.core.ApplicationDispatcher invoke 严重: Servlet.service() for servlet jsp threw exception java.lang.IllegalStateException: getOutputStream() has already been called for this response at org.apache.catalina.connector.Response.getWriter(Response.java:648) at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:213) at javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:104) at org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:125) at org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:118) at org.apache.jasper.runtime.PageContextImpl.release(PageContextImpl.java:186) at org.apache.jasper.runtime.JspFactoryImpl.internalReleasePageContext(JspFactoryImpl.java:126) at org.apache.jasper.runtime.JspFactoryImpl.releasePageContext(JspFactoryImpl.java:80) at org.apache.jsp.WEB_002dINF.xcaj.manage.yangTest.yzm_jsp._jspService(yzm_jsp.java:134) at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334) at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:748) at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:604) at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:543) at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:229) at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:263) at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1208) at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:992) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:939) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827) at javax.servlet.http.HttpServlet.service(HttpServlet.java:620) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812) at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at com.xcaj.www.util.filter.XssFilter.doFilter(XssFilter.java:26) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2440) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2429) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745) 八月 09, 2017 3:38:29 下午 org.apache.catalina.core.StandardWrapperValve invoke 严重: Servlet.service() for servlet [springmvc] in context with path [/xcaj] threw exception [java.lang.IllegalStateException: getOutputStream() has already been called for this response] with root cause java.lang.IllegalStateException: getOutputStream() has already been called for this response at org.apache.catalina.connector.Response.getWriter(Response.java:648) at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:213) at javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:104) at org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:125) at org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:118) at org.apache.jasper.runtime.PageContextImpl.release(PageContextImpl.java:186) at org.apache.jasper.runtime.JspFactoryImpl.internalReleasePageContext(JspFactoryImpl.java:126) at org.apache.jasper.runtime.JspFactoryImpl.releasePageContext(JspFactoryImpl.java:80) at org.apache.jsp.WEB_002dINF.xcaj.manage.yangTest.yzm_jsp._jspService(yzm_jsp.java:134) at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334) at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:748) at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:604) at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:543) at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:229) at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:263) at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1208) at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:992) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:939) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827) at javax.servlet.http.HttpServlet.service(HttpServlet.java:620) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812) at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at com.xcaj.www.util.filter.XssFilter.doFilter(XssFilter.java:26) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2440) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2429) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745)
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>验证码</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <script src="<%=basePath%>js/jquery-1.7.2.min.js" type="text/javascript"></script> <script src="<%=basePath%>js/checkBoxUtil.js" type="text/javascript"></script> <script src="<%=basePath%>js/tableUtil.js" type="text/javascript"></script> <script src="<%=basePath%>plug-in-js/lhgdialog4.2.0/lhgdialog.min.js" type="text/javascript"></script> <script type="text/javascript"> function refresh(obj){ obj.src= "<%=basePath%>manage/yzm/createCode.do?number="Math.random(); } </script> </head> <body> <img id="img" src="<%=basePath%>manage/yzm/createCode.do" onclick="refresh(this)"> </body> </html>
<%@page import="java.io.OutputStream"%> <%@ page contentType="image/jpeg" pageEncoding="utf-8" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*"%> <%!Color getRandColor(int fc, int bc) { Random random = new Random(); if (fc > 255) { fc = 255; } if (bc > 255) { bc = 255; } int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); }%> <% OutputStream os = null; try { char code[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789".toCharArray(); response.setHeader("Expires", "-1"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "-1"); //在内存中创建图像 int width = 85,height = 20; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //获取图形上下文 Graphics g = image.getGraphics(); //生成随机类 Random random = new Random(); //设定背景颜色 g.setColor(getRandColor(200,250)); g.fillRect(0, 0, width, height); //设置字体 g.setFont(new Font("Times New Roman", Font.PLAIN, 18)); //随机产生155条干扰线,使图像中的认证码不易被其他程序 g.setColor(getRandColor(160,200)); for(int i = 0; i < 155; i++){ int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(12); int yl = random.nextInt(12); g.drawLine(x, y, x+xl, y+yl); } //取随机产生的认证码(4位数字) String sRand = ""; for(int i = 0; i < 4; i++){ String rand = String.valueOf(code[random.nextInt(code.length)]); sRand+=rand; //将认证码显示在图片中 g.setColor(new Color(20+random.nextInt(110), 20+random.nextInt(110), 20+random.nextInt(110))); g.drawString(rand, 13*i+6,16); } session.setAttribute("rand", sRand); //图像生效 g.dispose(); ImageIO.setUseCache(true); os = response.getOutputStream(); ImageIO.write(image,"JPEG", os); } catch (Exception e) { e.printStackTrace(); }finally{ os.flush(); os.close(); out.clear(); out = pageContext.pushBody(); } %>
package com.xcaj.www.manage.yangTest.controller; import java.io.OutputStream; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.xcaj.www.manage.yangTest.util.CaptchaUtil; import com.xcaj.www.util.controller.UtilBaseController; @Controller @RequestMapping("/manage/yzm") public class CreatCodeController extends UtilBaseController{ @RequestMapping("createCode.do") public String createCode(HttpServletRequest request,HttpServletResponse response,Model model){ //OutputStream os = null; try { /*//通知浏览器不要缓存 response.setHeader("Expires", "-1"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "-1"); response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); CaptchaUtil util = CaptchaUtil.Instance(); //将验证码输入到session 中验证 String code = util.getString(); request.getSession().setAttribute("code", code); //输出到页面 os = response.getOutputStream(); ImageIO.write(util.getImage(),"JPEG", os); model.addAttribute("code",code); os.flush(); os.close();*/ return "/manage/yangTest/imgs"; } catch (Exception e) { e.printStackTrace(); } return ""; } @RequestMapping("yzm.do") public String yzm(HttpServletRequest request,HttpServletResponse response,Model model){ try { return "/manage/yangTest/yzm"; } catch (Exception e) { e.printStackTrace(); } return ""; } }