spring boot method of configuring Filter filters
- 2020-06-15 08:55:29
- OfStack
Filter filters are an important component of web development. How to use Filter in spring boot
First, prepare a class SessionFilter that implements the Filter interface:
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.
*
* The filter
*/
public class SessionFilter implements Filter {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(SessionFilter.class);
/**
* Encapsulated, does not need to filter list The list of
*/
protected static List<Pattern> patterns = new ArrayList<Pattern>();
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, 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 There are
chain.doFilter(httpRequest, httpResponse);
return;
} else {
// session There is no Ready to jump failed
/* RequestDispatcher dispatcher = request.getRequestDispatcher(path);
dispatcher.forward(request, response);*/
chain.doFilter(httpRequest, httpResponse);
return;
}
}
}
@Override
public void destroy() {
}
/**
* Do You need to filter
* @param url
* @return
*/
private boolean isInclude(String url) {
for (Pattern pattern : patterns) {
Matcher matcher = pattern.matcher(url);
if (matcher.matches()) {
return true;
}
}
return false;
}
}
In the actual development, there are often a lot of requests to directly request in, do not need authentication login, so the code to filter out such requests, put into list just.
/**
* Configuration filter
* @return
*/
@Bean
public FilterRegistrationBean someFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(sessionFilter());
registration.addUrlPatterns("/*");
registration.addInitParameter("paramName", "paramValue");
registration.setName("sessionFilter");
return registration;
}
/**
* create 1 a bean
* @return
*/
@Bean(name = "sessionFilter")
public Filter sessionFilter() {
return new SessionFilter();
}
With this two-step configuration, the filter is basically done.