When I send Objects of Javascript to my Spring boot application, it says "Invalid character found in the request target"

huangapple go评论78阅读模式
英文:

When I send Objects of Javascript to my Spring boot application, it says "Invalid character found in the request target"

问题

我已经为这个问题搜索了所有可能性,但是无法弄清楚为什么会发生这种情况。
我想在JavaScript中的localstorage中保存一个对象,然后获取此对象并将数据发送到我的spring boot应用程序。但是当我调用ajax时,它给我一个错误,错误如下:

```java
java.lang.IllegalArgumentException: 请求目标中发现无效字符[/product/cart/items?{%22cartItems%22:[{%22itemId%22:%22asfasfa%22,%22itemCount%22:2},{%22itemId%22:%22ijhar%22,%22itemCount%22:3}]}]。有效字符在RFC 7230和RFC 3986中定义
	at org.apache.coyote.http11.Http11InputBuffer.parseRequestLine(Http11InputBuffer.java:491) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	// 更多错误信息...

JavaScript代码

$(document).ready(function() {

  function getAllItemsFromCart() {
    let product;
    product = JSON.parse(localStorage.getItem("items"));
    return product;
  }
  
  let itemsList = {};
  let cartItems = [];
  let items = {};
  items['itemId'] = 'asfasfa';
  items['itemCount'] = 2;
  cartItems.push(items);
  items = {};
  items['itemId'] = 'ijhar';
  items['itemCount'] = 3;
  cartItems.push(items);
  itemsList['cartItems'] = cartItems;

  localStorage.setItem('items', JSON.stringify(itemsList));
  let itemsList1 = getAllItemsFromCart();

  $.ajax({
    url: "[[@{/product/cart/items}]]",
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    method: "GET",
    data: JSON.stringify(itemsList1),
    dataType: "json",
    success: function(response, status, xhr) {
      console.log("这是成功消息");
    },
    error: function(response) {
      console.debug(response.status + ":" + response.statusText);
    },
    beforeSend: function() {
      //talman.showAjaxLoader();
    },
    complete: function() {
      //talman.closeAjaxLoader();
    }

  });
});

Java控制器

@GetMapping(value = "/cart/items", consumes = "application/json", produces = "application/json")
@ResponseBody
public String addProductToCart(@RequestBody CartItemsBean itemList){  
   return "成功";
}

Bean

class ItemsBean {
    private String itemId;
    private String itemCount;

    public String getItemId() {
        return itemId;
    }

    public void setItemId(String itemId) {
        this.itemId = itemId;
    }

    public String getItemCount() {
        return itemCount;
    }

    public void setItemCount(String itemCount) {
        this.itemCount = itemCount;
    }
}

public class CartItemsBean {
    private List<ItemsBean> cartItems;

    public List<ItemsBean> getCartItems() {
        return cartItems;
    }

    public void setCartItems(List<ItemsBean> cartItems) {
        this.cartItems = cartItems;
    }
}

<details>
<summary>英文:</summary>

I have searched for every possibility for this problem but couldn&#39;t figure out why is it happening.
It want to save an object in localstorage in javascript, then fetch this object and send data to my spring boot application. But when i call ajax, it gives me an error which is below

java.lang.IllegalArgumentException: Invalid character found in the request target [/product/cart/items?{%22cartItems%22:[{%22itemId%22:%22asfasfa%22,%22itemCount%22:2},{%22itemId%22:%22ijhar%22,%22itemCount%22:3}]}]. The valid characters are defined in RFC 7230 and RFC 3986
at org.apache.coyote.http11.Http11InputBuffer.parseRequestLine(Http11InputBuffer.java:491) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:260) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590) [tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.36.jar:9.0.36]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_265]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_265]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.36.jar:9.0.36]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_265]

**JavaScript code**

&lt;!-- begin snippet: js hide: false console: true babel: false --&gt;

&lt;!-- language: lang-js --&gt;

    $(document).ready(function() {

      function getAllItemsFromCart() {
        let product;
        product = JSON.parse(localStorage.getItem(&quot;items&quot;));
        return product;
      }
      
      let itemsList = {};
      let cartItems = [];
      let items = {};
      items[&#39;itemId&#39;] = &#39;asfasfa&#39;;
      items[&#39;itemCount&#39;] = 2;
      cartItems.push(items);
      items = {};
      items[&#39;itemId&#39;] = &#39;ijhar&#39;;
      items[&#39;itemCount&#39;] = 3;
      cartItems.push(items);
      itemsList[&#39;cartItems&#39;] = cartItems;

      localStorage.setItem(&#39;items&#39;, JSON.stringify(itemsList));
      let itemsList1 = getAllItemsFromCart();

      $.ajax({
        url: &quot;[[@{/product/cart/items}]]&quot;,
        headers: {
          &#39;Accept&#39;: &#39;application/json&#39;,
          &#39;Content-Type&#39;: &#39;application/json&#39;
        },
        method: &quot;GET&quot;,
        data: JSON.stringify(itemsList1),
        dataType: &quot;json&quot;,
        success: function(response, status, xhr) {
          console.log(&quot;This is success message&quot;)
        },
        error: function(response) {
          console.debug(response.status + &quot;:&quot; + response.statusText);
        },
        beforeSend: function() {
          //talman.showAjaxLoader();
        },
        complete: function() {
          //talman.closeAjaxLoader();
        }

      });
    });

**Java controller**

@GetMapping(value = "/cart/items",consumes = "application/json", produces = "application/json")
@ResponseBody
public String addProductToCart(@RequestBody CartItemsBean itemList){
return "sucess";
}


**Bean**

class ItemsBean {
private String itemId;
private String itemCount;

public String getItemId() {
    return itemId;
}

public void setItemId(String itemId) {
    this.itemId = itemId;
}

public String getItemCount() {
    return itemCount;
}

public void setItemCount(String itemCount) {
    this.itemCount = itemCount;
}

}

public class CartItemsBean {
private List<ItemsBean> cartItems;

public List&lt;ItemsBean&gt; getCartItems() {
    return cartItems;
}

public void setCartItems(List&lt;ItemsBean&gt; cartItems) {
    this.cartItems = cartItems;
}

}



</details>


# 答案1
**得分**: 1

出于安全原因,Spring Boot 不接受在查询参数中使用某些特殊字符。

但是我认为在您的情况下,您需要使用 JSON.stringify 进行封装。

顺便说一句,让 GET 请求接收请求体或者充当 POST 或 PATCH 请求有点奇怪。

<details>
<summary>英文:</summary>

For security reasons, Spring Boot doesn&#39;t accept some special characters on QueryParams. 

But I think in your case you need to use JSON.stringfy to wrap it.

By the way, It is a bit weird to have a GET receiving body or acting as a POST or PATCH. 


</details>



huangapple
  • 本文由 发表于 2020年9月4日 12:09:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/63734718.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定