Search code examples
javajakarta-eehttp-request-parameters

Construct a URL with Request Parameters in Java


I've a servlet which is accessed through a URL and that URL has some request parameters in it. Now I need to redirect the user to a different page (from servlet), but also append the request parameters that I got from the request. This is what I'm doing

    StringBuffer sb=new StringBuffer("/test.jsp");
    sb.append( "?" );
    Enumeration en = request.getParameterNames();
    while( en.hasMoreElements() ){
        String paramName = (String) en.nextElement();
        sb.append( paramName );
        sb.append( "=" );
        sb.append(request.getParameter( paramName ));
        sb.append("&");
    }
           String constructedURLWithParams=sb.toString();

But the problem is, there is a "&" which will be added towards the end of the constructed URL. I don't want to again do some string operation and remove the trailing "&". Can you please suggest a better way to do this?


Solution

  • Simply append "?" + request.getQueryString() (if the parameters are passed in the URL - the query string contains all the get parameters)

    If they aren't, then your approach seems fine. Just have

    if (en.hasMoreElements()) sb.append("&");