带有验证码&session&退出的登录验证
需求:
1-1.登录时验证验证码(数字和字母的组合,不区分大小写)
1-2:验证码可以点击刷新。
2.验证用户名,密码。
3.登录后不关闭浏览器的条件下可以免输入账号密码登录。
4,登录后可以点击退出,退出登陆。
思路:1.验证码:使用VerifyCode类获取验证码(判断时忽略大小写 )
使用session保存验证码的text,与用户输入的进行判断。
2.验证码的刷新:在前端进行验证码路径进行更换
3.免登陆:用户登录后使用session保存用户的2用户名密码等信息。
4.登陆退出:即清除服务器的session,并重定向到登录的页面。
VerifyCode.java
package utils;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
public class VerifyCode {
private int w = 70;
private int h = 35;
private Random r = new Random();
// 定义有那些字体
private String[] fontNames = { "宋体", "华文楷体", "黑体", "微软雅黑", "楷体_GB2312" };
// 定义有那些验证码的随机字符
private String codes = "23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ";
// 生成背景色
private Color bgColor = new Color(250, 250, 250);
// 用于gettext 方法 获得生成的验证码文本
private String text;
// 生成随机颜色
private Color randomColor() {
int red = r.nextInt(150);
int green = r.nextInt(150);
int blue = r.nextInt(150);
return new Color(red, green, blue);
}
// 生成随机字体
private Font randomFont() {
int index = r.nextInt(fontNames.length);
String fontName = fontNames[index];
int style = r.nextInt(4);
int size = r.nextInt(5) + 24;
return new Font(fontName, style, size);
}
// 画干扰线
private void drawLine(BufferedImage image) {
int num = 3;
Graphics2D g2 = (Graphics2D) image.getGraphics();
for (int i = 0; i < num; i++) {
int x1 = r.nextInt(w);
int y1 = r.nextInt(h);
int x2 = r.nextInt(w);
int y2 = r.nextInt(h);
g2.setStroke(new BasicStroke(1.5F));// 不知道
g2.setColor(Color.blue);
g2.drawLine(x1, y1, x2, y2);
}
}
// 得到codes的长度内的随机数 并使用charAt 取得随机数位置上的codes中的字符
private char randomChar() {
int index = r.nextInt(codes.length());
return codes.charAt(index);
}
// 创建一张验证码的图片
public BufferedImage createImage() {
BufferedImage image = new BufferedImage(w, h,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = (Graphics2D) image.getGraphics();
StringBuilder sb = new StringBuilder();
// 向图中画四个字符
for (int i = 0; i < 4; i++) {
String s = randomChar() + "";
sb.append(s);
float x = i * 1.0F * w / 4;
g2.setFont(randomFont());
g2.setColor(randomColor());
g2.drawString(s, x, h - 5);
}
this.text = sb.toString();
drawLine(image);
// 返回图片
return image;
}
// 得到验证码的文本 后面是用来和用户输入的验证码 检测用
public String getText() {
return text;
}
// 定义输出的对象和输出的方向
public static void output(BufferedImage bi, OutputStream fos)
throws FileNotFoundException, IOException {
ImageIO.write(bi, "JPEG", fos);
}
}
VerifyServlet.java
package com.wang.servlet;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import utils.VerifyCode;
public class VerifyServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 生成验证码对象
VerifyCode code = new VerifyCode();
BufferedImage image = code.createImage();
String text = code.getText();
request.getSession().setAttribute("session_value", text);
System.out.println("执行ver验证码--"+text);
VerifyCode.output(image, response.getOutputStream());
}
}
LoginServlet
package com.wang.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.jms.Session;
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 LoginServlet extends HttpServlet {
// session 的最大不活动时间。
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 判断验证码是否一样 。
String session_input_code = request.getParameter("verify");
String session_code = (String) request.getSession().getAttribute("session_value");
// 判断
if (!session_code.equalsIgnoreCase(session_input_code)) {
System.out.println("登录失败!");
request.setAttribute("err_info", "验证码错误!");
request.getRequestDispatcher("login.jsp").forward(request, response);
return;
}
final String Myname = "wang";
final String Mypassword = "121";
String name = request.getParameter("username");
String password = request.getParameter("password");
if (name.equals(Myname) && password.equals(Mypassword)) {
// 保存session到服务器,转发到成功的页面
HttpSession session = request.getSession();
session.setAttribute("username", "wang");// 保存session
session.setAttribute("password", "121");
// 重定向
request.getRequestDispatcher("/succ1.jsp").forward(request, response);
} else {
String err_info_1 = "";
String err_info_2 = "";
if (!name.equals(Myname)) {
err_info_1 = "用户名错误!";
}
if (!password.equals(Mypassword)) {
err_info_2 = "密码错误!";
}
String err_info_ouput = err_info_1 + err_info_2;
// 重定向到login.jsp 并使用request域传递错误 的信息
/*
* 这里发送的错误信息必须使用转发,使用重定向会导致获取不到request域的信息
*/
request.setAttribute("err_info", err_info_ouput);
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
}
}
exitServlet.java
package com.wang.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/*
* 退出Servlet
*/
public class exitServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getSession().invalidate();
String path = request.getServletContext().getContextPath();
//
response.sendRedirect("/demo/login.jsp");
}
}
login.jsp
<%@ page language="java" import="java.util.*" 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">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.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">
<style type="text/css">
* {
padding: 0px;
margin: 0px;
text-align: center;
margin-top: 20px;
}
</style>
<body>
<form action="<%=basePath%>LoginServlet" method="post">
用户名:<input type="text" name="username"><br> 密码:<input
type="text" name="password"><br> 验证码:<input type="text"
name="verify" size="3" ><br> <img
src="<%=basePath%>VerifyServlet" id="img"><br> </a> <a
href="javascript:change_verify()">看不清?换一张</a><input type="submit"
value="提交">
</form>
<%
int index = 0;
String err_info = (String) request.getAttribute("err_info");
if (err_info == null) {
err_info = "";
}
Enumeration enumeration = session.getAttributeNames();
while (enumeration.hasMoreElements()) {
String name = enumeration.nextElement().toString();
String value = (String) session.getAttribute(name);
if (value.equals("wang") || value.equals("121")) {
index++;
}
}
if (index == 2) {
request.getRequestDispatcher("/succ1.jsp").forward(request, response);
}
%>
<%=err_info%>
</body>
<script type="text/javascript">
function change_verify() {
//获取验证码图片
var image = document.getElementById("img");
//更改路径
image.src = "VerifyServlet?a=" + new Date().getTime();
console.log(image.src);
}
</script>
</html>
succ1.jsp
<%@ page language="java" import="java.util.*" 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">
<html>
<head>
<base href="<%=basePath%>">
<title>page2</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">
</head>
<body>
<h1>这里是登录的成功的页面1</h1>
<%
//判断是是否有 用户登录后保存的session
String username = (String) session.getAttribute("username");
if (username == null) {
//如果没有 提供 错误的信息“未登录”,并重定向到login.jsp
request.setAttribute("err_info", "请登录!");
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
%>
你的名字是:<%=username%>
<br>
<a href="<%=basePath%>succ2.jsp">点击跳转到succ2.jsp</a>
<a href="<%=basePath%>exitServlet">退出登录</a>
</body>
</html>
succ2.jsp
<%@ page language="java" import="java.util.*" 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">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'b.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">
</head>
<body>
<%
//判断是是否有 用户登录后保存的session
String username = (String) session.getAttribute("username");
if (username == null) {
//如果没有 提供 错误的信息“未登录”,并重定向到login.jsp
request.setAttribute("err_info", "请登录!");
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
%>
<h1>这里是登录成功的页面2</h1>
</body>
</html>
项目结构: