一、后台接收URL拼接参数
后台代码:
@GetMapping("/item/{code}") //对应的链接为:/item/10001
public List<Description> getProduct(@PathVariable("code") String productCode) {
//your code
}
二、后台接收查询参数
后台代码:
@GetMapping("/detail") //对应的链接为:/detail?code=&name=
public String listMaterial(@RequestParam("code") String productCode, @RequestParam("name") String productName) {
//your code
}
前台代码:
1.通过表单提交
2.通过JavaScript使用Formdata对象提交
三、后台接收json
后台代码:
@PostMapping("/add")
public MaterialStandard addProduct(@RequestBody Product product ){
//your code
}
前台代码:
1.通过JavaScript提交
var product = new Product();
$.ajax({
url:"/add",
type:"POST",
data:(product),
contentType: "application/json;charset=UTF-8",
accept : "*/*",
success : function () {
("Successfully");
}
}); //使用了jQuery,原生JavaScript同理
四、接收文件
后台代码:
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file) {
//your code
}
前台代码:
1.通过表单提交
2.通过JavaScript使用FormData对象提交
<input type="file" name="file">
var fileInput = $("#file");
var selectedFile = fileInput[0].files[0];
var data = new FormData();
("file", selectedFile);
$.ajax({
url: '/upload',
type: 'POST',
data: data,
contentType: false, //不设置内容类型
processData: false, //不处理数据
accept : "*/*",
success : function () {
("Successfully");
}
}); 使用了jQuery,原生JavaScript同理
五、关于thymeleaf模板和Ajax
前台的视图模版我使用的是thymeleaf,它是SpringBoot官方推荐的一个html5模版引擎,SpringBoot官方不推荐使用jsp,SpringBoot官网也是使用这个模版引擎做的。
通过jQuery的ajax向Controller发送请求,在js回调函数中处理返回的数据,页面我用bootstrap快速的做了一个表格,渲染列表使用了一个叫做avalonjs的迷你mvvm框架,生成虚拟dom,可以参考官网。[链接]:/)
HTML页面示例:
<!DOCTYPE html>
<html xmlns:th="http:///1999/xhtml">
<head lang="en">
<meta charset="UTF-8"/>
<title></title>
<link rel="stylesheet" type="text/css" th:href="@{/css/}"/>
</head>
<body ms-controller="viewmodel">
<h1 th:text="${msg}">Hello World</h1>
<button type="button" class="btn btn-primary" style="margin: 10px;" ms-click="@request">{{@text}}</button>
<table class="table table-striped">
<thead>
<tr>
<td class="active">id</td>
<td class="success">姓名</td>
<td class="warning">性别</td>
<td class="danger">年龄</td>
<td class="info">角色</td>
</tr>
</thead>
<tbody>
<tr ms-for="el in @datalist">
<td >{{}}</td>
<td >{{}}</td>
<td>{{}}</td>
<td >{{}}</td>
<td >{{}}</td>
</tr>
</tbody>
</table>
</body>
<script th:src="@{/js/jquery-2.1.}"></script>
<script th:src="@{/js/}"></script>
<script th:src="@{/js/}"></script>
<script th:src="@{/js/}"></script>
</html>
js文件:
var viewmodel = ({
//id必须和页面上定义的ms-controller名字相同,否则无法控制页面
$id: "viewmodel",
datalist: {},
text: "请求数据",
request: function () {
$.ajax({
type: "post",
url: "/hello/data", //向后端请求数据的url
data: {},
success: function (data) {
$('button').removeClass("btn-primary").addClass("btn-success").attr('disabled', true);
= data;
= "数据请求成功,已渲染";
}
});
}
});