Java登录验证过滤器
基本概念
1、What-- 过滤器什么?
Java中servlet过滤器是动态拦截请求和响应,以便变换或使用请求和响应中的信息。当客户端请求服务器上的某些资源时,过滤器可以对这些请求进行拦截,先执行过滤器中的一段代码,然后再将请求交给相应的servlet或jsp去处理。
比如我们每次从request对象中读取数据时,都要设置request的字符编码,这时,我们可以将这些频繁使用的公共代码,放在过滤器中,这样在被每个请求处理之前先执行过滤器中的代码。
2、Why--为什么要使用过滤器
因为过滤器将公共代码放入其中,这样可以减少代码的冗余,也便于更新和维护。
3、How--怎样使用过滤器
Servlet过滤器实际上是servlet编程的Java类,我们只要建立一个实现Filter接口的类并指定要拦截的url规则,并重写doFilter()方法就可以了。
一、配置文件web.xml
说明:servlet3.0有了注解(annotation),就不必使用配置文件配置filter和路由的映射了。
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0"> <display-name>lessons</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> <welcome-file>index.html</welcome-file> </welcome-file-list> <!-- 存储用户信息session的键 --> <context-param> <param-name>userSessionKey</param-name> <param-value>user</param-value> </context-param> <!-- 登录页面 --> <context-param> <param-name>loginPage</param-name> <param-value>/Login.jsp</param-value> </context-param> <filter> <filter-name>LoginFilter</filter-name> <filter-class>com.zyz.util.LoginFilter</filter-class> </filter> <!-- 对/admin/*的请求进行过滤 --> <filter-mapping> <filter-name>LoginFilter</filter-name> <url-pattern>/admin/*</url-pattern> </filter-mapping> </web-app>
二、登录验证过滤器LoginFilter.java
package com.zyz.util; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.zyz.user.User; @WebFilter("/LoginFilter") public class LoginFilter implements Filter { private String userSessionKey;//存储用户的session键名 private String loginPage;//登录页面 public LoginFilter() { } public void destroy() { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest=(HttpServletRequest)request; HttpServletResponse httpResponse=(HttpServletResponse)response; User user=(User)httpRequest.getSession().getAttribute(userSessionKey); //如果没有登录,或登录的用户角色不是管理员 if(user==null || user.getRole()==0) { String servletPath=httpRequest.getServletPath(); if(servletPath.endsWith(".jsp")) { //session记下当前请求的jsp文件的url,以便登录时跳转至该文件 httpRequest.getSession().setAttribute("url",httpRequest.getContextPath()+servletPath); } //跳转到登录页面 httpResponse.sendRedirect(httpRequest.getContextPath()+loginPage); return; } //如果已经登录,且是角色是管理员,放行。 chain.doFilter(httpRequest, httpResponse); } public void init(FilterConfig fConfig) throws ServletException { ServletContext context=fConfig.getServletContext(); userSessionKey=context.getInitParameter("userSessionKey");//从配置文件web.xml获取该参数 loginPage=context.getInitParameter("loginPage");//从配置文件web.xml获取该参数 } }
三、登录处理LoginHandlerServlet.java
package com.zyz.user; import java.io.IOException; import java.util.Enumeration; 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; @WebServlet("/LoginHandlerServlet") public class LoginHandlerServlet extends HttpServlet { private static final long serialVersionUID = 1L; public LoginHandlerServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String name = request.getParameter("name"); String password = request.getParameter("password"); if (name!=null && !name.equals("") && password!=null && !password.equals("")) { User u = UserService.getInstance().loginCheck(name, password); if (u == null) { response.getWriter().println("用户名或密码不对,3秒后将跳转<a href='Login.jsp'>登录</a>页面..."); response.setHeader("refresh", "3;url=Login.jsp"); return; } else { HttpSession session=request.getSession(); //跳转前清空所有的session Enumeration<String> em=session.getAttributeNames(); while(em.hasMoreElements()){ String attributeName=em.nextElement(); if(!attributeName.equals("url")) { session.removeAttribute(attributeName); } } session.setAttribute("user", u); String url; if(session.getAttribute("url")!=null){ url=session.getAttribute("url").toString(); }else{ url="index.jsp"; } response.sendRedirect(url); } } } }
四、登录页面Login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String name=""; String password=""; Cookie[] cookies=request.getCookies(); for(Cookie c:cookies){ if(c.getName().equals("name")){ name=c.getValue(); } if(c.getName().equals("password")){ password=c.getValue(); } } %> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>用户登录</title> <meta name="renderer" content="webkit|ie-comp|ie-stand"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi" /> <meta http-equiv="Cache-Control" content="no-siteapp" /> <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" /> <link rel="stylesheet" href="./admin/css/font.css"> <link rel="stylesheet" href="./admin/css/xadmin.css"> <script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script> <script src="./lib/layui/layui.js" charset="utf-8"></script> <script type="text/javascript" src="./admin/js/xadmin.js"></script> </head> <body class="login-bg"> <div class="login layui-anim layui-anim-up"> <div class="message">用户登录</div> <div id="darkbannerwrap"></div> <form method="post" class="layui-form" action="LoginHandlerServlet"> <input name="name" placeholder="用户名" type="text" lay-verify="required|username" class="layui-input" value="<%= name %>" > <hr class="hr15"> <input name="password" lay-verify="required|password" placeholder="密码" type="password" class="layui-input" value=<%= password %>> <hr class="hr15"> <input value="登录" lay-submit lay-filter="login" style="width:100%;" type="submit"> <hr class="hr20" > </form> </div> <script> $(function () { layui.use('form', function(){ var form = layui.form; // layer.msg('玩命卖萌中', function(){ // //关闭后的操作 // }); //监听提交 /* form.on('submit(login)', function(data){ // alert(888) layer.msg(JSON.stringify(data.field),function(){ location.href='index.html' }); return false; }); */ /* form.verify({ 'username':[/\w{6,20}/,'用户名必须是6到20位字母、数字或下划线'], 'password':[/\w{6,12}/,'密码必须是6到12位字母、数字或下划线'] }) */ }); }) </script> <!-- 底部结束 --> </body> </html>