SpringMVC環境に実装されたJSON形式データのAjax非同期リクエスト

亚连
リリース: 2018-05-24 10:27:33
オリジナル
1419 人が閲覧しました

この記事では、Spring MVC 環境に実装されている JSON 形式データの Ajax 非同期リクエストの関連情報を主に紹介しますので、必要な方は参考にしてください

1 つの環境構築

1 つ目は、従来の Spring MVC 環境です。構築、これ以上行う必要はありません。ここでは、ジャクソン関連の jar パッケージを導入する必要があることに注意してください。その後、json 解析関連の設定が Spring 設定ファイル「springmvc-servlet.xml」に追加されます。これは次のとおりです:

<?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>
ログイン後にコピー

プロジェクトの構造:

2つのテスト例

(1) WEB-INF/jspディレクトリに新しいindex.jspファイルを作成します。これには、単純なjQuery ajaxが含まれています。 request データの形式は 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 : &#39;hello.json&#39;,
type : &#39;POST&#39;,
data : JSON.stringify(user), // Request body 
contentType : &#39;application/json; charset=utf-8&#39;,
dataType : &#39;json&#39;,
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) 単純なモデル クラス 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) コントローラー クラス 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) プロジェクトが開始された後、ブラウザーで Visit: http://localhost:8089/SpringDemo/hello.html にアクセスすると、リスト メソッドに移動します。コントローラにアクセスし、/WEB-INF/jsp/index.jsp に移動します (PS: コントローラ内で返されるのは、パスのプレフィックスとサフィックスで結合された後のファイルの実際のパスである論理ビューです) springmvc-servlet.xml ファイルで定義されています)

ii) Index.jsp ページにテキストを入力し、ボタンをクリックすると、Ajax リクエストがトリガーされます。このリクエストは、入力ボックス内のデータとデフォルトの「年齢」を取得します。パラメーターを指定して json 形式の文字列に結合し、最後にコントローラーで hello メソッドを実行する「hello.json」リクエストに送信します

iii) hello メソッドが実行されます 一連のデータが返され、最後にページ上に表示されます

(4) 効果は以下の通りです。

以上、皆様のお役に立てれば幸いです。

関連記事:

Ajaxリクエストテクノロジーについての簡単な説明

Ajaxローディング菊ローディング効果

非常に実用的なAjaxユーザー登録モジュール

以上がSpringMVC環境に実装されたJSON形式データのAjax非同期リクエストの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

関連ラベル:
ソース:php.cn
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
最新の問題
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!