以下是一个用户登录的Filter
package com.rs.outcall.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.rs.outcall.bean.AdminUser;
@WebFilter(urlPatterns = "/*", filterName = "logFilter")
public class LoginFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String[] notFilter = {"login", "login.jsp", "logout.dispatch", "login.dispatch", ".css", ".js", ".gif", ".png", ".htm",
".asp", ".jpg" };
String uri = request.getRequestURI();
boolean doFilter = true;
for (String s : notFilter) {
if (uri.toLowerCase().endsWith(s.toLowerCase())) {
doFilter = false;
break;
}
}
if (!doFilter) {
chain.doFilter(request, response);
return;
}
HttpSession session = ((HttpServletRequest)request).getSession();
String loginUser = (String)session.getAttribute("loginUser");
String url=((HttpServletRequest)request).getRequestURL().toString();
if( loginUser==null && url.lastIndexOf("/login.jsp")==-1 && url.lastIndexOf("/login.do")==-1 ){
((HttpServletResponse)response).sendRedirect("/login.jsp");
}
else
{
chain.doFilter(request, response);
}
}
public void destroy() {
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
在App里,需要加入@ServletComponentScan,才能找到Filter:
package com.rs.outcall;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
/**
* SpringBoot启动类
*
*
*/
@SpringBootApplication
@ServletComponentScan("com.rs.outcall.filter")
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}