1、创建spring-web-mvc.xml
?配置自动扫描的包
? ? ? ? com.atguigu.crowd.mvc是存放controller的地方
<!--配置自动扫描的包-->
<context:component-scan base-package="com.atguigu.crowd.mvc"/>
配置MVC注解驱动:
<!--配置springMVC注解驱动-->
<mvc:annotation-driven/>
配置视图解析器:
? ? ? ? prefix:代表前缀
? ? ? ? suffix:代表后缀? value是其中的值
<!--配置视图解析器-->
<bean id="resolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/"/>
<property name="suffix" value=".jsp"/>
</bean>
spring-web-mvc.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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tool http://www.springframework.org/schema/tool/spring-tool.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--配置自动扫描的包-->
<context:component-scan base-package="com.atguigu.crowd.mvc"/>
<!--配置springMVC注解驱动-->
<mvc:annotation-driven/>
<!--配置视图解析器-->
<bean id="resolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
2、测试SSM整合
? ? ? ? index.jsp:
<html>
<head>
<title>Title</title>
<%--http://localhost:8888/index.jsp--%>
<base href="http://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}/"/>
<script type="text/javascript" src="jquery/jquery-2.1.1.min.js"></script>
</head>
<body>
<h1>Hello!!!</h1>
<a href="test/ssm.html">测试</a><br>
</body>
</html>
target.jsp
? ? ? ? WEB-INF下创建target.jsp?
代码如下:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>Hi,you are success!</h1>
${requestScope.admins}
</body>
</html>
? ? ? ? 在mvc下的controller创建TestController:
TestController中的代码如下:
package com.atguigu.crowd.mvc.controller;
import com.atguigu.crowd.entity.Admin;
import com.atguigu.crowd.service.api.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@Controller
public class TestController {
@Autowired
private AdminService adminService;
@RequestMapping(value = "/test/ssm.html")
public String testController01(Model model){
List<Admin> admins= adminService.getAll();
model.addAttribute("admins",admins);
System.out.println(admins);
return "target";
}
}
?service中api以及impl代码如下
? ? ? ? AdminService
package com.atguigu.crowd.service.api;
import com.atguigu.crowd.entity.Admin;
import java.util.List;
public interface AdminService {
//保存
void saveAdmin(Admin admin);
//查询所有管理员信息
List<Admin> getAll();
}
????????AdminServiceImpl:
package com.atguigu.crowd.service.impl;
import com.atguigu.crowd.entity.Admin;
import com.atguigu.crowd.entity.AdminExample;
import com.atguigu.crowd.mapper.AdminMapper;
import com.atguigu.crowd.service.api.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class AdminServiceImpl implements AdminService {
@Autowired
AdminMapper adminMapper;
@Override
public void saveAdmin(Admin admin) {
adminMapper.insert(admin);
}
@Override
public List<Admin> getAll() {
//不带任何条件就是查询全部
return adminMapper.selectByExample(new AdminExample());
}
}
3、测试简单数据Ajax
? ? ? ? ?通过Ajax传递数组[5,8,12]
????????index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<%--http://localhost:8888/index.jsp--%>
<base href="http://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}/"/>
<script type="text/javascript" src="jquery/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="layer/layer.js"></script>
</head>
<body>
<h1>Hello!!!</h1>
<a href="test/ssm.html">测试</a><br>
<button id="btn2">send[5,8,12] Two</button>
<br>
</body>
<script>
$(function (){
$("#btn2").click(function (){
//准备好要发送到服务器端的数组
var array=[5,8,12];
//将json数组转化为json字符串
var requestBody = JSON.stringify(array);
$.ajax({
"url":"send/array/two.html", //请求目标资源的地址
"type":"post", //请求方式
"data":requestBody, //请求体
"contentType":"application/json;charset=UTF-8", //请求体的内容类型
"dataType":"text", //如何对待服务端返回的数据
"success":function (response){ //服务端处理成功后的回调函数
alert(response);
},
"error":function (response){ //服务端处理失败后的回调函数
alert(response);
}
});
});
});
</script>
</html>
在TestController中加入
@ResponseBody
@RequestMapping(value = "/send/array/two.html")
public String testSendArrayTwo(@RequestBody List<Integer> array){
for (Integer i:array) {
logger.info("number"+i);
}
return "succecss";
}
????????可以得到正确的响应:
?????????浏览器响应数据:
?4、测试复杂数据Ajax
通过Ajax传递封装好的Student对象
创建Student,Subject,Address类
? ? ? ? Student.class
package com.atguigu.crowd.entity;
import java.util.List;
import java.util.Map;
public class Student {
private Integer stuId;
private String stuName;
private Address address;
private List<Subject> subjectList;
private Map<String,String> map;
public Student() {
}
public Student(Integer stuId, String stuName, Address address, List<Subject> subjectList, Map<String, String> map) {
this.stuId = stuId;
this.stuName = stuName;
this.address = address;
this.subjectList = subjectList;
this.map = map;
}
public Integer getStuId() {
return stuId;
}
public void setStuId(Integer stuId) {
this.stuId = stuId;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public List<Subject> getSubjectList() {
return subjectList;
}
public void setSubjectList(List<Subject> subjectList) {
this.subjectList = subjectList;
}
public Map<String, String> getMap() {
return map;
}
public void setMap(Map<String, String> map) {
this.map = map;
}
@Override
public String toString() {
return "Student{" +
"stuId='" + stuId + '\'' +
", stuName='" + stuName + '\'' +
", address=" + address +
", subjectList=" + subjectList +
", map=" + map +
'}';
}
}
? ? ? ? Subject.class
package com.atguigu.crowd.entity;
public class Subject {
private String subjectName;
private Integer sunjectScore;
public Subject(){
}
public Subject(String subjectName, Integer sunjectScore) {
this.subjectName = subjectName;
this.sunjectScore = sunjectScore;
}
public String getSubjectName() {
return subjectName;
}
public void setSubjectName(String subjectName) {
this.subjectName = subjectName;
}
public Integer getSunjectScore() {
return sunjectScore;
}
public void setSunjectScore(Integer sunjectScore) {
this.sunjectScore = sunjectScore;
}
@Override
public String toString() {
return "Subject{" +
"subjectName='" + subjectName + '\'' +
", sunjectScore=" + sunjectScore +
'}';
}
}
Address.class
package com.atguigu.crowd.entity;
public class Address {
private String province;
private String city;
private String street;
public Address() {
}
public Address(String province, String city, String street) {
this.province = province;
this.city = city;
this.street = street;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
@Override
public String toString() {
return "Address{" +
"province='" + province + '\'' +
", city='" + city + '\'' +
", street='" + street + '\'' +
'}';
}
}
准备前端数据:
????????index.jsp
<html>
<head>
<title>Title</title>
<%--http://localhost:8888/index.jsp--%>
<base href="http://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}/"/>
<script type="text/javascript" src="jquery/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="layer/layer.js"></script>
</head>
<body>
<h1>Hello!!!</h1>
<a href="test/ssm.html">测试</a><br>
<button id="btn2">send[5,8,12] Two</button>
<br>
<button id="btn3">发送复杂对象</button>
<br>
</body>
<script>
$(function (){
$("#btn3").click(function (){
/* private Integer stuId;
private String stuName;
private Address address;
private List<Subject> subjectList;
private Map<String,String> map;*/
var student={
"stuId":5,
"stuName":"tom",
"address":{
"province":"湖北省",
"city":"武汉市",
"street":"后端"
},
"subjectList":[{
"subjectName":"Java编程",
"sunjectScore":100
},{
"subjectName":"c++",
"sunjectScore":100
},{
"subjectName":"python",
"sunjectScore":100
}],
map:{
"key1":"value1",
"key2":"value2",
"key3":"value3",
}
}
//将json对象转化为json字符串
var requestBody = JSON.stringify(student);
$.ajax({
"url":"send/compose/object.html",
"type":"post",
"data":requestBody,
"contentType":"application/json;charset=UTF-8", //请求体的内容类型
"dataType":"text", //如何对待服务端返回的数据
"success":function (response){ //服务端处理成功后的回调函数
alert(response);
},
"error":function (response){ //服务端处理失败后的回调函数
alert(response);
}
});
});
});
$(function (){
$("#btn2").click(function (){
//准备好要发送到服务器端的数组
var array=[5,8,12];
//将json数组转化为json字符串
var requestBody = JSON.stringify(array);
$.ajax({
"url":"send/array/two.html", //请求目标资源的地址
"type":"post", //请求方式
"data":requestBody, //请求体
"contentType":"application/json;charset=UTF-8", //请求体的内容类型
"dataType":"text", //如何对待服务端返回的数据
"success":function (response){ //服务端处理成功后的回调函数
alert(response);
},
"error":function (response){ //服务端处理失败后的回调函数
alert(response);
}
});
});
});
</script>
</html>
TestController中加入
@ResponseBody
@RequestMapping(value = "/send/compose/object.html")
public String testCompose(@RequestBody Student student,HttpServletRequest request){
boolean b = CrowdUtil.judgeRequestType(request);
logger.info("judgeRequestType---"+b);
logger.info(student.toString());
return "success";
}
可以得到响应:
?
?5、使用泛型对象传递数据
创建ResultEntity类
package com.atguigu.crowd.util;
/**
* 统一整个项目中ajax返回的结果
* @param <T>
*/
public class ResultEntity<T> {
public static final String SUCCESS = "SUCCESS";
public static final String FAILED = "FAILED";
//用来封装当前请求处理的结果是成功还是失败
private String result;
//请求失败时返回的消息
private String message;
//要返回的数据
private T data;
/**
* 请求处理成功时不需要返回数据使用的方法
* @param <Type>:泛型
* @return ResultEntity
*/
public static <Type> ResultEntity<Type> successWithoutData(){
return new ResultEntity<Type>(SUCCESS,null,null);
}
/**
* 请求处理成功时需要返回数据使用的方法
* @param <Type>:泛型
* @return ResultEntity
*/
public static <Type> ResultEntity<Type> successWithData(Type data){
return new ResultEntity<Type>(SUCCESS,null,data);
}
/**
* 请求处理失败时需要返回数据使用的方法
* @param message:消息
* @param <Type>:泛型
* @return ResultEntity
*/
public static <Type> ResultEntity<Type> filed(String message){
return new ResultEntity<Type>(FAILED,message,null);
}
public ResultEntity() {
}
public ResultEntity(String result, String message, T data) {
this.result = result;
this.message = message;
this.data = data;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
@Override
public String toString() {
return "ResultEntity{" +
"result='" + result + '\'' +
", message='" + message + '\'' +
", data=" + data +
'}';
}
}
jsp中加入
<button id="btn4">发送复杂对象(ResultEntity测试)</button>
<script>
$(function (){
$("#btn4").click(function (){
var student={
"stuId":5,
"stuName":"tom",
"address":{
"province":"湖北省",
"city":"武汉市",
"street":"后端"
},
"subjectList":[{
"subjectName":"Java编程",
"sunjectScore":100
},{
"subjectName":"c++",
"sunjectScore":100
},{
"subjectName":"python",
"sunjectScore":100
}],
map:{
"key1":"value1",
"key2":"value2",
"key3":"value3",
}
}
//将json对象转化为json字符串
var requestBody = JSON.stringify(student);
$.ajax({
"url":"send/compose/ResultEntity.json",
"type":"post",
"data":requestBody,
"contentType":"application/json;charset=UTF-8", //请求体的内容类型
"dataType":"json", //如何对待服务端返回的数据
"success":function (response){ //服务端处理成功后的回调函数
alert(response);
},
"error":function (response){ //服务端处理失败后的回调函数
alert(response);
}
});
});
});
</script>
测试内容与上一次相同
6、判断是否为Ajax请求
? ? ? ? 编写CrowdUtil工具类
package com.atguigu.crowd.util;
import javax.servlet.http.HttpServletRequest;
public class CrowdUtil {
public static boolean judgeRequestType(HttpServletRequest request){
// 1、获取请求消息头
String content = request.getHeader("Content-Type");
String header = request.getHeader("X-Requested-With");
// 2、判断
return (content!=null&&content.contains("application/json"))
||
(header!=null&&header.contains("XMLHttpRequest"));
}
}
? ? ? ? 注意:Ajax请求请求头中的内容于此对应。
|