javaweb前端向后端传值的几种方式总结(附代码)

一、javaweb中前端向后端传值的几种方式

1.查询字符串的方式

即在请求地址后拼接上请求参数,多个参数以&连接- 表单方式提交

2.第一种方式是在表单中直接提交,第二种方式是通过AJAX方式,data属性是js对象或者json对象,不指明contentType默认就是以表单方式提交。

3.json字符串方式

后端以@RequestBody方式接受,以对象形式接受,可以和查询字符串混用,除了对象之外后端还可以接受查询字符串参数。
经测试,后端不加@RequestBody,json字符串传到后台就不能正确匹配对象。

二、javaweb后台接收前台参数的三种注解

  • @RequestParam
  • @PathVariable
  • @RequestBody

2.1 @RequestParam

@RequestParam:将请求参数绑定到你控制器的方法参数上(是springmvc中接收普通参数的注解)。接收的参数是来自HTTP请求体或请求url的参数串中。。

语法:@RequestParam(value=”参数名”,required=”true/false”,defaultValue=””)

  • value:为接收url的参数名(相当于key值)。
  • required:是否包含该参数,默认为true,表示该请求路径中必须包含该参数,如果不包含就报错。
  • defaultValue:默认参数值,如果设置了该值,required=true将失效,自动为false,如果没有传该参数,就使用默认值。

@RequestParam用来处理 Content-Type 为 application/x-www-form-urlencoded 编码的内容,Content-Type默认为该属性。

@RequestParam也可用于其它类型的请求,例如:POST、DELETE等请求。

代码如下:

1.get请求参数带在url中。

前端代码:

  1. <button><a href=“/annotation/paramGet?name=tom&age=15” target=“_blank”>点我发送get请求</a></button>

后端代码:

  1. @RequestMapping(value = “paramGet”,produces = “application/json;charset=utf-8”)
  2. @ResponseBody
  3. public String paramGet(@RequestParam(“name”)String username,
  4.                      @RequestParam(“age”)int age,
  5.                      @RequestParam(value = “score”,required = false)Float score){
  6.      return username+“今年”+age+“岁”+“,考试得了”+score+“分!”;
  7. }

2.post请求参数带在url或者请求体中

前端代码:

  1. <button style=color: yellowgreen onclick=paramPost()>点我发送post请求</button>
  2.  
  3. <script type=“text/javascript>
  4.      //post请求参数带在url中。
  5.      function paramPost() {
  6.          $.ajax({
  7.              type:“post”,
  8.              //参数在url中,载荷是查询字符串,就是没有请求体
  9.              // url:”paramPost?name=jack&age=25″,
  10.              url:“paramPost”,
  11.              //参数在请求体中,js对象和json对象都可以提交,默认是提交表单数据
  12.              data:{name:“jack”,
  13.                  age:15
  14.              },
  15.              dataType:“json”,
  16.              success: function(data){
  17.                  console.log(data);
  18.                  alert(data);
  19.                  alert(data.sss);
  20.              }
  21.          });
  22.  
  23.      }
  24. </script>

后端代码:

  1. @RequestMapping(value = “paramPost”,produces = “application/json;charset=utf-8”,method = RequestMethod.POST)
  2. @ResponseBody
  3. public Map<String,String> paramPost(@RequestParam(“name”)String username,
  4.                      @RequestParam(“age”)int age,
  5.                      @RequestParam(value = “score”,required = false)Float score){
  6.          Map<String,String> map = new HashMap<>();
  7.          String ss = username+“今年”+age+“岁”+“,考试得了”+score+“分!”;
  8.          map.put(“sss”,ss);
  9.          return map;
  10. }

3.直接以表单方式提交

前端代码:

  1. <form action=”<%=basePath%>annotation/paramPost” method=”post”>
  2.      姓名:<input type=“text” name=“name” required=“required”><br>
  3.      年龄:<input type=“text” name=“age” required=“required”><br>
  4.      分数:<input type=“text” name=“score”><br>
  5.      <input type=“submit”>
  6. </form>

后端代码:

  1. @RequestMapping(value = “paramPost”,produces = “application/json;charset=utf-8”,method = RequestMethod.POST)
  2. @ResponseBody
  3. public Map<String,String> paramPost(@RequestParam(“name”)String username,
  4.                      @RequestParam(age”)int age,
  5.                      @RequestParam(value = “score”,required = false)Float score){
  6.          Map<String,String> map = new HashMap<>();
  7.          String ss = username+“今年”+age+“岁”+“,考试得了”+score+“分!”;
  8.          map.put(“sss”,ss);
  9.          return map;
  10. }

