jMn
jMn

Reputation: 238

spring interceptor handler confusing behavior

I'm playing with spring interceptors in last few days and want to catch and handle specific requests through interceptor. What I want to do is to intercept each request before it is processed by specific controller, check whether request contains specific parameters or not. If yes, do some stuff and than sign that stuff to controller which maps that request.

At the end I managed to do that, but when I execute multiple requests at once, with different param values, only param value from last request is assigned to each of controller handler, even every controller should have params which are contained within the request.

Example (executed at the same time):

http://domain.com/controller/method?param=xfg

http://domain.com/controller/method?param=mtc

http://domain.com/controller/method?param=abc

in responses from each request, I get abc! (sometimes I get xfg and abc, or mtc and abc, but never all three of them). When I execute these requests with timeout where every request have time to complete before next one is called, it is working fine.

Does anyone know how to handle this?

Thanks

UPDATED:

public class OLMyInterceptor extends HandlerInterceptorAdapter {

    static Logger LOG = Logger.getLogger(OLAuthentificationInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
     Map<String, Object> activeParamsMap = request.getParameterMap();
         for(Entry<String, Object> param : activeParamsMap.entrySet()) {
             if(param.getKey().startsWith("aP_")) {
                  activeParams.put(param.getKey().substring(3), param.getValue());
             }
         }

         ((MainController) handler).setParams(activeParams);

         return true;
    }
}

There you have code sample. Every controller of mine extends MainController, that's why I cast handler to MainController, which have setParams method. Every other controller use params in different way.

Upvotes: 0

Views: 2848

Answers (1)

masted
masted

Reputation: 1220

You must invoke a controller handler method with params, not setter which changes controller state.

The controller must be stateless or thread-safe. When you change state you do not have a guarantee when the setter applies changes - before handlers invoked in another thread, or after. Or another thread invokes setter with other params and previous thread invokes handler method for new params.

Upvotes: 1

Related Questions