1.搭建SpringMVC+Spring環境javascript
2.配置web.xml、SpringMVC-config.xmlhtml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <!-- 定義Spring MVC的前端控制器 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/springmvc-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- 讓Spring MVC的前端控制器攔截全部請求 --> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 編碼過濾器 --> <filter> <filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
<?xml version="1.0" encoding="UTF-8"?> <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-4.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"> <!-- spring能夠自動去掃描base-pack下面的包或者子包下面的java文件, 若是掃描到有Spring的相關注解的類,則把這些類註冊爲Spring的bean --> <context:component-scan base-package="Controller"/> <!-- 設置配置方案 --> <mvc:annotation-driven/> <!-- 使用默認的Servlet來響應靜態文件 --> <mvc:default-servlet-handler/> <!-- 視圖解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 前綴 --> <property name="prefix"> <value>/WEB-INF/content/</value> </property> <!-- 後綴 --> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans>
3.controller層前端
@Controller @RequestMapping("/json") public class BookController { private static final Log logger = LogFactory.getLog(BookController.class); // @RequestBody根據json數據,轉換成對應的Object @RequestMapping(value="/testRequestBody") public void setJson(@RequestBody Book book, HttpServletResponse response) throws Exception{ // ObjectMapper類是Jackson庫的主要類。它提供一些功能將Java對象轉換成對應的JSON格式的數據 ObjectMapper mapper = new ObjectMapper(); // 將book對象轉換成json輸出 logger.info(mapper.writeValueAsString(book) ); book.setAuthor("jackson"); response.setContentType("text/html;charset=UTF-8"); // 將book對象轉換成json寫出到客戶端 response.getWriter().println(mapper.writeValueAsString(book)); } }
4.實體類java
public class Book implements Serializable { private Integer id; private String name; private String author; 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 String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } @Override public String toString() { return "Book [id=" + id + ", name=" + name + ", author=" + author + "]"; } }
5.表現層jquery
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>測試接收JSON格式的數據</title> <script type="text/javascript" src="js/jquery-1.11.0.min.js"></script> <script type="text/javascript" src="js/json2.js"></script> <script type="text/javascript"> $(document).ready(function(){ testRequestBody(); }); function testRequestBody(){ $.ajax(//"${pageContext.request.contextPath}/json/testRequestBody",// 發送請求的URL字符串。 { url:"${pageContext.request.contextPath}/json/testRequestBody", dataType : "jsonp", // 預期服務器返回的數據類型。 type : "post", // 請求方式 POST或GET contentType:"application/json", // 發送信息至服務器時的內容編碼類型 // 發送到服務器的數據。 data:JSON.stringify({"id" : 1, "name" : "Spring MVC企業應用實戰"}), async: true , // 默認設置下,全部請求均爲異步請求。若是設置爲false,則發送同步請求 // 請求成功後的回調函數。 success :function(data){ // console.log(data); // data=eval('('+data+')'); $("#id").html(data.id); $("#name").html(data.name); $("#author").html(data.author); }, // 請求出錯時調用的函數 error:function(XMLHttpRequest, textStatus, errorThrown){ alert(XMLHttpRequest.status); alert(XMLHttpRequest.readyState); alert(textStatus); } }); } </script> </head> <body> 編號:<span id="id"></span><br> 書名:<span id="name"></span><br> 做者:<span id="author"></span><br> </body> </html>
運行結果:web