亲宝软件园·资讯

展开

@Controller和@Restcontroller

龙大盗 人气:0

@Controller和@Restcontroller

直接甩正事

我要返回如下页面路径:

控制层的注解为上图时,结果正常:

但注解的@Controller若是变为了@Restcontroller了呢

结果如下:

后来的经验总结

RestController相当于Controller+ResponseBody注解

如果只是使用@RestController注解Controller,则Controller中的方法无法返回jsp页面,或者html,配置的视图解析器 ,也就是相当于在方法上面自动加了ResponseBody注解,所以没办法跳转并传输数据到另一个页面,所以InternalResourceViewResolver也不起作用,返回的内容就是Return 里的内容,即数据直接甩在当前请求的页面上,适用于ajax异步请求。

如果需要返回到指定页面,则需要用 @Controller配合视图解析器InternalResourceViewResolver才行

@Controller和@RestController的区别?

官方文档:

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

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

加载全部内容

相关教程
猜你喜欢
用户评论