How can I set parameters in a JSP, something equivalent to setAttribute on a request object? That is, I need to do setParameter in order to read it as getParameter in the servlet.
Although that's a very elegant solution, it may be overkill. There are a couple of simple solutions available. The more elegant approach using Filters, however, could make for a much more reuasable, maintainable, and robust architecture.
Case 1: An HTTP request is submitted to a servlet. From this servlet, you are dispatching a request to another (third-party) servlet that needs a parameter that is not included in the request. You can add a parameter to the request by "appending" it to the URL. For example:
RequestDispatcher dispatcher = request.getRequestDispatcher("/servlet/some.ThirdPartyServlet" + "?" + "param_name=" + "somevalue"); dispatcher.forward(request, response);
Just be careful to run the parameters through the
java.net.URLEncoder.encode(String, String) method if there's a possibility that the values contain "illegal" characters.
Case 2: An HTTP request is submitted to a JSP that is forwarding (or including) a request to a (third-party) servlet. You would like to "add" parameters to the request when received by the JSP. Do so with the
<jsp:param ... > tag.
<jsp:forward page="/servlet/some.ThirdPartyServlet" > <jsp:param name="param_name" value="somevalue" /> </jsp:forward>
Note that the value of the
value attribute may be a request time expression (i.e.
<jsp:param name="param_name" value="<%= request.getAttribute("someAttributeWithAValidToString") %>" />. Here the JSP translator should take care of encoding "illegal" characters in the value.
Case 3: You have an HTML form that submits directly to a (third-party) servlet, but you do not want the user to see some fields (i.e. you want to keep the form simple). Use "hidden" form fields:
<input type="hidden" name="param_name" value="somevalue" />
If you want a dynamic value, you can create the HTML form with a JSP. Here, the browser "packages up" the form values, so you don't want to run the values through
Case 4: You want call the third-party servlet directly from HTML without using a form. Append the required parameters to the URL:
<a href="/servlet/some.ThirdPartyServlet?param_name=somevalue">Clickable Text</a>
Here again, if using a JSP to create "dynamic" links, make sure you properly encode the characters in the URL with