上面这种方式提交就是表单方式,它和通过ajax方式,data属性是js或者json对象,不指明contentType是一样的。

2.2 @PathVariable

Web应用中的URL通常不是一成不变的,例如微博两个不同用户的个人主页对应两个不同的URL:http://weibo.com/user1和http://weibo.com/user2。 我们不能对于每一个用户都编写一个被@RequestMapping注解的方法来处理其请求,也就是说,对于相同模式的URL(例如不同用户的主页,他们仅仅是URL中的某一部分不同, 为他们各自的用户名,我们说他们具有相同的模式)。
可以在@RequestMapping注解中用{ }来表明它的变量部分,例如:

  1. @RequestMapping(value=“/user/{username}”)

需要注意的是,在默认情况下,变量中不可以包含URL的分隔符/,例如路由不能匹配/user/Denny/Jon,即使你认为Denny/Jon是一个存在的用户名。

在路由中定义变量规则后,通常我们需要在处理方法(也就是@RequestMapping注解的方法)中获取这个URL的具体值,并根据这个值(例如用户名)做相应的操作, SpringMVC提供的@PathVariable可以帮助我们:

  1. @RequestMapping(value=“/user/{name}”)
  2. public String userProfile(@PathVariable(value=“name”) String username) {
  3. return “user”+username;
  4. }

PathVariable加RequestParam的组合方式:

前端代码:

  1. <button><a href=”<%=basePath%>annotation/pathTest/david/16?score=19.5″ target=”_blank”>点我发送path请求</a></button>

后端代码:

  1. @RequestMapping(value = “pathTest/{name}/{age}”,produces = “application/json;charset=utf-8”)
  2. @ResponseBody
  3. public Map<String,String> pathTest(@PathVariable(“name”)String username,
  4.                      @PathVariable(“age”)int age,
  5.                      @RequestParam(value = “score”,required = false)Float score){
  6.          Map<String,String> map = new HashMap<>();
  7.          String ss = username+“今年”+age+“岁”+“,考试得了”+score+“分!”;
  8.          map.put(“sss”,ss);
  9.          return map;
  10. }

2.3 @RequestBody

@RequestBody主要用来接收前端传递给后端的json字符串中的数据的(请求体中的数据的);而最常用的使用请求体传参的无疑是POST请求了, 所以使用@RequestBody接收数据时,一般都用POST方式进行提交。在后端的同一个接收方法里,@RequestBody与@RequestParam()可以同时使用, @RequestBody最多只能有一个,而@RequestParam()可以有多个。

注:一个请求,只有一个RequestBody;一个请求,可以有多个RequestParam。

前端代码:

  1. <button onclick=requestBodyTest()>点我测试requestbody</button>
  2.  
  3.  
  4. <script type=“text/javascript”>
  5. //测试requestbody
  6.      function requestBodyTest() {
  7.          let json = {“uName”:“david”,“phone”:13887898998};
  8.          alert(typeof json);
  9.          $.ajax({
  10.              type:“post”,
  11.              url:“<%=basePath%>annotation/requestBodyTest?score=17.8”,
  12.              //json字符串
  13.              data:JSON.stringify(json),
  14.              //指定发送数据的格式
  15.              contentType:“application/json”, //是这种格式,不是json/application
  16.              //指定返回数据的格式
  17.              dataType:“json”,
  18.              success: function(data){
  19.                  console.log(typeof data);
  20.                  console.log(data);
  21.                  alert(typeof data);
  22.                  alert(data.sss);
  23.              }
  24.          });
  25.  
  26.      }
  27. </script>

后端代码:

  1. @RequestMapping(value = “requestBodyTest”,produces = “application/json;charset=utf-8”,method = RequestMethod.POST)
  2. @ResponseBody
  3. public Map<String,String> requestBodyTest(@RequestBody User user,
  4.                      @RequestParam(value = “score”,required = false)Float score){
  5.          Map<String,String> map = new HashMap<>();
  6.          String ss = user.getuName()+“今年”+“考试得了”+score+“分!”;
  7.          map.put(“sss”,ss);
  8.          return map;
  9. }

总结

到此这篇关于javaweb前端向后端传值的几种方式总结的文章就介绍到这了,更多相关javaweb前端向后端传值内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

标签

发表评论