0

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";
            }
    }
}

My index.html file

My form.html file

dbreaux
  • 4,982
  • 1
  • 25
  • 64
abdv19
  • 5
  • 4
  • 1
    What _is_ actually happening, for what inputs? That is, are the error cases returning to the input page, but without text? Is the success case going to the correct page? Have you added logging to see what paths are being taken? – dbreaux Jun 07 '21 at 18:45
  • No, the error cases are not returning to the input page, rather, when i dont enter the name and age, it just gives me a new page with the output - Hello, your age is (basically the required output without name and age). Yes,the success case is going to the correct page though. I don't really know what logging is since, i am a beginner, but the code i've included above is all i've written. – abdv19 Jun 07 '21 at 19:05

1 Answers1

0

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.

dbreaux
  • 4,982
  • 1
  • 25
  • 64
  • Thank you so much! That helped me solve the issue. But I Used .isEmpty() method instead. But thanks for giving me the idea – abdv19 Jun 07 '21 at 23:40