(1)普通参数方式
前端传参:
http://localhost:8080/user/getUserById?id=1001
后端接收1 字符串接收
@RequestMapping("getUserById")
publuc String getUserById(String id){
}
后端接收2 对象接收
@RequestMapping("getUserById")
publuc String getUserById(User user){
}
(2)路径占位符方式
前端传参:
http://localhost:8080/user/getUserById/1001/张三
后端接收
@RequestMapping("getUserById/{id}/{name}")
publuc String getUserById(
@PathVariable("id") String id,
@PathVariable("name") String name){
}
(3)form表单方式
前端一: get方式:
<form action="getUserById" method="get">
<input type="text" name="id" />
</form>
后端接收1 字符串接收
@RequestMapping("getUserById")
publuc String getUserById(String id){
}
后端接收2 对象接收
@RequestMapping("getUserById")
publuc String getUserById(User user){
}
前端二: post方式:例如文件上传
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="photo" />
</form>
后端:
@RequestMapping("upload")
publuc String getUserById(MutiPartFile photo){
}
(4)json格式字符串传参
前端ajax请求
$.ajax({
url:'http://localhost:8080/test',
type:'POST'
contentType: 'application/json;charset=UTF-8',
async:false //true:异步,false:同步
data: "{'id': " + '1001' +"}",
dataType:'JSON' //回调数据格式
success:function(){
alert("请求成功");
},
error:function(){
alert("请求失败");
}
})
注意:不使用contentType: “application/json”则data可以是对象,使用contentType: “application/json”则data只能是json字符串
后端接收:方法参数前加@RequestBody
@RequestMapping("test")
publuc String getUserById(@RequestBody User user){
}
(5)其他、通过url字符串拼接向后台提交数据
1.直接在ajax中url拼接数据
$.ajax({
url: "TestJsonServlet?id="+id+"&gender="+"男", //提价的路径
type: "get", //提交方式
dataType: "JSON", //规定请求成功后返回的数据
success: function (data) {
//请求成功之后进入该方法,data为成功后返回的数据
},
error: function (errorMsg) {
//请求失败之后进入该方法,errorMsg为失败后返回的错误信息
}
});
2 JS提交数据,通过window.location.href指定路径提交数据。
var deleteUser = function (deleteId) {
if (confirm("确认删除编号是【"+deleteId+"】的成员吗?")){
window.location.href="DeleteUserServlet?deleteId="+deleteId;
}
}
3.通过a标签提交数据,通过a标签的href属性提交数据,和js提交数据类似。
<a href="DeleteUserServlet?id='3'&gender='男'"></a>
4.在后台中也可以互相访问相应的Servlet
request.setAttribute("id","3");
request.setAttribute("gender","男");
request.getRequestDispatcher("updateUser.jsp").forward(request,response);
然后在对应的Servlet中接受参数,进行相应的处理
String id = request.getAttribute("id");
String gender = request.getAttribute("gender");