保持热爱、奔赴山河
1 创建maven工程。
2 将打包方式改为war。
3 进入模块设置,创建web.xml。
4 在web.xml添加CharacterEncodingFilter、HiddenHttpMethodFilter过滤器,DispatcherServletServlet。
5 创建包结构。
6 创建springmvc配置文件,设置自动扫包,Thymeleaf视图解析器,首页视图控制器,开启mvc的注解驱动 ,配置默认的Servlet处理静态资源。
7 创建templates文件夹,创建index.html文件。
8 将项目添加到Tomcat中,运行并访问首页。
方式一
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.htmlh1>
<input type="button" value="测试SpringMVC处理ajax" @click="testAjax()">
div>
<script type="text/javascript" th:src="@{/static/js/vue.js}">script>
<script type="text/javascript" th:src="@{/static/js/axios.min.js}">script>
<script type="text/javascript">
var vue = new Vue({
// el挂在容器,data模型数据(没有可以不设置),methods为当前事件绑定的函数
el: "#app",
methods: {
testAjax() {
/**
* axios({
* url: "", // 请求路径
* method: "", // 请求方式
* param: {}, // 请求参数:name=value&name=value(无论get、post都会被拼接到请求地址后,使用request.getParameter()获取请求参数)
* data: {} // 请求参数:json发送请求参数(请求参数会被保存到请求报文的请求体中传输到服务器,使用SpringMVC获取)
* // then():ajax处理成功之后,处理服务器响应回来的结果
* }).then(response=>{ //括号内写的是箭头函数,
* // 对服务器响应数据具体的处理
* // 在浏览器控制台打印服务器响应数据
* console.log(response.data);
* });
*/
}
}
});
script>
body>
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.htmlh1>
<input type="button" value="测试SpringMVC处理ajax" @click="testAjax()">
div>
<script type="text/javascript" th:src="@{/static/js/vue.js}">script>
<script type="text/javascript" th:src="@{/static/js/axios.min.js}">script>
<script type="text/javascript">
let 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>
@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,ajax");
}
}
@RequestBody可以获取请求体信息,使用@RequestBody注解标识控制器方法的形参,当前请求的请求体就会为当前注解所标识的形参赋值。
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.htmlh1>
<input type="button" value="测试SpringMVC处理ajax" @click="testAjax()">
<input type="button" value="测试@RequestBody注解处理json格式的请求参数" @click="testRequestBodyAjax()">
div>
<script type="text/javascript" th:src="@{/static/js/vue.js}">script>
<script type="text/javascript" th:src="@{/static/js/axios.min.js}">script>
<script type="text/javascript">
let vue = new Vue({
el: "#app",
methods: {
testAjax() {
axios.post(
"/springmvc/test/ajax?id=1001",
{username: "admin", password: "123456"}
).then(response => {
console.log(response.data);
});
}, testRequestBodyAjax() {
axios.post(
"/springmvc/test/request/body?id=1001",
{username: "admin", password: "123456"}
).then(response => {
console.log(response.data);
});
}
}
});
script>
body>
html>
@RequestMapping("/test/request/body")
public void testRequestBody(@RequestBody String username, HttpServletResponse response) throws IOException {
response.getWriter().write("RequestBody:" + username);
}
RequestBody:{"username":"admin","password":"123456"}
在使用了axios发送ajax请求之后,浏览器发送到服务器的请求参数有两种格式:
在SpringMVC中,直接使用@RequestBody注解标识控制器方法的形参即可将json格式转换为java对象。
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.12.1version>
dependency>
<mvc:annotation-driven />
在控制器方法的形参位置,设置json格式的请求参数要转换成的java类型(实体类或map)的参数,并使用@RequestBody注解标识。
创建User实体类
public class User {
private Integer id;
private String username;
private String password;
private Integer age;
private String gender;
// 构造方法
// set/get方法
// toString方法
}
<div id="app">
<input type="button" value="测试@RequestBody注解处理json格式的请求参数转实体类" @click="testRequestBodyUserAjax()">
div>
<script type="text/javascript" th:src="@{/static/js/vue.js}">script>
<script type="text/javascript" th:src="@{/static/js/axios.min.js}">script>
<script type="text/javascript">
var vue = new Vue({
el: "#app",
methods: {
testRequestBodyUserAjax() {
axios.post(
"/springmvc/test/request/body/map?id=1001",
{username: "admin", password: "123456", age:12, gender:"女"}
).then(response => {
console.log(response.data);
});
}
}
});
script>
//将json格式的数据转换为实体类对象
@RequestMapping("/test/request/body/user")
public void testRequestBodyUser(@RequestBody User user, HttpServletResponse response) throws IOException {
System.out.println(user);
response.getWriter().write(user.toString());
}
//将json格式的数据转换为map集合
@RequestMapping("/test/request/body/map")
public void testRequestBodyMap(@RequestBody Map<String, Object> map, HttpServletResponse response) throws IOException {
System.out.println(map);
response.getWriter().write("成功");
}
@ResponseBody用于标识一个控制器方法,可以将该方法的返回值直接作为响应报文的响应体响应到
浏览器
@RequestMapping("/test/response/body")
public String testResponseBody(){
//此时会跳转到逻辑视图success所对应的页面
return "success";
}
@RequestMapping("/test/response/body")
@ResponseBody
public String testResponseBody(){
//此时响应浏览器数据success
return "success";
}
服务器处理ajax请求之后,大多数情况都需要向浏览器响应一个java对象,此时必须将java对象转换为json字符串才可以响应到浏览器,之前我们使用操作json数据的jar包gson或jackson将java对象转换为json字符串。
在SpringMVC中,我们可以直接使用@ResponseBody注解实现此功能。
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.12.1version>
dependency>
<mvc:annotation-driven />
使用@ResponseBody注解标识控制器方法,在方法中,将需要转换为json字符串并响应到浏览器的java对象作为控制器方法的返回值,此时SpringMVC就可以将此对象直接转换为json字符串并响应到浏览器。
页面
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.htmlh1>
<input type="button" value="测试SpringMVC处理ajax" @click="testAjax()"><br/>
<input type="button" value="测试@RequestBody注解处理json格式的请求参数" @click="testRequestBodyAjax()"><br/>
<input type="button" value="测试@RequestBody注解处理json格式的请求参数转实体类"
@click="testRequestBodyUserAjax()"><br/>
<input type="button" value="测试@ResponseBody注解响应json格式的数据" @click="testResponseBodyAjax()"><br/>
div>
<script type="text/javascript" th:src="@{/static/js/vue.js}">script>
<script type="text/javascript" th:src="@{/static/js/axios.min.js}">script>
<script type="text/javascript">
let vue = new Vue({
el: "#app",
methods: {
testAjax() {
axios.post(
"/springmvc/test/ajax?id=1001",
{username: "admin", password: "123456"}
).then(response => {
console.log(response.data);
});
}, testRequestBodyAjax() {
axios.post(
"/springmvc/test/request/body?id=1001",
{username: "admin", password: "123456"}
).then(response => {
console.log(response.data);
});
}, testRequestBodyUserAjax() {
axios.post(
"/springmvc/test/request/body/user?id=1001",
{username: "admin", password: "123456", age: 12, gender: "女"}
).then(response => {
console.log(response.data);
});
}, testResponseBodyAjax() {
axios.post(
"/springmvc/test/response/body/json"
).then(response => {
console.log(response.data);
});
}
}
});
script>
body>
html>
TestAjaxController
// 响应浏览器实体类--->json对象
@RequestMapping("/test/response/body/json")
@ResponseBody
public User testResponseBadyJson() {
return new User(1001, "张三", "123", 23, "男");
}
//响应浏览器list集合--->json数组
@RequestMapping("/test/response/body/list")
@ResponseBody
public List<User> testRequestBody() {
User user1 = new User("admin1", 123);
User user2 = new User("admin2", 123);
User user3 = new User("admin3", 123);
User user4 = new User("admin4", 123);
User user5 = new User("admin5", 123);
User user6 = new User("admin6", 123);
List<User> list = Arrays.asList(user1, user2, user3, user4, user5, user6);
return list;
}
//响应浏览器map集合--->json对象
@RequestMapping("/test/response/body/map")
@ResponseBody
public Map<String, Object> testRequestBody() {
User user1 = new User("admin1", 123);
User user2 = new User("admin2", 123);
User user3 = new User("admin3", 123);
User user4 = new User("admin4", 123);
User user5 = new User("admin5", 123);
User user6 = new User("admin6", 123);
Map<String, Object> map = new HashMap<>();
map.put("1",user1);
map.put("2",user2);
map.put("3",user3);
map.put("4",user4);
map.put("5",user5);
map.put("6",user6);
return map;
}
@RestController注解是springMVC提供的一个复合注解,标识在控制器的类上,就相当于为类添加了@Controller 注解,并且为其中的每个方法添加了@ResponseBody注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
/**
* The value may indicate a suggestion for a logical component name,
* to be turned into a Spring bean in case of an autodetected component.
* @return the suggested component name, if any (or empty String otherwise)
* @since 4.0.1
*/
@AliasFor(annotation = Controller.class)
String value() default "";
}