mardi 13 octobre 2020

Thymeleaf Model vs HttpServletRequest

I'm using Spring and Thymeleaf. I have discovered that if I want to pass a variable between the Controller class and the template, I can do this in 2 ways. Either by adding it to the org.springframework.ui.Model object (in the Controller class):

@RequestMapping("trial")
public String trial(Model model) {
  model.addAttribute("variable", "abc");
  return "trialTemplate"
}

or by setting the relevant attribute in the javax.servlet.http.HttpServletRequest object (in the Controller class):

@RequestMapping("trial")
public String trial(HttpServletRequest request) {
  request.setAttribute("variable", "abc");
  return "trialTemplate"
}

In both cases, the variable can be accessed in the template like this:

<td th:text="${variable}"/>

My question is simply what is the difference and when should you use one over the other?




Aucun commentaire:

Enregistrer un commentaire