Session和Cookie综合案例
程序员文章站
2022-07-04 18:51:28
...
案例:验证码,rememberMe
1. 案例需求:
1. 访问带有验证码的登录页面login.jsp
2. 用户输入用户名,密码以及验证码。
* 如果用户名和密码输入有误,跳转登录页面,提示:用户名或密码错误
* 如果验证码输入有误,跳转登录页面,提示:验证码错误
* 如果全部输入正确,则跳转到主页success.jsp,显示:用户名,欢迎您
2. 分析:其中有几个点需要注意,是要使用session的
1. 验证码生成之后的获取,是存放在session中的
2. 登录成功之后,user对象是存放在session中的,为了在success中获取用户信息
3. 在写回信息(错误信息)也是放在session中的,也可以放在request中,但是在登陆成功之后的返回并不友好(是返回servlet不是jsp页面)
4. 其中记住我使用的是cookie(通过用户选择下拉菜单栏来设置记住的时长或不记住)
3. 代码实现(省略了数据库,实体类,userdao工具类)
* UserDao类
public class UserDao {
//获取jdbctemplate对象
private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
//select方法
public User login(User loginUser){
try {
String sql = "select * from user where username = ? and password = ?";
User user = template.queryForObject(sql, new BeanPropertyRowMapper<>(User.class),
loginUser.getUsername(),loginUser.getPassword());
return user;
} catch (DataAccessException e) {
return null;
}
}
}
* loginServlet
package com.qin.servlet;
import com.qin.dao.UserDao;
import com.qin.domain.User;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置页面的编码
request.setCharacterEncoding("utf-8");
//获取session
HttpSession session = request.getSession();
//如果页面刷新之后请求要删除之前存储的的错误信息session
session.removeAttribute("loginerror");
session.removeAttribute("checkerror");
//获取系统生成验证码
String checkCode = (String) session.getAttribute("checkCode");
//让验证码获取之后失效
session.removeAttribute("checkCode");
//获取参数,封转对象
String username = request.getParameter("username");
String password = request.getParameter("password");
User user = new User(username, password);
//获取用户填写的验证码
String checkcode = request.getParameter("checkcode");
//忽略大小写比较checkcode
if (checkCode != null && checkCode.equalsIgnoreCase(checkcode)) {
//判断用户名密码是否输入正确
UserDao dao = new UserDao();
User login = dao.login(user);
if (login != null) {
//登录成功,跳转success.jsp
//登录成功时候判断记住密码
rememberMe(request, response, username, password);
//设置user的session
request.getSession().setAttribute("user", login);
response.sendRedirect("/day16/success.jsp");
} else {
//写回信息(使用request域对象,不建议,因为在登陆之后返回是返回的servlet)
//request.setAttribute("loginerror", "用户名或密码错误");
//request.getRequestDispatcher("/login.jsp").forward(request, response);
//使用session域对象
session.setAttribute("loginerror","用户名或密码错误");
response.sendRedirect("/day16/login.jsp");
}
} else {
//写回信息(使用request域对象,不建议)
//request.setAttribute("checkerror", "验证码错误");
//request.getRequestDispatcher("/login.jsp").forward(request, response);
//使用session域对象
session.setAttribute("checkerror","验证码错误");
response.sendRedirect("/day16/login.jsp");
}
}
//抽取方法是否记住我
private void rememberMe(HttpServletRequest request, HttpServletResponse response, String username, String password) {
//获取是否记住密码的参数
String remember = request.getParameter("remember");
//使用cookie
if (remember != null) {
Cookie cookie = new Cookie("remName", username);
Cookie cookie1 = new Cookie("remPass", password);
int time = 0;
if ("0".equals(remember)){
//不记住
time = 0;
}
if ("1".equals(remember)){
//一天
time = 60*60*24;
}
if ("2".equals(remember)){
//一周
time = 60*60*24*7;
}
if ("3".equals(remember)){
//一个月
time = 60*60*24*30;
}
//设置cookie的存活时间
cookie.setMaxAge(time);
cookie1.setMaxAge(time);
//response返回cookie
response.addCookie(cookie);
response.addCookie(cookie1);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
*login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>login小案例</title>
<script>
window.onload = function () {
document.getElementById("check").onclick = function () {
this.src = "/day16/checkServlet?time=" + new Date().getTime();
}
}
</script>
<style>
div {
color: red;
}
</style>
</head>
<body>
<%--拿到cookie--%>
<% Cookie[] cookies = request.getCookies();
String username = null;
String password = null;
if (cookies != null && cookies.length > 0) {
for (Cookie cookie : cookies) {
String name = cookie.getName();
if ("remName".equals(name)){
username = cookie.getValue();
}
if ("remPass".equals(name)){
password = cookie.getValue();
}
}
}
%>
<form action="/day16/loginServlet" method="post">
<table>
<tr>
<td>用户名</td>
<td><input type="text" name="username" value="<%= username==null?"":username%>"></td>
</tr>
<tr>
<td>密码</td>
<td><input type="password" name="password" value="<%= password==null?"":password%>"></td>
</tr>
<tr>
<td>验证码</td>
<td><input type="text" name="checkcode"></td>
</tr>
<tr>
<td colspan="2"><img id="check" src="/day16/checkServlet"></td>
</tr>
<tr>
<td>记住密码</td>
<td>
<select name="remember" id="rem">
<option value="0" selected>--不记住--</option>
<option value="1">--记住一天--</option>
<option value="2">--记住一周--</option>
<option value="3">--记住一月--</option>
</select>
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="登录"></td>
</tr>
</table>
<div>
<%= request.getSession().getAttribute("checkerror") == null ? "" : request.getSession().getAttribute("checkerror")%>
</div>
<div>
<%= request.getSession().getAttribute("loginerror") == null ? "" : request.getSession().getAttribute("loginerror")%>
</div>
</form>
</body>
</html>
*验证码是一个工具类(借助了java.awt.*画出来的)
package com.qin.servlet;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
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("/checkServlet")
public class CheckServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//验证码的完成
//生成验证码
int width = 150;
int height = 35;
//创建img对象
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//画笔对象
Graphics p = image.getGraphics();
//设置画笔颜色
p.setColor(Color.pink);
p.fillRect(0,0,width,height);
//画边框
p.setColor(Color.BLUE);
p.drawRect(0,0,width-1,height-1);
//生产验证码并记录
StringBuilder stringBuilder = new StringBuilder();
//生成随机角标
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
for (int i = 1; i <= 4; i++) {
p.setFont(new Font("微软雅黑",Font.BOLD,16));
char ch = str.charAt(random.nextInt(str.length()));
stringBuilder.append(ch);
p.drawString(ch+"",width/5*i-4,height/2+1);
}
String checkCode = stringBuilder.toString();
//存入一个session
request.getSession().setAttribute("checkCode",checkCode);
//画干扰线
p.setColor(Color.green);
for (int i = 0; i < 6; i++) {
//生成随机的四条线
int x1 = random.nextInt(width);
int x2 = random.nextInt(width);
int y1 = random.nextInt(height);
int y2 = random.nextInt(height);
p.drawLine(x1,y1,x2,y2);
}
//将图片对象输出到页面
//图片对象,后缀名,输出流
ImageIO.write(image,"jpg",response.getOutputStream());
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
* success.jsp
<%@ page import="com.qin.domain.User" %><%--
Created by IntelliJ IDEA.
User: Sun
Date: 2018/9/17
Time: 19:47
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录成功</title>
</head>
<body>
<h1>欢迎您,<%= ((User)request.getSession().getAttribute("user")).getUsername()%></h1>
</body>
</html>
上一篇: gitflow工作流
下一篇: Struts2学习
推荐阅读
-
PHP中cookie和session的区别实例分析_php实例
-
php中session和cookie实现自动登录_PHP教程
-
php同时使用session和cookie来保存用户登录信息的实现代码,sessioncookie_PHP教程
-
cookie与session的用户登录案例(4-20)-2018年5月1日零点30分
-
详解PHP中cookie和session的区别及cookie和session用法小结,cookiesession
-
thinkphp中session和cookie无效的解决方法,thinkphpsession
-
cookie和session的加密?
-
php中cookie和session使用范例
-
php同时使用session和cookie来保存用户登录信息的实现代码
-
ASP.NET中Application、Cookie、Session、Cache和ViewState