springmvc实现rest风格webservice

1.controller中的方法添加ResponseBody注解

 

@ResponseBody
	public UserDTO getUser(@PathVariable("id") Long id) {
		User user = accountService.getUser(id);
                UserDTO dto = .....
		return dto;
	}

 2.返回的UserDTO类上方,添加【@XmlRootElement(name = "User") 】注解

 

3.spring-mv.xml文件添加配置

 

<!-- REST中根据URL后缀自动判定Content-Type及相应的View -->
	<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
	    <property name="mediaTypes" >
	        <value>
	            json=application/json
	            xml=application/xml
	        </value>
	    </property>
	</bean>

 

 

4.最后可以通过

(1)http://localhost:8080/user/1.xml返回xml格式的数据

(2)http://localhost:8080/user/1.json返回json格式的数据

(3)http://localhost:8080/user/1默认返回的是xml格式的数据(可能的原因是UserDTO类被添加了@XmlRootElement注解,如果去掉的话,返回的是json,但是这样就得不到xml格式的数据了

注:spring版本为3.2

 

你可能感兴趣的:(springMVC,REST)