springboot 配合 thymeleaf,调用接口不跳转页面只显示文本

问题一:thymeleaf 不跳转页面,只显示文本 index
代码如下:
复制代码
这个代码的初衷是返回 index.html 页面,但是执行的结果是在页面中输出 index。
原因分析:
@RestController 注解相当于 @ResponseBody 和 @Controller 合在一起的作用。在使用 @RestController 注解 Controller 时,Controller 中的方法无法返回 jsp 页面,或者 html,配置的视图解析器 InternalResourceViewResolver 不起作用,返回的内容就是 Return 里的内容。
包括在 Mapping 注解使用的同时使用 @ResponseBody 时也会出现同样的问题。
解决方案
解决办法①:去除 @ResponseBody 或将含有 Rest 的注解换成对应的原始注解 @Controller;
复制代码
解决办法②:不通过 String 返回,通过 ModelAndView 对象返回,上述例子可将 return 语句换成下面的句子,在使用 ModelAndView 对象返回的时候,不需要考虑有没有 @ResponseBody 类似的注解。
复制代码
评论