java - 使用 RequestMapping 和 fromUriString 从浏览器进行 http 调用中的任意输入参数

标签 java http spring-boot

我有以下电话:

http://localhost:8080/report?name=HelloReport&download=true

如何在http请求末尾附加任意输入参数?

我的代码:

    ...
    @RequestMapping(value = "/report", params = {"name", "download"})
    public ResponseEntity<byte[]> report(
        @RequestParam(value = "name") String name,
        @RequestParam(value = "download") boolean download) {

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType("application/pdf"));
    if (download) {
        headers.setContentDispositionFormData("inline", name + ".pdf");
    }
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");

    //MultiValueMap<String, String> parameters = UriComponentsBuilder.fromUriString(request.getRequestURI()).build().getQueryParams();
    ...

我想使用:

MultiValueMap<String, String> parameters = UriComponentsBuilder.fromUriString(request.getRequestURI()).build().getQueryParams();

新的 http 是什么样子的?

新的@RequestMapping和report()方法是什么样的?

最佳答案

您的 Spring 注释不允许任意查询参数。它可能会根据端点所需的缺少参数来限制对端点的访问。但不会限制额外端点对端点的访问。

基于该方法,现在我可以使用此查询 /report?name=test&download=false&myfoobar=21243hjof&blablablaba=beepboopbap 访问它。 Spring不关心我添加的myfoobarblablablaba .

要访问所有内容,只需添加 HttpServletRequest方法签名的参数,顺序并不重要

@RequestMapping(value = "/report", params = {"name", "download"})
public ResponseEntity<byte[]> report(
    HttpServletRequest request,
    @RequestParam(value = "name") String name,
    @RequestParam(value = "download") boolean download) {

然后只需使用即可获取所有参数

request.getQueryString() // everything after ?, so its name=test&download=false&myfoobar=21243hjof&blablablaba=beepboopbap

或者您可以使用请求方法:

request.getParameter("myfoobar") // 21243hjof

或者对于你的例子,你可以这样做

MultiValueMap<String, String> parameters = UriComponentsBuilder.fromUriString("?"+request.getQueryString()).build().getQueryParams();
<小时/>

您也可以使用@RequestParam Map<String,String> allRequestParams获取所有参数。

@RequestMapping(value = "/report", params = {"name", "download"})
public ResponseEntity<byte[]> report(
    @RequestParam Map<String,String> allRequestParams,
    @RequestParam(value = "name") String name,
    @RequestParam(value = "download") boolean download) {

关于java - 使用 RequestMapping 和 fromUriString 从浏览器进行 http 调用中的任意输入参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47100693/

相关文章:

c - 用c语言构建简单的http客户端

http - fasthttp中获取一个请求参数key-value

java - 使用 Hibernate JPA 启动 Spring Boot 应用程序时出现 NoSuchMethodError

java - 如何使用 OpenSMPP

java - 迁移到新 Roo 版本的问题

java - JButton 数组上的 ActionListener

c++ - native IIS7.5 模块未运行

jenkins - Spring Boot-Gradle Intellij Idea构建和Jenkins构建结果不相同。

java - httpSession.getAttribute ("userId") 在来自 Angular 前端的一些频繁的 API 请求后,在 Spring Boot 中返回 null

java - KeyListener 不工作?