本文主要是介绍使用过滤器做登录,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
设置controller
@RestController
public class TestController {
@RequestMapping("/login")
public String login(HttpSession session,String name,String password){
System.out.println(name);
System.out.println(password);
// 这个需要查数据库判断用户名和密码是否正确
if(Objects.equals(name, "xx") && Objects.equals(password, "xx"))
{
// 成功服务器记录sessionid,并设置生存时间,可以自行设置删除策略
LoginInterceptor.MAP.put(session.getId(),16);
return "成功";
}
return "失败";
}
@RequestMapping("/index")
public String index(){
return "登录";
}
@RequestMapping("/hello")
public String helloWorld(){
return "hello world";
}
@RequestMapping("/hello02")
public String helloWorld02(){
return "hello world 02";
}
}
设置过滤器
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
public class LoginFilter implements Filter {
// 这里我们也可以放在redis
public static final HashMap<String, Integer> MAP = new HashMap<>();
//不需要登录就可以访问的路径(比如:注册登录等)
String[] includeUrls = new String[]{"/login","/index"};
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
if(!isNeedFilter(request.getRequestURI())){
return;
}
HttpServletResponse response = (HttpServletResponse) servletResponse;
if(MAP.containsKey(((HttpServletRequest) servletRequest).getRequestedSessionId())) {
filterChain.doFilter(servletRequest,servletResponse);
return;
}
request.getRequestDispatcher("/index").forward(request,response);
}
public boolean isNeedFilter(String uri) {
for (String includeUrl : includeUrls) {
if(includeUrl.equals(uri)) {
return false;
}
}
return true;
}
}
过滤器配置
import org.springframework.boot.web.servlet.FilterRegistrationBean;
public class FilterConfig {
public FilterRegistrationBean registFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new LoginFilter());
registration.addUrlPatterns("/*");
registration.setName("LogCostFilter");
registration.setOrder(1);
return registration;
}
}
这篇关于使用过滤器做登录的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!