SpringMVC環境下實現的Ajax非同步請求JSON格式資料_AJAX相關

來源:互聯網
上載者:User

一 環境搭建

首先是常規的spring mvc環境搭建,不用多說,需要注意的是,這裡需要引入jackson相關jar包,然後在spring設定檔“springmvc-servlet.xml”中添加json解析相關配置,我這裡的完整代碼如下:

<?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:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"><!-- 避免IE執行AJAX時,返回JSON出現下載檔案 --><bean id="mappingJacksonHttpMessageConverter"class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"><property name="supportedMediaTypes"><list><value>text/html;charset=UTF-8</value><value>application/json;charset=UTF-8</value></list></property><property name="objectMapper"><bean class="org.codehaus.jackson.map.ObjectMapper"><property name="dateFormat"><bean class="java.text.SimpleDateFormat"><constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss"></constructor-arg></bean></property></bean></property></bean><!-- 啟動Spring MVC的註解功能,完成請求和註解POJO的映射 --><beanclass="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"><property name="messageConverters"><list><ref bean="mappingJacksonHttpMessageConverter" /><!-- json轉換器 --></list></property></bean><mvc:annotation-drivencontent-negotiation-manager="contentNegotiationManager" /><bean id="contentNegotiationManager"class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean"><!-- true,開啟副檔名支援,false關閉支援 --><property name="favorPathExtension" value="false" /><!-- 用於開啟 /userinfo/123?format=json的支援 --><property name="favorParameter" value="true" /><!-- 設定為true以忽略對Accept Header的支援 --><property name="ignoreAcceptHeader" value="false" /><property name="mediaTypes"><value>atom=application/atom+xmlhtml=text/htmljson=application/jsonxml=application/xml*=*/*</value></property></bean><context:annotation-config /><!-- 啟動自動掃描該包下所有的Bean(例如@Controller) --><context:component-scan base-package="cn.zifangsky.controller" /><mvc:default-servlet-handler /><!-- 定義視圖解析器 --><bean id="jspViewResolver"class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="requestContextAttribute" value="rc" /><property name="viewClass"value="org.springframework.web.servlet.view.JstlView" /><property name="prefix" value="/WEB-INF/jsp/" /><property name="suffix" value=".jsp" /><property name="order" value="1"></property></bean></beans>

項目結構:

註:我這裡測試使用的完整jar包:http://pan.baidu.com/s/1dEUwdmL

二 測試執行個體

(1)在WEB-INF/jsp目錄下建立了一個index.jsp檔案,包含了簡單的jQuery的ajax請求,請求資料的格式是JSON,具體代碼如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()+ path + "/";%><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><base href="<%=basePath%>"><script type="text/javascript" src="scripts/jquery/jquery-1.6.2.min.js"></script><script type="text/javascript" src="scripts/jquery/jquery.i18n.properties-min-1.0.9.js"></script><script type="text/javascript" src="scripts/jquery/jquery.autocomplete.js"></script><script type="text/javascript" src="scripts/jquery/jquery.loadmask.js"></script><script type="text/javascript" src="scripts/jquery/jquery.form.js"></script><script type="text/javascript" src="scripts/jquery/jquery.timers.js"></script><title>jQuery i18n</title><script type="text/javascript">$().ready(function() {$("#sub").click(function() {var name = $("#username").val();var age = 18;var user = {"username":name,"age":age};$.ajax({url : 'hello.json',type : 'POST',data : JSON.stringify(user), // Request body contentType : 'application/json; charset=utf-8',dataType : 'json',success : function(response) {//請求成功alert("你好" + response.username + "[" + response.age + "],目前時間是:" + response.time + ",歡迎訪問:http://www.zifangsky.cn");},error : function(msg) {alert(msg);}});});});</script></head><body><input type="text" id="username"style="width: 100px; height: 30px; font-size: 20px; font-weight: bold;"><input type="button" id="sub" value="Go"style="height: 40px; height: 30px;"><br></body></html>

(2)一個簡單的model類User,代碼如下:

package cn.zifangsky.controller;public class User {private String username;private int age;public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}

(3)controller類TestController.java:

package cn.zifangsky.controller;import java.text.Format;import java.text.SimpleDateFormat;import java.util.Date;import java.util.HashMap;import java.util.Map;import org.springframework.context.annotation.Scope;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.RequestMethod;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.servlet.ModelAndView;@Controller@Scope("prototype")public class TestController {/*** 轉到頁面*/@RequestMapping(value = "/hello.html")public ModelAndView list() {ModelAndView view = new ModelAndView("index");return view;}/*** ajax非同步請求, 請求格式是json*/@RequestMapping(value = "/hello.json", method = { RequestMethod.POST })@ResponseBodypublic Map<String, String> hello(@RequestBody User user) {// 返回資料的Map集合Map<String, String> result = new HashMap<String, String>();Format format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 返回請求的usernameresult.put("username", user.getUsername());// 返回年齡result.put("age", String.valueOf(user.getAge()));// 返回目前時間result.put("time", format.format(new Date()));return result;}}

關於具體的執行步驟我簡單說一下:

i)項目啟動後,在瀏覽器中訪問:http://localhost:8089/SpringDemo/hello.html,然後會轉到執行controller中的list方法,接著會轉到/WEB-INF/jsp/index.jsp(PS:在controller中返回的是邏輯視圖,跟在springmvc-servlet.xml檔案中定義的路徑首碼和尾碼進行拼接後合成檔案的真正路徑)

ii)在index.jsp頁面輸入文字然後點擊按鈕,將會觸發ajax請求,這個請求會擷取輸入框中的資料和預設的“age”參數拼接成json格式字串最後提交到“hello.json”這個請求,也就是執行controller中的hello方法

iii)hello方法執行完畢後會返回一系列資料最後在頁面中顯示出來

(4)效果如下:

以上所述是小編給大家介紹的SpringMVC環境下實現的Ajax非同步請求JSON格式資料的相關內容,希望對大家有所協助!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.