@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"; } }
已经登录,可以继续执行
package com.example.dockerredisqueue.Interceptor; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; public class LoginInterceptor implements HandlerInterceptor { // 这里我们也可以放在redis public static final HashMap<String, Integer> MAP = new HashMap<>(); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 如果我们的map有浏览器存过来的sessionid我们就任务他是已经登录了。 if(MAP.containsKey(request.getRequestedSessionId())) { return true; } // 失败我们跳转新的页面 request.setAttribute("msg","登录出错"); request.getRemoteHost(); request.getRequestDispatcher("/index").forward(request,response); return false; } }
package com.example.dockerredisqueue.Interceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.handler.MappedInterceptor; @Configuration public class InterceptorConfig { @Bean public MappedInterceptor loginInterceptor(){ // 设置拦截器的作用域 return new MappedInterceptor(new String[]{"/**"},new String[]{"/login","/index"},new LoginInterceptor()); } }