附:实体类

Class : User

package com.c61.entity;

import java.text.SimpleDateFormat;
import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; import com.alibaba.fastjson.annotation.JSONField; public class User {
private Integer id;
private String name;
//@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern="yyyy-MM-dd")//定制在接收请求参数时的日期格式
@JSONField(format="yyyy-MM-dd")//作用在java序列化成json时
private Date birth;
private String dateStr; public String getDateStr() {
return dateStr;
}
public void setDateStr(String dateStr) {
this.dateStr = dateStr;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
this.dateStr=format.format(birth);
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", birth=" + birth + "]";
}
public User(){}
public User(Integer id, String name, Date birth) {
super();
this.id = id;
this.name = name;
this.birth = birth;
} }

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

1.配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list> <!-- 前端控制器
/=默认的url-pattern
/a/b/c /a /a/d/c
/a/d
/a
/
*注意:此控制器默认加载/WEB-INF下的xxx-servlet.xml文件
:其中xxx等于【DispatcherServlet的配置名】
-->
<servlet>
<servlet-name>mvc61</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:mvc62.xml</param-value>
</init-param>
<!-- 随项目启动而启动 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc61</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> <!-- 专治Post请求参数乱码 -->
<filter>
<filter-name>encoding61</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!-- 将请求的编码方式设置为utf-8 -->
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding61</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

2.配置SpringMVC.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- xmlns:xml name space 是每一个schema唯一标识 -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <!-- 扫描所有控制器中的注解 -->
<context:component-scan base-package="com.c61.controller"></context:component-scan>
<!--
MVC中基于注解开发,导入注解驱动
-->
<mvc:annotation-driven></mvc:annotation-driven>
</beans>

3.配置控制器

package com.c61.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import com.c61.entity.User; @Controller
@RequestMapping(value="/mvc5")//等价于namespace
public class JSONController {
/**
* 响应json
* @return
*/
@RequestMapping("/json")//等价于<action name="mvc1"
@ResponseBody//可以加载方法上或者返回值上
//方法的返回值即请求的响应内容
//会将方法的返回值转换成json,并响应
public User queryUser(){
User user=new User(1,"lime",new Date());
return user;
} @RequestMapping("/jsons")//等价于<action name="mvc1"
@ResponseBody//可以加载方法上或者返回值上
//方法的返回值即请求的响应内容
//会将方法的返回值转换成json,并响应
public List<User> queryUsers(){
User user1=new User(1,"lime1",new Date());
User user2=new User(1,"lime2",new Date());
User user3=new User(1,"lime3",new Date());
List<User> users=new ArrayList<User>();
users.add(user1);
users.add(user2);
users.add(user3);
return users;
} @RequestMapping("/json2")//等价于<action name="mvc1"
@ResponseBody
//@RequestBody:将请求体中的数据取出,解析成java对象,赋值给对应参数
public String testJson(@RequestBody User user){
System.out.println(user);
return "ok";
}
}

4.配置视图

View : json.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function(){
$("#json2").click(function(){
$.ajax({
url:"${pageContext.request.contextPath}/mvc5/json2",
type:"post",
data:'{"id":1,"name":"limeOracle3","birth":"2016-09-29"}',
contentType:"application/json",//请求数据类型为json
success:function(ret){
alert(ret);
}
});
});
$("#json").click(function(){
$.ajax({
url:"${pageContext.request.contextPath}/mvc5/json",
type:"post",
success:function(ret){//由于springMVC在响应json时会设置响应头:application/json,
//则ret已经时解析后的js对象
alert(ret.id+" "+ret.name+" "+ret.birth);
}
});
});
});
</script>
</head> <body>
<a href="${pageContext.request.contextPath}/mvc5/jsons">json</a>
<input type="button" value="ajax_send_json" id="json2"/>
<input type="button" value="ajax_receive_json" id="json"/>
</body>
</html>

Client :

Client : json

Client : ajax_send_json

Client : ajax_receive_json

啦啦啦

啦啦啦

6.1 springMVC向客户端响应一个json : @ResponseBody

6.1.1 使用方式

@ResponseBody//可以加在方法上或者返回值上
//方法的返回值即请求的响应内容
//会将方法的返回值转换成json,并响应
public User queryUser(){
User user=new User(1,"lime",new Date());
return user;
}
*注意:在springMVC将java对象序列化成json时,默认使用的是Jackson
:如果就是要使用jackson做序列化,只要导入jackson的jar包即可

6.1.2 springMVC响应json细节

springMVC在响应json时会设置响应头为:application/json,
响应头可以告知客户端响应数据的格式为json
所以在异步请求中,不用在定制【dataType:"json"】
$.ajax({
url:"${pageContext.request.contextPath}/mvc5/json",
type:"post",
success:function(ret){//由于springMVC在响应json时会设置响应头:application/json,
//则【$.ajax】会解析响应值,则ret已经是解析后的js对象
alert(ret.id+" "+ret.name+" "+ret.birth);
}
});

