下面用实际登陆跳转举例
1、写自己的拦截器implements HandlerInterceptor,实现跳转去执行拦截内容并传,执行拦截之后的URI
@Component
public class LoginRequiredInterceptor implements HandlerInterceptor {
@Autowired
HostHolder hostHolder;
//目前页面是需要登陆,如果没有登陆应该先跳到登陆界面
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
if (hostHolder.getUser()==null){
httpServletResponse.sendRedirect("/reglogin?next="+httpServletRequest.getRequestURI());
}
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
2、WebMvcConfigurerAdapter中注册自己写的拦截器,并添加拦截路径/user/*
@Component
public class WendaWebConfiguration extends WebMvcConfigurerAdapter {
@Autowired
LoginRequiredInterceptor loginRequiredInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginRequiredInterceptor).addPathPatterns("/user/*");
super.addInterceptors(registry);
}
}
3、将要去往拦截事务的jsp,这是一个中间过渡页面。用@param后去得到URI,并添加到渲染的页面,也就是你需要临时跳转页面去view层中
@RequestMapping(path = "/reglogin")
public String reglogin(Model model,
@RequestParam(value = "next" ,required = false) String next){
model.addAttribute("next",next);//把拦截器带来的参数放在model层中去
return "login";
}
4、到达拦截事务的jsp,处理拦截事务时候带上刚刚model中加入的参数
5、到达拦截事务@Controller中,处理完成后,决定跳转
if (!StringUtils.isBlank(next)){
return "redirect:"+next;//登陆成功后跳转
}
================================================
第一次离开去执行自己写的拦截器,所以第一次redirect是在MyInterceptor中执行;
第二次是跳回来去执行一开始想要访问的页面,所以应该是在自己拦截器访问地址完成之后。如这里的loginController,之后。
第一次,redirect:reglogin+RequestURI();—-》controller[用@Param]—-》[model.addtribute]到达view层中—-》[
第一次是跳到拦截事务中,第二次是拦截事务完成,[紧接着会执行拦截之后跳转]