spring-boothttp-redirectspring-thymeleaf

How to prevent Thymleaf Page rendering when doing redirect (302)?


This is my spring-boot(3.3.5)/thymeleaf application pom.xml deps:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

I have a simple controller with two Get mappings.

firefox dev console

My controller (IndexController.java):

@Controller
public class IndexController {
    
    @GetMapping("/")
    public String index(Model model){
        return "index";
    }

    @GetMapping("/redirect")
    public String redirect(Model model){
        return "redirect:/"; //302 reponse has rendered "index.html"
    }

}

Thymeleaf template (/resources/templates/index.html:

<h1>hai</h1>
  1. How do I make the 302 redirect itself not render the page?
  2. Why is it the default behavior?

Solution

  • The 302 doesn't contain the HTML. It only shows it like this as the browser will follow it.

    If you would call it with something like CURL or HTTPie you will see that the 302 response only contains a Location header and no content.