Call a controller from an interceptor's preHan

2020-05-04 05:39发布

问题:

I have an interceptor that checks the ldap group membership of a user and if it's deemed wrong will redirect to a NoAuthorisation page like so:

public class MyIntercept implements HandlerInterceptor {

public boolean preHandle (HttpServletRequest request, HttpServletReaponse response, Object handler) {
If ( // check access) {
  response.redirect(/NoAuthorisation?reason=Blablabla);
  return false;
}
return true
}

}

This works but I'd like to send the reason in a more not so obvious fashion (not in url)

I was thinking I call the NoAuthorisation controller directly but don't know how to do that.

Any advise and best practices?

回答1:

SpringMVC has a concept of Flash. It is a way to simply pass arbitrary attributes to a redirected request with 2 characteristics:

  • you do not use the URL
  • you are not limited to strings

It is very simple to use in @RequestMapping annotated controllers, since you simply pass a RedirectAttributes parameter to the controller method, populates it and return a redirect:... string.

It can be used in an interceptor but you must explicitely require the output flash map with static methods from RequestContextUtils.

public boolean preHandle (HttpServletRequest request, HttpServletReaponse response, Object handler) {
If ( // check access) {
  Map<String, Object> flash = RequestContextUtils.getOutputFlashMap(request);
  // populate the flash map with attributes you want to pass to redirected controller
  response.redirect(/NoAuthorisation?reason=Blablabla);
  return false;
}
return true
}

}

Extract from Spring reference manual:

Flash attributes provide a way for one request to store attributes intended for use in another. This is most commonly needed when redirecting — for example, the Post/Redirect/Get pattern. Flash attributes are saved temporarily before the redirect (typically in the session) to be made available to the request after the redirect and removed immediately.

...

Flash attribute support is always "on" and does not need to enabled explicitly although if not used, it never causes HTTP session creation. On each request there is an "input" FlashMap with attributes passed from a previous request (if any) and an "output" FlashMap with attributes to save for a subsequent request. Both FlashMap instances are accessible from anywhere in Spring MVC through static methods in RequestContextUtils.

... after the redirect, attributes from the "input" FlashMap are automatically added to the Model of the controller serving the target URL.



回答2:

You could get the Session from the request and put a reason on the session as session parameter and get it back from the session at your redirect endpoint.

Don't forget to clean your session as soon as possible though.



标签: spring-mvc