1.java代码
1 import java.awt.Color; 2 import java.awt.Font; 3 import java.awt.Graphics; 4 import java.awt.image.BufferedImage; 5 import java.io.IOException; 6 import java.util.Random; 7 import javax.imageio.ImageIO; 8 import javax.servlet.ServletException; 9 import javax.servlet.http.HttpServlet; 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 13 public class ImageServlet extends HttpServlet{ 14 @Override 15 public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 16 //通知浏览器不要缓存 17 resp.setHeader("Expires", "-1"); 18 resp.setHeader("Cache-Control", "no-cache"); 19 resp.setHeader("Prama", "no-cache"); 20 21 String code = req.getParameter("code"); //接受jsp页面表单填入的验证码 22 int width=120; 23 int height=50; 24 //在内存中创建一幅图 25 BufferedImage bu = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB); 26 //得到一个画笔 27 Graphics gr = bu.getGraphics(); 28 //画边框 29 gr.setColor(Color.gray); 30 gr.drawRect(0, 0, width, height); 31 //背景 32 gr.setColor(Color.pink); 33 gr.fillRect(1, 1, width-2, height-2); 34 //干扰线 35 Random ran = new Random(); 36 gr.setColor(Color.black); 37 for(int i=0;i<=10;i++){ 38 gr.drawLine(ran.nextInt(width), ran.nextInt(height), ran.nextInt(width), ran.nextInt(height)); 39 } 40 //验证码 41 gr.setColor(Color.red); 42 gr.setFont(new Font("宋体", Font.BOLD|Font.ITALIC, 35)); 43 int x =18; 44 String s =""; //接收随机生成的验证码 45 for(int j=0;j<4;j++){ 46 s+=ran.nextInt(10)+""; 47 gr.drawString(s.substring(j,j+1), x, 35); 48 x+=25; 49 } 50 req.getSession().setAttribute("racode", s); // 51 //System.out.println(s); 52 if(code.equals(s)){ // 对比检测前端与后端的验证码是否一致 53 System.out.println("验证码输入正确"); 54 }else{ 55 System.out.println("验证码输入错误"); 56 } 57 //输出到网页上 58 ImageIO.write(bu, "jpg", resp.getOutputStream()); 59 } 60 @Override 61 public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 62 this.doGet(req, resp); 63 } 64 }
2.jsp代码
1 <%@ page language="java" contentType="text/html" pageEncoding="UTF-8"%> 2 <!DOCTYPE html> 3 <html> 4 <head> 5 <title>验证码</title> 6 <script type="text/javascript"> 7 function tofresh(){ 8 document.location.href="ImageLogin.jsp"; 9 } 10 11 </script> 12 </head> 13 <body> 14 <form action="ImageServlet" method="post"> 15 用户名<input type="text" name="username"><br/> 16 密码<input type="password" name="pass"><br/> 17 验证码<input type="text" name="code"><br/> 18 <img alt="验证码" src="/WEB/ImageServlet"> 19 <a href="javascript:tofresh()">看不清,请再换一张</a> 20 </form> 21 </body> 22 </html>
3.配置web.xml 文件
1 <servlet> 2 <servlet-name>ImageServlet</servlet-name> 3 <servlet-class>ImageServlet</servlet-class> 4 </servlet> 5 <servlet-mapping> 6 <servlet-name>ImageServlet</servlet-name> 7 <url-pattern>/code</url-pattern> 8 </servlet-mapping>