javaweb前端向后端传值的方式有哪些

发布时间:2023-03-28 14:49:25 作者:iii
来源:亿速云 阅读:109

这篇文章主要介绍“javaweb前端向后端传值的方式有哪些”,在日常操作中,相信很多人在javaweb前端向后端传值的方式有哪些问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”javaweb前端向后端传值的方式有哪些”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

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

1.查询字符串的方式

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

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

3.json字符串方式

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

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

2.1 @RequestParam

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

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

@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  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;
}

到此,关于“javaweb前端向后端传值的方式有哪些”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

推荐阅读:
  1. JavaWeb表单及时验证功能在输入后立即验证(含用户类型,性别,爱好...的验证)
  2. JavaWeb servlet如何实现下载与上传功能

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

javaweb

上一篇:怎么使用llama Index训练pdf

下一篇:Spring Security基本架构与初始化操作流程是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》