欢迎访问WDPHP素材源码!今天是2024年05月02日 星期四,上午工作顺利吗?
您好,游客 [ 马上登录 | 注册帐号 | 微信登录 | QQ登录]
当前位置:首页 > 教程 > 前端开发 > 

javaweb前端向后端传值的方式有哪些
栏目分类:前端开发    发布日期:2023-07-08    浏览次数:302次     收藏

这篇文章主要介绍“javaweb前端向后端传值的方式有哪些”,在日常操作中,相信很多人在javaweb前端向后端传值的方式有哪些问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”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><a href="https://www.19jp.com">

    后端代码:

    @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="https://www.19jp.com">

    后端代码:

    @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;
    }
    源码 模板 特效 素材 资源 教程 站长