简体   繁体   English

当带有数据的POST请求到达Java Servlet时读取URL参数

[英]Reading URL parameters when POST request with data arrives in Java Servlet

In Java servlets you read a JSON from a POST request eg via 在Java Servlet中,您可以通过POST请求读取JSON,例如通过

new JSONObject(toString(httpRequest.getInputStream()))

Now additionally to the JSON I would like to specify parameters in the URL, they can be read via: 现在,除了JSON,我想在URL中指定参数,可以通过以下方式读取它们:

httpRequest.getParameterMap().get("someURLParam")

All is working (I'm using AJAX post requests and jetty for server side) 一切正常 (我在服务器端使用AJAX发布请求和码头)

BUT

I'm concerned and confused if and when these two methods influence each other as the javadocs from javax.​servlet.​ServletRequest.getParamter(String) says: 我担心和困惑这两种方法是否以及何时相互影响,就像来自javax.​servlet.​ServletRequest.getParamter(String)的javadocs一样:

If the parameter data was sent in the request body, such as occurs with an HTTP POST request, then reading the body directly via ServletRequest.getInputStream or ServletRequest.getReader can interfere with the execution of this method. 如果参数数据是在请求正文中发送的(例如与HTTP POST请求一起发送),则直接通过ServletRequest.getInputStream或ServletRequest.getReader读取正文可能会干扰此方法的执行。

What does it mean in my case? 对我而言是什么意思? Or do they only interfere if content type is x-www-form-urlencoded ? 还是仅在内容类型为x-www-form-urlencoded干扰它们? Or only if using getParameter and the method getParameterMap is fine? 还是仅当使用getParameter并且方法getParameterMap很好时?

If you are only using getParameter/getParameterMap, you will be fine. 如果仅使用getParameter / getParameterMap,就可以了。 This is because, behind the scenes, those methods may call getInputStream. 这是因为在后台,这些方法可能会调用getInputStream。 The spec says MAY because it's up to the implementation, so the behavior may vary from one container to another. 规范说MAY是因为它取决于实现,因此行为可能因一个容器而异。

If your content isn't form encoded, or you are processing a GET request, etc., getParameter/getParameterMap only needs to get the parameters from the query string, so it makes sense that Jetty wouldn't read the body in those cases. 如果您的内容不是经过表单编码的,或者您正在处理GET请求等,则getParameter / getParameterMap仅需要从查询字符串中获取参数,因此在这种情况下,Jetty不会读取主体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM