Tutorial :How the attribute field of a HttpServletRequest maps to a raw HTTP request?



Question:

In Java, the attribute field of a HttpServletRequest object can be retrieved using the getAttribute method:

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

Where the HttpServletRequest attribute data is stored in a raw HTTP request? Is it in the body of the request?

For example, I'm trying to create a raw GET HTTP request that will be sent to my servlet using some client program. My servlet.doGet() method would be something like this:

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

Where should I put the 'my.username' data in the raw HTTP request so that the 'myAttribute' String receives the value "John Doe" after the attribution?


Solution:1

To add to @gid's answer, attributes are not present in any way in the HTTP request as it travels over the wire. They are created (by your code) when processing the request. A very common use is to have a server set (aka create) some attributes and then forward to a JSP that will make use of those attributes. That is, an HTTP request arrives and is sent to a Servlet. The Servlet attaches some attributes. Additional server-side processing is done, eventually sending the page to a JSP, where the attributes are used. The response is generated in the JSP. The HTTP request and the HTTP response do not contain any attributes. Attributes are 100% purely server-side information.

When a single given HTTP request has completed, the attributes become available for garbage collection (unless they are persisted in some other location, such as a session). Attributes are only associated with a single request object.


Solution:2

Just to be clear as I think @Jon's answer doesn't make it perfectly clear. The values for getAttribute and setAttribute on HttpServletRequest are not present on what is actually sent over the wire, they are server side only.

// 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");   


Solution:3

I think what he is really asking is "how do I get parameteres into my program", not attributes. If that is the question, then send parameters in the GET request as part of the URL (after a question mark, http://myhost.com/myapp?name=joe&age=26) then retrieve them using request.getParameter("name") and request.getParameter("age"), or whatever you need.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »