多平台统一管理软件接口,如何实现多平台统一管理软件接口
222
2023-05-30
spring boot 配置Filter过滤器的方法
Filter 过滤器是web开发中很重要的一个组件,下面以一个session登陆的例子介绍下spring boot中如何使用Filter
首先要准备一个实现了Filter的接口的类 SessionFilter:
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;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by mazhenhua on 2016/12/27.
*
* 过滤器
*/
public class SessionFilter implements Filter {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(SessionFilter.class);
/**
* 封装,不需要过滤的list列表
*/
protected static List
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequesrZGxiBt, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
logger.info("aaaaaaaaaa");
String url = httpRequest.getRequestURI().substring(httpRequest.getContextPath().length());
if (url.startsWith("/") && url.length() > 1) {
url = url.substring(1);
}
if (isInclude(url)){
chain.doFilter(httpRequest, httpResponse);
return;
} else {
HttpSession session = httpRequest.getSession();
if (session.getAttribute("") != null){
// session存在
chain.doFilter(httpRequest, httpResponse);
return;
} else {
// session不存在 准备跳转失败
/* RequestDispatcher dispatcher = request.getRequestDispatcher(path);
dispatcher.forward(request, response);*/
chain.doFilter(httpRequest, httpResponse);
return;
}
}
}
@Override
public void destroy() {
}
/**
* 是否需要过滤
* @param url
* @return
*/
private boolean isInclude(String url) {
for (Pattern pattern : patterns) {
Matcher matcher = pattern.matcher(url);
if (matcher.matches()) {
return true;
}
}
return false;
}
}
实际开发中往往有很多请求要直接请求进来,不需要鉴权登陆的,所以代码中过滤掉这种请求的代码,装进list就好了。
/**
* 配置过滤器
* @returnrZGxiB
*/
@Bean
public FilterRegistrationBean someFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(sessionFilter());
registration.addUrlPatterns("/*");
registration.addInitParameter("paramName", "paramValue");
registration.setName("sessionFilter");
return registration;
}
/**
* 创建一个bean
* @return
*/
@Bean(name = "sessionFilter")
public Filter sessionFilter() {
return new SessionFilter();
}
经过上面这俩步的配置,过滤器基本上就可以了。
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~