关于@Controller和@Restcontroller的那点奇葩事

2022-07-17,,,

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

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

《关于@Controller和@Restcontroller的那点奇葩事.doc》

下载本文的Word格式文档,以方便收藏与打印。