Javaweb 验证码(详细)

Servlet类(核心)

package com.fruit.util;

import javax.imageio.ImageIO;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet(name = "VerifyCodeServlet", urlPatterns = "/code")
public class VerifyCodeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	//防止浏览器缓存验证码
    	response.setDateHeader("Expires",-1);
    	response.setHeader("Cache-Control","no-Cache");
    	response.setHeader("pragma","no-Cache");
    	 int width = 100;//验证码总宽度
         int height = 30;//验证码总高度
//         随机数
         char[] codeChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456".toCharArray();//字符串转换成字符数组
         String captcha = "";//定义一个临时路径
         Random random = new Random();//new 随机类Random
//         生成验证码图片
         BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//         绘制矩形
         Graphics graphics = image.getGraphics();//绘制环境对象
         graphics.setColor(Color.gray);//背景色
         graphics.fillRect(0, 0, width, height);//绘制矩形

//         生成验证码图片
         for (int i = 0; i < 4; i++) {
        	  int index = random.nextInt(codeChar.length);
              // 设置验证码字体图片颜色
        	  graphics.setColor(new Color(random.nextInt(110), random.nextInt(150), random.nextInt(200)));
              // 每个验证码字体的宽间距,高度
              graphics.drawString(codeChar[index] + "", (i * 20) + 15, 20);
              captcha += codeChar[index];//把生成的验证码保存在临时变量中
         }
         request.getSession().setAttribute("codes", captcha); //把验证码保存在Session对象中
//         利用ImageI0输出验证码
         ImageIO.write(image, "jpg", response.getOutputStream());

    }
}

JSP显示页面

<%@page import="java.net.URLDecoder"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
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>My JSP 'login.jsp' starting page</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 type="text/javascript">
	/* 解决cookie乱码*/
	window.onload=function(){
		var str=decodeURI('${cookie.name.value }');
		document.getElementsByName("user")[0].value=str;
	}
</script>
  </head>
  
  <body>
 <div align="center">
    <form action="login" method="post" onsubmit="return lgo()">
			<table>
				<tr>
					<td>账号:</td>
					<td><input type="text" id="user" value="${cookie.name.value }" name="user"/></td>
				</tr>
				<tr>
					<td>密码:</td>
					<td><input type="password" id="pwd" value="" name="pwd" /></td>
				</tr>
				<tr>
	   				<td colspan="2">
	   					<image  src="code"  id="identity" onload="btn.disable=false;" style="cursor:pointer; vertical-align:middle"/>
	   					<input type="button" value="看不清,更换验证码" onclick="changeImageCode()" id="btn"  style="vertical-align:middle;border:0">
	   				</td>
   				</tr>
   				<tr>
	   				<td>验证码:</td>
	   				<td><input type="text" name="valistr"/></td>
	   				<td id="valistr_id">${yan}</td>
   				</tr>
   				<tr>
	   				<td>
	   					<input type="checkbox" name="rename" value="true"
	   						<c:if test="${cookie.name !=null}">
	   							checked='checked';
	   						</c:if>
	   					/>记住用户名
	   				</td>
   					<td><input type="checkbox" name="autologin" value="true"/>30天内自动登录</td>
   				</tr>
   				<tr>
	   				<td >
	   					<input type="hidden" name="action" value="login">
	   					<input type="submit" value="登录" style="margin-left:50px" /> 
	   				</td>
	   				<td >
	   				<button style="width:50px"><a href="arar/regist.jsp" style="text-decoration: none;color:black;
	   					">注册</a> </button>
	   				</td>
   				</tr>
			</table>
		</form>
</div>
		<script type="text/javascript">
    	function lgo(){
    		var flag = true;
    		var admin = document.getElementById("user").value;
    		var password = document.getElementById("pwd").value;
			if ("" == admin){
				alert("请输入账号!");
				flag = false;
				return false;
			}
			else if ("" == password){
				alert("请输入密码!");
				flag = false;
				return false;
			}
			if(flag == true){
				//form.submit();
				return true;
			}
		};
        <!--验证码切换-->
		function changeImageCode() {
        document.getElementById('btn').isDisabled=true;
        document.getElementById('identity').src='code?ts='+new Date().getTime();

    }
    var err ='<%=request.getParameter("status")%>';
  	if(err=='on'){
	  	 alert("登录失败!");
	 	 }
    </script>
  </body>
</html>

后台处理Servlet类

package com.fruit.servlet;
//登录
import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fruit.Factory.BasicFactory;
import com.fruit.pojo.Member;
@WebServlet(name="Loginh",urlPatterns="/login")
public class Loginh extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
			doPost(req,resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		String name=req.getParameter("user");
		String pwd=req.getParameter("pwd");
		String cher=req.getParameter("valistr");
		String cher2=req.getSession().getAttribute("codes").toString();
		String path=null;
		if(!cher.toLowerCase().equals(cher2.toLowerCase())){//校验验证码
			req.setAttribute("yan","验证码不一致!");
			req.getRequestDispatcher("arar/login.jsp").forward(req,resp);
			return;
		}else{
			Member mem = new Member();//用于接收用户传过来的账号与密码
			if(!name.equals("") && name!=null){
				mem.setMember_name(name);
				mem.setMember_password(pwd);
				try {
					boolean flag = BasicFactory.getMemberm().selseUser(mem);
					if(flag){
//						保存用户名(通过Session注销用户)
						req.getSession().setAttribute("member", mem);
						req.getSession().setAttribute("id",mem.getMember_id());
						req.getSession().setAttribute("member_name",mem.getMember_name());
//						处理记住用户名
						if("true".equals(req.getParameter("rename"))){
							Cookie cookie = new Cookie("name",URLEncoder.encode(mem.getMember_name(),"utf-8"));
							cookie.setMaxAge(3600*24*30);//设置30天内记住用户
					    	resp.addCookie(cookie);
						}else{
							Cookie cookie =new Cookie("name"," ");
							cookie.setMaxAge(0);
							resp.addCookie(cookie);
						}
//						记住用户30天内登录
						if("true".equals(req.getParameter("autologin"))){
							Cookie cookie2 = new Cookie("autologin",URLEncoder.encode(mem.getMember_name()+":"+mem.getMember_password(),"utf-8"));
							cookie2.setMaxAge(3600*24*30);//设置30天内记住用户
					    	resp.addCookie(cookie2);
						}
						path = "arar/log.jsp?user=yes";
					}else{
						path = "arar/login.jsp?status=on";//登录失败
					}
				} catch (Exception e) {
					
					e.printStackTrace();
				}
			}
			req.getRequestDispatcher(path).forward(req, resp);
		}
	}
}

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页