How to submit and send values of a HTML form in JSP file to a Servlet?

21,718

Solution 1

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:

Solution 2

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.

Share:
21,718
H.Rabiee
Author by

H.Rabiee

=== Good link I've gathered over time Genode OS framework http://genode.org/documentation/general-overview/ About Linear Algebra https://nolaymanleftbehind.wordpress.com/2011/07/10/linear-algebra-what-matrices-actually-are/ How to program good C https://github.com/btrask/stronglink/blob/master/SUBSTANCE.md http://www.algorithmist.com/index.php/Main_Page http://www.ndpsoftware.com/git-cheatsheet.html http://genomewiki.ucsc.edu/index.php/Resolving_merge_conflicts_in_Git http://blog.dennisrobinson.name/reorder-commits-with-git/

Updated on January 01, 2020

Comments

  • H.Rabiee
    H.Rabiee over 4 years

    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(...)?

  • H.Rabiee
    H.Rabiee about 12 years
    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?
  • BalusC
    BalusC about 12 years
    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.