1.用户登录拦截器
package com.trs.wenxin.spreadstatis.intercepter;
/**
* 用户登录拦截
*
* @Author quwei
* @Date 2019/07/30
*/
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class UserLoginInterceptor implements HandlerInterceptor {
/*
* 视图渲染之后的操作
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//System.out.println("执行了afterCompletion方法");
}
/*
* 处理请求完成后视图渲染之前的处理操作
* 通过ModelAndView参数改变显示的视图,或发往视图的方法
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//System.out.println("执行了postHandle的方法");
}
/*
* 进入controller层之前拦截请求
* 返回值:表示是否将当前的请求拦截下来 false:拦截请求,请求别终止。true:请求不被拦截,继续执行
* Object obj:表示被拦的请求的目标对象(controller中方法)
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (request.getSession().getAttribute("session_user") == null) {
response.setHeader("Access-Control-Allow-Origin", "*");
response.sendRedirect("/spreadstatis/Login");
return false;
}
return true;
}
}
2. 放行可以访问的接口
package com.trs.wenxin.spreadstatis.intercepter;//package com.trs.spreadstatis.intercepter;
/**
* 拦截器
*
* @Author quwei
* @Date 2019/07/30
*/
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class SessionInterceptor implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
/**
* 自定义拦截器,添加拦截路径和排除拦截路径
* addPathPatterns():添加需要拦截的路径
* excludePathPatterns():添加不需要拦截的路径
* 在括号中还可以使用集合的形式,如注释部分代码所示
*/
//registry.addInterceptor(new UserLoginInterceptor()).addPathPatterns("/user/queryAllUser").excludePathPatterns("/user/userLogin");
//举例:利用集合的形式
List list = new ArrayList();
list.add("/spreadstatis/Login");
list.add("/spreadstatis/userLogin");
list.add("/spreadstatis/checkCode");
list.add("/spreadstatis/userRegister");
list.add("/spreadstatis/registerpage");
list.add("/spreadstatis/forgetPwd");
registry.addInterceptor(new UserLoginInterceptor()).addPathPatterns("/**").excludePathPatterns(list);
}
}
3.返回给前端的数据
//拦截没有登录的用户
@CrossOrigin
@ResponseBody
@RequestMapping(value = {"/Login"})
public BaseResponse loginHtml() {
return BaseResponse.ok(401, "用户没有登录,请登录!");
}
4.资源跨域问题
(1).在拦截器中设置:
response.setHeader("Access-Control-Allow-Origin", "*");
(2).在controller中的接口上加入注解
@CrossOrigin