javax.servlet Package
February 18, 2008 by muralis
Check here and read about javax.servlet package.
Getting and Setting Initialization Parameters for a Servlet
The servlet container supports the ability to store startup and configuration information for a servlet. After the container instantiates the servlet, it makes this information available to the servlet instance. This example demonstrates a servlet that retrieves some initialization parameters in its init() method:
// This method is called by the servlet container just before this servlet
// is put into service.
public void init() throws ServletException {
getServletContext().log(”getinit init”);
// Get the value of an initialization parameter
String value = getServletConfig().getInitParameter(”param1″);
// Get all available intialization parameters
java.util.Enumeration enum = getServletConfig().getInitParameterNames();
for (; enum.hasMoreElements(); ) {
// Get the name of the init parameter
String name = (String)enum.nextElement();
// Get the value of the init parameter
value = getServletConfig().getInitParameter(name);
}
// The int parameters can also be retrieved using the servlet context
value = getServletContext().getInitParameter(”param1″);
}
The initialization parameters for the servlet are specified in the deployment descriptor (i.e., web.xml file). Here is an example of a deployment descriptor that specifies two initialization parameters:
MyServletName
com.mycompany.MyServlet
param1
value1
param2
value2
…
…
Note that the leading and trailing space around the parameter value is trimmed.
Saving Data in a ServletThere are three places a servlet can save data for its processing - in the request, in the session (if present), and in the servlet context (which is shared by all servlets and JSP pages in the context). Data saved in the request is destroyed when the request is completed. Data saved in the session is destroyed when the session is destroyed. Data saved in the servlet context is destroyed when the servlet context is destroyed.Data is saved using a mechanism called attributes. An attribute is a key/value pair where the key is a string and the value is any object. It is recommended that the key use the reverse domain name convention (e.g., prefixed with com.mycompany) to minimize unexpected collisions when integrating with third party modules.
Note: The three locations are identical to the three scopes — request, session, and application - - on a JSP page . So, if a servlet saves data in the request, the data will be available on a JSP page in the request scope. A JSP page-scoped value is simply implemented by a local variable in a servlet.
This example saves and retrieves data in each of the three places:
// Save and get a request-scoped value
req.setAttribute(”com.mycompany.req-param”, “req-value”);
Object value = req.getAttribute(”com.mycompany.req-param”);
// Save and get a session-scoped value
HttpSession session = req.getSession(false);
if (session != null) {
session.setAttribute(”com.mycompany.session-param”, “session-value”);
value = session.getAttribute(”com.mycompany.session-param”);
}
// Save and get an application-scoped value
getServletContext().setAttribute(”com.mycompany.app-param”, “app-value”);
value = getServletContext().getAttribute(”com.mycompany.app-param”);
The following example retrieves all attributes in a scope:
// Get all request-scoped attributes
java.util.Enumeration enum = req.getAttributeNames();
for (; enum.hasMoreElements(); ) {
// Get the name of the attribute
String name = (String)enum.nextElement();
// Get the value of the attribute
Object value = req.getAttribute(name);
}
// Get all session-scoped attributes
HttpSession session = req.getSession(false);
if (session != null) {
enum = session.getAttributeNames();
for (; enum.hasMoreElements(); ) {
// Get the name of the attribute
String name = (String)enum.nextElement();
// Get the value of the attribute
Object value = session.getAttribute(name);
}
}
// Get all application-scoped attributes
enum = getServletContext().getAttributeNames();
for (; enum.hasMoreElements(); ) {
// Get the name of the attribute
String name = (String)enum.nextElement();
// Get the value of the attribute
Object value = getServletContext().getAttribute(name);
}
Getting a Request Parameter in a ServletIn a GET request, the request parameters are taken from the query string (the data following the question mark on the URL). For example, the URL http://hostname.com?p1=v1&p2=v2 contains two request parameters - - p1 and p2. In a POST request, the request parameters are taken from both query string and the posted data which is encoded in the body of the request. This example demonstrates how to get the value of a request parameter in either a GET or POST request.// See also e1035 The Quintessential Servlet
// This method is called by the servlet container to process a GET request.
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
doGetOrPost(req, resp);
}
// This method is called by the servlet container to process a POST request.
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
doGetOrPost(req, resp);
}
// This method handles both GET and POST requests.
private void doGetOrPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// Get the value of a request parameter; the name is case-sensitive
String name = “param”;
String value = req.getParameter(name);
if (value == null) {
// The request parameter ‘param’ was not present in the query string
// e.g. http://hostname.com?a=b
} else if (”".equals(value)) {
// The request parameter ‘param’ was present in the query string but has no value
// e.g. http://hostname.com?param=&a=b
}
// The following generates a page showing all the request parameters
PrintWriter out = resp.getWriter();
resp.setContentType(”text/plain”);
// Get the values of all request parameters
Enumeration enum = req.getParameterNames();
for (; enum.hasMoreElements(); ) {
// Get the name of the request parameter
name = (String)enum.nextElement();
out.println(name);
// Get the value of the request parameter
value = req.getParameter(name);
// If the request parameter can appear more than once in the query string, get all values
String[] values = req.getParameterValues(name);
for (int i=0; i<values.length; i++) {
out.println(” “+values[i]);
}
}
out.close();
}
Preventing Concurrent Requests to a ServletBy default, a servlet container will use a servlet instance to concurrently process multiple requests. Although, this behavior burdens the servlet developer to properly synchronize shared state, this ability to handle multiple requests allows for a more scalable architecture. However, if it is necessary to disable this ability, the servlet should implement the SingleThreadModel interface:// This servlet can only handle a single request at a time.
public class MyServlet extends HttpServlet implements SingleThreadModel {
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// Handle GET request…
}
}
However, forcing the servlet container to route requests one at a time through a servlet does not prevent the container from creating multiple instances of the servlet. Hence, the servlet developer must still properly synchronize shared state. Effectively, the main benefit of implementing the SingleThreadModel is not having to synchronize the servlet’s instance variables.
Getting the Requesting URL in a ServletA servlet container breaks up the requesting URL into convenient components for the servlet. The standard API does not require the original requesting URL to be saved and therefore it is not possible to get the requesting URL exactly as the client sent it. However, a functional equivalent of the original URL can be constructed. The following example assumes the original requesting URL is:http://hostname.com/mywebapp/servlet/MyServlet/a/b;c=123?d=789
The most convenient method for reconstructing the original URL is to use ServletRequest.getRequestURL(), which returns all but the query string. Adding the query string reconstructs an equivalent of the original requesting URL:
// http://hostname.com/mywebapp/servlet/MyServlet/a/b;c=123?d=789
public static String getUrl(HttpServletRequest req) {
String reqUrl = req.getRequestURL().toString();
String queryString = req.getQueryString(); // d=789
if (queryString != null) {
reqUrl += “?”+queryString;
}
return reqUrl;
}
If the hostname is not needed, ServletRequest.getRequestURI() should be used:
// /mywebapp/servlet/MyServlet/a/b;c=123?d=789
public static String getUrl2(HttpServletRequest req) {
String reqUri = req.getRequestURI().toString();
String queryString = req.getQueryString(); // d=789
if (queryString != null) {
reqUri += “?”+queryString;
}
return reqUri;
}
The original URL can also be reconstructed from more basic components available to the servlet:
// http://hostname.com:80/mywebapp/servlet/MyServlet/a/b;c=123?d=789
public static String getUrl3(HttpServletRequest req) {
String scheme = req.getScheme(); // http
String serverName = req.getServerName(); // hostname.com
int serverPort = req.getServerPort(); // 80
String contextPath = req.getContextPath(); // /mywebapp
String servletPath = req.getServletPath(); // /servlet/MyServlet
String pathInfo = req.getPathInfo(); // /a/b;c=123
String queryString = req.getQueryString(); // d=789
// Reconstruct original requesting URL
String url = scheme+”://”+serverName+”:”+serverPort+contextPath+servletPath;
if (pathInfo != null) {
url += pathInfo;
}
if (queryString != null) {
url += “?”+queryString;
}
return url;
}
// Get client’s IP address
String addr = req.getRemoteAddr(); // 123.123.123.123
// Get client’s hostname
String host = req.getRemoteHost(); // hostname.com
Processing a HEAD Request in a ServletBy default, a HEAD request is automatically processed by the HttpServlet.doGet() method using a modified response object that simply counts and discards any characters written to the buffer. If it is necessary to improve the performance of a servlet that is frequently accessed with a HEAD request method, you can override the HttServlet.doHead() method and implement a more efficient algorithm. Typically, a doHead() implementation sets the content length and type, as demonstrated by this example.Note: In the JWSDP 1.0, calling resetBuffer() does nothing in a HEAD request. Therefore, if resetBuffer() is used during servlet processing, a GET and HEAD request may return different content lengths.
// See also e1035 The Quintessential Servlet
// This method is called by the servlet container to process a HEAD request.
// There may be many threads calling this method simultaneously.
public void doHead(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// Set the content length and type
resp.setContentLength(123);
resp.setContentType(”text/html”);
}