02javaweb基础:Jsp+Servlet实现的数字验证码

1:功能说明:验证码登陆验证

2:功能展示:

3:代码:

3.1:LoginServlet.java    //登陆主要的逻辑功能
package com.sample.servlet;
/**
 * 

Title: LoginServlet

*

Description: 用来验证验证码是否正确,结果会向控制台打印并跳转页面successful.jsp|erro.jsp

* @author Mr_z * @time 2018年3月2日 * 下午4:39:35 */ import java.io.IOException; import java.util.Date; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.swing.JOptionPane; public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { JOptionPane.showMessageDialog(null, "标题【出错啦】", "年龄请输入数字", JOptionPane.ERROR_MESSAGE); String validationCode = req.getParameter("validationCode"); HttpSession session = req.getSession(); String validation_code = (String)session.getAttribute("validation_code"); System.out.print(new Date(System.currentTimeMillis())); System.out.println("--from class LoginServlet -> Accepted validation code:"+validation_code.toString()); if(validationCode.equalsIgnoreCase(validation_code)){ System.out.print(new Date(System.currentTimeMillis())); System.out.println("--from class LoginServlet -> Correct verification code"); RequestDispatcher rd = req.getRequestDispatcher("successful.jsp"); rd.forward(req, resp); }else{ System.out.print(new Date(System.currentTimeMillis())); System.out.println("--from class LoginServlet -> False verification code"); RequestDispatcher rd = req.getRequestDispatcher("erro.jsp"); rd.forward(req, resp); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
3.2:ValidateCode.java       //生成验证码图片
package com.sample.servlet;
/**
 * 

Title: ValidateCode

*

Description:用来生成验证码,生成一次验证码会向控制台打印一次

* @author Mr_z * @time 2018年3月2日 * 下午4:38:27 */ import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.OutputStream; import java.util.Date; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class ValidateCode extends HttpServlet { private static final long serialVersionUID = 1L; private static String codeChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获得验证码集合的长度 int charsLength = codeChars.length(); // 下面3条记录是关闭客户端浏览器的缓冲区 // 这3条语句都可以关闭浏览器的缓冲区,但是由于浏览器的版本不同,对这3条语句的支持也不同 // 因此,为了保险起见,同时使用这3条语句来关闭浏览器的缓冲区 response.setHeader("ragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); // 设置图形验证码的长和宽 int width = 90, height = 30; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); Random random = new Random(); g.setColor(getRandomColor(180, 250)); g.fillRect(0, 0, width, height); g.setFont(new Font("Times New Roman", Font.ITALIC, height)); g.setColor(getRandomColor(120, 180)); // 用户保存最后随机生成的验证码 StringBuffer validationCode = new StringBuffer(); // 验证码的随机字体 String[] fontNames = { "Times New Roman", "Book antiqua", "Arial" }; // 随机生成4个验证码 for (int i = 0; i < 4; i++) { // 随机设置当前验证码的字符的字体 g.setFont(new Font(fontNames[random.nextInt(3)], Font.ITALIC, height)); // 随机获得当前验证码的字符 char codeChar = codeChars.charAt(random.nextInt(charsLength)); validationCode.append(codeChar); // 随机设置当前验证码字符的颜色 g.setColor(getRandomColor(10, 100)); // 在图形上输出验证码字符,x和y都是随机生成的 g.drawString(String.valueOf(codeChar), 16 * i + random.nextInt(7), height - random.nextInt(6)); } // 获得HttpSession对象 HttpSession session = request.getSession(); // 设置session对象5分钟失效 session.setMaxInactiveInterval(5 * 60); // 将验证码保存在session对象中,key为validation_code session.setAttribute("validation_code", validationCode.toString()); System.out.print(new Date(System.currentTimeMillis())); System.out.println("--from class ValidateCode -> Generate a verifying code:"+validationCode.toString()); //关闭Graphics对象 g.dispose(); OutputStream outS = response.getOutputStream(); ImageIO.write(image, "JPEG", outS); } private Color getRandomColor(int minColor, int maxColor) { Random random = new Random(); if(minColor > 255){ minColor = 255; } if(maxColor > 255){ maxColor = 255; } //获得r的随机颜色值 int red = minColor+random.nextInt(maxColor-minColor); int green = minColor + random.nextInt(maxColor-minColor); int blue = minColor + random.nextInt(maxColor-minColor); return new Color(red,green,blue); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
3.3:web.xml


  yzm
  
    login.jsp
  
  
    loginServlet
    com.sample.servlet.LoginServlet
  
  
    loginServlet
    /loginServlet
  
  
    validateCode
    com.sample.servlet.ValidateCode
  
  
    validateCode
    /validateCode
  
3.4:login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




登录界面




    

你可能感兴趣的:(jsp,servlet,login)