1

I'd like to ask. How to modify http request before handling in the Spring REST (MVC) controller?

As far as I found I can make with servlets through filter and custom request wrapper. So does anyone know how to make it in Spring (e.g. via interceptors)?

My aim is to add new request parameter to request to use it into controller

Thx in advance

3
  • 1
    This sounds like an XY problem. What are you actually trying to achieve? Adding a parameter to a request sounds like a very bad idea to me, and there is probably a much better way to solve the problem you're trying to solve. Commented Apr 18, 2016 at 6:05
  • @b3lowster, what you have tried? put some code here. Commented Apr 18, 2016 at 6:46
  • Let me explain what I want to achieve. In the controller I have a few endpoints and several of them expect a non-mandatory parameter (let's assume the parameter has name "type"). So I want to fill this parameter in AOP-style when parameter value is null (but not through default value). Commented Apr 18, 2016 at 6:46

1 Answer 1

2

You can use Filter to modify httprequestparameter value. Watchout the implementation:

Web.xml

<filter> <description>check request for service token</description> <filter-name>CustomFilter</filter-name> <filter-class>com.filters.CustomFilter</filter-class> </filter> <filter-mapping> <filter-name>CustomFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> 

Create a Filter Class:

public class CustomFilter implements Filter { String encoding; public void init(FilterConfig config) throws ServletException { encoding = config.getInitParameter("requestEncoding"); if (encoding == null) { encoding = "UTF-8"; } } public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws ServletException, IOException { // next handler System.out.println("accessed"); filterChain.doFilter(new CustomFilterWrapper((HttpServletRequest)request),(HttpServletResponse)response); } public void destroy() { } } 

Create a CustomFilterWrapper where you override getParameter method to modify certain request parameter. In my case I change value if the request param is maverick.

public class CustomFilterWrapper extends HttpServletRequestWrapper { public CustomFilterWrapper(HttpServletRequest request) { super(request); } @Override public String getParameter(String name) { String[] vals = getParameterMap().get(name); if (name.equalsIgnoreCase("maverick")) { return "modify value"; } else if (vals != null && vals.length > 0) { return vals[0]; } else { return null; } } } 
Sign up to request clarification or add additional context in comments.

1 Comment

I know how it works. It's not a problem for me at all. In this way I cannot add new parameter or change existed from the request

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.