【问题标题】:How the attribute field of a HttpServletRequest maps to a raw HTTP request?HttpServletRequest 的属性字段如何映射到原始 HTTP 请求?
【发布时间】:2010-10-29 00:46:46
【问题描述】:

在 Java 中,可以使用 getAttribute 方法检索 HttpServletRequest 对象的属性字段:

String myAttribute = request.getAttribute("[parameter name]");

HttpServletRequest 属性数据存储在原始 HTTP 请求中的什么位置?它在请求的正文中吗?

例如,我正在尝试创建一个原始的 GET HTTP 请求,该请求将使用一些客户端程序发送到我的 servlet。我的 servlet.doGet() 方法是这样的:

public void doGet(HttpServletRequest request, HttpServletResponse response)
{
     String myAttribute = request.getAttribute("my.username");
     ...
}

我应该将“my.username”数据放在原始 HTTP 请求中的什么位置,以便“myAttribute”字符串在归属之后接收值“John Doe”?

【问题讨论】:

    标签: java http servlets


    【解决方案1】:

    为了清楚起见,我认为@Jon 的回答并没有说得很清楚。 HttpServletRequest 上的 getAttribute 和 setAttribute 的值并不存在于实际通过网络发送的内容中,它们仅存在于服务器端。

    // only visible in this request and on the server
    request.getAttribute("myAttribute"); 
    
    // value of the User-Agent header sent by the client
    request.getHeader("User-Agent"); 
    
    // value of param1 either from the query string or form post body
    request.getParameter("param1"); 
    

    【讨论】:

      【解决方案2】:

      添加到@gid 的答案中,HTTP 请求中不存在任何属性,因为它通过网络传输。它们是在处理请求时(由您的代码)创建的。一个非常常见的用途是让服务器设置(也称为创建)一些属性,然后转发到将使用这些属性的 JSP。也就是说,一个 HTTP 请求到达并被发送到一个 Servlet。 Servlet 附加了一些属性。完成额外的服务器端处理,最终将页面发送到使用属性的 JSP。响应在 JSP 中生成。 HTTP 请求和 HTTP 响应不包含任何属性。属性是 100% 纯服务器端信息。

      当一个给定的 HTTP 请求完成后,这些属性就可用于垃圾回收(除非它们被持久化在某个其他位置,例如会话)。属性只与单个请求对象相关联。

      【讨论】:

        【解决方案3】:

        我认为他真正要问的是“我如何将参数放入我的程序中”,而不是属性。如果这是问题所在,则在 GET 请求中发送参数作为 URL 的一部分(在问号之后,http://myhost.com/myapp?name=joe&age=26),然后使用 request.getParameter("name") 和 request.getParameter("age") 检索它们,或任何你需要的。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-01-10
          • 2014-06-21
          • 1970-01-01
          • 2022-01-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多