cookie技术实现自动登录+验证用户名输入是否正确
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了cookie技术实现自动登录+验证用户名输入是否正确相关的知识,希望对你有一定的参考价值。
login页面
<%@ 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>登录界面</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"> <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-2.1.4.js"></script> <style type="text/css"> .error{ color: red; } </style> </head> <script type="text/javascript"> //页面加载 $(function(){ //派发失去焦点事件 $("#username").blur(function(){ //获取输入的用户名 var $username = $(this).val(); if($username.trim() == ""){ $("#userspanid").addClass("error"); $("#userspanid").html("用户名不能为空"); } else { var url="${pageContext.request.contextPath}/loginServlet"; var params={"username":$username}; $.post(url,params,function(data){ if( data == 0 ){ $("#userspanid").addClass("error"); $("#userspanid").html("您输入的用户名不存在,请核对用户名"); } else { $("#userspanid").removeClass("error"); $("#userspanid").html("用户名正确"); } }); } }); }); //阻止表单提交 //function checkForm() { //让提交之前先校验一下是否存在错误,如果存在,则不能提交 //} </script> <body> <form method="post" id="sub" action="${pageContext.request.contextPath }/loginInServlet"> <table> <tr> <td>用户名:</td> <td><input type="text" name="username" id="username"></td> <td><span id="userspanid"></span></td> </tr> <tr> <td>密码:</td> <td><input type="password" name="password" id="username"></td> <td><span id="pwdspanid"></span></td> </tr> <tr> <td colspan="3"> <input type="checkbox" name="autologin" id="autologin" value="autologinOk">自动登录</td> </tr> <tr> <td colspan="3"><input type="submit" value="login"></td> </tr> </table> </form> </body> </html>
//success.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>成功页面</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"> <link rel="stylesheet" type="text/css" href="styles.css"> </head> <body> ${user.username }:欢迎回家 </body> </html>
//User类
package com.tbamaw.domain; public class User { private int uid; private String username; private String password; public int getUid() { return uid; } public void setUid(int uid) { this.uid = uid; } 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; } public User() {} public User(String username, String password) { this.username = username; this.password = password; } }
constant
package com.tbamaw.constant; /** * 常量 * @author bamaw * */ public interface Constant { //勾选自动登录 String IS_AOTO_LOGIN = "autologinOk"; }
servlet
package com.tbamaw.web.servlet; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.tbamaw.domain.User; import com.tbamaw.service.UserService; /** * 验证用户是否输入正确 * @author bamaw * */ public class LoginServlet extends HttpServlet { private static final long serialVersionUID = -6706822935446915300L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String username = request.getParameter("username"); User user = null; if( username != null ){ try { user = new UserService().findByName(username); if (user != null) { response.getWriter().print("1"); } else{ response.getWriter().print("0"); } } catch (SQLException e) { e.printStackTrace(); } } } }
package com.tbamaw.web.servlet; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.tbamaw.constant.Constant; import com.tbamaw.domain.User; import com.tbamaw.service.UserService; /** * 用户登录 * @author bamaw * */ public class LoginInServlet extends HttpServlet { private static final long serialVersionUID = -1501341575375720050L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); //获取用户输入的用户名和密码 String username = request.getParameter("username"); String password = request.getParameter("password"); User user = null; //调用Service try { user = new UserService().login(username,password); if (user == null) { request.setAttribute("msg", "用户名和密码不匹配!"); request.getRequestDispatcher("/user/login.jsp").forward(request, response); return; } else { //若不为空,跳转到success.jsp页面上 request.getSession().setAttribute("user", user); //判断是否勾选了自动登录,若是,需要将用户名和密码放入到cookie中,写回浏览器 if (Constant.IS_AOTO_LOGIN.equals(request.getParameter("autologin"))) { //创建Cookie //第一项给cookie设置名字autologin Cookie c = new Cookie("autologin",username+"-"+password); c.setMaxAge(3600); c.setPath(request.getContextPath()+"/"); response.addCookie(c); } //页面重定向 response.sendRedirect(request.getContextPath()+"/success.jsp"); } } catch (SQLException e) { e.printStackTrace(); } } }
sevice
package com.tbamaw.service; import java.sql.SQLException; import com.tbamaw.dao.UserDao; import com.tbamaw.domain.User; public class UserService { //验证用户名是否输入正确 public User findByName(String username) throws SQLException { return new UserDao().findByName(username); } //用户登录 public User login(String username, String password) throws SQLException { return new UserDao().login(username,password); } }
DAO
package com.tbamaw.dao; import java.sql.SQLException; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import com.tbamaw.domain.User; import com.tbamaw.utils.DataSourceUtils; public class UserDao { //验证用户名是否输入正确 public User findByName(String username) throws SQLException { QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource()); String sql = "SELECT username from t_user where username= ?"; return qr.query(sql, new BeanHandler<User>(User.class),username); } //用户登录 public User login(String username, String password) throws SQLException { QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource()); String sql = "select username,password from t_user where username=? and password=?"; return qr.query(sql, new BeanHandler<User>(User.class),username,password); } }
package com.tbamaw.filter; import java.io.IOException; import java.sql.SQLException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.tbamaw.domain.User; import com.tbamaw.service.UserService; import com.tbamaw.utils.CookieUtils; public class AutoLoginFilter implements Filter { public void destroy() { } public void init(FilterConfig filterConfig) throws ServletException { } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { // 强转 HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; // 完成自动登录,在此之前先判断session中有没有登录用户,若没有,则自动登录 User user = (User) request.getSession().getAttribute("user"); if (user == null) {// 先判断用户是否为空,为空时,则自动登录 // 判断访问的资源是否和登录或者注册等有关,若没有关系,自动登录 String path = request.getRequestURI();// "/auto_login/xxxx" if (!path.contains("/login")) { // 获取指定cookie Cookie cookie = CookieUtils.getCookieByName("autologin",request.getCookies()); // 判断cookie是否为空,若不为空,取值(username,password),调用service,完成登录, // 判断user是否为空,不为空,放入session中 if (cookie != null) { String username = cookie.getValue().split("-")[0]; String password = cookie.getValue().split("-")[1]; // 调用service完成登录 try { user = new UserService().login(username, password); } catch (SQLException e) { e.printStackTrace(); } if (user != null) { request.getSession().setAttribute("user", user); } } } } // 放行 chain.doFilter(request, response); } }
utils
package com.tbamaw.utils; import javax.servlet.http.Cookie; public class CookieUtils { /** * 通过名称在cookie数组获取指定的cookie * @param name cookie名称 * @param cookies cookie数组 * @return */ public static Cookie getCookieByName(String name, Cookie[] cookies) { if(cookies!=null){ for (Cookie c : cookies) { //通过名称获取 if(name.equals(c.getName())){ //返回 return c; } } } return null; } }
以上是关于cookie技术实现自动登录+验证用户名输入是否正确的主要内容,如果未能解决你的问题,请参考以下文章