【Java】Spring4.0 @RestController与@Controller

spring4.0重要的一个新的改进是@RestController注解,它继承自@Controller注解。4.0之前的版本,Spring MVC的组件都使用@Controller来标识当前类是一个控制器servlet。

 

使用这个特性,我们可以开发REST服务的时候不需要使用@Controller而专门的@RestController。

 

当你实现一个RESTful web services的时候,response将一直通过response body发送。为了简化开发,Spring 4.0提供了一个专门版本的controller。下面我们来看看@RestController实现的定义:

@Target(value=TYPE)  
 @Retention(value=RUNTIME)  
 @Documented  
 @Controller  
 @ResponseBody  
public @interface RestController  

官方文档解释:

A convenience annotation that is itself annotated with @Controller and @ResponseBody. Types that carry this annotation are treated as controllers where @RequestMapping methods assume @ResponseBody semantics by default.  
注解本身使用@Controller和@ResponseBody注解。使用了这个注解的类会被看作一个controller-使用@RequestMapping的方法有一个默认的@ResponseBody注解。  
@ResponseBody – As of version 4.0 this annotation can also be added on the type level in which case is inherited and does not need to be added on the method level.  
@ResponseBody也可以加到类一级,通过继承方法一级不需要添加。  

实体类UserDetails.java

import javax.xml.bind.annotation.XmlAttribute;  
import javax.xml.bind.annotation.XmlRootElement;  
@XmlRootElement  
public class UserDetails {  
    private String userName;  
    private String emailId;  
  
    @XmlAttribute  
    public String getUserName() {  
        return userName;  
    }  
    public void setUserName(String userName) {  
        this.userName = userName;  
    }  
  
    @XmlAttribute  
    public String getEmailId() {  
        return emailId;  
    }  
    public void setEmailId(String emailId) {  
        this.emailId = emailId;  
    }  
}  

 测试Controller层 SpringRestControllerDemo.java

import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.http.HttpStatus;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestMethod;  
import org.springframework.web.bind.annotation.ResponseStatus;  
import org.springframework.web.bind.annotation.RestController;  
  
@RestController  
public class SpringRestControllerDemo {  
    @Autowired UserDetails userDetails;  
    @RequestMapping(value="/springcontent",  
            method=RequestMethod.GET,produces={"application/xml", "application/json"})  
    @ResponseStatus(HttpStatus.OK)  
    public UserDetails getUser() {  
        UserDetails userDetails = new UserDetails();  
        userDetails.setUserName("Krishna");  
        userDetails.setEmailId("krishna@gmail.com");  
        return userDetails;  
    }  
  
    @RequestMapping(value="/springcontent.htm", method=RequestMethod.GET)  
    @ResponseStatus(HttpStatus.OK)  
    public String getUserHtml() {  
        //Test HTML view  
        return "example";  
    }  
}  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值