简单实现一个登陆过滤器Filter

简单实现一个登陆过滤器Filter-刘师傅
刘师傅
擅长邻域:Java,HTML,JavaScript,CSS,SQL,ORACLE,MySQL,SQL SERVER,Spring 全家桶

2020-10-20 21:04:35   205浏览 分类: Java

简单实现一个登陆过滤器Filter,用来防止未登录授权访问,注意使用白名单排除登录页本身和其他需要排除过滤的地址,实现代码如下:
public class LoginFilter implements Filter{
private String redirectUrl;
private String uncheckedUrls;

@Override
public void init(FilterConfig filterConfig) throws ServletException {
ServletContext servletContext = filterConfig.getServletContext();
//获取XML文件中配置参数
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<String> urls = Arrays.asList(uncheckedUrls.split(","));
for (String url : urls) {
if(servletPath.contains(url)) {
filterChain.doFilter(httpRequest, httpResponse);
return;
}
}

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

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

@Override
public void destroy() {
}
}
在项目的web.xml中添加对应的Filter配置:
 <!--若未登录,需要重定向的页面-->
<context-param>
<param-name>redirectPage</param-name>
<param-value>/login</param-value>
</context-param>
<!--不需要拦截的URL列表-->
<context-param>
<param-name>uncheckedUrls</param-name>
<param-value>/login,/resources,/bootstrap,/img,favicon.ico</param-value>
</context-param>

<filter>
<filter-name>LoginFilter</filter-name>
<filter-class>com.weixin.filter.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

好文章就要一起分享哦!分享海报

此处可发布评论

评论(0

暂无评论,快来写一下吧
客服QQ 1913284695