6.2 springMVC接收客户端发送来的json数据:@RequestBody

$.ajax({
url:"${pageContext.request.contextPath}/mvc5/json2",
type:"post",
data:'{"id":1,"name":"limeOracle3","birth":"2016-09-29"}',
contentType:"application/json",//请求数据类型为json
success:function(ret){
alert(ret);
}
});
//@RequestBody:将请求体中的数据取出,解析成java对象,赋值给对应参数
public String testJson(@RequestBody User user){
System.out.println(user);
return "ok";
}
*注意,@RequestBody需要jdk7,需要更换tomcat的jdk

6.3 springMVC更换JSON处理方案:由jackson换成fastjson

1>导入fastjson的jar
2>配置:
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<!-- 支持的格式:application/json -->
<value>application/json</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
3>如此则springMVC中使用@ResponseBody 和 @RequestBody时,需要做的json序列化和反序列化都由fastjson完成。
啦啦啦

SpringMVC -- 梗概--源码--壹--springMVC json处理的更多相关文章

  1. SpringMVC -- 梗概--源码--壹--数据传递

    附:实体类 Class : User package com.c61.entity; import java.text.SimpleDateFormat; import java.util.Date; ...

  2. SpringMVC -- 梗概--源码--壹--收参

    附:实体类 Class : User package com.c61.entity; import java.text.SimpleDateFormat; import java.util.Date; ...

  3. SpringMVC -- 梗概--源码--壹--跳转

    1.配置web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app version=&qu ...

  4. SpringMVC -- 梗概--源码--贰--下载

    1.配置web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app version=&qu ...

  5. SpringMVC -- 梗概--源码--贰--上传

    1.配置web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app version=&qu ...

  6. SpringMVC -- 梗概--源码--贰--拦截器:Interceptor

    附:实体类 1.配置web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app versi ...

  7. SpringMVC -- 梗概--源码--贰--异常管理

    附:实体类 Class : User package com.c61.entity; import java.text.SimpleDateFormat; import java.util.Date; ...

  8. SpringMVC -- 梗概--源码--贰--RestFul收参(了解) @PathVariable

    1>定制方式: //如下两个路径都可以访问到如下方法,请求路径不同,则name61和pwd61匹配到的值不同 //http://localhost:8989/appname/ful/lime/1 ...

  9. SpringMVC -- 梗概--源码--贰--mvc:annotation-driven

    1>在springMVC的处理流程中,有两个重要组件:HandlerMapping和HandlerAdapter 分别负责解析Handler和执行Handler 2>如果配置了<mv ...

随机推荐

  1. .net dll类库 生成chm说明文档

    效果图: 制作步骤: 1.下载Sandcastle http://shfb.codeplex.com/releases/view/105809 2.下载Html Help WorkShop http: ...

  2. 解析Google集群资源管理系统Omega

    1. 背景 Google的第一代/第二代集群(资源)管理系统被称为Borg,Borg设计细节因零零星星出现在各种文章中而知名,但一直未公开(比如发一篇paper).然而,我们可从腾讯公布的Torca( ...

  3. 半个月使用rust语言的体验

    从第一次下载rust语言的编译器到今天刚好第14天. 简单说一下对这个语言的感觉吧. 一.性能 把以前用java写的一个中文地址切分的算法,用rust重新实现了一下(https://github.co ...

  4. Java中的this和super

    在Java中有两个非常特殊的变量:this和super,这两个变量在使用前都是不需要声明的.this变量使用在一个成员函数的内部,指向当前对象,当前对象指的是调用当前正在执行方法的那个对象.super ...

  5. Python 内置方法new

    class Dog(object): def __new__(self): print("i am new .") def __init__(self): print(" ...

  6. Android 软键盘弹出与关闭监听

    private void listenerSoftInput() { final View activityRootView = findViewById(R.id.activityRoot); ac ...

  7. android地址位置

    有精度纬度确定地理位置 latitude: 23.1352888---longitude: 113.3297445 调用Google API接口: URL: http://maps.google.cn ...

  8. unity---------------------关于BuildAssetBundles的使用(打包)

    using UnityEditor;using UnityEngine; public class BuildAssetBundle{ /// <summary> /// 点击后,所有设置 ...

  9. 目标跟踪之meanshift---meanshift2

    均值漂移,可以对非刚性物理进行跟踪,是分参数估计,过程是迭代的过程,对光和形态不敏感,缺点是检测目标是固定的,特征不较少,模板背景没有实时更新,没有目标的位置精度预测只是梯度浓聚, 原理: 用文字标书 ...

  10. C#常用数据类型间的转换

    数据类型有很多种,数据类型间的转换也是有很多的方法,如果不细心整理的话等到用的时候再查就会显得很浪费时间,所以决心整理出这篇博文.主要是讲解常用数据类型之间的转换方法以及常见数据类型所占字节数. 字节 ...