Session & Cookie登录案例 January 27,2020
Posted yyanghang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Session & Cookie登录案例 January 27,2020相关的知识,希望对你有一定的参考价值。
## 案例:验证码
1. 案例需求:
1. 访问带有验证码的登录页面login.jsp
2. 用户输入用户名,密码以及验证码。
* 如果用户名和密码输入有误,跳转登录页面,提示:用户名或密码错误
* 如果验证码输入有误,跳转登录页面,提示:验证码错误
* 如果全部输入正确,则跳转到主页success.jsp,显示:用户名,欢迎您
2. 分析:
package domain; /** * 用户 实体类 */ public class User { private int id; private String username; private String password; public User() { } public User(int id, String username, String password) { this.id = id; this.username = username; this.password = password; } public int getId() { return id; } public void setId(int 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; } @Override public String toString() { return "User{" + "id=" + id + ", username=‘" + username + ‘‘‘ + ", password=‘" + password + ‘‘‘ + ‘}‘; } }
package util; 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.SQLException; import java.util.Properties; /** * JDBC工具类 druid */ public class JDBCUtils { private static DataSource ds; static { try { //1.加载配置文件 Properties properties = new Properties(); //使用ClassLoader加载配置文件,获取字节输入流 InputStream resourceAsStream = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"); properties.load(resourceAsStream); //2.初始化连接池对象 ds = DruidDataSourceFactory.createDataSource(properties); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } /** * 获取Connection对象 */ public static Connection getConnection() throws SQLException { return ds.getConnection(); } /** * 获取连接池对象 */ public static DataSource getDataSource(){ return ds; } }
package dao; import domain.User; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import util.JDBCUtils; /** * 操作数据库User表的类 * */ public class UserDao { //声明JDBCTemplate对象共用 private JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource()); /** * 登录方法 * @param loginUser 只有用户和密码 * @return user返回用户的所有信息 */ public User login(User loginUser){ try { String sql = "select * from user where username=? and password = ?"; //将查询的结果封装为USER User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), loginUser.getUsername(), loginUser.getPassword()); return user; } catch (DataAccessException e) { e.printStackTrace(); return null; } } }
package web.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 { //1.创建一个对象,在内存中 存放图片 int width = 100; int heigth = 50; BufferedImage image = new BufferedImage(width,heigth,BufferedImage.TYPE_INT_RGB); //2.美化图片 //2.1填充背景色 Graphics graphics = image.getGraphics();//画笔对象 graphics.setColor(Color.PINK);//设置画笔颜色 graphics.fillRect(0,0,width,heigth);//填充矩形 //2.2画边框 graphics.setColor(Color.BLUE); graphics.drawRect(0,0,width-1,heigth-1);//因为画笔有1px 所以要减一 //2.3填写验证码 String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; StringBuilder img_str = new StringBuilder();//用来存储验证码信息 Random random = new Random(); for (int i = 1; i <=4 ; i++) { int index = random.nextInt(str.length()); graphics.drawString(str.charAt(index)+"",width/5*i,heigth/2); img_str.append(str.charAt(index)); } HttpSession session = request.getSession(); session.setAttribute("checkCode_session",img_str.toString()); //2.4画干扰线 graphics.setColor(Color.green); for (int i = 0; i <10 ; i++) { int x1 = random.nextInt(width); int x2 = random.nextInt(width); int y1 = random.nextInt(heigth); int y2 = random.nextInt(heigth); graphics.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); } }
package web.servlet; import dao.UserDao; import domain.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; @WebServlet("/loginServlet") public class LoginServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.设置编码 request.setCharacterEncoding("utf-8"); //2.获取请求参数 String login_username = request.getParameter("username"); String login_password = request.getParameter("password"); String login_checkCode = request.getParameter("checkCode"); //3.获取验证码 HttpSession session = request.getSession(); String checkCode_session = (String) session.getAttribute("checkCode_session"); //删除session中存储的验证码 session.removeAttribute("checkCode_session"); //4.判断验证码是否正确 忽略大小写比较 if(login_checkCode!=null && checkCode_session.equalsIgnoreCase(login_checkCode)){ //5.验证码正确 判断账号与密码是否正确 User loginUser = new User(); loginUser.setUsername(login_username); loginUser.setPassword(login_password); UserDao userDao = new UserDao(); User user = userDao.login(loginUser); if(user==null){ //登录失败 //存储提示信息到request request.setAttribute("login_error","用户名或密码错误"); //转发到登录页面 request.getRequestDispatcher("/login.jsp").forward(request,response); }else{ //登录成功 // 存储信息,用户信息 因为User信息可能跨越很多页面,所以使用session而不使用request session.setAttribute("user",user.getUsername()); //重定向到success.jsp response.sendRedirect(request.getContextPath()+"/success.jsp"); } }else{ request.setAttribute("cc_error","验证码错误"); //验证码错误 request.getRequestDispatcher("login.jsp").forward(request,response); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request,response); } }
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>登录案例</title> <!-- 分析: 点击图片,需要换一张 1.给超链接和图片绑定单击事件 2.重新设置图片的src属性值 --> <script> window.onload = function () { document.getElementById("img").onclick= function () { this.src = "${pageContext.request.contextPath}/checkCodeServlet?"+new Date().getTime(); } } </script> </head> <body> <form action="${pageContext.request.contextPath}/loginServlet" method="post"> <table> <tr> <td>用户名</td> <td><input type="text" placeholder="请输入用户名" name="username"></tr></td> <tr> <td>密码</td> <td><input type="text" placeholder="请输入用户密码" name="password"></td> </tr> <tr > <td>验证码</td> <td><input type="text" placeholder="请输入验证码" name="checkCode"></td> </tr> <tr> <td colspan="2"><img id="img" src="${pageContext.request.contextPath}/checkCodeServlet"></td> </tr> <tr> <td colspan="2"><input type="submit" value="登录"></td> </tr> </table> </form> ${requestScope.cc_error} ${requestScope.login_error} </body> </html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>登录成功页面</title> </head> <body> <% HttpSession session1 = request.getSession(); String user = (String) session1.getAttribute("user"); out.print(user+"欢迎登录"); %> </body> </html>
以上是关于Session & Cookie登录案例 January 27,2020的主要内容,如果未能解决你的问题,请参考以下文章