SpringMVC的请求处理方法接收请求参数
1.请求处理方法接收json参数
1.1创建项目
1.2完善项目
1.3导入依赖
<!-- 配置开发SpringMVC所以来的jar包 -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- 配置ServletAPI依赖 -->
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.8</version>
</dependency>
1.4配置web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>dispatcherServlet</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>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.zz</url-pattern>
</servlet-mapping>
</web-app>
1.5配置SpringMVC配置文件
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--开启注解-->
<mvc:annotation-driven></mvc:annotation-driven>
<!--配置自动扫描包-->
<context:component-scan base-package="com.wangxing.springmvc.controller"></context:component-scan>
</beans>
1.6创建HTML页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户注册</title>
</head>
<body>
<table>
<tr>
<td colspan="2"><h1>用户注册</h1></td>
</tr>
<tr>
<td>用户名:</td>
<td><input id="username" type="text" name="username"/></td>
</tr>
<tr>
<td>密码</td>
<td><input id="password" type="password" name="password"/></td>
</tr>
<tr>
<td>年龄:</td>
<td><input id="myage" type="text" name="myage"/></td>
</tr>
<tr>
<td>地址:</td>
<td><input id="myaddress" type="text" name="myaddress"/></td>
</tr>
<tr>
<td colspan="2"><input id="but1" type="button" value="提交"/> </td>
</tr>
</table>
</body>
</html>
1.7.在webapp文件夹中创建jquery文件,并将jquery-3.5.1.min.js复制进jquery文件。
重新加载一次jquery文件中的jquery-3.5.1.min.js文件
1.8 在html文件中导入jquery,并发送ajax请求
<script src="js/jquery-3.5.1.min.js"></script>
<script>
$(function () {
$("#but1").click(function () {
var username=$("#username").val();
var password=$("#password").val();
var myage=$("#myage").val();
var myaddress=$("#myaddress").val();
//组织成json数据[json对象]
var params={"username":username,"password":password,"myage":myage,"myaddress":myaddress};
//3.将上面组织好的json数据发送到控制器类的请求处理方法中接收处理
$.ajax({
//设置访问地址
url:"http://localhost:8080/SpringMyDemo6_war/test1.zz",
//设置被发送的具体数据【json字符串】
data:JSON.stringify(params),
//设置请求提交方式
type:"POST",
//设置响应数据的类型是json
dataType:"json",
//设置请求的数据是json数据,绝对不可以省略
contentType:"application/json",
//设置请求发送成功以后的处理函数
success:function (data) {
alert(data);
}
})
})
})
</script>
注意:不能使用jquery的post方式发送ajax请求,因为jquery的post方式发送ajax请求时http协议的请求头中的contentType的属性值不是"application/json",所以会出现“Failed to load resource: the server responded with a status of 415 (Unsupported Media Type)”错误。
1.9 创建被提交的json数据对应的java实体类
注意:java实体类的成员变量名称与被提交的json数据中的key值相同。
package com.wangxing.springmvc.bean;
public class PersonBean {
private String username;
private String password;
private Integer myage;
private String myaddress;
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 getMyage() {
return myage;
}
public void setMyage(Integer myage) {
this.myage = myage;
}
public String getMyaddress() {
return myaddress;
}
public void setMyaddress(String myaddress) {
this.myaddress = myaddress;
}
}
1.10创建控制器
package com.wangxing.springmvc.controller;
import com.wangxing.springmvc.bean.PersonBean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class HelloController {
@RequestMapping(value = "/test1.zz",method = RequestMethod.POST)
public void testRequest(@RequestBody PersonBean personBean){
System.out.println("username=="+personBean.getUsername());
System.out.println("password=="+personBean.getPassword());
System.out.println("myage=="+personBean.getMyage());
System.out.println("myaddress=="+personBean.getMyaddress());
}
}
11.测试
http://localhost:8080/SpringMyDemo6_war/spring.html
@RequestBody
@RequestBody注解接收来自请求体中的参数。
一般用于处理非 Content-Type: application/x-www-form-urlencoded编码格式的数据,比如:application/json、application/xml等类型的数据。
“Content-Type:application/json”使用注解@RequestBody可以将请求体里面所有的json数据传到后端,后端再进行解析,封装成java对象。
请求处理方法向浏览器页面返回json数据
@RequestMapping(value = "/test2.zz")
@ResponseBody
public PersonBean testRequest(){
PersonBean per=new PersonBean();
per.setUsername("zhangsan");
per.setPassword("000000");
per.setMyage(23);
per.setMyaddress("西安");
return per;
}
@RequestMapping(value = "/test3.zz")
@ResponseBody
public List<PersonBean>testRequest2(){
PersonBean per2=new PersonBean();
per2.setUsername("lisi");
per2.setPassword("111111");
per2.setMyage(22);
per2.setMyaddress("北京");
PersonBean per3=new PersonBean();
per3.setUsername("wangwu");
per3.setPassword("555555");
per3.setMyage(90);
per3.setMyaddress("成都");
List<PersonBean>personBeanList=new ArrayList<PersonBean>();
personBeanList.add(per2);
personBeanList.add(per3);
return personBeanList;
}
运行结果
http://localhost:8080/SpringMyDemo6_war/test2.zz
{“username”:“zhangsan”,“password”:“000000”,“myage”:23,“myaddress”:“西安”}
http://localhost:8080/SpringMyDemo6_war/test3.zz
[{“username”:“lisi”,“password”:“111111”,“myage”:22,“myaddress”:“北京”},{“username”:“wangwu”,“password”:“555555”,“myage”:90,“myaddress”:“成都”}]
@ResponseBody的作用其实是将java对象转为json格式的数据【json对象】。
Json对象与json字符串之间的转换
Json对象—》json字符串 JSON.stringify(json对象)
json字符串—》Json对象 eval("("+json字符串+")");
例如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>json转换</title>
<script src="js/jquery-3.5.1.min.js"></script>
<script>
$(function () {
$("#but1").click(function () {
//定义json对象
var jsonObj = {id: 1001, username: "zhangsan", age: 23, address: "西安"};
var jsonString = JSON.stringify(jsonObj);
//alert(jsonOb);
//alert(jsonString);
});
$("#but2").click(function () {
var json = "{'id':1001,'username':'zhangsan','age':23,'address':'西安'}";
var jsonObj = eval("(" + json + ")");
alert(jsonObj);
});
})
</script>
</head>
<body>
<input id="but1" type="button" value="json对象转换成json字符串"/><br>
<input id="but2" type="button" value="json字符串转换成json对象"/><br>
</body>
</html>