banner



How To Set Parameter In Http Request In Java

DISABLE ADBLOCK

ADBlock is blocking some content on the site

ADBlock errore

  •   coffee  -  spider web-applications
  • |
  • |
  • ( words)

Question

I am using a javax.servlet.http.HttpServletRequest to implement a web application.

I have no problem to get the parameter of a asking using the getParameter method. However I don't know how to set up a parameter in my asking.

Solution

You can't, not using the standard API. HttpServletRequest represent a request received by the server, so calculation new parameters is non a valid pick (as far as the API is concerned).

You could in principle implement a subclass of HttpServletRequestWrapper which wraps the original request, and intercepts the getParameter() methods, and pass the wrapped asking on when you forward.

If yous go this route, you should use a Filter to supplant your HttpServletRequest with a HttpServletRequestWrapper:

                public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {     if (servletRequest instanceof HttpServletRequest) {         HttpServletRequest request = (HttpServletRequest) servletRequest;         // Check wether the current asking needs to be able to back up the torso to be read multiple times         if (MULTI_READ_HTTP_METHODS.contains(request.getMethod())) {             // Override electric current HttpServletRequest with custom implementation             filterChain.doFilter(new HttpServletRequestWrapper(request), servletResponse);             return;         }     }     filterChain.doFilter(servletRequest, servletResponse); }                              

OTHER TIPS

If y'all really want to do this, create an HttpServletRequestWrapper.

                public form AddableHttpRequest extends HttpServletRequestWrapper {     private HashMap params = new HashMap();     public AddableingHttpRequest(HttpServletRequest request) {            super(asking);    }     public String getParameter(String name) {            // if nosotros added i, return that one            if ( params.get( name ) != zero ) {                  return params.become( name );            }            // otherwise return what's in the original request            HttpServletRequest req = (HttpServletRequest) super.getRequest();            render validate( proper name, req.getParameter( proper name ) );    }     public void addParameter( Cord proper name, String value ) {            params.put( name, value );    }  }                              

From your question, I think what you are trying to practise is to store something (an object, a string...) to foward it then to another servlet, using RequestDispatcher(). To exercise this you don't need to set a paramater but an attribute using

                void setAttribute(Cord name, Object o);                              

and and then

                Object getAttribute(String proper name);                              

Every bit mentioned in the previous posts, using an HttpServletReqiestWrapper is the way to go, however the missed part in those posts was that autonomously from overriding the method getParameter(), you should also override other parameter related methods to produce a consistent response. e.yard. the value of a param added by the custom asking wrapper should also be included in the parameters map returned past the method getParameterMap(). Hither is an example:

                                  public class AddableHttpRequest extends HttpServletRequestWrapper {      /** A map containing additional asking params this wrapper adds to the wrapped request */     private terminal Map<String, String> params = new HashMap<>();      /**      * Constructs a request object wrapping the given request.      * @throws java.lang.IllegalArgumentException if the request is null      */     AddableHttpRequest(terminal HttpServletRequest asking) {         super(asking)     }      @Override     public String getParameter(final Cord name) {         // if we added 1 with the given name, return that one         if ( params.become( name ) != null ) {             render params.go( proper name );         } else {             // otherwise return what'southward in the original request             return super.getParameter(name);         }     }       /**      * *** OVERRIDE THE METHODS BELOW TO Reflect PARAMETERS ADDED BY THIS WRAPPER ****      */      @Override     public Map<Cord, Cord> getParameterMap() {         // defaulf impl, should exist overridden for an approprivate map of request params         render super.getParameterMap();     }      @Override     public Enumeration<String> getParameterNames() {         // defaulf impl, should exist overridden for an approprivate map of request params names         return super.getParameterNames();     }      @Override     public String[] getParameterValues(final String name) {         // defaulf impl, should be overridden for an approprivate map of asking params values         render super.getParameterValues(name);     } }                              

The missing getParameterMap override ended up existence a real problem for me. Then this is what I ended upwards with:

                import java.util.HashMap; import java.util.Map;  import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper;  /***  * Request wrapper enabling the update of a asking-parameter.  *   * @author Eastward.K. de Lang  *  */ final class HttpServletRequestReplaceParameterWrapper     extends HttpServletRequestWrapper {      private concluding Map<Cord, String[]> keyValues;      @SuppressWarnings("unchecked")     HttpServletRequestReplaceParameterWrapper(HttpServletRequest asking, String fundamental, Cord value)     {         super(asking);          keyValues = new HashMap<String, String[]>();         keyValues.putAll(request.getParameterMap());         // Can override the values in the request         keyValues.put(key, new Cord[] { value });      }      @SuppressWarnings("unchecked")     HttpServletRequestReplaceParameterWrapper(HttpServletRequest asking, Map<String, Cord> additionalRequestParameters)     {         super(request);         keyValues = new HashMap<String, Cord[]>();         keyValues.putAll(request.getParameterMap());         for (Map.Entry<String, String> entry : additionalRequestParameters.entrySet()) {             keyValues.put(entry.getKey(), new Cord[] { entry.getValue() });         }      }      @Override     public String getParameter(Cord name)     {         if (keyValues.containsKey(name)) {             String[] strings = keyValues.get(name);             if (strings == goose egg || strings.length == 0) {                 return null;             }             else {                 return strings[0];             }         }         else {             // Only in case the request has some tricks of information technology's ain.             return super.getParameter(proper noun);         }     }      @Override     public String[] getParameterValues(Cord name)     {         String[] value = this.keyValues.become(proper noun);         if (value == null) {             // Only in case the request has some tricks of it'south own.             return super.getParameterValues(name);         }         else {             render value;         }     }      @Override     public Map<String, Cord[]> getParameterMap()     {         return this.keyValues;     }  }                              

Sorry, but why not use the following construction:

                request.getParameterMap().put(parameterName, new String[] {parameterValue});                              

How To Set Parameter In Http Request In Java,

Source: https://www.generacodice.com/en/articolo/203737/How+to+set+a+parameter+in+a+HttpServletRequest%3F

Posted by: ornelashavoily.blogspot.com

0 Response to "How To Set Parameter In Http Request In Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel