首頁 web前端 js教程 SpringMVC環境Ajax非同步請求JSON的方法

SpringMVC環境Ajax非同步請求JSON的方法

Apr 04, 2018 pm 04:02 PM
ajax javascript springmvc

這次帶給大家SpringMVC環境Ajax非同步請求JSON的方法,SpringMVC環境Ajax非同步請求JSON的注意事項有哪些,下面就是實戰案例,一起來看一下。

一環境搭建

首先是常規的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.xsd
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://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的映射 -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" /><!-- json转换器 -->
</list>
</property>
</bean>
<mvc:annotation-driven
content-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+xml
html=text/html
json=application/json
xml=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 })
@ResponseBody
public 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");
// 返回请求的username
result.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 )效果如下:

相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

怎麼用ajax傳遞多個參數

建構AJAX實作表單JSON轉換的方法

以上是SpringMVC環境Ajax非同步請求JSON的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

解決jQuery AJAX請求遇到403錯誤的方法 解決jQuery AJAX請求遇到403錯誤的方法 Feb 20, 2024 am 10:07 AM

標題:解決jQueryAJAX請求出現403錯誤的方法及程式碼範例403錯誤是指伺服器禁止存取資源的請求,通常會導致出現這個錯誤的原因是請求缺少權限或被伺服器拒絕。在進行jQueryAJAX請求時,有時會遇到這種情況,本文將介紹如何解決這個問題,並提供程式碼範例。解決方法:檢查權限:首先要確保請求的URL位址是正確的,同時驗證是否有足夠的權限來存取該資

PHP 與 Ajax:建立一個自動完成建議引擎 PHP 與 Ajax:建立一個自動完成建議引擎 Jun 02, 2024 pm 08:39 PM

使用PHP和Ajax建置自動完成建議引擎:伺服器端腳本:處理Ajax請求並傳回建議(autocomplete.php)。客戶端腳本:發送Ajax請求並顯示建議(autocomplete.js)。實戰案例:在HTML頁面中包含腳本並指定search-input元素識別碼。

解決jQuery AJAX請求403錯誤的方法 解決jQuery AJAX請求403錯誤的方法 Feb 19, 2024 pm 05:55 PM

jQuery是一個受歡迎的JavaScript函式庫,用來簡化客戶端端的開發。而AJAX則是在不重新載入整個網頁的情況下,透過發送非同步請求和與伺服器互動的技術。然而在使用jQuery進行AJAX請求時,有時會遇到403錯誤。 403錯誤通常是伺服器禁止存取的錯誤,可能是由於安全性原則或權限問題導致的。在本文中,我們將討論如何解決jQueryAJAX請求遭遇403錯誤

如何解決jQuery AJAX報錯403的問題? 如何解決jQuery AJAX報錯403的問題? Feb 23, 2024 pm 04:27 PM

如何解決jQueryAJAX報錯403的問題?在開發網頁應用程式時,經常會使用jQuery來發送非同步請求。然而,有時在使用jQueryAJAX時可能會遇到錯誤代碼403,表示伺服器禁止存取。這種情況通常是由伺服器端的安全性設定所導致的,但可以透過一些方法來解決這個問題。本文將介紹如何解決jQueryAJAX報錯403的問題,並提供具體的程式碼範例。一、使

如何使用Ajax從PHP方法取得變數? 如何使用Ajax從PHP方法取得變數? Mar 09, 2024 pm 05:36 PM

使用Ajax從PHP方法取得變數是Web開發中常見的場景,透過Ajax可以實作頁面無需刷新即可動態取得資料。在本文中,將介紹如何使用Ajax從PHP方法中取得變量,並提供具體的程式碼範例。首先,我們需要寫一個PHP檔案來處理Ajax請求,並傳回所需的變數。下面是一個簡單的PHP檔案getData.php的範例程式碼:

PHP 與 Ajax:建立動態載入內容的解決方案 PHP 與 Ajax:建立動態載入內容的解決方案 Jun 06, 2024 pm 01:12 PM

Ajax(非同步JavaScript和XML)允許在不重新載入頁面情況下新增動態內容。使用PHP和Ajax,您可以動態載入產品清單:HTML建立一個帶有容器元素的頁面,Ajax請求載入資料後將資料加入到該元素中。 JavaScript使用Ajax透過XMLHttpRequest向伺服器傳送請求,從伺服器取得JSON格式的產品資料。 PHP使用MySQL從資料庫查詢產品數據,並將其編碼為JSON格式。 JavaScript解析JSON數據,並將其顯示在頁面容器中。點選按鈕觸發Ajax請求,載入產品清單。

PHP 與 Ajax:提升 Ajax 安全性的方法 PHP 與 Ajax:提升 Ajax 安全性的方法 Jun 01, 2024 am 09:34 AM

為了提升Ajax安全性,有幾種方法:CSRF保護:產生令牌並將其傳送到客戶端,在請求中新增至伺服器端進行驗證。 XSS保護:使用htmlspecialchars()過濾輸入,防止惡意腳本注入。 Content-Security-Policy頭:限制惡意資源加載,指定允許載入腳本和樣式表的來源。驗證伺服器端輸入:驗證從Ajax請求接收的輸入,防止攻擊者利用輸入漏洞。使用安全Ajax函式庫:利用jQuery等函式庫提供的自動CSRF保護模組。

透過使用Ajax函數實現非同步資料交換的方法 透過使用Ajax函數實現非同步資料交換的方法 Jan 26, 2024 am 09:41 AM

如何利用Ajax函數實現非同步資料互動隨著網路和Web技術的發展,前端與後端之間的資料互動變得十分重要。傳統的資料互動方式,如頁面刷新和表單提交,已經無法滿足使用者的需求。而Ajax(AsynchronousJavaScriptandXML)則成為了實現非同步資料互動的重要工具。 Ajax透過使用JavaScript和XMLHttpRequest對象,使得網

See all articles