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

作者:一路向前-执着 时间:2022-04-28 09:21:29 

一、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中。

前端代码:

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

后端代码:

@RequestMapping(value = "paramGet",produces = "application/json;charset=utf-8")
@ResponseBody
public String paramGet(@RequestParam("name")String username,
                      @RequestParam("age")int age,
                      @RequestParam(value = "score",required = false)Float score){
   return username+"今年"+age+"岁"+",考试得了"+score+"分!";
}

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

前端代码:

<button style="color: yellowgreen" onclick="paramPost()">点我发送post请求</button>

<script type="text/javascript">
   //post请求参数带在url中。
   function paramPost() {
       $.ajax({
           type:"post",
           //参数在url中,载荷是查询字符串,就是没有请求体
           // url:"paramPost?name=jack&age=25",
           url:"paramPost",
           //参数在请求体中,js对象和json对象都可以提交,默认是提交表单数据
           data:{name:"jack",
               age:15
           },
           dataType:"json",
           success: function(data){
               console.log(data);
               alert(data);
               alert(data.sss);
           }
       });

}
</script>

后端代码:

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

3.直接以表单方式提交

前端代码:

<form action="<%=basePath%>annotation/paramPost" method="post">
   姓名:<input type="text" name="name" required="required"><br>
   年龄:<input type="text" name="age" required="required"><br>
   分数:<input type="text" name="score"><br>
   <input type="submit">
</form>

后端代码:

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

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

2.2 @PathVariable

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

@RequestMapping(value="/user/{username}")

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

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

@RequestMapping(value="/user/{name}")
public String userProfile(@PathVariable(value="name") String username) {
return "user"+username;
}

PathVariable加RequestParam的组合方式:

前端代码:

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

后端代码:

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

2.3 @RequestBody

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

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

前端代码:

<button onclick="requestBodyTest()">点我测试requestbody</button>

<script type="text/javascript">
//测试requestbody
   function requestBodyTest() {
       let json = {"uName":"david","phone":13887898998};
       alert(typeof json);
       $.ajax({
           type:"post",
           url:"<%=basePath%>annotation/requestBodyTest?score=17.8",
           //json字符串
           data:JSON.stringify(json),
           //指定发送数据的格式
           contentType:"application/json", //是这种格式,不是json/application
           //指定返回数据的格式
           dataType:"json",
           success: function(data){
               console.log(typeof data);
               console.log(data);
               alert(typeof data);
               alert(data.sss);
           }
       });

}
</script>

后端代码:

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

来源:https://blog.csdn.net/weixin_40228534/article/details/127862881

标签:前端,后端,传值
0
投稿

猜你喜欢

  • Java实现文件读取和写入过程解析

    2023-06-28 11:35:36
  • c# WPF实现Windows资源管理器(附源码)

    2022-10-01 14:34:46
  • Android使用onCreateOptionsMenu()创建菜单Menu的方法详解

    2023-05-13 06:21:01
  • Android使用Xutils3进行断点下载的实例

    2021-08-13 21:59:27
  • SpringBoot自定义注解之实现AOP切面日志详解

    2022-12-18 17:58:06
  • springboot中使用redis并且执行调试lua脚本

    2022-02-15 08:49:52
  • Spring MVC项目中log4J和AOP使用详解

    2022-11-16 08:36:29
  • springBoot项目中使用@Value取值出现的问题及解决

    2023-05-29 12:59:16
  • Android滑动拼图验证码控件使用方法详解

    2021-10-03 02:56:06
  • Android Retrofit的使用详解

    2022-12-11 01:28:37
  • java判断list不为空的实现,和限制条数不要在一起写

    2022-01-24 13:14:38
  • Android开发中synchronized的三种使用方式详解

    2023-12-13 03:33:37
  • c#进程之间对象传递方法

    2022-04-22 09:41:10
  • IntelliJ IDEA 2017.1.4 x64配置步骤(介绍)

    2022-02-25 13:48:48
  • springboot快速整合Mybatis组件的方法(推荐)

    2022-03-23 11:59:15
  • SrpingDruid数据源加密数据库密码的示例代码

    2021-06-21 03:26:26
  • Mybatis如何通过接口实现sql执行原理解析

    2022-11-30 11:31:26
  • java mybatis如何操作postgresql array数组类型

    2023-04-25 22:59:37
  • Mybatis Plus使用XML编写动态sql的超简易方法

    2022-02-20 01:49:16
  • 用命令行编译java并生成可执行的jar包方法

    2023-01-15 23:21:35
  • asp之家 软件编程 m.aspxhome.com