springmvc注解之@Controller和@RestController注解

来源:互联网 发布:施工进度网络计划软件 编辑:程序博客网 时间:2024/05/22 12:14

一、使用说明

官方文档:

@RestController is a stereotype annotation that combines @ResponseBody and @Controller.

意思是:

@RestController注解相当于@ResponseBody + @Controller合在一起的作用。

@Controller    @ResponseBody    public class MyController { }    上面的语句与下面语句的作用相同@RestController    public class MyRestController { }

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

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

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

3)如果需要返回JSON,XML或自定义mediaType内容到页面,则需要在对应的方法上加上@ResponseBody注解。

二、示例

举例如下:

假定一个user对象,对象有很多属性(name,sex,age,birth,address,tel)

在@controller注解中,返回的是字符串,或者是字符串匹配的模板名称,即直接渲染视图,与html页面配合使用的。在这种情况下,前后端的配合要求比较高,java后端的代码要结合html的情况进行渲染,使用model对象(或者modelandview)的数据将填充user视图中的相关属性,然后展示到浏览器,这个过程也可以称为渲染。

java示例代码如下:

@Controller@RequestMapping(method = RequestMethod.GET, value = "/")    public String getuser(Model model) throws IOException {        model.addAttribute("name",bob);        model.addAttribute("sex",boy);        return "user";//user是模板名    }

对应视图user.jsp中的html代码:

<html xmlns:th="http://www.thymeleaf.org"><body>    <div>        <p>"${name}"</p>        <p>"${sex}"</p>    </div></body></html>

而在@restcontroller中,返回的应该是一个对象,即return一个user对象,这时,在没有页面的情况下,也能看到返回的是一个user对象对应的json字符串,而前端的作用是利用返回的json进行解析渲染页面,java后端的代码比较自由。

@RestController@RequestMapping(method = RequestMethod.GET, value = "/")    public User getuser( ) throws IOException {        User bob=new User();        bob.setName("bob");        bob.setSex("boy");        return bob;    }

访问网址得到的是json字符串{“name”:”bob”,”sex”:”boy”},前端页面只需要处理这个字符串即可。

参考自:http://blog.csdn.net/yzllz001/article/details/54312929

http://blog.csdn.net/pinebud55/article/details/52183238?locationNum=12

原创粉丝点击