SpringBoot获取URL请求参数方式

直接把表单的参数写在Controller相应的方法的形参中

适用于get方式提交,不适用于post方式提交。
url形式:http://localhost/SSMDemo/demo/addUser1?username=lixiaoxi&password=111111 提交的参数需要和Controller方法中的入参名称一致。

/**
 * 1.直接把表单的参数写在Controller相应的方法的形参中
 * @param username
 * @param password
 * @return
**/
@RequestMapping("/addUser1")
public String addUser1(String username,String password) {
	System.out.println("username is:"+username);
	System.out.println("password is:"+password);
	return "demo/index";
}

使用HttpServletRequest接收

适用于post方式和get方式都可以

/**
 - 2、通过HttpServletRequest接收
 - @param request
 - @return
**/
@RequestMapping("/addUser2")
public String addUser2(HttpServletRequest request) {
	String username=request.getParameter("username");
	String password=request.getParameter("password");
	System.out.println("username is:"+username);
	System.out.println("password is:"+password);
	return "demo/index";
}

GET:

  • 地址栏中直接给出参数:http://localhost/param/ParamServlet?p1=v1&p2=v2;
  • 超链接中给出参数:<a href=”
    http://localhost/param/ParamServlet?p1=v1&p2=v2”>???
  • 表单中给出参数:…
  • Ajax暂不介绍

POST:

  • 表单中给出参数:
<form method=”POST” action=”ParamServlet”></form>
  • Ajax暂不介绍

URL传参数无论是用GET还是POST都是可以的,只是POSt还多了更多数据传输通道(还可以通过body传更多数据,而不受URL长度限制),而且利用URL传参的格式是统一的,不区分GET和POST

