Marouen Ghozzi
Marouen Ghozzi

Reputation: 99

redirect to HTML page using spring boot / thymyleaf

This is my controller:

@RestController
public class GraphController {

    @GetMapping("/displayBarGraph")
    public String barGraph(Model model) {
        Map<String, Integer> surveyMap = new LinkedHashMap<>();
        surveyMap.put("Java", 40);
        surveyMap.put("Dev oops", 25);
        surveyMap.put("Python", 20);
        surveyMap.put(".Net", 15);
        model.addAttribute("surveyMap", surveyMap);
        return "barGraph";
    }

    @GetMapping("/displayPieChart")
    public String pieChart(Model model) {
        model.addAttribute("pass", 50);
        model.addAttribute("fail", 50);
        return "pieChart";
    }

This is my file.proprieties:

spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.enabled=false

spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.html

Those are my HTML files:

enter image description here

but it always redirect me like this:

enter image description here

Any solution please?

Upvotes: 2

Views: 4688

Answers (3)

Matt
Matt

Reputation: 13943

  1. Setting spring.thymeleaf.enabled to false disables Thymeleaf for Spring MVC/Web. Therefore, the controller just returns the name of the Thymeleaf template instead of going through the Thymeleaf view resolution.

    To solve this, remove the spring.thymeleaf.enabled property or set it to true which is the default for Thymeleaf auto-configuration:

    spring.thymeleaf.enabled=true
    
  2. Use @Controller instead of @RestController when working with a templating engine and you don't want the return value to be bound to the response body:

    @Controller
    public class GraphController {
    
        @GetMapping("/displayBarGraph")
        public String barGraph(Model model) {
            // ...
            return "barGraph";
        }
    
        // ...
    }
    
  3. Your configured template path needs to match the actual path where the templates are stored. So either change setspring.thymeleaf.prefix=classpath:/template/ or rename the template directory to templates.

  4. Remove the two properites spring.mvc.view.prefix and spring.mvc.view.suffix from your configuration. This would be necessary if you want to use JSP.

Upvotes: 2

Alien
Alien

Reputation: 15878

Couple of changes to make this work.

  1. Change @RestController to @Controller so that it returns page instead of response in the body.

  2. Rename folder to templates or change the path in properties file for view resolver.

  3. no need of thymeleaf enabled property.

Upvotes: 1

Ajay Kumar
Ajay Kumar

Reputation: 3250

Rename your

src/main/resources/template

folder to

src/main/resources/templates

You are missing "s" in the folder name.

Upvotes: 0

Related Questions