Session实现验证码登陆笔记
1.生成验证码Servlet
package com.isit.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 javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random; @WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int width = 100;
int height = 50; //1.创建一对象,在内存中图片(验证码图片对象)
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //2.美化图片
//2.1 填充背景色
Graphics g = image.getGraphics();//画笔对象
g.setColor(Color.PINK);//设置画笔颜色
g.fillRect(0, 0, width, height); //2.2画边框
g.setColor(Color.BLUE);
g.drawRect(0, 0, width - 1, height - 1); String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789";
//生成随机角标
StringBuffer sb = new StringBuffer();
Random ran = new Random();
for (int i = 1; i <= 4; i++) {
int index = ran.nextInt(str.length());
//获取字符
char ch = str.charAt(index);//随机字符
sb.append(ch);
//2.3写验证码
g.drawString(ch + "", width / 5 * i, height / 2);
}
String checkCode = sb.toString();
HttpSession session = request.getSession();
session.setAttribute("checkCode", checkCode);
//2.4画干扰线
g.setColor(Color.GREEN); //随机生成坐标点 for (int i = 0; i < 10; i++) {
int x1 = ran.nextInt(width);
int x2 = ran.nextInt(width); int y1 = ran.nextInt(height);
int y2 = ran.nextInt(height);
g.drawLine(x1, y1, x2, y2);
} //3.将图片输出到页面展示
ImageIO.write(image, "jpg", response.getOutputStream()); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
CheckCodeServlet
2.登陆Servlet
package com.isit.servlet; import com.isit.dao.UserDao;
import com.isit.entity.User;
import org.apache.commons.beanutils.BeanUtils; 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 javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map; /**
* @program: LoginServlet
* @description: 登陆
* @author: wxh
* @date: 2019-06-11 15:03
**/
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
//1.验证验证码是否正确
HttpSession session = req.getSession();
String checkCode = (String) session.getAttribute("checkCode");
//1.1.验证码错误
String code = req.getParameter("checkCode");
if (checkCode != null && !checkCode.equalsIgnoreCase(code)) {
req.setAttribute("msg", "验证码错误");
req.getRequestDispatcher("/index.jsp").forward(req, resp);
} else {
//1.2.验证码正确
//2.校验登陆密码
User user = new User();
Map<String, String[]> parameterMap = req.getParameterMap();
//使用BeanUtils工具类封装成JavaBean对象
try {
BeanUtils.populate(user, parameterMap);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
UserDao userDao = new UserDao();
User entity = userDao.checkUser(user);
if (entity != null) {
//2.1.匹配重定向到登录成功 Success.jsp 页面
session.setAttribute("username", entity.getUsername());
resp.sendRedirect(req.getContextPath() + "/success.jsp");
} else {
//2.2.不匹配,转发到登陆界面
req.setAttribute("msg", "用户名或密码错误");
req.getRequestDispatcher("/index.jsp").forward(req, resp);
}
}
}
}
LoginServlet
3.JavaBean实体类代码
package com.isit.entity; /**
* @program: User
* @description: User实体类
* @author: wxh
* @date: 2019-06-11 14:15
**/
public class User {
private String id;
private String username;
private String password; public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
}
}
User
4.UserDao数据库操作层
package com.isit.dao; import com.isit.entity.User;
import com.isit.utils.JDBCUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper; import java.sql.ResultSet;
import java.sql.SQLException; /**
* @program: UserDao
* @description: UserDao
* @author: wxh
* @date: 2019-06-11 14:46
**/
public class UserDao {
JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource()); public User checkUser(User user){
String sql = "select * from user where username = ? and password = ?";
try{
User entity= jdbcTemplate.queryForObject(sql, new RowMapper<User>() {
@Override
public User mapRow(ResultSet resultSet, int i) throws SQLException {
User user = new User();
String username = resultSet.getString("username");
String password = resultSet.getString("password");
user.setUsername(username);
user.setPassword(password);
return user;
}
},user.getUsername(),user.getPassword());
return entity;
}catch (Exception e){
e.printStackTrace();
return null;
}
} }
UserDao
5.JDBC工具类
package com.isit.utils; import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties; /**
* @program: JDBCUtils
* @description: 数据库连接池工具类
* @author: wxh
* @date: 2019-06-11 14:17
**/
public class JDBCUtils { private static DataSource ds;
static {
Properties properties = new Properties();
InputStream resourceAsStream = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
try {
properties.load(resourceAsStream);
ds = DruidDataSourceFactory.createDataSource(properties);
} catch (IOException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
} public static DataSource getDataSource(){
return ds;
} public static Connection getConnection() throws SQLException {
return ds.getConnection();
} public static void close(Connection con, Statement statement, ResultSet resultSet){
if(resultSet !=null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement!=null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(con!=null){
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} public static void close(Connection connection,Statement statement){
close(connection,statement,null);
} }
JDBCUtils
6.JSP页面
<%--
Created by IntelliJ IDEA.
User: isit
Date: 2019/6/11
Time: 14:09
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登陆</title>
<script>
window.onload= function () {
document.getElementById("img").onclick=function () {
this.src = "/loginJsp/checkCodeServlet?time="+ new Date().getTime();
}
}
</script>
</head> <body>
<form method="post" action="/loginJsp/loginServlet">
<div>登录名:<input type="text" name="username"></div>
<div>密 码:<input type="password" name="password"></div>
<div><img src="/loginJsp/checkCodeServlet" id="img"></div>
<div> <input type="text" name="checkCode"></div>
<div><input type="submit"></div>
</form>
<div><%=request.getAttribute("msg")%></div>
</body>
</html>
index.jsp
<%--
Created by IntelliJ IDEA.
User: isit
Date: 2019/6/11
Time: 16:11
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>
<%=request.getSession().getAttribute("username")%> ,登陆成功
</h1>
</body>
</html>
success.jsp
总结:
1.实现登陆操作需要验证码Servlet和登陆Servlet两个Servlet,一个会话中需要请求两次,一个生成验证码图片,一个做验证操作(验证码匹配和登陆账号密码匹配);
2.CheckCodeServlet生成验证码图片到index.jsp页面,并将生成的验证码存到session中,以供LoginServlet做验证码验证操作;
3.LoginServlet需要两步验证,(1)验证验证码(2)验证登陆名和密码
3.1.通过HttpServletRequst对象获取Session对象,从Session对象中获取CheckCodeServlet添加到session中的验证码,以做验证操作,成功,继续下一步的登陆名和密码操作,失败,转发到登陆index.jsp页面,提示验证码错误;
3.2.验证码校验通过后,通过Dao层操作数据库返回查询结果(使用Druid数据库连接池,并使用JDBCTemple对数据库连接池对象进行封装,执行queryForObject方法返回实体类User)
3.3.校验通过,设置登陆名到session中(setAttribute),重定向到success.jsp页面,jsp页面取session中存放的登录名,展示XXX,登陆成功;
3.4.校验失败,转发到index.jsp页面中,提示登陆名密码错误。
Session实现验证码登陆笔记的更多相关文章
- JavaWeb-SpringSecurity使用短信验证码登陆
相关博文 JavaWeb-SpringBoot_一个类实现腾讯云SDK发送短信 传送门 系列博文 项目已上传至guthub 传送门 JavaWeb-SpringSecurity初认识 传送门 Java ...
- SpringSceurity(5)---短信验证码登陆功能
SpringSceurity(5)---短信验证码登陆功能 有关SpringSceurity系列之前有写文章 1.SpringSecurity(1)---认证+授权代码实现 2.SpringSecur ...
- web自动化测试中绕开验证码登陆的方式
web自动化测试中登陆需验证码是很大的一个困扰.现推荐一种简单的避开验证码登陆的方式,先代码进入登录页,人工输入验证码登录后浏览器自动保存cookie,再在新的标签中登录. 具体代码如下: publi ...
- Web UI自动化测试中绕开验证码登陆方式浅谈
web自动化测试中让测试者感到困惑的是登陆验证码,每次都不一样.现在推荐一种绕开验证码登陆的方式,其实就是将web浏览器获取的登陆cookie加载到程序中就可以了,这样程序就会认为你已经登陆,就可以跳 ...
- 用Session实现验证码
新建一个 ashx 一般处理程序 如: YZM.ashx继承接口 IRequiresSessionState //在一般处理程序里面继承 HttpContext context 为请求上下文,包含此次 ...
- Session、Cookie 学习笔记
在开始今天的博文之前首先为自己庆祝一下自己有了三个粉丝,也有了同僚的评论,说实话因为这个开心了好久!哈哈,好了在开始今天的正题之前,首先大家需要了解以下几点: a. HTTP 协议是无状态的协议,WE ...
- PHP会话(Session)实现用户登陆功能 转自#落人间#
对比起 Cookie,Session 是存储在服务器端的会话,相对安全,并且不像 Cookie 那样有存储长度限制,本文简单介绍 Session 的使用. 由于 Session 是以文本文件形式存储在 ...
- 通过cookies跳过验证码登陆页面,直接访问网站的其它URL
我每次手动访问去NN网的一家酒店,就不需要登陆,一旦我用脚本打开就会让我登陆,而登陆页面又有验证码,不想识别验证码,所以就想:“通过cookies跳过验证码登陆页面,直接访问网站的其它URL” 转 ...
- Spring Cloud OAuth2(二) 扩展登陆方式:账户密码登陆、 手机验证码登陆、 二维码扫码登陆
概要 基于上文讲解的spring cloud 授权服务的搭建,本文扩展了spring security 的登陆方式,增加手机验证码登陆.二维码登陆. 主要实现方式为使用自定义filter. Authe ...
随机推荐
- Python3之异常处理
写自动化脚本时经常会用到异常处理,下面将python中的异常处理做一整理: 注意:以下所有事列中的111.txt文件不存在,所以会引起异常 用法一:try...except...else..类型 1. ...
- Vue.js 注册组件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- TNS-01106: Listener using listener name LISTENER has already been started
-- 启动监听,提示已经启动. [oracle@sh ~]$ lsnrctl startLSNRCTL for Linux: Version 12.1.0.2.0 - Production on 06 ...
- 应用安全 - 代码审计 -Java
Java %c0%ae 安全模式绕过漏洞 原理 在Java端"%c0%ae"解析为"\uC0AE",最后转义为ASCCII低字符-".".通 ...
- C#打印单据
HTML: <form id="form1"> <div id="t_border"> <!- ...
- 20190902 On Java8 第十六章 代码校验
第十六章 代码校验 你永远不能保证你的代码是正确的,你只能证明它是错的. 测试 测试覆盖率的幻觉 测试覆盖率,同样也称为代码覆盖率,度量代码的测试百分比.百分比越高,测试的覆盖率越大. 当分析一个未知 ...
- 在使用spring中的ContextConfiguration、test注解时出现的错误
错误: 在使用测试注解时出现ContextConfiguration注解和test注解无法正常导包使用的编译异常,如图: 解决办法: 将pom.xml文件中以下依赖管理 中的<scope> ...
- Struts2异常:HTTP Status 404 - There is no Action mapped for action name addBook.
HTTP Status 404 - There is no Action mapped for action name addBook. 在地址栏进行访问的时候,出现了这个错误信息,导致出现此异常的原 ...
- 关于java的数组
一定要写成 int[] arr = new int[30] 这样每个元素默认为0; 介样子的 如果写成 int[] arr = {1,2,3,4}; 那么他的长度就是4
- 手写一个SpringMVC框架(转)
一:梳理SpringMVC的设计思路 本文只实现自己的@Controller.@RequestMapping.@RequestParam注解起作用,其余SpringMVC功能读者可以尝试自己实现. 1 ...