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; }
}

  

 

spring mvc: xml生成的更多相关文章

  1. Spring MVC Xml视图解析器

    XmlViewResolver用于在xml文件中定义的视图bean来解析视图名称.以下示例演示如何在Spring Web MVC框架使用XmlViewResolver. XmlViewResolver ...

  2. Spring,SpringMvc配置常见的坑,注解的使用注意事项,applicationContext.xml和spring.mvc.xml配置注意事项,spring中的事务失效,事务不回滚原因

    1.Spring中的applicationContext.xml配置错误导致的异常 异常信息: org.apache.ibatis.binding.BindingException: Invalid ...

  3. spring mvc: xml练习

    xml练习,得到的结果是: <?xml version="1.0" encoding="UTF-8" standalone="yes" ...

  4. spring mvc 自动生成代码

    generator mybaits 详细配置: 目录结构 执行命令 OK git:https://gitee.com/xxoo0_297/generator.git

  5. spring Mvc 执行原理 及 xml注解配置说明 (六)

    Spring MVC 执行原理 在 Spring Mvc 访问过程里,每个请求都首先经过 许多的过滤器,经 DispatcherServlet 处理; 一个Spring MVC工程里,可以配置多个的 ...

  6. Spring MVC入门的实例

      作为Spring MVC入门,以XML配置的方式为例.首先需要配置Web工程的web.xml文件. 代码清单14-1:web.xml配置Spring MVC <?xml version=&q ...

  7. 关于Spring MVC的问题

    一.SpringMVC的流程是什么? 1. 用户发送请求至前端控制器DispatcherServlet: 2. DispatcherServlet收到请求后,调用HandlerMapping处理器映射 ...

  8. Spring MVC MultipartFile实现图片上传

    <!--Spring MVC xml 中配置 --><!-- defaultEncoding 默认编码;maxUploadSize 限制大小--><!-- 配置Multi ...

  9. Spring 4 官方文档学习(十一)Web MVC 框架之配置Spring MVC

    内容列表: 启用MVC Java config 或 MVC XML namespace 修改已提供的配置 类型转换和格式化 校验 拦截器 内容协商 View Controllers View Reso ...

随机推荐

  1. java 多线程 day09 线程池

    import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.c ...

  2. What does Quick Sort look like in Python?

    Let's talk about something funny at first. Have you ever implemented the Quick Sort algorithm all by ...

  3. javascript 闭包 内存

  4. CCF 炉石传说(模拟)

    试题编号: 201612-3 试题名称: 炉石传说 时间限制: 1.0s 内存限制: 256.0MB 问题描述 <炉石传说:魔兽英雄传>(Hearthstone: Heroes of Wa ...

  5. [转]美国最大婚恋交友网站eHarmony的机器学习实践

    转自:http://www.csdn.net/article/2015-03-19/2824267 上周,我去洛杉矶参加了一个机器学习的meetup,一位主讲是eHarmony公司(美国最大的婚恋交友 ...

  6. 安卓 和 IOS 的icon 尺寸

    安卓 36*36 48*48 72*72 96*96 IOS Icon.png – 57×57 iPhone (ios5/6) Icon@2x.png – 114×114 iPhone Retina  ...

  7. Ubuntu下安装keras

    0 系统版本Ubuntu16.04 1 系统更新 sudo apt update sudo apt upgrade 2 安装python基础开发包 sudo apt install -y python ...

  8. NC二次开发常用的方法

    //这张表存放的是所有单据模板的信息表 如果不知道单据模板的信息后可在数据库中查询PUB_BILLTEMPLET//这张表是打印模板的表改模板可以再此表修改pub_print_template//获取 ...

  9. $Python技巧大全

    知乎上有一个问题:Python 有什么奇技淫巧?其中有各种不按套路出牌的招数,也不乏一些惊为天人的"奇技淫巧",会让你大呼:居然还有这种操作??? 本文就是对日常使用过的或者觉得很 ...

  10. 金融即服务(FaaS),将开启场景化金融新格局

    转自: https://www.iyiou.com/p/28494/fs/1 [ 亿欧导读 ] 金融即服务揭示了场景金融的实现路径,通过双向连接做一个开放的系统,按需给客户提供金融服务. 本文系作者在 ...