根据前一篇文章,Maven + Spring mvc: Hello World, 已经介绍了spring mvc的简单使用,此片文章介绍一下,如何利用前端将数据传递到后端。
添加依赖引用:
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.7</version>
</dependency>
前端代码:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function(){
$("button").click(function(){
$.ajax({
type:"POST",
url:"helloworld",
contentType:"application/json;charset=utf-8",
dataType:"json",
data:JSON.stringify({
"Name": "test",
"Password": "123456",
"Address": "SD"
}),
success:function(){
console.log("success");
}
});
});
})
</script>
</head>
<body>
<h1>hello world.</h1>
<button>Click</button>
</body>
</html>
后端代码, 实体类:
package com.iotzzh.entity;
import com.fasterxml.jackson.annotation.JsonProperty;
public class User {
@JsonProperty(value="Name")
private String Name;
@JsonProperty(value="Password")
private String Password;
@JsonProperty(value="Address")
private String Address;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "User:" + Name + "\n" + "Password:" + Password +
"\n" + "Address:" + Address;
}
}
后端代码,controller 代码:
package com.iotzzh.controller;
import org.springframework.stereotype.Controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.iotzzh.entity.User;
@Controller
@RequestMapping("/hello")
public class HelloWorldController {
@RequestMapping(value="/helloworld", method=RequestMethod.POST, produces="application/json;charset=utf-8")
@ResponseBody
public void helloworld(@RequestBody User user) {
System.out.println("success");
System.out.println(user);
}
@RequestMapping("/helloworld")
public String helloworld(){
System.out.println("nihao");
return "hello";
}
}
测试:
点击click按钮:
网友评论