目录
SpringMVC处理ajax请求
一 准备工作
1 新建spring_mvc_ajax com.atguigu
2 .导入依赖
3 添加web模块
4 .配置web.xml
5 . springmvc.xml
6 .创建控制层
7 . index.html
8 静态
9 部暑到tomcat上
10 启动tomcat
二 . 测试SpringMVC处理ajax
1 . index.html
2 .控制层
3 .测试
三 @RequestBody
1 控制层
2 测试
四 @RequestBody获取json格式的请求参数
1. index.html
2 .TestAjaxController
3 . 导入jackson的依赖
4 .创建实体类
五 @ResponseBody
1. index.html
2. TestAjaxController
六 @ResponseBody响应浏览器json数据
实体类-->json对象
1 .index.html
2 . 控制层
3 .测试
map-->json对象
1 .控制层
2. 测试
list-->json数组
1 .控制层
2. 测试
七 @RestController注解
总结
SpringMVC处理ajax请求
一 准备工作
1 新建spring_mvc_ajax com.atguigu
2 .导入依赖
<packaging>war</packaging> <dependencies> <!-- SpringMVC --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.1</version> </dependency> <!-- 日志 --> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.3</version> </dependency> <!-- ServletAPI --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!-- Spring5和Thymeleaf整合包 --> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> <version>3.0.12.RELEASE</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.12.1</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> </dependencies>
3 添加web模块
src\main\webapp\
D:\review_ssm\workspace\SSM\spring_mvc_ajax\src\main\webapp\WEB-INF\web.xml
4 .配置web.xml
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<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>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
5 . 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: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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--扫描控制层组件-->
<context:component-scan base-package="com.atguigu.controller"></context:component-scan>
<!-- 配置Thymeleaf视图解析器 -->
<bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
<property name="order" value="1"/>
<property name="characterEncoding" value="UTF-8"/>
<property name="templateEngine">
<bean class="org.thymeleaf.spring5.SpringTemplateEngine">
<property name="templateResolver">
<bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
<!-- 视图前缀 -->
<property name="prefix" value="/WEB-INF/templates/"/>
<!-- 视图后缀 -->
<property name="suffix" value=".html"/>
<property name="templateMode" value="HTML5"/>
<property name="characterEncoding" value="UTF-8" />
</bean>
</property>
</bean>
</property>
</bean>
<!--
配置默认的servlet处理静态资源
当前工程的web.xml配置的前端控制器DispatcherServlet的url-pattern是/
tomcat的web.xml配置的DefaultServlet的url-pattern也是/
此时,浏览器发送的请求会优先被DispatcherServlet进行处理,但是DispatcherServlet无法处理静态资源
若配置了<mvc:default-servlet-handler />,此时浏览器发送的所有请求都会被DefaultServlet处理
若配置了<mvc:default-servlet-handler />和<mvc:annotation-driven />
浏览器发送的请求会先被DispatcherServlet处理,无法处理在交给DefaultServlet处理
-->
<mvc:default-servlet-handler />
<!--开启mvc的注解驱动-->
<mvc:annotation-driven />
<!--配置视图控制器-->
<mvc:view-controller path="/" view-name="index"></mvc:view-controller>
</beans>
6 .创建控制层
@Controller
public class TestAjaxController {
}
7 . index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<h1>index.html</h1>
</body>
</html>
8 静态
9 部暑到tomcat上
10 启动tomcat
二 . 测试SpringMVC处理ajax
1 . index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<div id="app">
<h1>index.html</h1>
<input type="button" value="测试SpringMVC处理ajax" @click="testAjax()"><br>
</div>
<script type="text/javascript" th:src="@{/js/vue.js}"></script>
<script type="text/javascript" th:src="@{/js/axios.min.js}"></script>
<script type="text/javascript">
/**
* axios({
url:"",//请求路径
method:"",//请求方式
//以name=value&name=value的方式发送的请求参数
//不管使用的请求方式是get或post,请求参数都会被拼接到请求地址后
//此种方式的请求参数可以通过request.getParameter()获取
params:{},
//以json格式发送的请求参数
//请求参数会被保存到请求报文的请求体传输到服务器
//此种方式的请求参数不可以通过request.getParameter()获取
data:{}
}).then(response=>{
console.log(response.data);
});
*/
var vue = new Vue({
el:"#app",
methods:{
testAjax(){
axios.post(
"/springmvc/test/ajax?id=1001",
{username:"admin",password:"123456"}
).then(response=>{
console.log(response.data);
});
}
}
});
</script>
</body>
</html>
2 .控制层
@Controller
public class TestAjaxController {
@RequestMapping("/test/ajax")
public void testAjax(Integer id, HttpServletResponse response) throws IOException {
System.out.println("id:"+id);
response.getWriter().write("hello,axios");
}
}
3 .测试
三 @RequestBody
1 控制层
@RequestMapping("/test/ajax")
public void testAjax(Integer id, @RequestBody String requestBody, HttpServletResponse response) throws IOException {
System.out.println("requestBody:"+requestBody);
System.out.println("id:"+id);
response.getWriter().write("hello,axios");
}
2 测试
四 @RequestBody获取json格式的请求参数
1. index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<div id="app">
<h1>index.html</h1>
<input type="button" value="测试SpringMVC处理ajax" @click="testAjax()"><br>
<input type="button" value="使用@RequestBody注解处理json格式的请求参数" @click="testRequestBody()"><br>
</div>
<script type="text/javascript" th:src="@{/js/vue.js}"></script>
<script type="text/javascript" th:src="@{/js/axios.min.js}"></script>
<script type="text/javascript">
/**
* axios({
url:"",//请求路径
method:"",//请求方式
//以name=value&name=value的方式发送的请求参数
//不管使用的请求方式是get或post,请求参数都会被拼接到请求地址后
//此种方式的请求参数可以通过request.getParameter()获取
params:{},
//以json格式发送的请求参数
//请求参数会被保存到请求报文的请求体传输到服务器
//此种方式的请求参数不可以通过request.getParameter()获取
data:{}
}).then(response=>{
console.log(response.data);
});
*/
var vue = new Vue({
el:"#app",
methods:{
testAjax(){
axios.post(
"/sprngMVC/test/ajax?id=1001",
{username:"admin",password:"123456"}
).then(response=>{
console.log(response.data);
});
}
},
testRequestBody(){
axios.post(
"/sprngMVC/test/RequestBody/json",
{username:"admin",password:"123456",age:23,gender:"男"}
).then(response=>{
console.log(response.data);
});
}
});
</script>
</body>
</html>
2 .TestAjaxController
@RequestMapping("/test/RequestBody/json")
public void testRequestBody(@RequestBody Map<String, Object> map, HttpServletResponse response) throws IOException {
System.out.println(map);
response.getWriter().write("hello,RequestBody");
}
3 . 导入jackson的依赖
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.12.1</version> </dependency>
4 .创建实体类
package com.atguigu.pojo;
public class User {
private Integer id;
private String username;
private String password;
private Integer age;
private String gender;
public User() {
}
public User(Integer id, String username, String password, Integer age, String gender) {
this.id = id;
this.username = username;
this.password = password;
this.age = age;
this.gender = gender;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
'}';
}
}
测试
五 @ResponseBody
1. index.html
2. TestAjaxController
@RequestMapping("/test/ResponseBody")
@ResponseBody
public String testResponseBody(){
return "success";
}
3 测试
六 @ResponseBody响应浏览器json数据
实体类-->json对象
1 .index.html
2 . 控制层
@RequestMapping("/test/ResponseBody/json")
@ResponseBody
public User testResponseBodyJson(){
User user = new User(1001, "admin1", "123456", 20, "男");
return user;
}
3 .测试
map-->json对象
1 .控制层
@RequestMapping("/test/ResponseBody/json")
@ResponseBody
public Map<String, Object> testResponseBodyJson(){
User user1 = new User(1001, "admin1", "123456", 20, "男");
User user2 = new User(1002, "admin2", "123456", 20, "男");
User user3 = new User(1003, "admin3", "123456", 20, "男");
Map<String, Object> map = new HashMap<>();
map.put("1001", user1);
map.put("1002", user2);
map.put("1003", user3);
return map;
}
2. 测试
list-->json数组
1 .控制层
@RequestMapping("/test/ResponseBody/json")
@ResponseBody
public List<User> testResponseBodyJson(){
User user1 = new User(1001, "admin1", "123456", 20, "男");
User user2 = new User(1002, "admin2", "123456", 20, "男");
User user3 = new User(1003, "admin3", "123456", 20, "男");
List<User> list = Arrays.asList(user1, user2, user3);
return list;
}
2. 测试
七 @RestController注解
总结
/** * 1、@RequestBody:将请求体中的内容和控制器方法的形参进行绑定 * 2、使用@RequestBody注解将json格式的请求参数转换为java对象 * a>导入jackson的依赖 * b>在SpringMVC的配置文件中设置<mvc:annotation-driven /> * c>在处理请求的控制器方法的形参位置,直接设置json格式的请求参数要转换的java类型的形参,使用@RequestBody注解标识即可 * 3、@ResponseBody:将所标识的控制器方法的返回值作为响应报文的响应体响应到浏览器 * 4、使用@ResponseBody注解响应浏览器json格式的数据 * a>导入jackson的依赖 * b>在SpringMVC的配置文件中设置<mvc:annotation-driven /> * c>将需要转换为json字符串的java对象直接作为控制器方法的返回值,使用@ResponseBody注解标识控制器方法 * 就可以将java对象直接转换为json字符串,并响应到浏览器 * 常用的Java对象转换为json的结果: * 实体类-->json对象 * map-->json对象 * list-->json数组 */