zoukankan      html  css  js  c++  java
  • SpringBoot登录拦截器

    1:首先在调用登录接口中添加session值;当然也可以不用添加,在拦截器中比对拦截的接口,下面的就是直接比对接口的;

    2:不说了贴代码;

    import javax.servlet.*;
    import javax.servlet.annotation.WebFilter;
    import javax.servlet.annotation.WebInitParam;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import java.io.IOException;

    @WebFilter(filterName = "loginFilter",
    urlPatterns = "/*",
    initParams = {
    @WebInitParam(name = "loginUI", value = "/admin/adminlogin"),
    @WebInitParam(name = "loginProcess", value = "home/login"),
    @WebInitParam(name = "encoding", value = "utf-8")
    })
    public class LoginFilter implements Filter {
    private FilterConfig config;

    @Override
    public void init(FilterConfig config) throws ServletException {
    this.config = config;
    }


    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
    throws IOException, ServletException {
    // 获取配置参数
    String loginUI = config.getInitParameter("loginUI");
    String loginProcess = config.getInitParameter("loginProcess");
    String encoding = config.getInitParameter("encoding");


    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    // 设置请求的字符集(post请求方式有效)
    request.setCharacterEncoding(encoding);

    // 不带http://域名:端口的地址
    String uri = request.getRequestURI();
    if (uri.contains(loginUI) || uri.contains(loginProcess)) {

    HttpSession session = request.getSession();
    // 请求的登录,放行
    chain.doFilter(request, response);
    } else {
    if (request.getSession().getAttribute("username") == null) {
    // 重定向到登录页面
    response.sendRedirect(request.getContextPath() + loginUI);
    } else {
    // 已经登录,放行
    chain.doFilter(request, response);
    }
    }
    }

    @Override
    public void destroy() {
    this.config = null;
    }
    }
    3:根据自己实际情况修改自己的路径

  • 相关阅读:
    数论练习
    AC自动机*
    矩阵乘法*
    概率期望*
    组合数学练习*
    图论升级*
    【终端使用】"su"命令切换用户
    【终端使用】"which"命令可以查看执行命令所在的位置
    【终端使用】"usermod"命令 和 组(包括:主组、附加组)
    Ubuntu 18.04安装 MySQL 8.0+版本的数据库
  • 原文地址:https://www.cnblogs.com/gloveli/p/9266555.html
Copyright © 2011-2022 走看看