In HTTP servlets for Java I want to submit a form. What is the recommended way
of carrying the values from the input fields? Is it using hidden fields
and get them through request.getParameter(...)
or with request.getAttribute(...)
?
Asked
Active
Viewed 2.6k times
2
2 Answers
8
All the form data will be sent as request parameters with the input field name as parameter name and the input field value as parameter value.
E.g.
<form action="servletURL" method="post">
<input type="text" name="foo" />
<input type="text" name="bar" />
<input type="submit" />
</form>
With inside doPost()
method:
String foo = request.getParameter("foo");
String bar = request.getParameter("bar");
// ...
You don't need to use JavaScript to transfer them to other hidden fields or something nonsensicial, unless you want to pass additional data which the enduser don't need to enter itself.
The request attributes are to be used for the other way round; for passing the results from the servlet to the JSP file which should in turn present them along all the HTML.
See also:
-
Ok, so there's nothing "wrong" or bad style to use hidden fields? I discovered I must use Javascript in the following case: if there are several elements with unique ids, the user can only select one element for further processing. Now to carry which element was selected, I need JS to set some flag in a hidden field. Or is there a better way? – H.Rabiee Apr 12 '12 at 14:12
-
I don't understand what you're saying. The element ID is irrelevant for HTML forms. Just give the element a name and check it in request parameter map. – BalusC Apr 12 '12 at 14:17
1
All form submitted can ONLY be accessed through getParameter(...)
. getAttribute()
is meant for transferring request scoped data across servlet/jsp within the context of a single request on server side.

Aravind Yarram
- 78,777
- 46
- 231
- 327