过滤器篇(1)-----用户登录验证过滤器(LoginFilter)

1. 过滤器简介

用过滤器实现登录和访问权限.     

Java中的Filter 并不是一个标准的Servlet ,它不能处理用户请求,也不能对客户端生成响应。 主要用于对HttpServletRequest 进行预处理,也可以对HttpServletResponse 进行后处理,是个典型的处理链。

优点:过滤链的好处是,执行过程中任何时候都可以打断,只要不执行chain.doFilter()就不会再执行后面的过滤器和请求的内容。而在实际使用时,就要特别注意过滤链的执行顺序问题

2.登录过滤器Code案例

  1. 用户登录界面(login.jsp)
<%--
  Created by IntelliJ IDEA.
  User: 网络黑寡妇
  Date: 17-5-18 
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    登录界面


用户登录


用户名:
密  码:
   

2.后台(Servlet)处理Code (LoginServlet)

package com.Servlet;

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;

/**
 * Created by dhc on 17-5-18.
 * user: 网络黑寡妇
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet{
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        String adminName = request.getParameter("username");
        String adminpsw = request.getParameter("password");

        session.setAttribute("username", adminName); //存储在Session中

        if ( adminName.equals(admin) && adminpsw.equals(password))) {
        //main.jsp文件为要跳转的jsp界面.
          request.getRequestDispatcher("main.jsp").forward(request, response);
        } else {
          request.getRequestDispatcher("login.jsp").forward(request,response);
        }
    }

3.重点过滤器的编写 (LoginFilter)

package com.Filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * Created by dhc on 17-5-18.
 * Description: 所有请求都走此过滤器来判断用户是否登录
 * user: 网络黑寡妇
 **/
public class LoginFilter implements Filter{
    private String sessionKey;
    private String redirectUrl;
    private String uncheckedUrls;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ServletContext servletContext = filterConfig.getServletContext();
        //获取XML文件中配置参数
        sessionKey = servletContext.getInitParameter("userSessionKey");
        //System.out.println("sessionKey======" + sessionKey);//调试用
        redirectUrl = servletContext.getInitParameter("redirectPage");
       //System.out.println("redirectPage======" + redirectUrl);
        uncheckedUrls = servletContext.getInitParameter("uncheckedUrls");
        //System.out.println("uncheckedUrls=====" + uncheckedUrls);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 获得在下面代码中要用的request,response,session对象
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        //1.获取请求URL
        String servletPath = httpRequest.getServletPath();    

        //2.检测1中获取的servletPath是否为不需要检测的URl中的一个.若是,放行
        List urls = Arrays.asList(uncheckedUrls.split(","));
        if (urls.contains(servletPath)) {
            filterChain.doFilter(httpRequest, httpResponse);
            return;
        }

        //3.从session中获取SessionKey对应值,若值不存在,则重定向到redirectUrl
        Object user = httpRequest.getSession().getAttribute("username");
        if ((user == null)) {
           httpResponse.sendRedirect(httpRequest.getContextPath() + redirectUrl);            
           return;
        }

        //4.若存在,则放行
        filterChain.doFilter(httpRequest, httpResponse);
    }

    @Override
    public void destroy() {
    }
}

4.配置 web.XML 文件


        

    
    
    
        userSessionKey
        username
    
    
    
        redirectPage
        /login.jsp
    
    
    
        uncheckedUrls
        /index.jsp,/LoginServlet
    

    
        LoginFilter
        com.Filter.LoginFilter
    
    
        LoginFilter
        
        /*
    

 转自:https://blog.csdn.net/m0_37726549/article/details/72528494

你可能感兴趣的:(JavaWeb,过滤器)