Search code examples
javaspring-mvcspring-bootbootstrap-4thymeleaf

Property or field 'email' cannot be found on null


I'm trying to POST from a form within a Boostrap Modal.

Here's my form:

            <form role="form" id="emailForm" action="#" th:action="@{/emailSubmission}" th:object="${university}" method="post">
                <div class="form-group">
                    <label for="emailID"><span class="glyphicon glyphicon-user"></span> Username</label>
                    <input type="text" class="form-control" id="emailID" th:value="*{email}" placeholder="Enter email"></input>
                </div>
                <button type="submit" value="Submit" id="submitButton"  class="btn btn-default btn-success btn-block" ><span class="glyphicon glyphicon-check"></span> Register</button>
            </form>

Here's my controller:

@Controller
public class RegistrationController {


    @RequestMapping(value = "/emailSubmission", method = RequestMethod.POST)
    public String registerEmail(@ModelAttribute("university") University uni, BindingResult result, Model model)
    {
        System.out.println(uni.getEmail());
        return "index";
    }
}

And my University class:

public class University {

    private String email;

    public University(){
    }

    public String getEmail(){
        return email;
    }

    public void setEmail(String email){
        this.email = email;
    }
} 

I'm new to Spring and can't figure out what's going wrong and why I'm receiving the error mentioned in the title.

Changing:

th:value="*{email}"

to:

th:field="*{email}"

gives me 'Neither BindingResult nor plain target object for bean name 'university' available as request attribute' error.


Solution

  • You have to add the university object as an attribute to the model in your controller:

    @GetMapping(value = "/index") 
    public String login(Model model) { 
        model.addAttribute("university", new University()); 
        return "index"; 
    }