您的位置:首页 > 编程语言 > Java开发

springmvc发布rest服务

2016-05-18 22:59 507 查看
1.配置springmvc的ContentNegotiatingViewResolver

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1" />
<!-- 指定是否以format参数形式如get?format=json get?format=xml -->
<property name="favorParameter" value="true" />
<!-- 忽略请求头中的Accept 由于浏览器的Accept不同 一般默认设置为true-->
<property name="ignoreAcceptHeader" value="true" />
<!-- 默认response返回的contenttype -->
<property name="defaultContentType" value="text/html" />
<!-- 指定是否以扩展名形式返回数据如get.json get.xml 默认就是true -->
<property name="favorPathExtension" value="true"/>
<property name="mediaTypes">
<map>
<entry key="xml" value="application/xml" />
<entry key="json" value="application/json" />
</map>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</list>
</property>
<property name="defaultViews">

<!--
数据格式的转换器部分,需要说的是,在spring的包里面有2个不同的类:SON解析器也不同如下
org.springframework.web.servlet.view.json.MappingJacksonJsonView
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>1.9.13</version>
</dependency>

org.springframework.web.servlet.view.json.MappingJackson2JsonView

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.2.2</version>
</dependency>
-->
<list>
<!-- <bean id="jsonView" class="org.springframework.web.servlet.view.json.MappingJackson2JsonView" /> -->
<bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView">
<!-- <property name="extractValueFromSingleKeyModel" value="false"/> -->
<!-- <property name="prettyPrint" value="true"/> -->
<!-- <property name="contentType" value="text/plain"/> -->
</bean>
<bean id="xmlView" class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<!-- <property name="classesToBeBound"> -->
<!-- <list> -->
<!-- <value>com.ly.easyui.model.User</value> -->
<!-- </list> -->
<!-- </property> -->
<property name="packagesToScan">
<value>com.ly.easyui.model</value>
</property>
</bean>
</constructor-arg>

<!--
也可以用XStream解析器 相对应的model类的annotation也要改:类名 @XStreamAlias("user")@ 属性名@XStreamAsAttributeXStreamAlias("id")
XStream有点问题 暂时未解决
<property name="marshaller">
<bean class="org.springframework.oxm.xstream.XStreamMarshaller"/>
</property>
-->
</bean>
</list>
</property>
</bean>


2.controller 注解用restcontroller相当于原来的controller+responsebody
也可以用controller+responsebody

也可以用controller+@RequestMapping (produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})

但是在配置上述步骤1的ContentNegotiatingViewResolver时 不要指定默认的contenttype<property name="defaultContentType" value="text/html" />

发送http://localhost:8090/easyui/view/get/6 此时如下面步骤4返回默认xml数据不同 而是produces 指定的第一个MediaType值  本例即json

package com.ly.easyui.controller;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ly.easyui.model.User;

/**
* 创建时间:2016年5月18日 下午8:44:25
* @author liyong
* 文件名称:ViewController.java
* 类说明: 测试发布rest服务 主要看springmvc.xml中的ContentNegotiatingViewResolver配置
*
* @RestController相当于@Controller+@ResponseBody
*
*/

@RestController
@RequestMapping("/view")
public class ViewController {

@RequestMapping("get/{id}")
public User get(@PathVariable Long id){
User user = new User(id, "u", "p", "order");
return user;
}
}


3.实体User 通过@XmlRootElement注解 当请求为xml数据时
package com.ly.easyui.model;

import java.util.Date;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.ly.easyui.util.CustomDateDeSerializer;
import com.ly.easyui.util.CustomDateSerializer;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;