springboot在普通类中获取HttpServletRequest对象

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
HttpServletRequest request =((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();

常用API

  1. Map getParameterMap():获取所有参数对应的Map,其中key为参数名,value为参数值。(推荐使用)

  2. String param = request.getQueryString(); 该方法获取到的参数,部分字符是经过转义的,如"<“转义成”%3C"等。

    private static Map<String, String> getQueryMap(HttpServletRequest request, String charset) throws IOException {
        Map<String, String> queryMap = new HashMap<String, String>();
        String queryString = request.getQueryString();
        String[] params = queryString.split("&");
        for (int i = 0; i < params.length; i++) {
            String[] kv = params[i].split("=");
            if (kv.length == 2) {
                String key = URLDecoder.decode(kv[0], charset);
                String value = URLDecoder.decode(kv[1], charset);
                queryMap.put(key, value);
            } else if (kv.length == 1) {
                String key = URLDecoder.decode(kv[0], charset);
                queryMap.put(key, "");
            }
        }
        return queryMap;
    }
  1. String getParameter(String name):通过指定名称获取参数值;

  2. String[] getParameterValues(String name):通过指定名称获取参数值数组,有可能一个名字对应多个值,例如表单中的多个复选框使用相同的name时;

  3. Enumeration getParameterNames():获取所有参数的名字;

HttpServletRequest可以通过getQueryString和getInputStream和getParameterMap来获取参数。
三者有什么区别:

在这里插入图片描述

使用一个bean来接收

适用于post方式和get方式都可以。

  • 建立一个和表单中参数对应的bean
package demo.model;
 
public class UserModel {
    
    private String username;
    private String password;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    
}
  • 用这个bean来封装接收的参数
/**
 * 3、通过一个bean来接收
  * @param user
 * @return
 */
@RequestMapping("/addUser3")
public String addUser3(UserModel user) {
	System.out.println("username is:"+user.getUsername());
	System.out.println("password is:"+user.getPassword());
	return "demo/index";
}

使用@PathVariable获取路径中的参数

例如,访问http://localhost/SSMDemo/demo/addUser4/lixiaoxi/111111 路径时,则自动将URL中模板变量{username}和{password}绑定到通过@PathVariable注解的同名参数上,即入参后username=lixiaoxi、password=111111。

/**
 * 4、通过@PathVariable获取路径中的参数
  * @param username
 * @param password
 * @return
 */
@RequestMapping(value="/addUser4/{username}/{password}",method=RequestMethod.GET)
public String addUser4(@PathVariable String username,@PathVariable String password) {
	System.out.println("username is:"+username);
	System.out.println("password is:"+password);
	return "demo/index";
}

使用注解@RequestParam绑定请求参数到方法入参

当请求参数username不存在时会有异常发生,可以通过设置属性required=false解决,例如: @RequestParam(value=“username”, required=false)

/**
 * 6、用注解@RequestParam绑定请求参数到方法入参
  * @param username
 * @param password
 * @return
 */
@RequestMapping(value="/addUser6",method=RequestMethod.GET)
public String addUser6(@RequestParam("username") String username,@RequestParam("password") String password) {
	System.out.println("username is:"+username);
	System.out.println("password is:"+password);
	return "demo/index";
}

使用@ModelAttribute注解获取POST请求的FORM表单数据

Jsp表单如下:

<form action ="<%=request.getContextPath()%>/demo/addUser5" method="post"> 
     用户名:&nbsp;<input type="text" name="username"/><br/>&nbsp;&nbsp;码:&nbsp;<input type="password" name="password"/><br/>
     <input type="submit" value="提交"/> 
     <input type="reset" value="重置"/> 
</form>

Java Controller如下:

/**
 * 5、使用@ModelAttribute注解获取POST请求的FORM表单数据
  * @param user
 * @return
 */
@RequestMapping(value="/addUser5",method=RequestMethod.POST)
public String addUser5(@ModelAttribute("user") UserModel user) {
	System.out.println("username is:"+user.getUsername());
	System.out.println("password is:"+user.getPassword());
	return "demo/index";
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用 RestTemplate 发送带参数的 POST 请求,示例代码如下: ```java RestTemplate restTemplate = new RestTemplate(); MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); params.add("param1", "value1"); params.add("param2", "value2"); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers); String url = "http://example.com/api"; String response = restTemplate.postForObject(url, requestEntity, String.class); ``` 其中,params 是请求参数,headers 是请求头,requestEntity 是请求实体,url请求地址,response 是响应结果。 ### 回答2: 使用Spring Boot发送带参数的POST请求,可以通过RestTemplate或者使用HttpClient来实现。以下是使用RestTemplate发送带参数的POST请求的示例代码: ```java @RestController public class MyController { @Autowired private RestTemplate restTemplate; @PostMapping("/sendPost") public String sendPostWithParams() { String url = "http://example.com/api"; // 设置请求头 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); // 设置请求参数 MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); params.add("param1", "value1"); params.add("param2", "value2"); // 创建请求实体对象 HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers); // 发送POST请求并返回结果 ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class); HttpStatus statusCode = responseEntity.getStatusCode(); String responseBody = responseEntity.getBody(); return "Status code: " + statusCode + "\n" + "Response body: " + responseBody; } } ``` 在该示例中,首先通过`@Autowired`注解将`RestTemplate`自动注入到`MyController`中,然后在`sendPostWithParams`方法中构建请求头和请求参数。构建请求头时,我们设置了`Content-Type`为`application/json`,你也可以根据实际需求设置其他类型。构建请求参数时,我们使用了`MultiValueMap`来存储参数,可以根据需要添加更多参数。然后,将请求头和请求参数封装到`HttpEntity`对象中。最后使用`restTemplate`的`postForEntity`方法发送POST请求,并获取返回的状态码和响应体。最后将结果返回给客户端。 注意:在使用RestTemplate发送POST请求前,需要先添加RestTemplate的依赖,例如在pom.xml文件中添加以下依赖: ```xml <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web-services</artifactId> </dependency> </dependencies> ``` 然后,你需要在Spring Boot应用的配置类中添加一个`@Bean`注解来创建`RestTemplate`的实例,例如: ```java @Configuration public class AppConfig { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } } ``` 以上就是使用Spring Boot发送带参数的POST请求的一个简单示例。 ### 回答3: 在Spring Boot中发送带参数的POST请求,可以通过使用RestTemplate或者HttpClient来实现。 使用RestTemplate发送POST请求的示例代码如下: ``` import org.springframework.http.*; import org.springframework.web.client.RestTemplate; public class PostRequestExample { public static void main(String[] args) { // 创建RestTemplate对象 RestTemplate restTemplate = new RestTemplate(); // 构造请求体和请求头 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); // 构造请求参数 MultiValueMap<String, Object> params = new LinkedMultiValueMap<>(); params.add("param1", "value1"); params.add("param2", "value2"); // 创建HttpEntity对象,设置请求体和请求头 HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, headers); // 发送POST请求 ResponseEntity<String> response = restTemplate.exchange("URL", HttpMethod.POST, requestEntity, String.class); // 获取响应结果 String responseBody = response.getBody(); System.out.println(responseBody); } } ``` 上述代码中,我们通过RestTemplate发送了一个POST请求,并且设置了请求参数。其中,`param1`和`param2`是请求参数的键,对应的`value1`和`value2`是请求参数的值。 另外,还需要自定义请求头`Content-Type`为`application/json`,根据实际情况设置请求URL地址,然后使用RestTemplate的`exchange`方法发送POST请求。 当然,你也可以使用HttpClient来发送POST请求。使用HttpClient发送POST请求的示例代码如下: ``` import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class PostRequestExample { public static void main(String[] args) throws Exception { // 创建HttpClient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建HttpPost对象,并设置请求URL HttpPost httpPost = new HttpPost("URL"); // 构造请求参数 StringEntity params = new StringEntity("{\"param1\":\"value1\",\"param2\":\"value2\"}"); // 设置请求头和请求体 httpPost.addHeader("Content-Type", "application/json"); httpPost.setEntity(params); // 发送POST请求 CloseableHttpResponse response = httpClient.execute(httpPost); // 获取响应结果 HttpEntity entity = response.getEntity(); String responseBody = EntityUtils.toString(entity); System.out.println(responseBody); // 关闭资源 response.close(); httpClient.close(); } } ``` 上述代码中,我们通过HttpClient发送了一个POST请求,并且设置了请求参数请求头。其中,请求参数是一个JSON字符串,根据实际情况设置请求URL地址。通过设置请求头`Content-Type`为`application/json`,然后使用HttpClient的`execute`方法发送POST请求。 以上就是使用Spring Boot发送带参数的POST请求的示例代码,你可以根据实际情况进行调整和扩展。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值