spring mvc: xml生成
准备:
javax.xml.bind.annotation.XmlElement;
javax.xml.bind.annotation.XmlRootElement;
spring类:
org.springframework.web.bind.annotation.PathVariable;
org.springframework.web.bind.annotation.ResponseBody;
@PathVariable 映射 URL 绑定的占位符
- 带占位符的 URL 是 Spring3.0 新增的功能,该功能在SpringMVC 向 REST 目标挺进发展过程中具有里程碑的意义
- 通过 @PathVariable 可以将 URL 中占位符参数绑定到控制器处理方法的入参中:URL 中的 {xxx} 占位符可以通过@PathVariable(“xxx“) 绑定到操作方法的入参中。
//@PathVariable可以用来映射URL中的占位符到目标方法的参数中
@RequestMapping("/testPathVariable/{id}")
public String testPathVariable(@PathVariable("id") Integer id)
{
System.out.println("testPathVariable:"+id);
return SUCCESS;
}
@ResponseBody用法
作用:
- 该注解用于将Controller的方法返回的对象,根据HTTP Request Header的
Accept
的内容,通过适当的HttpMessageConverter
转换为指定格式后,写入到Response对象的body数据区。
使用时机:
- 返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用.
配置返回JSON和XML数据
- 添加
jackson
依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.1</version>
</dependency>
-
开启
<mvc:annotation-driven />
-
java代码为
@RequestMapping("/testResponseBody")
public @ResponseBody
Person testResponseBody() {
Person p = new Person();
p.setName("xiaohong");
p.setAge(12);
return p;
}
Person类
@XmlRootElement(name = "Person")
public class Person {
private String name;
private int age;
public String getName() { return name; }
@XmlElement
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
@XmlElement
public void setAge(int age) { this.age = age; }
}
- Ajax代码
$.ajax({
url: "testResponseBody",
type: 'GET',
headers: {
Accept: "application/xml",
// Accept:"application/json",
},
success: function(data, textStatus){
console.log(data);
alert(data);
},
error: function (data, textStatus, errorThrown) {
console.log(data);
},
});
分析
-
如果没有配置
Person
类的XML注解,那么只会JSON
数据,无论Accept
是什么, -
如果配置了
Person
类的xml注解,那么如果Accept
含有applicatin/xml
, 就会返回xml数据.例如通过浏览器直接访问,浏览器的http request header appect字段
一般都为Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
, 故返回XML数据.
改accept: "application/json"
,即可返回JSON数据.
用此注解或者ResponseEntity等类似类, 会导致response header
含有accept-charset
这个字段,而这个字段对于响应头是没有用的,以下方法可以关掉
<mvc:annotation-driven>
<mvc:async-support default-timeout="3000"/>
<!-- utf-8编码 -->
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
<property name="writeAcceptCharset" value="false"/>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
开始:
本例有三个配置文件:web.xml, applicationContent.xml, xml2-servlet.xml
访问地址:
http://localhost:8080/gugua3/user/bagayalu
项目: gugua3
包名:xml2
web.xml:
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!--配置文件路径-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<!-- 字符过滤器 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 监听转发 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>xml2</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>xml2</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
applicationContent.xml
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 默认:注解映射支持 -->
<mvc:annotation-driven/>
<!-- 静态资源配置 -->
<mvc:resources location="/pages/**" mapping="/pages/"/>
<!-- 自动扫描包名,controller -->
<context:component-scan base-package="xml2"/>
</beans>
xml2-servlet.xml
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
</beans>
User.java
package xml2;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class User {
String name;
Integer id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
UserController.java
package xml2;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.PathVariable;
@Controller
@RequestMapping(value="/user")
public class UserController {
@RequestMapping(value="{name}", method=RequestMethod.GET)
public @ResponseBody User getUser(@PathVariable String name)
{
User user = new User();
user.setName(name);
user.setId(10);
return user;
}
}