使用原生JavaScriptAjax以及jQuery的Ajax结合SpringMVC发送和获取json数据

一.原生Ajax

1.在WEB-INF/lib目录中加入spring和json与Jackson的jar文件,json与Jackson的jar文件如下:


2.配置web.xml文件:配置前端控制器

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SpringMVC_1</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
  <servlet-name>springmvc</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
  	<param-name>contextConfigLocation</param-name>
  	<param-value>classpath:springmvc.xml</param-value>
  </init-param>
  <!-- 让servlet随服务启动 -->
  <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
  <servlet-name>springmvc</servlet-name>
  <url-pattern>*.action</url-pattern>
  </servlet-mapping>
</web-app>

3.配置SpringMVC的xml文件:springmvc.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:tx="http://www.springframework.org/schema/tx" 
	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.1.xsd
  		http://www.springframework.org/schema/mvc
  		http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
  		http://www.springframework.org/schema/context
  		http://www.springframework.org/schema/context/spring-context-4.1.xsd">
	<!-- 将注解的类,扫描加载 -->
	<context:component-scan base-package="com.controller"/>
	<!-- 注解的映射器和适配器,对类中使用了@RequestMapping标志的方法进行映射和适配
	<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
	<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>-->
	<!-- 实际开发中使用<mvc:annotation-driven/>代替注解适配器和映射器 -->
	<mvc:annotation-driven/>
	<!-- 加载静态文件 -->
	<mvc:default-servlet-handler/>
	<!-- 配置视图解析器 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- 前缀 -->
		<property name="prefix">
			<value>/WEB-INF/</value>
		</property>
		<!-- 后缀 -->
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>

</beans>


4.编写实体类:Users.java


package com.beans;

public class Users {
	private Integer id;
	private String name;
	public Users() {
		// TODO Auto-generated constructor stub
	}
	public Users(Integer id,String name) {
		this.id = id;
		this.name = name;
	}
	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;
	}

}

5.编写前端html和Ajax代码:


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<table>
<tr>
<button οnclick="show()">获取</button>
<td>编号</td>
<td>姓名</td>
</tr>
<tr>
<td id="id"></td>
<td id="name"></td>
</tr>
</table>
</body>
</html>
<script type="text/javascript">
	function show() {
		//使用ajax的步骤
		var xmlhttp;//定义用于实现和服务器交互的变量
		if (window.XMLHttpRequest) {//code for IE7+,Firefox,Chrome,Opera,Safari
			xmlhttp = new XMLHttpRequest();
		} else {//code for IE6,IE5
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {//请求成功时的操作
				//document.getElementById("msg").innerHTML=xmlhttp.responseText;
				var str = xmlhttp.responseText;
				var obj = JSON.parse(str);
				document.getElementById("id").innerHTML = obj.id;
				document.getElementById("name").innerHTML = obj.name;
				
				//alert(txt.trim());
			}
		}
		xmlhttp.open("POST", "post.action", true);//建立和服务器的连接,true是异步
		xmlhttp.setRequestHeader("Content-type","application/json;charset=utf-8");
		var data = JSON.stringify({
			"id": 1,
			"name" : "zhangsan"
		});
		
		xmlhttp.send(data);//发送请求
	}
</script>

6.编写处理类handler:MyHandler.java


package com.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import com.beans.Users;

import net.sf.json.JSONObject;


@Controller
public class MyHandler {
	
	@RequestMapping("/post")
	public void returnBack2(@RequestBody Users user,HttpServletResponse response) throws IOException{
		JSONObject json = JSONObject.fromObject(user);
		response.getWriter().println(json.toString());
	}
}

二.jQuery的Ajax

1.导入jar包以及web.xml、springmvc.xml的配置同上面原生Ajax。在WebContent下新建一个名为js的文件夹,向其中导入使用jQuery以及json2的需要用到的js文件,比如jquery-1.11.1.min.js和json2.js:


2.编写实体类:Book.java


package com.domain;

import java.io.Serializable;

public class Book implements Serializable{

	private Integer id;
	private String name;
	private String author;
	public Book() {
		// TODO Auto-generated constructor stub
	}
	public Book(Integer id,String name, String author) {
		this.id = id;
		this.name = name;
		this.author = 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 + "]";
	}
	
}

3.编写html和jQuery代码:


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<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.1.min.js"></script>
<script type="text/javascript" src="js/json2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
	$("#btn").click(testRequestBody);
});
function testRequestBody(){
	$.ajax("testRequestBody.action",
	{
		dataType : "json",
		type : "post",
		contentType : "application/json",
		data : JSON.stringify({"id" : 1, "name" : "Spring MVC学习"}),
		async : true,
		success : function(data){
			console.log(data);
			$("#id").html(data.id);
			$("#name").html(data.name);
			$("#author").html(data.author);
		},
		error:function(){
			alert("数据发送失败");
		}
	});
}
</script>
</head>
<body>
<button id="btn">点击获取</button><br>
编号:<span id="id"></span><br>
书名:<span id="name"></span><br>
作者:<span id="author"></span><br>
</body>
</html>

4.编写处理类handler:BookController.java



package com.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import com.domain.Book;
import com.fasterxml.jackson.databind.ObjectMapper;

@Controller
public class BookController {

	private static final Log logger = LogFactory.getLog(BookController.class);
	
	@RequestMapping("/testRequestBody")
	public void setJson(@RequestBody Book book,HttpServletResponse response) throws IOException{
		ObjectMapper mapper = new ObjectMapper();
		logger.info(mapper.writeValueAsString(book));
		book.setAuthor("张三");
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().println(mapper.writeValueAsString(book));
	}
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值