/**
* 创建时间:2016年1月13日 下午9:42:45
* 项目名称:easyui1.3.4
* @author liyong
* 文件名称:User.java
* 类说明: 通过下面两种方式都可以自定义JackSon序列化Json字符串日期问题
* @JsonSerialize(using = CustomDateSerializer.class)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")

@JsonDeserialize 前台json格式日期字符串反序列化到后台date

默认前台日期字符串和后台Date交互使用springmvc.xml配置文件的默认格式yyyy-MM-dd HH:mm:ss(jackson序列化与反序列化)

<mvc:annotation-driven conversion-service="conversionService">
<!-- 处理responseBody 里面日期类型 -->
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="com.fasterxml.jackson.databind.ObjectMapper">
<property name="dateFormat">
<bean class="java.text.SimpleDateFormat">
<constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss" />
</bean>
</property>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
*/

//http://www.tuicool.com/articles/aYfaqa
@XmlRootElement(name="user")
//@XStreamAlias("user")
public class User extends BaseEntity {

private static final long serialVersionUID = 6775344473251113619L;

// @XStreamAsAttribute
// @XStreamAlias("id")
private Long userId;
// @XStreamAsAttribute
// @XStreamAlias("username")
private String username;
// @XStreamAsAttribute
// @XStreamAlias("password")
private String password;

private Date createDateTime;
private Date createDateTimeStart;
private Date createDateTimeEnd;
private Date modifyDateTime;
private Date modifyDateTimeStart;
private Date modifyDateTimeEnd;
// @XStreamAsAttribute
// @XStreamAlias("order")
private String order;//测试用属性

public User(){

}

public User(Long userId, String username, String password, String order) {
super();
this.userId = userId;
this.username = username;
this.password = password;
this.order = order;
}

@XmlElement(name="uid")
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
@XmlElement
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}

@JsonSerialize(using = CustomDateSerializer.class)
// @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
// @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
public Date getCreateDateTime() {
return createDateTime;
}

@JsonDeserialize(using = CustomDateDeSerializer.class)
public void setCreateDateTime(Date createDateTime) {
this.createDateTime = createDateTime;
}
public Date getCreateDateTimeStart() {
return createDateTimeStart;
}
public void setCreateDateTimeStart(Date createDateTimeStart) {
this.createDateTimeStart = createDateTimeStart;
}
public Date getCreateDateTimeEnd() {
return createDateTimeEnd;
}
public void setCreateDateTimeEnd(Date createDateTimeEnd) {
this.createDateTimeEnd = createDateTimeEnd;
}

//可以自动义配置@JsonSerialize覆盖springmvc配置
// @JsonSerialize(using = CustomDateSerializer.class)
// @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
// @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
public Date getModifyDateTime() {
return modifyDateTime;
}

// @JsonDeserialize(using = CustomDateDeSerializer.class)
public void setModifyDateTime(Date modifyDateTime) {
this.modifyDateTime = modifyDateTime;
}

public Date getModifyDateTimeStart() {
return modifyDateTimeStart;
}
public void setModifyDateTimeStart(Date modifyDateTimeStart) {
this.modifyDateTimeStart = modifyDateTimeStart;
}
public Date getModifyDateTimeEnd() {
return modifyDateTimeEnd;
}
public void setModifyDateTimeEnd(Date modifyDateTimeEnd) {
this.modifyDateTimeEnd = modifyDateTimeEnd;
}

@XmlElement
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String toString() {
return "User [userId=" + userId + ", username=" + username
+ ", password=" + password + ", createDateTime="
+ createDateTime + ", createDateTimeStart="
+ createDateTimeStart + ", createDateTimeEnd="
+ createDateTimeEnd + ", modifyDateTime=" + modifyDateTime
+ ", modifyDateTimeStart=" + modifyDateTimeStart
+ ", modifyDateTimeEnd=" + modifyDateTimeEnd + "]";
}

@XmlElement
public String getOrder() {
return order;
}
public void setOrder(String order) {
this.order = order;
}

}



4.请求http://localhost:8090/easyui/view/get/6 默认返回xml数据如下图



5.请求http://localhost:8090/easyui/view/get/6 并且制定Headers为application/json会返回json数据 如下图



6.当然像上面的请求http://localhost:8090/easyui/view/get/6 可以在6后面加上后缀如6.json或者6.xml 返回相应的数据 如下图



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: