I was looking over Stackoverflow today, and saw a question about how to set response headers in Thymeleaf. The question was from a guy new to Thymeleaf, but accustomed to JSP.

The short answer, is you don’t. Setting response headers is a function of the controller, not of the templating engine.

In my experience as a Java developer, some of the worst code I’ve ever seen has been in JSP pages. I’ve seen absolutely awful stuff. Sadly, JSP allows, almost encourages poor development practices. Just because you can do something, does not mean you should do something. I can make a JDBC call directly from a JSP page. That does not mean I should make a JDBC call from a JSP page.

I expect people moving over to Thymeleaf from the JSP world will have issues from bad habits of poor coding practices. Thymeleaf is a template engine. Not a dumping ground for bad code.

thymeleaflogonameverysmall

In the video below, I step you through how to use Spring MVC to set a HTTP response header when using Thymeleaf. Following the video, is a code example.

Setting Response Headers in Spring MVC

Setting response headers in Spring MVC is simple. In your controller method, make the HttpServletResponse object an argument. Spring MVC will provide the method the response object, and then you can set the appropriate response headers.

@Controller
public class ProductController {

    @RequestMapping("/product")
    public String getProduct(HttpServletResponse response){
        response.setHeader("Cache-Control","no-cache,no-store,must-revalidate asdf");
        return "product";
    }
}

 

The post Setting Response Headers in Thymeleaf appeared first on Spring Framework Guru.