spring能夠輕鬆的集成多種restful風格的web-service,但其實spring-mvc中已經提供了這一支持。java
能夠根據須要生成xml、json、text等格式。git
生成xml依賴於JAXB,主要是@XmlRootElement、@XmlAttribute、@XmlElement等註解的使用,JDK1.6開始就有jaxb了,也能夠單獨加jaxb-api依賴。web
生成json就須要jackson,依賴jackson-mapper-asl-xxx.jar、jackson-core-asl-xxx.jar。maven依賴以下,jackson-core-asl會自動加入。spring
<!-- jackson --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.7.9</version> </dependency>
下面是一個簡單的controller。@RequestMapping註解中的produces指定輸出的格式,xml、json等
json
package com.spring.demo.web.controller; import javax.annotation.PostConstruct; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import com.spring.demo.core.entity.Member; /** * rest demo * * @author sean * */ @Controller @RequestMapping("/rest") public class RestController { private Logger logger = LoggerFactory.getLogger(getClass()); private Member member; @PostConstruct public void postConstruct() { member = new Member(); member.setEmail("657620636@qq.com"); member.setName("張三"); member.setStreet("南山區白石洲天河街55號"); member.setZip("518025"); } /** * 輸出xml * * @return */ @RequestMapping(value = "/xml", produces = { MediaType.APPLICATION_XML_VALUE }) @ResponseBody public Member xml() { logger.debug("rest xml"); return member; } /** * 輸出json * * @return */ @RequestMapping(value = "/json", produces = { MediaType.APPLICATION_JSON_VALUE }) @ResponseBody public Member json() { logger.debug("rest json"); return member; } /** * 更新操做,只須要返回成功與否的狀態。 * * @return */ @RequestMapping(value="/updateAndReturnOk") @ResponseBody public String updateAndReturnOk() { logger.debug("rest updateAndReturnOk"); return "Ok"; } /** * 更新操做,什麼都不返回。 */ @RequestMapping(value="/update") @ResponseStatus(value=HttpStatus.NO_CONTENT) @ResponseBody public void update() { logger.debug("rest update and return no content"); } }
源碼參考RestController、Member
api