本次记录分角色登陆以及验证码的Servlet。
1.登陆验证
<html>
<%--
Created by IntelliJ IDEA.
User: jiachenglin
Date: 2022/11/11
Time: 14:31
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<head>
<title>Title</title>
</head>
<html>
<head>
<title>顾客登陆</title>
<h1 style="text-align: center">学生登陆</h1>
</head>
<body>
<form action="${pageContext.request.contextPath}/StudentServlet" method="post">
<div style="color: red;text-align: center">${login_err}</div><br>//从Servlet中传回登陆错误信息
学号:<input type="text" id="userne" name="id" maxlength="20"><br> //maxlength是指此处最长输入20个字符
<span id="ne_err" style="color: red;display:none">输入有误</span><br>
<span id="ne_num" style="display: none">最长20位</span>
密码:<input type="password" id="pswd" name="password" maxlength="20"><br>
<span id="pswd_err" style="color: red;display:none">输入有误</span><br>
验证码:<input type="text" name="valistr">
<image src="code" id="identity" onl oad="btn.disable=false;" style="cursor:pointer; vertical-align:middle"/>
<input type="button" value="看不清,更换验证码" onclick="changeImageCode()" id="btn" ><br>
<div style="color: red">${yan}</div><br>
<input type="submit" value="登陆"><input type="reset" value="重制"><br>
<input type="hidden" name="method" value="login"><br>
<a href="index.jsp">点击返回</a>
</form>
<script type="text/javascript">
<!--验证码切换-->
function changeImageCode() {
document.getElementById('btn').isDisabled=true;
document.getElementById('identity').src='code?ts='+new Date().getTime();
}
let ne_num=document.getElementById("ne_num");
ne_num.onblur=function (){
let ne_num1=ne_num.value.trim();
if(ne_num1.length==20){
document.getElementById("ne_num").style.display='';
}else{
document.getElementById("ne_num").style.display='none';
}
}
</script>
</body>
</html>
___________________________________________________________________________________________________________________
Servlet内容
case "login":
String id = request.getParameter("id");
String password = request.getParameter("password");
String cher = request.getParameter("valistr");
String cher2 = request.getSession().getAttribute("randomCode").toString();
List<Student> list1 = studentDao.login(id, password);
if (list1.isEmpty()) {
request.setAttribute("login_err", "用户名或密码错误");
request.getRequestDispatcher("student.jsp").forward(request, response);
} else if (!cher.toLowerCase().equals(cher2.toLowerCase())) {//校验验证码
request.setAttribute("yan", "验证码不一致!");
request.getRequestDispatcher("student.jsp").forward(request, response);
} else {
request.setAttribute("user", id);
request.getRequestDispatcher("studentjm.jsp").forward(request, response);
}
break;
___________________________________________________________________________________________________________________
2.验证码Servlet
import javax.imageio.ImageIO;标签:Javaweb,random,request,验证码,nextInt,登陆,import,response From: https://www.cnblogs.com/joranger/p/16997382.html
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 javax.servlet.http.HttpSession;
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 = 60;//验证码总宽度
int height = 20;//验证码总高度
// 随机数
char[] codeChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray();//字符串转换成字符数组
String captcha = "";//定义一个临时路径
Random random = new Random();//new 随机类Random
// 生成验证码图片
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 绘制矩形
Graphics2D graphics = image.createGraphics();//绘制环境对象
graphics.setColor(Color.WHITE);//背景色
graphics.fillRect(0, 0, width, height);//绘制矩形
Font font=new Font("Times New Roman",Font.PLAIN,18);
graphics.setFont(font);
//画边框
graphics.setColor(Color.BLACK);
graphics.drawRect(0,0,-1,-1);
//随机产生160条干扰线
graphics.setColor(Color.LIGHT_GRAY);
for(int i=0;i<160;i++){
int x=random.nextInt(width);
int y=random.nextInt(height);
int x1=random.nextInt(12);
int y1=random.nextInt(12);
graphics.drawLine(x,y,x+x1,y+y1);
}
//randomCode用于保存随机产生的验证码
StringBuffer randomCode=new StringBuffer();
int red=0,green=0,blue=0;
// 生成验证码图片
for (int i = 0; i < 4; i++) {
int strRand=random.nextInt(codeChar.length)+1;
String s= String.valueOf(codeChar[strRand]);
//产生随机的颜色分量来构造颜色值
red=random.nextInt(110);
green=random.nextInt(50);
blue=random.nextInt(50);
graphics.setColor(new Color(red,green,blue));
graphics.drawString(s,13*i+6,16);
randomCode.append(s);
// 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];//把生成的验证码保存在临时变量中
}
//将四位验证码保存在session中
HttpSession session= request.getSession();
session.setAttribute("randomCode",randomCode.toString());
//防止浏览器缓存验证码
response.setDateHeader("Expires",-1);
response.setHeader("Cache-Control","no-Cache");
response.setHeader("pragma","no-Cache");
response.setContentType("image/jpeg");
ServletOutputStream sos=response.getOutputStream();
// request.getSession().setAttribute("codes", captcha); //把验证码保存在Session对象中
// 利用ImageI0输出验证码
ImageIO.write(image, "jpeg", sos);
sos.close();
}
}