用户点击结算功能时会进入该拦截器
/**
* 用户登录拦截器
*/
public class LoginInterceptor implements HandlerInterceptor {
@Value("${SSO_URL}")
private String SSO_URL;
@Autowired
private TokenService tokenService;
@Autowired
private CartService cartService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//从cookie中取token
String token = CookieUtils.getCookieValue(request, "token");
//判断token是否存在
if (StringUtils.isBlank(token)) {
//如果token不存在,未登录状态,跳转到sso系统的登录页面。用户登录成功后,跳转到当前请求的url
response.sendRedirect(SSO_URL + "/page/login?redirect=" + request.getRequestURL());
//拦截
return false;
}
//如果token存在,需要调用sso系统的服务,根据token取用户信息
E3Result e3Result = tokenService.getUserByToken(token);
//如果取不到,用户登录已经过期,需要登录。
if (e3Result.getStatus() != 200) {
//如果token不存在,未登录状态,跳转到sso系统的登录页面。用户登录成功后,跳转到当前请求的url
response.sendRedirect(SSO_URL + "/page/login?redirect=" + request.getRequestURL());
//拦截
return false;
}
//如果取到用户信息,是登录状态,需要把用户信息写入request。
TbUser user = (TbUser) e3Result.getData();
request.setAttribute("user", user);
//判断cookie中是否有购物车数据,如果有就合并到服务端。
String jsonCartList = CookieUtils.getCookieValue(request, "cart", true);
if (StringUtils.isNoneBlank(jsonCartList)) {
//合并购物车
cartService.mergeCart(user.getId(), JsonUtils.jsonToList(jsonCartList, TbItem.class));
}
//放行
return true;
}
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
// TODO Auto-generated method stub
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
// TODO Auto-generated method stub
}
}
@RequestMapping("/page/login")
public String showLogin(String redirect, Model model) {
model.addAttribute("redirect", redirect);
return "login";
}
jsp中如果用户登录成功将跳转到原来的订单提交页面
<script type="text/javascript">
var redirectUrl = "${redirect}";
var LOGIN = {
checkInput:function() {
$("#sfbestNameErr").attr("class", "").html("").prev().attr("class", "border");
$("#sfbestPwdErr").attr("class", "").html("").prev().attr("class", "border");
if(!$("#formlogin #loginname").val()) {
$("#sfbestNameErr").attr("class", "error").show().html("请输入用户名").prev().attr("class", "border-error");
return false;
}
if(!$("#formlogin input[name='password']").val()) {
$("#sfbestPwdErr").attr("class", "error").show().html("请输入密码").prev().attr("class", "border-error");
return false;
}
$("#username").val($("#loginname").val());
return true;
},
doLogin:function() {
$.post("/user/login", $("#formlogin").serialize(),function(data){
if (data.status == 200) {
jAlert('登录成功!',"提示", function(){
<!--跳转到首页-->
if (redirectUrl == "") {
location.href = "http://localhost:8082";
} else {
location.href = redirectUrl;
}
});
} else {
jAlert("登录失败,原因是:" + data.msg,"失败");
}
});
},
login:function() {
if (this.checkInput()) {
this.doLogin();
}
}
};
$(function(){
$("#login_sub").click(function(){
LOGIN.login();
});
});
</script>