SpringBoot使用拦截器无效

附上代码:

public class WendaWebConfiguration extends WebMvcConfigurerAdapter {

@Autowired
PassportInterceptor passportInterceptor;

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(passportInterceptor);
super.addInterceptors(registry);
}
}

@Component
public class PassportInterceptor implements HandlerInterceptor{

private static final Logger logger = LoggerFactory.getLogger(PassportInterceptor.class);
@Autowired
private LoginTicketDAO loginTicketDAO;

@Autowired
private UserDAO userDAO;

@Autowired
private HostHolder hostHolder;

@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
String ticket = null;
for(Cookie cookie: httpServletRequest.getCookies()){
if("ticket".equals(cookie.getName())){
ticket = cookie.getValue();
break;
}
}
if (ticket != null) {
LoginTicket loginTicket = loginTicketDAO.selectByTicket(ticket);
if (loginTicket == null || loginTicket.getExpired().before(new Date()) || loginTicket.getStatus() != 0) {
return true;
}

User user = userDAO.selectById(loginTicket.getUserId());
logger.info("user:"+user.getName());

hostHolder.setUser(user);
}
return true;
}

@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
if(modelAndView!=null&&hostHolder.getUser()!=null){
modelAndView.addObject("user",hostHolder.getUser());
}
}

@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
hostHolder.clear();
}
}header.html:
#if(!$user)
<ul class="topnav-noauth clearfix">
<li>
<a href="/reglogin">注册/登陆</a>
</li>
</ul>
#else
...

测试运行:

期望的结果是如下:

 


 

代码思想:

通过

WendaWebConfiguration注册拦截器PassportInterceptor,拦截器在渲染页面之前,会将user通过modelAndView保存,然后在header.html读取user的值。所以,既然登录成功,就应该
$user为真,因此,按理就不会出现测试结果。

解决方案:通过debug测试,找出在拦截器PassportInterceptor中,
logger.info("user:"+user.getName());
根本没有输出。因此,说明,整个项目根本没有使用拦截器,也就是拦截器配置出现了问题。但是,拦截器配置代码
WendaWebConfiguration中好像都OK,找不出哪里错了。最后,仔细分析,是以为忘记写组件@Component了。导致,无法启动拦截器配置。
修改如下:
@Component
public class WendaWebConfiguration extends WebMvcConfigurerAdapter {

@Autowired
PassportInterceptor passportInterceptor;

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(passportInterceptor);
super.addInterceptors(registry);
}
}
再次测试,结果为:

 




 


posted @ 2017-04-09 14:54  知我者,足以  阅读(17071)  评论(1编辑  收藏  举报