springboot集成thymeleaf中爬过的坑

使用springboot 搭建了框架,然后再加入thymeleaf ,经过测试后发现thymeleaf 完全无效,

错误:不能返回页面,只返回字符串。

application.properties的配置:

#thymeleaf
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.cache=false
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.enabled=true
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML5

项目路径


Controller:

@RestController
@RequestMapping("/main")
public class mainCrontroller {


    @RequestMapping(value="/to_login")
    public String toLogin() {
        return "login";
    }
    
    @RequestMapping("/them")
    public ModelAndView  them(ModelAndView  model) {
    	model.setViewName("hello");
    	model.addObject("name","limingcong");
    	return model;
    }
    
    
}

无论返回 字符串 或者返回 ModelAndView,最终页面只显示了字符串,并没有跳去目标页面,一度以为的maven的依赖版本问题造成的,测试了很久,最终发现是Controller的问题。

因为在controller类中一直用的是@ResController这个注解,后来查了下资料发现:

官方文档:
@RestController is a stereotype annotation that combines @ResponseBody and @Controller.
意思是:
@RestController注解相当于@ResponseBody + @Controller合在一起的作用。

1)如果只是使用@RestController注解Controller,则Controller中的方法无法返回jsp页面,配置的视图解析器InternalResourceViewResolver不起作用,返回的内容就是Return 里的内容。

例如:本来应该到success.jsp页面的,则其显示success.

2)如果需要返回到指定页面,则需要用 @Controller配合视图解析器InternalResourceViewResolver才行。
3)如果需要返回JSON,XML或自定义mediaType内容到页面,则需要在对应的方法上加上@ResponseBody注解。

修改:修改注解为@Controller

修改后测试成功。


猜你喜欢

转载自blog.csdn.net/a241903820/article/details/80723674