附:實體類javascript
Class : Usercss
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; } }
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------html
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.xmljava
<?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.配置控制器jquery
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.配置視圖web
View : json.jspajax
<%@ 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 : spring
Client : jsonjson
Client : ajax_send_json
Client : ajax_receive_json
啦啦啦
啦啦啦
@ResponseBody//能夠加在方法上或者返回值上 //方法的返回值即請求的響應內容 //會將方法的返回值轉換成json,並響應 public User queryUser(){ User user=new User(1,"lime",new Date()); return user; } *注意:在springMVC將java對象序列化成json時,默認使用的是Jackson :若是就是要使用jackson作序列化,只要導入jackson的jar包便可
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); } });
$.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
啦啦啦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完成。