Issue
I am trying to build a simple Web application using Spring Mvc with the following features:
A page with a form for the user to enter their name and age and submit
User should be redirected to a new page on form submission with a message as below
Hello "name", you are "age" years old.
I want to display an error message on the same form web page when either of the name or age fields are empty and the user hits submit. I've written code for that as below, but it doesn't seem to work properly. Am i getting my concepts confused? If i am,then can someone sort this out and make me understand better please. Thank you!
My Controller Code:
@Controller
public class form {
@RequestMapping(value = "/form", method = RequestMethod.GET)
public String getForm(ModelMap model) {
return "form";
}
@RequestMapping(value = "/form",method = RequestMethod.POST)
public String postForm(ModelMap model, @RequestParam String name, @RequestParam String age){
if(name==null || age==null){
model.put("error","Please Enter Name and Age Fields");
return "form";
}
else if(name==null && age!=null){
model.put("error","Name field is Empty.");
return "form";
}
else if(age==null && name!=null){
model.put("error","Age field is Empty.");
return "form";
}
else {
model.put("name", name);
model.put("age", age);
return "index";
}
}
}
Solution
I think your immediate issue is that empty fields are submitted as empty string, not null
. You can check for empty string, or if you prefer do something like this to have Spring convert empty strings to nulls.
Answered By - dbreaux