jsp-5 生成验证码并校验
Posted lgp20151222
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jsp-5 生成验证码并校验相关的知识,希望对你有一定的参考价值。
jsp-5 生成验证码并校验
依然是以上次的代码为底
index.jsp
新增了验证码一栏
注意他的servlet是新建的ImageServlet
而且中间插了一段JS代码用于刷新验证码
<%@ page language="java" contentType="text/html; charset=UTF-8" 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" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <% String username=""; String password=""; //取出Cookie Cookie [] cookie=request.getCookies(); for(int i=0;i<cookie.length;i++){ if(cookie[i].getName().equals("username")){ username=cookie[i].getValue(); } if(cookie[i].getName().equals("password")){ password=cookie[i].getValue(); } } %> <script type="text/javascript"> //看不清楚重载图片的点击事件 function reloadCode(){ var time=new Date().getTime(); document.getElementById("imagecode").src="<%= request.getContextPath()%>/ImageServlet?d="+time; } </script> <form action="<%=basePath%>/login.do" method="post"> <table border=0 cellpadding=0 cellspacing=0 style="margin:auto;border-collapse:separate; border-spacing:10px;"> <tr align="center"> <td colspan="2"> <label>登录</label> </td> </tr> <tr> <td> 用户名: </td> <td> <input type="text" name="username" value="<%=username%>"> </td> </tr> <tr> <td> 密码: </td> <td> <input type="password" name="password" value="<%=password%>"> </td> </tr> <tr> <td> 验证码: </td> <td> <input type="text" name="checkCode"/> <img alt="验证码" id="imagecode" src="<%= request.getContextPath()%>/ImageServlet"/><a href="javascript:reloadCode();">看不清楚</a><br> </td> </tr> <tr> <td> <input type="checkbox" name="ischeck">记住我? </td> <td> <a href="<%=basePath%>/toRegister.do">注册</a> </td> </tr> <tr align="center"> <td> <input type="submit" value="登录"> </td> <td> <input type="reset" value="重置"> </td> </tr> </table> </form> </body> </html>
ImageServlet类
还是那一句理论上肯定有人写好包给我们用的
但是我没找到
哈哈哈哈哈哈哈哈哈
package com.javaweb.action; import java.awt.Color; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; 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; public class ImageServlet extends HttpServlet{ /** * */ private static final long serialVersionUID = 54354321L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub doPost(req, resp); } public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException{ //这个方法实现验证码的生成 BufferedImage bi=new BufferedImage(68, 22,BufferedImage.TYPE_INT_RGB);//创建图像缓冲区 Graphics g=bi.getGraphics(); //通过缓冲区创建一个画布 Color c=new Color(200,150,255); //创建颜色 /* * 根据背景画了一个矩形框 */ g.setColor(c);//为画布添加背景颜色 g.fillRect(0, 0, 68,22); //fillRect:填充指定的矩形 char[] ch="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();//转化为字符型的数组 Random r=new Random(); int len=ch.length; int index; //index用于存放随机数字 StringBuffer sb=new StringBuffer(); for(int i=0;i<4;i++) { index=r.nextInt(len);//产生随机数字 g.setColor(new Color(r.nextInt(88),r.nextInt(188),r.nextInt(255))); //设置颜色 g.drawString(ch[index]+"",(i*15)+3, 18);//画数字以及数字的位置 sb.append(ch[index]); } request.getSession().setAttribute("piccode",sb.toString()); //将数字保留在session中,便于后续的使用 ImageIO.write(bi, "JPG", response.getOutputStream()); //输出图片 } }
web.xml
不要忘记静态注册新的servlet
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>servlet_sql_mvc_cookie</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>servletSqlMvcCookie</servlet-name> <servlet-class>com.javaweb.action.ServletSqlMvcCookie</servlet-class> </servlet> <servlet-mapping> <servlet-name>servletSqlMvcCookie</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <servlet> <servlet-name>ImageServlet</servlet-name> <servlet-class>com.javaweb.action.ImageServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ImageServlet</servlet-name> <url-pattern>/ImageServlet</url-pattern> </servlet-mapping> </web-app>
最后只要改改login方法
public void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { User user=new User(); String username=req.getParameter("username"); user.setUsername(username); String password=req.getParameter("password"); user.setPassword(password); String piccode=(String) req.getSession().getAttribute("piccode"); String checkCode=req.getParameter("checkCode"); //取值 //checkCode=checkCode.toUpperCase(); //把字符全部转换为大写的(此语句可以用于验证码不区分大小写) resp.setContentType("text/html;charset=gbk");//解决乱码问题 if(checkCode.equals(piccode)){ User use=userServive.login(user); if(use!=null){ String [] ischeck=req.getParameterValues("ischeck"); if(ischeck!=null&&"true".equals(ischeck[0])){ //添加cookie信息 Cookie usernameCookie=new Cookie("username", username); Cookie passwordCookie=new Cookie("password",password ); usernameCookie.setMaxAge(60*60*24*1);//一天 passwordCookie.setMaxAge(60*60*24*1); resp.addCookie(usernameCookie); resp.addCookie(passwordCookie); } resp.sendRedirect("loginSuccess.jsp"); }else{ resp.sendRedirect("loginFail.jsp"); } }else{ resp.sendRedirect("loginFail.jsp"); } }
验证码写不对怎么都登录不了不是吗?
以上是关于jsp-5 生成验证码并校验的主要内容,如果未能解决你的问题,请参考以下文章