【问题标题】:session attribute null in my spring interceptor我的春季拦截器中的会话属性为空
【发布时间】:2015-04-19 16:53:53
【问题描述】:

我无法获取已放入会话的值。 我想用拦截器检查这个值,但我只得到一个空值。

这是我放置变量“trustedUser”的地方

@RequestMapping(value = "/context/{token}", method = { RequestMethod.GET })
public @ResponseBody
ResponseEntity<ContexteUI> getContextByToken(@PathVariable("token") String token, HttpSession session)
        throws ContextFault_Exception {

    HttpStatus httpStatus = HttpStatus.OK;
    if (validation(token)){
        session.setAttribute("trustedUser","trustedUser");
    } else {
        httpStatus = HttpStatus.BAD_REQUEST;
    }

    return new ResponseEntity<ContexteUI>(contexte, httpStatus);
}

这是我的拦截器:

 public class AuthentificationInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request,
        HttpServletResponse response, Object handler) throws Exception {

       System.out.println("Pre-handle");

       String trustedUserTest = (String) request.getSession().getAttribute("trustedUser");
       System.out.println("trustedUserTest: "+ trustedUserTest); // I only get null here, why ?

       return true;

    }
}

我哪里做错了?

【问题讨论】:

  • 你试过了吗 getContextByToken(@PathVariable("token") String token, HttpServletRequest request) {HttpSession session = request.getSession(); session.setAttribute("trustedUser",trustedUser);

标签: spring session controller


【解决方案1】:

抱歉,问题是由另一个原因引起的: 我在 8000 端口上用 grunt 删除了 jsp 页面 并且我的 API(服务)显示在 8080 端口上。

显然浏览器无法在两者之间建立链接。

所以我把所有东西都移到了 8080 端口上,现在它可以工作了

【讨论】:

    【解决方案2】:

    HandlerInterceptor 在适当的 HandlerAdapter 触发处理程序本身的执行之前被调用。那些说,您正试图在preHandle() 阶段从会话访问属性,该阶段在处理程序执行之前调用,并且您尚未将属性设置为会话。

    因此,您可以将您的逻辑移至postHandle() 阶段并在那里获取会话属性,或者如果您确实需要在preHandlephase 中执行某些操作,请更改您的逻辑。

    postHandle() 在处理程序执行后被调用(这就是为什么它允许在将 ModelAndView 对象渲染到视图页面之前对其进行操作)

    【讨论】:

    • 感谢您的努力,但问题是 elsewehre(非小事)
    猜你喜欢
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-20
    • 1970-01-01
    • 2012-06-08
    • 2013-11-01
    • 2021-04-20
    相关资源
    最近更新 更多