There are some questions about similar problem to mine but none of them helped me.I have a form that its fields get empitied after submission, I am using @ModelAttribute and I suppose it should keep the values but it does not. I also used @SessionAttributes("contact") but it did not help. Commented parts of the code are some of the methods that Ive tried already.
How to keep values of a form after submission?
@RequestMapping(value = "/contact", method = RequestMethod.GET)
public ModelAndView contactForm() {
return new ModelAndView("contact", "command", new Contact());
}
@RequestMapping(value = "/contact", method = RequestMethod.POST)
public String processForm(
@Valid @ModelAttribute("Contact") Contact contact,
BindingResult result, SessionStatus status, Model m) {
if (result.hasErrors()) {
System.err.println("errors");
} else {
System.err.println("Contact Name is:" + contact.getName());
m.addAttribute("message", "Successfully added");
// m.addAttribute("name", "Jack"); // does not work
// m.addAttribute("contact.name", "Jack"); // does not work
// m.addAttribute(contact); //does not work
// status.setComplete();
}
// return new ModelAndView("contact", "command", contact); // the page wont be shown at all
return "contact";
}
view
<form class="form-horizontal" role="form" method="post"
action="/contact">
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Name
</label> <input type="text" class="form-control" id="name"
name="name" placeholder="Your name" value="">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Email
Address</label> <input type="email" class="form-control" id="email"
name="email" placeholder="Your email" value="">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Phone
Number</label> <input type="number" class="form-control" id="phone"
name="phone" placeholder="Phone number" value="">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Enquiry</label>
<textarea class="form-control" rows="4" name="message"
placeholder="Please enter your enquiry"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-md-2 " style="float: right;">
<input id="submit" name="submit" type="submit" value="Send"
class="btn btn-primary">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<! Will be used to display an alert to the user>
</div>
</div>
</form>
After submission it shows "Successfully added" message but the fields are blank.