Xetius
Xetius

Reputation: 46884

Change the body of a request

I have a Java Servlet, which is handling a REST request. However, this is breaking when it receives invalid data. This is POSTed in XML format, and to attempt to resolve this I have added a filter into the filter chain. The filter is being called, and I can access the data in the body of the request, accessing the XML.

I can validate this and manipulate it to ensure that the data is correct, but I cannot work out how to reset it back into the request object.

How can you set the body of an HttpServletRequest object?

Upvotes: 3

Views: 5365

Answers (2)

Andy
Andy

Reputation: 1618

Take look at HttpServletRequestWrapper

You can wrap original request with a new object by using public HttpServletRequestWrapper(HttpServletRequest request) constructor, you won't have to do a lot work yourself.

Upvotes: 2

Tomasz Jędzierowski
Tomasz Jędzierowski

Reputation: 969

You can wrap Your HttpServletRequest object with a new class lets name it: NewHttpServletRequest. The actual rewriting should be done in the appropriate overriden methods e.g getParameter(String)

package com.example;

import javax.servlet.http.HttpServletRequestWrapper;

public class MyHttpServletRequest extends HttpServletRequestWrapper {

    public MyHttpServletRequest(HttpServletRequest request) {
        super(request);
    }

    public String getParameter(String name) {
        String str = super.getParameter(name);
        // DO THE REWRITING
        return str;
    }

}

Upvotes: 2

Related Questions