登录过滤器LoginFilter的实现

需求:对url进行拦截, 当用户未登录的时候,跳转到登录界面。

LoginFilter

package com.tao.smp.web.filter;

import com.tao.smp.common.constant.SmpConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * 登录过滤器
 */
public class LoginFilter implements Filter {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoginFilter.class);

    /**
     * 保存不拦截的url
     */
    private static List passUrls = new ArrayList<>();

    /**
     * 上下文
     */
    private String ctxPath = null;

    /**
     * 重定向url
     */
    private static String redirectUrl = "";


    /**
     * 过滤器初始化方法
     *
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        // 获取web.xml中的初始化参数
        String ignoreURL = filterConfig.getInitParameter("passURL");
        redirectUrl = filterConfig.getInitParameter("redirectURL");
        // 保存不拦截的url
        String[] ignoreURLArray = ignoreURL.split(",");
        for (String url : ignoreURLArray) {
            passUrls.add(url.trim());
        }
        ctxPath = filterConfig.getServletContext().getContextPath();
        System.out.println("ctx = " + ctxPath);
        LOGGER.info("不拦截的URL包括:");
        for (String url : passUrls) {
            LOGGER.info(url);
        }
    }


    /**
     * 过滤器方法
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 请求的url
        String url = request.getRequestURI();
        // 相对路径
        String subUrl = url.substring(ctxPath.length() + 1);

        for (String urlStr : passUrls) {
            // 如果匹配, 则放行
            if (subUrl.indexOf(urlStr) > -1) {
                filterChain.doFilter(request, response);
                return;
            }
        }

        // 获得session
        HttpSession session = request.getSession();
        // 从session中获取SessionKey对应值,若值不存在,则重定向到redirectUrl
        Object user = session.getAttribute(SmpConst.SESSION_KEY_USERNAME);
        if (user != null) {
            filterChain.doFilter(request, response);
        } else {
            response.sendRedirect(ctxPath + "/" + redirectUrl);
        }
    }


    @Override
    public void destroy() {

    }
}

在web.xml配置LoginFilter


    <filter>
        <description>登录过滤器description>
        <filter-name>loginFilterfilter-name>
        <filter-class>com.tao.smp.web.filter.LoginFilterfilter-class>
        
        <init-param>
            <param-name>passURLparam-name>
            <param-value>login,login.do,login.jsp,css,image,javascript,font,
                ui/user/info/exportDataToExcel,
                ui/user/info/getExportExcelFile,
                api/userInfoService/v1/info/upload
            param-value>
        init-param>
        <init-param>
            <param-name>redirectURLparam-name>
            <param-value>loginparam-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>loginFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

LoginController

package com.tao.smp.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 登录Controller
 */
@Controller
@RequestMapping(value = "/")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private UserDao userDao;

    /**
     * 返回登录页面
     *
     * @return 登录页面
     */
    @GetMapping("/login")
    public String getLogin() {
        return "login";
    }

    /**
     * 处理登录请求
     *
     * @param request http请求
     * @return
     * @throws Exception 异常
     */
    @PostMapping("/login")
    @ResponseBody
    public ApiResult doLogin(@RequestBody LoginFormDto loginFormDto, HttpServletRequest request) throws Exception {

        String username = loginFormDto.getUsername();
        String password = loginFormDto.getPassword();

        User dbUser = userDao.queryByUsername(username);

        if (dbUser == null) {
            throw new SmpRuntimeException(ResultCode.USERNAME_ERROR);
        }

        if (!dbUser.getPassword().equals(password)) {
            throw new SmpRuntimeException(ResultCode.PASSWORD_ERROR);
        }

        // 获得session
        HttpSession session = request.getSession();
        session.setAttribute(SmpConst.SESSION_KEY_USERNAME, username);
        return ApiResult.of(ResultCode.SUCCESS);
    }


    @GetMapping("/logout")
    public String logout(HttpSession session) {

        session.removeAttribute(SmpConst.SESSION_KEY_USERNAME);
        return "redirect:/login";
    }

}

注意:sessionSmpConst.SESSION_KEY_USERNAME 的设置与删除,登录过滤器就是通过这个来判断用户是否已经登录的。

你可能感兴趣的:(Spring框架学习)