Gero
Gero

Reputation: 13553

How to preload html form with data in java servlet jsp

I have a html site and that site has a form. Imagine:

First Name:
Last Name:
<form action="" method="POST">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>

I would like to press a button that would trigger a java servlet. And that servlet should return data and preload my form. e.g.:

<form action="" method="POST">
First Name: <input type="text" name="first_name" value="MyFirstName">
<br />
Last Name: <input type="text" name="last_name" value="MyLastName" />
<input type="submit" value="Submit" />
</form>

First Name: MyFirstName
Last Name: MyLastName

How do I get the data from my servlet back to my html or .jsp site? What is the proper approach to get data from a servlet (doPost()) and preload a form?

Upvotes: 0

Views: 1332

Answers (2)

Adam Tychoniewicz
Adam Tychoniewicz

Reputation: 678

As in Java EE docs, you can use EL (Expression Language).

For example, when evaluating the expression${customer}, the container will look for customer in the page, request, session, and application scopes and will return its value. If customer is not found, a null value is returned.

So you should be able to write #{firstname} for example.

Upvotes: 2

Shaggy
Shaggy

Reputation: 1464

If I understand your question correctly - just add the names to your ModelAndView in your controller:

public ModelAndView defaultPage() {
    ModelAndView mav = new ModelAndView("pageName");
    // fetch the first and last name here
    mav.addObject("firstName", firstName);
    mav.addObject("lastName", lastName);
return mav;

}

Then preload the form with the values:

<form action="" method="post">
    First Name: <input type="text" name="first_name" value="${firstName}">
    <br />
    Last Name: <input type="text" name="last_name" value="${lastName}" />
    <input type="submit" value="Submit" />
</form>

Upvotes: 0

Related Questions