Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read request parameter values Using HandlerInterceptor in spring?

I'm using HandlerInterceptor to trigger all the events/actions happens in my applications and save it to audit table. In table I'm saving the information like servername, session, parameters etc..

So using HandlerInterceptor how can I read all those parameters values and the pathvariable values what I'm passing in my controller.

Here is my code :

    public class AuditInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {
            LOG.debug("URL path"+request.getRequestURI());
                return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        LOG.debug("URL PATH :"+request.getRequestURI());

    } 

}

My controller class enter code here::

public class ABCDController {
@RequestMapping(value="categories",method=RequestMethod.GET)
    @ResponseBody
    public List<Category> getCategoryList(@RequestParam String divisions){
        return service.getCategoryList(divisions);
    }
}

So how can I read the parameter name and values using HandlerInterceptor's HttpServletRequest request object.

like image 422
user3095886 Avatar asked Sep 06 '25 02:09

user3095886


2 Answers

The Servlet API provides a way to read the Request Parameters. For example,

ServletRequest.getParameterMap() returns a map of key-values of the request parameters.

However, for Path variables and values, I don't know if Spring MVC offers a simplified way of doing it, but using Servlet API again, you can read the URI using HttpServletRequest.getRequestURI(). You'll have to have your own logic to split it up into appropriate Path parameters.

like image 182
asgs Avatar answered Sep 07 '25 15:09

asgs


You should be able to get the variables and its values as a map using the following,

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        final Map<String, String> variableValueMap = (Map<String, String>) request
                .getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);

        variableValueMap.forEach((k,v)->System.out.println("Key:"+k+"->"+"Value : "+v));

        return true;
    }
like image 27
codeworks Avatar answered Sep 07 '25 15:09

codeworks