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注解。

 

原来,并没有集成失败 ,而是因为注解是 @RestController 配置的视图解析器InternalResourceViewResolver不起作用,所以返回的内容是字符串(就是Return 里的内容),把 @RestController 修改为 @Controller 后,视图解析器InternalResourceViewResolver才能成功调用返回指定页面

修改:修改注解为@Controller

修改后测试成功。

 

更多技术干货,请观柱贡眾呺 【程序论】

 

 

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值