Makoto
Makoto

Reputation: 775

session attribute null in my spring interceptor

I am having trouble with getting a value that I had put into a session. I want to check this value with an interceptor but I only get a null.

This is where I put the variable "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);
}

This is my interceptor:

 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;

    }
}

Where did I get wrong ?

Upvotes: 1

Views: 2465

Answers (2)

Makoto
Makoto

Reputation: 775

Sorry the problem was due to another cause: I had deplued the jsp page with grunt on the 8000 port and my API(services) was displayed on the 8080 port.

Apparently the browser could not make a link between the two.

So I moved all on the 8080 port and it works now

Upvotes: 2

vtor
vtor

Reputation: 9319

A HandlerInterceptor gets called before the appropriate HandlerAdapter triggers the execution of the handler itself. Those said, you are trying to access the attribute from session in preHandle() phase, which is called before the handler execution itslef and you haven't set the attribute into session yet.

So either you can move your logic to postHandle() phase and get session attribute there, or change your logic if you really need something to do in preHandlephase.

And postHandle() is called after the handler execution (that is why , it allows to manipulate the ModelAndView object before rendering it to the view page)

Upvotes: 1

Related Questions