简体   繁体   中英

Spring MVC and thymeleaf ModelAttribute either null or not evaluated

I'm developing a web application with Spring MVC and Thymeleaf as my ViewResolver. I have the following controller handler method:

    @RequestMapping(value = "/something", method = RequestMethod.POST, params = "submit")
    public String doSomething(@ModelAttribute("error") String error /*, other attributes */) {
        // find out if there is an error 
        error = getErrorMessage();

        return "someHTMLfile";
    }

My view contains this line:

<p><span th:text="${error}">Error Message goes here</span></p>

When executed, the tag does not render to anything. This is probably due to ${error} evaluating to an empty string but I can't understand why. Doesn't Spring's @ModelAttribute annotation add the object to the model map automatically, where Thymeleaf can find it?

If I instead have:

@RequestMapping(value = "/something", method = RequestMethod.POST, params = "submit")
public String doSomething(ModelMap map /*, other attributes */) {
    // find out if there is an error 
    String error;
    error = getErrorMessage();
    map.addAttribute("error", error);

    return "someHTMLfile";
}

The view is rendered perfectly fine with the error message. Does @ModelAttribute not add the object to the request model?

Edit: I've tried doing both:

@RequestMapping(value = "/something", method = RequestMethod.POST, params = "submit")
public String doSomething(@ModelAttribute("error") String error, ModelMap map /*, other attributes */) {
    // find out if there is an error 
    error = getErrorMessage();
    map.addAttribute("error", error);

    return "someHTMLfile";
}

This also doesn't work.

Actually I don't think your issue is related to Thymeleaf, just SpringMVC :-)

In your first snippet, you don't add anything to the request model but try to get an object called "error" back from the form.

In your second snippet, you do add an object to the model, that's why your view is well rendered.

Take a look at the SpringMVC doc here (16.3.3.8) to have a better understanding of the @ModelAttribute annotation on a method argument.

I feel stupid but whatever, we all make mistakes.

Spring was creating a new String instance for me and injecting it into my method and into the model under the key error . String is an immutable object, so when I do error = getErrorMessage() , I assign another instance to my error object. Now there is my error and the error String in Spring's model with a value of "" . That's why Thymeleaf rendering only finds the empty string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM