怎么在Java项目中利用servlet实现一个自动登录退出功能?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
UserDao.java从数据库中查询用户名与密码
//登录 public User login(User user) throws SQLException { QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource()); String sql = "select from user where username = ? and password = ?"; return qr.query(sql, new BeanHandler<User>(User.class),user.getUsername(),user.getPassword()); } UserService.java public User login(User user){ try { return ud.login(user); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
UserServlet.java实现登录功能
//登录 public void login(HttpServletRequest request, HttpServletResponse response) throws IOException, IllegalAccessException, InvocationTargetException, ServletException{ Map<String,String[]> map = request.getParameterMap(); User user = new User(); BeanUtils.populate(user,map); if (map.get("autoLogin")!=null){ Cookie username = new Cookie("username", map.get("username")[0]); username.setMaxAge(6060); Cookie password = new Cookie("password", map.get("password")[0]); password.setMaxAge(60*60); response.addCookie(username); response.addCookie(password); } user = us.login(user); if (user != null){ request.getSession().setAttribute("user", user); response.sendRedirect("/ShopStore/default.jsp"); } else{ request.setAttribute("message", "用户或密码错误!"); request.getRequestDispatcher("/login.jsp").forward(request, response); } }
工具类:AutoLoginFilter.java用来实现自动登录
package com.yinhe.web.filter; import java.io.IOException; 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.yinhe.bean.User; import com.yinhe.service.UserService; public class AutoLoginFilter implements Filter{br/>@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest)request; HttpServletResponse resp = (HttpServletResponse)response; //是否已登录 if (req.getSession().getAttribute("user") == null){//如果已登录,则啥都不干 //判断cookie中有没有账户密码 Cookie[] cookies = req.getCookies(); if (cookies != null){ String username = ""; String userpass = ""; for (Cookie cookie : cookies) { if (cookie.getName().equals("username")){//找到感兴趣的cookie username = cookie.getValue(); } if (cookie.getName().equals("password")){//找到感兴趣的cookie userpass = cookie.getValue(); } } UserService us = new UserService(); User user = new User(); user.setUsername(username); user.setPassword(userpass); if (us.login(user) != null){ req.getSession().setAttribute("user", user); } } } chain.doFilter(request, response);br/>} @Override public void init(FilterConfig filterConfig) throws ServletException { // TODO Auto-generated method stubbr/>} @Override public void destroy() { // TODO Auto-generated method stub } }
前台:login.jsp此单选框被选中下次访问即为自动登录
<div class="checkbox"> <label> <input type="checkbox" name="autoLogin" > 自动登录 </label> <label> <input type="checkbox" > 记住用户名 </label> </div> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>系统首页</title> <style> #nav{ height: 88px; padding: 5px 200px; background-color: aquamarine; } #logo{ float: left; } #userinfo{ float: right; height: 50px; line-height: 80px; } #container{ background-color: aqua; height: 800px; margin: 2px 200px; font-size: xx-large; text-align: center; } </style> </head> <body> <div id="nav"> <div id="logo"> <img src="csdn-logo.png" width="180" height="88"> </div> <div id="userinfo"> <%-- 不推荐使用 <% String loginUser = (String) request.getAttribute("loginUser"); if (loginUser != null){ out.println(loginUser); }else { %> <a href="login.jsp" rel="external nofollow" rel="external nofollow" rel="external nofollow" >登录</a><a>/注册</a> <% } %> --%> <% String loginUser = (String) session.getAttribute("loginUser"); if (loginUser != null){ out.println(loginUser); out.println("<a href='logoutServlet'>退出</a>"); }else { %> <a href="login.jsp" rel="external nofollow" rel="external nofollow" rel="external nofollow" >登录</a><a>/注册</a> <% } %> </div> </div> <div id="container">
主页内容
<a href="info.jsp" rel="external nofollow" >Python——画一棵漂亮的樱花树(不同种樱花+玫瑰+圣诞树喔)</a> </div> </body> </html> login.jsp <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>登录</title> <style> tr{ height:50px; } td{ text-align: center; } </style> </head> <body> <% String msg = (String)request.getAttribute("msg"); %> <% if(msg != null){ out.print(msg); } %> <form action="myServlet02" method="get"> <h2 align="center">登录</h2> <table width="500" border="1" cellspacing="0" cellpadding="0" align="center"> <tr> <td>账号:</td> <td><input type="text" name="username" /></td> </tr> <tr> <td>密码:</td> <td><input type="password" name="password" /></td> </tr> <tr> <td colspan="2"><input type="submit" value="登录" /></td> </tr> </table> </form> </body> </html>
info.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <style> #nav{ height: 88px; padding: 5px 200px; background-color: aquamarine; } #logo{ float: left; } #userinfo{ float: right; height: 50px; line-height: 80px; } #container{ background-color: aqua; height: 800px; margin: 2px 200px; font-size: xx-large; text-align: center; } </style> </head> <body> <div id="nav"> <div id="logo"> <img src="csdn-logo.png" width="180" height="88"> </div> <div id="userinfo"> <% String loginUser = (String) session.getAttribute("loginUser"); if (loginUser != null){ out.println(loginUser); out.println("<a href='logoutServlet'>退出</a>"); }else { %> <a href="login.jsp" rel="external nofollow" rel="external nofollow" rel="external nofollow" >登录</a><a>/注册</a> <% } %> </div> </div> <div id="container"> 主页内容 </div> </body> </html>
Servlet02.java
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException;br/>@WebServlet("/myServlet02") public class Servlet02 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //修改编码 request.setCharacterEncoding("utf-8");//请求过来的编码是亨达返佣www.kaifx.cn/broker/hantecglobal.htmlutf-8 response.setContentType("text/html;charset=utf-8");//响应出去的内容,为网页编码utf-8 //获取表单数据 String username = request.getParameter("username"); String password = request.getParameter("password"); //验证 if("aaa".equals(username) && "123".equals(password)){ //跳转(请求转发 请求重定向) //重定向:两次请求,不能在request作用域中共享数据。 //如果要在两次请求或多次请求之间,进行数据共享,需要用session //使用session步骤 //获取session HttpSession session = request.getSession();//如果存在已有的session,则直接返回,否则会创建一个新的,返回。 //HttpSession session = request.getSession(true);//同上 //HttpSession session = request.getSession(false);//如果存在已有的session,则直接返回,否则返回null。 //在session的作用域保存数据,供后续请求使用 session.setAttribute("loginUser",username); response.sendRedirect("index.jsp"); / 多个页面不推荐使用请求转发 request.setAttribute("loginUser",username); request.getRequestDispatcher("index.jsp").forward(request,response); / }else { //转发:一次请求,可以在request作用域中,共享数据 request.setAttribute("msg","<script>alert('登录失败!');</script>"); // response.sendRedirect("login.jsp"); request.getRequestDispatcher("login.jsp").forward(request,response); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }
LogoutServlet.java
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;br/>@WebServlet("/logoutServlet") public class LogoutServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //退出系统 //获取session HttpSession session = request.getSession(); //删除session session.removeAttribute("loginUser"); //跳转到登录页面/首页 response.sendRedirect("index.jsp"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
看完上述内容,你们掌握怎么在Java项目中利用servlet实现一个自动登录退出功能的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。