欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringMVC环境下实现的Ajax异步请求JSON格式数据

程序员文章站 2022-05-18 12:59:51
一 环境搭建 首先是常规的spring mvc环境搭建,不用多说,需要注意的是,这里需要引入jackson相关jar包,然后在spring配置文件“springmvc-s...

一 环境搭建

首先是常规的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>

项目结构:

SpringMVC环境下实现的Ajax异步请求JSON格式数据

注:我这里测试使用的完整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)效果如下:

SpringMVC环境下实现的Ajax异步请求JSON格式数据

以上所述是小编给大家介绍的springmvc环境下实现的ajax异步请求json格式数据的相关内容,希望对大家有所帮助!