Tuesday, May 20, 2008

Servlets Basics

javax.servlet.http.HttpServlet Is an abstract class that extends the javax.servlet.GenericServlet class.
All the methods in it have protected identifier and the service method is overloaded

protected void service(HttpServletRequest req, HttpServletResponse resp)

Receives standard HTTP requests from the public service method and dispatches them to the doXXX methods defined in this class.

 void service(ServletRequest req, ServletResponse res)

Dispatches client requests to the protected service method.

Clicking on a hyperlink always sends a GET request and thus, the doGet() method of the servlet will be called. < href = " /servlet/TestServlet " method="POST"> Some URL < / a >
The method="POST" attribute-value pair does not make sense in the anchor tag.
Retrieve Request Parameter

String[ ] getParameterValues(String paramName)

The above method is for html element like dropbox etc
 Enumeration getParameterNames() 

This method is useful when you don’t know the names of the parameters. You can iterate through the Enumeration of Strings returned by this method and for each element you can call getParameter() or getParameterValues().

Retrieve request headers

There is one difference , though; unlike parameters, headers are specific to the HTTP protocol and so the methods that deal with the headers belong to HttpServletRequest and not to ServletRequest.

 String getHeader(String headerName) 

This method returns just one of the values associated with the given header.
 Enumeration getHeaderValues(String headerName)

This method returns all the values associated with the header as an Enumeration of String object.
 Enumeration getHeaderNames() 

This method is useful when you don’t know the names of the headers. You can iterate through the enumeration returned by this method, and for each element you can call getHeader() or getHeaderValues().

Which method would you use to retrieve the number of parameters present in a request?
Neither ServletRequest nor HttpServletRequest provides any method to retrieve the number of parameters directly. You’ll have to use ServletRequest.getParameterNames(), which returns an Enumeration, and count the number of parameters yourself.

No comments: