简单说下步骤:
1、定义一个类实现HandlerInterceptor
public class LoginInterceptor implements HandlerInterceptor {
@Value("${TT_TOKEN_KEY}")
private String TT_TOKEN_KEY;
@Value("${SSO_URL}")
private String SSO_URL;
@Autowired
private UserLoginService userLoginService;
//在进入目标方法之前执行
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
//request.getRequestURL 获取请求的url
//http://localhost:8093/order/order-cart.html
StringBuffer requestURL = request.getRequestURL();
String token = CookieUtils.getCookieValue(request, TT_TOKEN_KEY);
if(StringUtils.isBlank(token)){
response.sendRedirect(SSO_URL +"/page/login?redirectUrl="+requestURL);
return false;
}
TaotaoResult taotaoResult = userLoginService.getUserByToken(token);
if(taotaoResult!=null && taotaoResult.getStatus()==200){
Object data = taotaoResult.getData();
if(data!=null){
//将用户信息存储在reqeust域中
request.setAttribute("USER_INFO", data);
return true;
}else{
response.sendRedirect(SSO_URL +"/page/login?redirectUrl="+requestURL);
return false;
}
}
return false;
}
//在进入目标方法之后,在返回modelandview之前执行
//共用变量的一些设置。
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// TODO Auto-generated method stub
}
//返回modelandview之后,渲染到页面之前
//异常处理 ,清理工作
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
// TODO Auto-generated method stub
}
}
2、在springmvc.xml中配置
<!-- 配置用户身份认证的拦截器拦截订单确认和订单相关的处理 -->
<mvc:interceptors>
<mvc:interceptor>
<!-- ** 表示当前路径及其子路径 * 只是拦截当前路径-->
<mvc:mapping path="/order/**"/>
<bean class="com.taotao.order.interceptor.LoginInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>