Search code examples
springspring-bootjspjstl

Spring: How to get the model attribute and check if it is null in JSP?


I just start to learn Spring framework recently. In my controller, I write

@GetMapping("/users/{username}")
public String getUserByUsername(@PathVariable(value = "username") String username, ModelMap model) {
    User founduser = userRepository.findById(username)
            .orElseThrow(() -> new ResourceNotFoundException("User", "username", username));

    model.addAttribute("founduser",founduser);
    return "redirect:/profile";
}

Then, I try to get the model attribute and print it in my JSP.

 <c:when test="${not empty founduser}">
             <table style="border: 1px solid;">
                <c:forEach var="one" items="${founduser}">
                    <tr>
                        <td>${one.username}</td>

                        <td>${one.createdAt}</td>
                    </tr>
                </c:forEach>
            </table>
        </c:when>

However, I found that the test="${not empty founduser} is always false, which mean my founduser attribute is null. When I debug, it shows that the model adds the founduser successfully.

Who can tell me why I got error? Thank you so much!


Solution

  • First, ${not empty founduser} will access values from the current request attribute only.

    However you use redirect:/profile to display JSP .Redirect means another new request will be send to server. This new request will not go through getUserByUsername controller and hence there are no founduser in this new request attribute and JSP cannot find it.

    To solve it , depending on your application architecture , you can

    1. Do not redirect in your controller , just return profile.

    2. If you really need to redirect , add the values to the flash attribute such that they can still be survived and accessed after redirect:

      model.addFlashAttribute("founduser",founduser);