场景
前面项目已经搭建到SSM中进行注解式和XML配置式事务管理阶段
在此项目基础上搭建使用json进行前后端交互
实现
项目配置
1.引入bootstrap以及jquery
2.配置json中文问题
打开SpringMVC.xml
原来:
<mvc:annotation-driven />
改为:
<mvc:annotation-driven >
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name= "supportedMediaTypes"value="text/plain;charset=UTF-8" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.badao.controller">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- <mvc:annotation-driven /> -->
<mvc:annotation-driven >
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name= "supportedMediaTypes"value="text/plain;charset=UTF-8" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<mvc:default-servlet-handler />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
前端提交后端接受
在WebContent目录下的jsp目录下新建submit.jsp
submit.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
pageContext.setAttribute("APP_PATH", request.getContextPath());
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>用AJAX以JSON方式提交数据</title>
</head>
<script type="text/javascript" src="${APP_PATH }/static/js/jquery-1.12.4.min.js"></script>
<link href="${APP_PATH }/static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
<script src="${APP_PATH }/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
<body>
<form >
<div class="form-group">
<label for="name">用户名</label>
<input type="text" class="form-control" id="name" name ="name" placeholder="name">
</div>
<div class="form-group">
<label for="age">年龄</label>
<input type="number" class="form-control" id="age" name="age" placeholder="age">
</div>
<button type="submit" class="btn btn-default" id="sender">提交</button>
</form>
<div id="messageDiv"></div>
<script>
$('#sender').click(function(){
var name=document.getElementById('name').value;
var age=document.getElementById('age').value;
var user={"name":name,"age":age};
var jsonData = JSON.stringify(user);
var page="submitUser";
$.ajax({
type:"post",
url: page,
data:jsonData,
dataType:"json",
contentType : "application/json;charset=UTF-8",
success: function(result){
}
});
alert("提交成功,请在Tomcat控制台查看服务端接收到的数据");
});
</script>
</body>
</body>
</html>
后台Controller
在userController下新建
@ResponseBody
@RequestMapping("/submitUser")
public String submitUser(@RequestBody User user) {
System.out.println("SSM接受到浏览器提交的json,并转换为User对象:"+user);
return "ok";
}
用于接收json数据
再在UserController下新建
@RequestMapping("testJson")
public ModelAndView testJson(){
ModelAndView mav = new ModelAndView();
// 放入jsp路径
mav.setViewName("submit");
return mav;
}
用于页面跳转
部署运行
将项目部署到服务器,启动服务器输入:
http://localhost:8080/ssmJarTemplate/testJson
输入用户名以及年龄,点击提交
可以看到提示效果
这时看后台输出
这样后台就接受到浏览器提交的json数据并转换成user对象。
前端通过AJAX获得一个User对象并显示
新建前端jsp
在jsp目录下新建getOneUser.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
pageContext.setAttribute("APP_PATH", request.getContextPath());
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>用AJAX以JSON方式提交数据</title>
</head>
<script type="text/javascript" src="${APP_PATH }/static/js/jquery-1.12.4.min.js"></script>
<link href="${APP_PATH }/static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
<script src="${APP_PATH }/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
<body>
<input type="button" class="btn btn-success" value="通过AJAX获取一个User对象---" id="sender">
<div id="messageDiv" class="alert alert-success" role="alert"></div>
<script>
$('#sender').click(function(){
var url="getOneUser";
$.post(
url,
function(data) {
var json=JSON.parse(data);
var name =json.user.name;
var id = json.user.id;
var age = json.user.age;
$("#messageDiv").html("用户id:"+ id + "<br>用户名称:" +name+"<br>用户年龄:"+age );
});
});
</script>
</body>
</html>
编写后台Controller
在userController下新建getOneUser模拟从数据库查询一个User对象并返回给前段并返回给前端
@ResponseBody
@RequestMapping("/getOneUser")
public String getOneUser() {
User user = new User();
user.setId(100);
user.setName("第100个用户");
user.setAge(100);
JSONObject json= new JSONObject();
json.put("user", JSONObject.toJSON(user));
return json.toJSONString();
}
修改上面的testJson请求方法,用于跳转到jsp页面到getOneUser.jsp
@RequestMapping("testJson")
public ModelAndView testJson(){
ModelAndView mav = new ModelAndView();
// 放入jsp路径
mav.setViewName("getOneUser");
return mav;
}
将项目部署到服务器,部署到服务器,启动服务器,输入:
http://localhost:8080/ssmJarTemplate/testJson
点击按钮后
通过AJAX请求后台获取多个User
新建jsp页面
在jsp目录下新建getManyUser.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
pageContext.setAttribute("APP_PATH", request.getContextPath());
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>用AJAX以JSON方式提交数据</title>
</head>
<script type="text/javascript" src="${APP_PATH }/static/js/jquery-1.12.4.min.js"></script>
<link href="${APP_PATH }/static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
<script src="${APP_PATH }/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
<body>
<input type="button" class="btn btn-success" value="通过AJAX获取多个user对象" id="sender">
<div id="messageDiv" class="alert alert-success" role="alert"></div>
<script>
$('#sender').click(function(){
var url="getManyUser";
$.post(
url,
function(data) {
console.log(data);
var users = $.parseJSON(data);
console.log(users.length);
for(i in users){
var old = $("#messageDiv").html();
var user = users[i];
$("#messageDiv").html(old + "<br>"+user.id+" ----- "+user.name+" ----- "+user.age);
}
});
});
</script>
</body>
</html>
新建Controller
在userControler下新建getManyUser用来模拟从数据库查询多个User对象返回一个list
@ResponseBody
@RequestMapping("/getManyUser")
public String getManyUser() {
List<User> us = new ArrayList<>();
for (int i = 0; i < 10; i++) {
User user = new User();
user.setId(i);
user.setName("用户名称:"+i);
user.setAge(i+1);
us.add(user);
}
return JSONObject.toJSON(us).toString();
}
修改前面的testJson实现页面跳转到getManyUser.jsp
@RequestMapping("testJson")
public ModelAndView testJson(){
ModelAndView mav = new ModelAndView();
// 放入jsp路径
mav.setViewName("getManyUser");
return mav;
}
部署项目
将项目部署到服务器,启动服务器,浏览器输入:
http://localhost:8080/ssmJarTemplate/testJson
点击按钮