开发者

best way to remove a HttpServletRequest parameter in a controller/class?

开发者 https://www.devze.com 2023-01-20 06:07 出处:网络
I have a case where I need to redirect my HTTP request object to other controllers/classes for further processing. The problem is that in some controller, I would like to get better control on the par

I have a case where I need to redirect my HTTP request object to other controllers/classes for further processing. The problem is that in some controller, I would like to get better control on the parameters I'm forwarding to the next class: modify, edit, remove them. So, I would like to know if there is a good prac开发者_StackOverflow社区tice/pattern to achieve this basic control on the HTTP request parameters.


The good practice is to wrap the request object in another object using a servlet filter. Since HttpServletRequest is an interface, you can write your own implementation of it. Your implementation can hold the request you received and delegate any and all of its own methods to the original request object, but also modify the return values as you see fit. So your getParameter() etc. methods could call the same method on the original request object, and modify the result as you see fit before returning it.

class MyHttpServletRequestWrapper implements HttpServletRequest {
   private HttpServletRequest originalRequest;

   public MyHttpServletRequestWrapper(HttpServletRequest originalRequest) {
      this.originalRequest = originalRequest;

   public String getAuthType() {return originalRequest.getAuthType();}
   public String getQueryString() {return originalRequest.getQueryString();}
   // etc.

   public Map getParameterMap() {
      Map params = originalRequest.getParameterMap();
      params.remove("parameter-to-remove");
      params.put("parameter-to-add", "<a value>");
      //etc.
   }
}

Your servlet filter:

class MyFilter implements Filter {
    public void init(FilterConfig config) {
       // perhaps you might want to initialize something here
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
        HttpServletRequest originalRequest = (HttpServletRequest) request;
        HttpServletRequest newRequest = new MyHttpServletRequest(originalRequest);
        chain.doFilter(newRequest, response);
    }
}

You can also subclass javax.servlet.request.HttpServletRequestWrapper, which will save you a bunch of work.

See this post for more.


If you're after a simple one-liner, this regex technique worked for me:

myURL = myURL.replaceAll("[&?]clear=([^&]$|[^&]*)", "");

If you need it in Javascript, it's very similar indeed - which is nice!

var myUrl = (""+window.location).replace(/&?clear=([^&]$|[^&]*)/i, "");

clear is the name of the parameter to be removed.

0

精彩评论

暂无评论...
验证码 换一张
取 消