0


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

前端代码:

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

后端代码:

@RequestMapping(value ="paramGet",produces ="application/json;charset=utf-8")@ResponseBodypublicStringparamGet(@RequestParam("name")String username,@RequestParam("age")int age,@RequestParam(value ="score",required =false)Float score){return username+"今年"+age+"岁"+",考试得了"+score+"分!";}
  1. post请求参数带在url或者请求体中

前端代码:

<buttonstyle="color: yellowgreen"onclick="paramPost()">点我发送post请求</button><scripttype="text/javascript">//post请求参数带在url中。functionparamPost(){
        $.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)@ResponseBodypublicMap<String,String>paramPost(@RequestParam("name")String username,@RequestParam("age")int age,@RequestParam(value ="score",required =false)Float score){Map<String,String> map =newHashMap<>();String ss = username+"今年"+age+"岁"+",考试得了"+score+"分!";
        map.put("sss",ss);return map;}
  1. 直接以表单方式提交

前端代码:

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

后端代码:

@RequestMapping(value ="paramPost",produces ="application/json;charset=utf-8",method =RequestMethod.POST)@ResponseBodypublicMap<String,String>paramPost(@RequestParam("name")String username,@RequestParam("age")int age,@RequestParam(value ="score",required =false)Float score){Map<String,String> map =newHashMap<>();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}")publicStringuserProfile(@PathVariable(value="name")String username){return"user"+username;}

PathVariable加RequestParam的组合方式:

前端代码:

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

后端代码:

@RequestMapping(value ="pathTest/{name}/{age}",produces ="application/json;charset=utf-8")@ResponseBodypublicMap<String,String>pathTest(@PathVariable("name")String username,@PathVariable("age")int age,@RequestParam(value ="score",required =false)Float score){Map<String,String> map =newHashMap<>();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。

前端代码:

<buttononclick="requestBodyTest()">点我测试requestbody</button><scripttype="text/javascript">//测试requestbodyfunctionrequestBodyTest(){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)@ResponseBodypublicMap<String,String>requestBodyTest(@RequestBodyUser user,@RequestParam(value ="score",required =false)Float score){Map<String,String> map =newHashMap<>();String ss = user.getuName()+"今年"+"考试得了"+score+"分!";
        map.put("sss",ss);return map;}
标签: 前端 java servlet

本文转载自: https://blog.csdn.net/weixin_40228534/article/details/127862881
版权归原作者 一路向前-执着 所有, 如有侵权,请联系我们删除。

“javaweb中前端向后端传值的几种方式”的评论:

还没有评论