注意请求体只有form表单才有,而对于链接来说不使用
1)、在Controller中写
@RequestBody String body是基本用法
另外可以封装对象@RequestBody Employee employee是高级用法
@requestBody接收的是前端传过来的json字符串
写在参数位置
@RequestMapping("/testRequestBody") public String testRequestBody(@RequestBody Employee employee){ System.out.println("请求体:"+employee); return "success"; }
2)、在页面中写,$.ajax();//js对象(object)转json(string)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <% pageContext.setAttribute("ctp", request.getContextPath()); %> </head> <script type="text/javascript" src="scripts/jquery-1.9.1.min.js"></script> <body> <form action="${ctp }/test02" method="post" enctype="multipart/form-data"> <input name="username" value="tomcat" /> <input name="password" value="123456"> <input type="file" name="file" /> <input type="submit" /> </form> <a href="${ctp }/testRequestBody">ajax发送json数据</a> </body> <script type="text/javascript"> $("a:first").click(function() { //点击发送ajax请求,请求带的数据是json var emp = { lastName : "张三", email : "aaa@aa.com", gender : 0 }; //alert(typeof emp); //js对象(object)转json(string) var empStr = JSON.stringify(emp); //alert(typeof empStr); $.ajax({ url : ‘${ctp}/testRequestBody‘, type : "POST", data : empStr, contentType : "application/json", success : function(data) { alert(data); } }); return false; }); </script> </html>
看一个例子,如果我们需要获取Url=localhost:8080/hello/id/name中的id值和name值,实现代码如下:
@RestController public class HelloController { @RequestMapping(value="/hello/{id}/{name}",method= RequestMethod.GET) public String sayHello(@PathVariable("id") Integer id,@PathVariable("name") String name){ return "id:"+id+" name:"+name; } }
以上,通过@PathVariable注解来获取URL中的参数时的前提条件是我们知道url的格式时怎么样的。只有知道url的格式【/传参/并列】,我们才能在指定的方法上通过相同的格式获取相应位置的参数值。
一般情况下,url的格式为:localhost:8080/hello?id=98,【?传参&并列】这种情况下该如何来获取其id值呢,这就需要借助于@RequestParam来完成了
后端不以表单形式从前端获取值
1.在浏览器中输入地址:localhost:8080/hello?id=1000,可以看到如下的结果:
2.当我们在浏览器中输入地址:localhost:8080/hello?id ,即不输入id的具体值,此时返回的结果为null。具体测试结果如下:
3.但是,当我们在浏览器中输入地址:localhost:8080/hello ,即不输入id参数,则会报如下错误:
@RequestParam注解给我们提供了这种解决方案,即允许用户不输入id时,使用默认值,具体代码如下:
@RestController public class HelloController { @RequestMapping(value="/hello",method= RequestMethod.GET) //required=false 表示url中可以不穿入id参数,此时就使用默认参数 public String sayHello(@RequestParam(value="id",required = false,defaultValue = "1") Integer id){ return "id:"+id; } }
SpringMvc获取前端的数据@RequestBody请求体/@PathVaribale/@RequestParam【支持Ajax】
原文:https://www.cnblogs.com/yanl55555/p/11906857.html