标签:拦截器 return String 登录 request new 使用 import public
定义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";
}
}
编写拦截的具体逻辑
已经登录,可以继续执行
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());
}
}
标签:拦截器,return,String,登录,request,new,使用,import,public 来源: https://www.cnblogs.com/jefferyeven/p/16060550.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。