HttpServletRequest的属性字段如何映射到原始HTTP请求?

时间:2009-05-26 16:17:29

标签: java http servlets

在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”?

3 个答案:

答案 0 :(得分:17)

我想@ 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"); 

答案 1 :(得分:12)

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

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

答案 2 :(得分:3)

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