SpringMVC获取请求参数

前端视图层

前端视图中使用链接<a>或者表单<form>或者axios来发送请求。

1. 使用链接发送请求
<a th:href="@{/test(username='admin',password=123456)}">测试</a>

在这里插入图片描述

2. 使用表单发送请求

使用表单<form>,且method可以设置为get或post。

  1. method为get
<form th:action="@{/test}" method="get">
    username:<input type="text" name="username" /><br/>
    password:<input type="password" name="password"/><br/>
    <input type="submit" value="提交"/>
</form>

在这里插入图片描述
2. method为post

<form th:action="@{/test}" method="post">
    username:<input type="text" name="username" /><br/>
    password:<input type="password" name="password"/><br/>
    <input type="submit" value="提交"/>
</form>

在这里插入图片描述

3. 使用axios发送请求
<body>
    <button onclick="handleClick()">点击测试</button>
    <script th:src="@{/static/js/axios.min.js}"></script>
    <script th:inline="javascript">
        //获取上下文路径
        var contextPath = /*[[@{/}]]*/'';

        function handleClick(){
            axios({
                method:"get",
                // method:"post",
                url:contextPath+"test",
                params:{
                    username:"admin",
                    password:"123456"
                }
            })
        }
    </script>
</body>

在这里插入图片描述

后端控制层

后端控制层获取请求参数有四种方式。

1. 通过Servlet API方式
//    @RequestMapping(value = "/test",method = RequestMethod.POST)
@RequestMapping(value = "/test",method = RequestMethod.GET)
public String test(HttpServletRequest request){
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    System.out.println(username+","+password);
    return "success";
}
10:06:32.279 [http-nio-8080-exec-5] DEBUG org.springframework.web.servlet.DispatcherServlet - GET "/demo6/test?username=admin&password=123456", parameters={masked}
10:06:32.282 [http-nio-8080-exec-5] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped to com.example.mvc.controller.TestController#test(HttpServletRequest)
admin,123456
2. 控制器方法形参名称与请求参数名称一致。
//    @RequestMapping(value = "/test",method = RequestMethod.POST)
@RequestMapping(value = "/test",method = RequestMethod.GET)
public String test(String username,String password){
    System.out.println(username+","+password);
    return "success";
}
09:50:14.278 [http-nio-8080-exec-4] DEBUG org.springframework.web.servlet.DispatcherServlet - GET "/demo6/test?username=admin&password=123456", parameters={masked}
09:50:14.280 [http-nio-8080-exec-4] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped to com.example.mvc.controller.TestController#test(String, String)
admin,123456
3. 使用@RequestParam

控制器方法形成名称与请求参数名称不一致,使用@RequestParam建立二者间的映射关系

//    @RequestMapping(value = "/test",method = RequestMethod.POST)
@RequestMapping(value = "/test",method = RequestMethod.GET)
public String test(@RequestParam("username") String name,@RequestParam("password") String passwd){
    System.out.println(name+","+passwd);
    return "success";
}
10:01:27.103 [http-nio-8080-exec-5] DEBUG org.springframework.web.servlet.DispatcherServlet - GET "/demo6/test?username=admin&password=123456", parameters={masked}
10:01:27.107 [http-nio-8080-exec-5] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped to com.example.mvc.controller.TestController#test(String, String)
admin,123456
4. 控制器方法形参是一个实体类

控制器方法形参是一个实体类,且实体类属性名称与请求参数名称一致。

package com.example.mvc.bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private Integer id;
    private String username;
    private String password;
}
//    @RequestMapping(value = "/test",method = RequestMethod.POST)
@RequestMapping(value = "/test",method = RequestMethod.GET)
public String test(User user){
    System.out.println(user);
    return "success";
}
10:03:54.520 [http-nio-8080-exec-7] DEBUG org.springframework.web.servlet.DispatcherServlet - GET "/demo6/test?username=admin&password=123456", parameters={masked}
10:03:54.523 [http-nio-8080-exec-7] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped to com.example.mvc.controller.TestController#test(User)
User(id=null, username=admin, password=123456)
5. 使用RequestEntity(仅用于获取查询字符串)
@RequestMapping(value = "/test",method = RequestMethod.GET)
public String test(RequestEntity<String> requestEntity){
    URI uri = requestEntity.getUrl();
    String query = uri.getQuery();
    String[] arr = query.split("&");
    for(String el:arr){
        String[] keyValues= el.split("=");
        String key = keyValues[0];
        String value = keyValues[1];
        System.out.println(key+"="+value);
    }
    return "success";
}
10:30:37.640 [http-nio-8080-exec-5] DEBUG org.springframework.web.servlet.DispatcherServlet - GET "/demo6/test?username=admin&password=123456", parameters={masked}
10:30:37.641 [http-nio-8080-exec-5] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped to com.example.mvc.controller.TestController#test(RequestEntity)
10:30:37.661 [http-nio-8080-exec-5] DEBUG org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor - Read "application/octet-stream" to []
username=admin
password=123456
6. 使用@RequestBody(不接受get请求,接受post请求,且必须包含请求体)

使用@RequestBody时,不接受get请求,否则报错:Required request body is missing
使用@RequestBody时,可以接受post请求,且必须包含请求体数据。

  • 比如,使用form发送post请求,控制器方法形参是String类型。
    在这里插入图片描述
<form th:action="@{/test}" method="post">
    username:<input type="text" name="username" /><br/>
    password:<input type="password" name="password"/><br/>
    <input type="submit" value="提交"/>
</form>
@RequestMapping(value = "/test",method = RequestMethod.POST)
public String test(@RequestBody String requestBody){
    System.out.println(requestBody);
    return "success";
}
14:27:15.741 [http-nio-8080-exec-6] DEBUG org.springframework.web.servlet.DispatcherServlet - POST "/demo6/test", parameters={masked}
14:27:15.744 [http-nio-8080-exec-6] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped to com.example.mvc.controller.TestController#test(String)
14:27:15.767 [http-nio-8080-exec-6] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor - Read "application/x-www-form-urlencoded;charset=UTF-8" to ["username=admin&password=123456"]
username=admin&password=123456
  • 比如,使用axios发送post请求,控制器方法形参是String类型。
    在这里插入图片描述
<body>
    <button onclick="handleClick()">点击测试</button>
    <script th:src="@{/static/js/axios.min.js}"></script>
    <script th:inline="javascript">
        //获取上下文路径
        var contextPath = /*[[@{/}]]*/'';

        function handleClick(){
            axios({
                method:"post",
                url:contextPath+"test",
                data:{
                    "username":"admin",
                    "password":"123456"
                }
            })
        }
    </script>
</body>
@RequestMapping(value = "/test",method = RequestMethod.POST)
public String test(@RequestBody String requestBody){
    System.out.println(requestBody);
    return "success";
}
14:28:02.357 [http-nio-8080-exec-2] DEBUG org.springframework.web.servlet.DispatcherServlet - POST "/demo6/test", parameters={}
14:28:02.357 [http-nio-8080-exec-2] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped to com.example.mvc.controller.TestController#test(String)
14:28:02.358 [http-nio-8080-exec-2] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor - Read "application/json;charset=UTF-8" to ["{"username":"admin","password":"123456"}"]
{"username":"admin","password":"123456"}
  • 比如,使用axios发送post请求,控制器方法形参是一个实体类。
    在这里插入图片描述
<body>
    <button onclick="handleClick()">点击测试</button>
    <script th:src="@{/static/js/axios.min.js}"></script>
    <script th:inline="javascript">
        //获取上下文路径
        var contextPath = /*[[@{/}]]*/'';

        function handleClick(){
            axios({
                method:"post",
                url:contextPath+"test",
                data:{
                    "username":"admin",
                    "password":"123456"
                }
            })
        }
    </script>
</body>
package com.example.mvc.bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private Integer id;
    private String username;
    private String password;
}
@RequestMapping(value = "/test",method = RequestMethod.POST)
public String test(@RequestBody User user){
    System.out.println(user);
    return "success";
}
14:33:59.565 [http-nio-8080-exec-6] DEBUG org.springframework.web.servlet.DispatcherServlet - POST "/demo6/test", parameters={}
14:33:59.566 [http-nio-8080-exec-6] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped to com.example.mvc.controller.TestController#test(User)
14:33:59.678 [http-nio-8080-exec-6] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor - Read "application/json;charset=UTF-8" to [User(id=null, username=admin, password=123456)]
User(id=null, username=admin, password=123456)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: SpringMVC获取请求参数的方式有多种,最常用的是通过注解@RequestParam获取请求参数。例如,@RequestParam("username") String username表示获取名为username的请求参数,并将其赋值给String类型的变量username。另外,还可以通过HttpServletRequest对象获取请求参数,例如HttpServletRequest.getParameter("username")。此外,还可以使用@PathVariable注解获取URL路径中的参数,例如@RequestMapping("/user/{id}"),其中{id}表示获取路径中的id参数。 ### 回答2: SpringMVC是一种基于Java的web框架,用于开发web应用程序。通过SpringMVC框架,可以很方便地获取请求参数。 在SpringMVC中,获取请求参数有多种方式。其中,最常用的方式是通过方法的参数获取请求参数。在控制器方法中定义参数参数名与请求参数名一致,SpringMVC会自动将请求参数的值绑定到对应的参数上。例如,如果请求中有一个参数名为"username"的参数,可以在控制器方法中定义一个同名的String类型的参数来接收该参数的值。 除了通过方法参数获取请求参数,还可以使用@RequestParam注解。该注解可以用于方法参数上,指定请求参数的名称,以及是否为必需的参数。例如,@RequestParam("id") int userId,表示要获取名为"id"的请求参数,并将其转换为int类型的userId参数。可以通过设置required属性来指定该参数是否必需,默认为true,如果请求中没有该参数,会抛出异常。 另外,还可以使用@PathVariable注解来获取路径参数。路径参数是在URL中定义的参数,可以通过在控制器方法的路径中使用占位符来表示。例如,@RequestMapping("/user/{id}"),可以通过@PathVariable("id")来获取路径中的参数值。 除了以上方式,还可以通过HttpServletRequest对象来获取请求参数。在控制器方法中,可以将HttpServletRequest对象作为方法参数传入,然后通过该对象的getParameter方法来获取请求参数的值。 总之,SpringMVC提供了多种简便的方式来获取请求参数。无论是通过方法参数、@RequestParam注解、@PathVariable注解,还是使用HttpServletRequest对象,都可以方便地获取请求参数的值,便于进行后续的业务逻辑处理。 ### 回答3: SpringMVC是基于Java的一种MVC(Model-View-Controller)框架,用于构建Web应用程序。在SpringMVC中,获取请求参数是非常常见的任务并且非常容易。 首先,要使用SpringMVC获取请求参数,你需要定义一个处理请求的控制器类,并在类的方法上添加@RequestMapping注解来指定请求的URL映射。 在控制器方法中,你可以使用@RequestParam注解来获取请求参数。该注解有几个属性可以使用,最常用的是value属性,用于指定请求参数的名称。例如,你可以使用@RequestParam("name")来获取名为name的请求参数。如果请求参数的名称与方法参数的名称相同,你也可以省略value属性,只使用@RequestParam注解。 @RequestParam注解也支持一些其他属性,例如required属性用于指示请求参数是否是必需的,默认为true,即必须提供该参数。你还可以使用defaultValue属性来指定请求参数的默认值。 除了@RequestParam注解,你还可以使用@PathVariable注解来获取URL路径中的参数。该注解将URL中的占位符与方法参数进行映射。例如,如果URL中有一部分为"/users/{id}",你可以在方法参数中使用@PathVariable("id")来获取该路径中的id参数。 另外,SpringMVC还支持通过@RequestParamMap注解来获取所有的请求参数,并以Map的形式进行处理。这对于处理不确定数量的请求参数非常有用。 总而言之,SpringMVC提供了多种方法来获取请求参数。你可以使用@RequestParam注解来获取单个请求参数,使用@PathVariable注解来获取URL路径中的参数,或者使用@RequestParamMap注解来获取所有的请求参数。这些功能使得处理请求参数变得非常方便和灵活。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值