jump to navigation

ServletContext Listener August 24, 2005

Posted by Coolguy in Java.
add a comment
  • To listen for ServletContext events write a listener class that implements
    and tell the container by putting a <listener> element in DD.
  • This class will get notifed when context is initialized and destroyed
  • E.g:
    Listener Class
    import javax.servlet.*;
    public class MyServletContextListener implements ServletContextListener{
    public void contextInitialized(ServletContextEvent se)
    ServletContext sc=se.getServletContext();
    String breed=sc.getInitParameter(“breed”);
    Dog d = new Dog(breed);
    public void contextDestroyed(ServletContextEvent se)
    Testing servlet
    import java.io.IOException;
    import java.io.PrintWriter;import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    public class ListenerTest extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
    public ListenerTest()

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    PrintWriter out = response.getWriter();
    Dog dog = (Dog) getServletContext().getAttribute(“dog”);

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    // TODO Auto-generated method stub


Servlet Config August 23, 2005

Posted by Coolguy in Servlets/Jsp.
add a comment
  • When container initializes a servlet it makes a unique ServletConfig for the servlet
  • The container reads the servlet init parameters from the deployment descriptor and gives them to the ServletConfig and then passes ServletConfig to the servlet’s init() method
  • There is one version of init which takes a ServletConfig as a parameter and there is one which doesn’t
  • Developers typically override the no-arg version as the arg version calls the no-arg version !!
  • Once the parameters are in ServletConfig, container never reads the init parameters again till the servlet is redeployed.
  • E.g:
    <description>test parameter
    String name=ServletConfig.getInitParameter(“myname”);
    Enumeration e= getServletConfig().getInitParameterNames();

Session Tracking August 23, 2005

Posted by Coolguy in J2EE.
add a comment

Session Tracking Mechanisms

  • Cookies : Session tracking through HTTP cookies is the most used session tracking mechanism and is required to be supported by all servlet containers. The container sends a cookie to the client. The client will then return the cookie on each subsequent request to the server, unambiguously associating the request with a session. The name of the session tracking cookie must be JSESSIONID.
  • SSL Sessions : Secure Sockets Layer, the encryption technology used in the HTTPS protocol, has abuilt-in mechanism allowing multiple requests from a client to be unambiguously identified as being part of a session. A servlet container can easily use this data to define a session.
  • URL Rewriting : When a client will not accept a cookie, URL rewriting may be used by the server as the basis for session tracking. URL rewriting involves adding data, a session ID, to the URL path that is interpreted by the container to associate the request with a session. The session ID must be encoded as a path parameter in the URL string. The name of the parameter must be jsessionid. Here is an example of a URL containing encoded path information:http://www.myserver.com/catalog/index.html;jsessionid=1234
  • A client joins a session when session tracking information has been returned to the server indicating that a session has been established.
  • HttpSession objects must be scoped at the application (or servlet context) level.
  • Object referenced, including the attributes in that object, must never be shared between contexts by the container.
  • A servlet can bind an object attribute into an HttpSession implementation by name. Any object bound into a session is available to any other servlet that belongs to the same ServletContext and handles a request identified as being a part of the same session.
  • Some objects may require notification when they are placed into, or removed from, a session. This information can be obtained by having the object implement the HttpSessionBindingListener interface.
  • This interface defines the following methods that will signal an object being bound into, or being unbound from, a session.• valueBound• valueUnbound
  • The valueBound method must be called before the object is made available via the getAttribute method of the HttpSession interface.
  • The valueUnbound method must be called after the object is no longer available via the getAttributemethod of the HttpSession interface.
  • The default timeout period for sessions is defined by the servlet container and can be obtained via the getMaxInactiveInterval method of the HttpSession interface.
  • This timeout can be changed by the Developer using the setMaxInactiveInterval method of the HttpSession interface. The timeout periods used by these methods are defined in seconds.
  • If the timeout period for a session is set to -1, the session will never expire.
  • The session invalidation will not take effect until all servlets using that session have exited theservice method.
  • The getLastAccessedTime method of the HttpSession interface allows a servlet to determine the last time the session was accessed before the current request.
  • Multiple servlets executing request threads may have active access to a single session object at the same time.
  • Within an application marked as distributable, all requests that are part of a session must be handled by one Java Virtual Machine1 (“JVM”) at a time.
  • The distributed servlet container must support the mechanism necessary for migrating objects that implement Serializable.
  • In distributes systems, the Container Provider can ensure scalability and quality of service featureslike load-balancing and failover by having the ability to move a session object, and its contents, from any active node of the distributed system to a different node of the system.
  • Containers must notify any session attributes implementing the HttpSessionActivationListener during migration of a session. They must notify listeners of passivation prior to serialization of a session, and of activation after deserialization of a session.
  • Developer should always assume that all windows of a client are participating in the same session.

Servlet Interface August 23, 2005

Posted by Coolguy in Servlets/Jsp.
add a comment
  • The Servlet interface is the central abstraction of the Java Servlet API. All servlets implement this interface either directly, or more commonly, by extending a class that implements the interface.
  • The two classes in the Java Servlet API that implement the Servlet interface are GenericServlet and HttpServlet. For most purposes, Developers will extend HttpServlet to implement their servlets.
  • The basic Servlet interface defines a service method for handling client requests. This method is called for each request that the servlet container routes to an instance of a servlet.
  • Generally the Web container handles concurrent requests to the same servlet by concurrent execution of the service method on different threads.
  • The HttpServlet abstract subclass adds additional methods beyond the basic Servlet interface that are automatically called by the service method in the HttpServlet class to aid in processing HTTP-based requests.
  • These methods are:• doGet for handling HTTP GET requests• doPost for handling HTTP POST requests• doPut for handling HTTP PUT requests• doDelete for handling HTTP DELETE requests• doHead for handling HTTP HEAD requests• doOptions for handling HTTP OPTIONS requests• doTrace for handling HTTP TRACE requests
  • Typically when developing HTTP-based servlets, a Servlet Developer will only concern himself with the doGet and doPost methods.
  • The doPut and doDelete methods allow Servlet Developers to support HTTP/1.1 clients that employ these features.
  • The doHead method in HttpServlet is a specialized form of the doGet method that returns only the headers produced by the doGet method.
  • The doOptions method responds with which HTTP methods are supported by the servlet.
  • The doTrace method generates a response containing all instances of the headers sent in the TRACE request.
  • The HttpServlet interface defines the getLastModified method to support conditional GET operations. A conditional GET operation requests a resource be sent only if it has been modified since a specified time.
  • For a servlet not hosted in a distributed environment (the default), the servlet container must use only one instance per servlet declaration.
  • For a servlet implementing the SingleThreadModel interface, the servlet container may instantiate multiple instances to handle a heavy request load and serialize requests to a particular instance.
  • In the case where a servlet was deployed as part of an application marked in the deployment descriptor as distributable, a container may have only one instance per servlet declaration per Java Virtual Machine (JVM).
  • The use of the SingleThreadModel interface guarantees that only one thread at a time will execute in a given servlet instance’s service method.
  • SingleThreadModel Interface is deprecated now

Servlet Context August 23, 2005

Posted by Coolguy in Servlets/Jsp.
add a comment


  • Context parameters are available to entire webapp
  • Any servlet or JSP in the webapp can access context parameters
  • Eg:
  • To get ServletContext
    getServletConfig.getServletContext.getInitParameter(“myname”); or
  • You need to use getServletConfig.getServletContext.getInitParameter(“myname”); if you are in a Servlet class that doesn’t inherit GenericServlet or HttpServlet.


  • The ServletContext interface defines a servlet’s view of the Web application within which the servlet is running.
  • The Container Provider is responsible for providing an implementation of the ServletContext interface in the servlet container.
  • Using the ServletContext object, a servlet can log events, obtain URL references to resources, and set and store attributes that other servlets in the context can access.
  • ServletContext is rooted at a known path within a Web server. For example, a servlet context could be located at http://www.mycorp.com/catalog. All requests that begin with the /catalog request path, known as the context path, are routed to the Web application associated with the ServletContext.
  • There is one instance object of the ServletContext interface associated with each Web application deployed into a container.
  • In cases where the container is distributed over many virtual machines, a Web application will have an instance of the ServletContext for each JVM.
  • The following methods of the ServletContext interface allow the servlet access tocontext initialization parameters associated with a Web application as specified bythe Application Developer in the deployment descriptor:• getInitParameter• getInitParameterNames
  • Initialization parameters are used by an Application Developer to convey setup information. Typical examples are a Webmaster’s e-mail address, or the name of a system that holds critical data.
  • A servlet can bind an object attribute into the context by name.
  • Any attribute bound into a context is available to any other servlet that is part of the same Webapplication.
  • The following methods of ServletContext interface allow access to this functionality:• setAttribute• getAttribute• getAttributeNames• removeAttribute
  • Context attributes are local to the JVM in which they were created.
  • When information needs to be shared between servlets running in a distributed environment, the information should be placed into a session
  • The ServletContext interface provides direct access only to the hierarchy of static content documents that are part of the Web application, including HTML, GIF, and JPEG files, via the following methods of the ServletContext interface:• getResource• getResourceAsStream
  • The getResource and getResourceAsStream methods take a String with a leading “/” as an argument that gives the path of the resource relative to the root of the context.
  • This hierarchy of documents may exist in the server’s file system, in a Web application archive file, on a remote server, or at some other location.
  • These methods are not used to obtain dynamic content. For example, in a container supporting the JSP a method call of the form getResource(“/index.jsp”) would return the JSP source code and not theprocessed output.
  • The full listing of the resources in the Web application can be accessed using the getResourcePaths(String path) method.
  • Web servers may support multiple logical hosts sharing one IP address on a server. This capability is sometimes referred to as “virtual hosting”. In this case, each logical host must have its own servlet context or set of servlet contexts. Servlet contexts can not be shared across virtual hosts.
  • A temporary storage directory is required for each servlet context. Servletcontainers must provide a private temporary directory for each servlet context, andmake it available via the javax.servlet.context.tempdir context attribute.
  • This common convenience provided in many servlet engine implementations.
  • The container is not required to maintain the contents of the temporary directory when the servlet container restarts, but is required to ensure that the contents of the temporary directory of one servlet context is not visible to the servlet contexts of other Web applications running on the servletcontainer.

ServletConfig vs ServletContext August 23, 2005

Posted by Coolguy in Servlets/Jsp.
add a comment

ServletConfig :

  • One ServletConfig per servlet
  • Used to pass deploy-time info to servlet and configured in deployment descriptor
  • Used to access ServletContext
  • Within servlet element in DD:

    <description>test parameter</description>

  • getServletConfig.getInitParameter(“myname”);
  • Available to only to the servlet which has init-param configured


  • One per webapp
  • If webapp is distributed, one per JVM
  • Used to access webapp parameters configured in deployment descriptor
  • Application bulletin-board
  • Use to get server info
  • Within web-app element of DD
  • <context-param>

  • Avilable to any servlet or JSP that are part of webapp

The Response Object August 23, 2005

Posted by Coolguy in Servlets/Jsp.
add a comment
  • The response object encapsulates all information to be returned from the server to the client. In the HTTP protocol, this information is transmitted from the server to the client either by HTTP headers or the message body of the request.
  • A servlet container is allowed, but not required, to buffer output going to the client for efficiency purposes.
  • The following methods in the ServletResponse interface allow a servlet to access and set buffering information:
    • getBufferSize
    • setBufferSize
    • isCommitted
    • reset
    • resetBuffer
    • flushBuffer
  • These methods are provided on the ServletResponse interface to allow buffering operations to be performed whether the servlet is using a ServletOutputStream or a Writer.
  • The getBufferSize method returns the size of the underlying buffer being used. If no buffering is being used, this method must return the int value of 0 (zero).
  • The servlet can request a preferred buffer size by using the setBufferSize method. The buffer assigned is not required to be the size requested by the servlet, but must be at least as large as the size requested.
  • The method must be called before any content is written using a ServletOutputStream or Writer. If any content has been written or the response object has been committed, this method must throw an IllegalStateException.
  • The isCommitted method returns a boolean value indicating whether any response bytes have been returned to the client.
  • The flushBuffer method forces content in the buffer to be written to the client.
  • The reset method clears data in the buffer when the response is not committed. Headers and status codes set by the servlet prior to the reset call must be cleared as well.
  • The resetBuffer method clears content in the buffer if the response is not committed without clearing the headers and status code.
  • If the response is committed and the reset or resetBuffer method is called, an IllegalStateException must be thrown. The response and its associated buffer will be unchanged.
  • A servlet can set headers of an HTTP response via the following methods of the HttpServletResponse interface:
  • The setHeader method sets a header with a given name and value. A previous header is replaced by the new header. Where a set of header values exist for the name, the values are cleared and replaced with the new value.It overwrites a exisiting value if the header is present.
  • The addHeader method adds a header value to the set with a given name. If there are no headers already associated with the name, a new set is created.It adds a additional value to the header if its already present.
  • Headers may contain data that represents an int or a Date object. The following convenience methods of the HttpServletResponse interface allow a servlet to set a header using the correct formatting for the appropriate data type:
  • To be successfully transmitted back to the client, headers must be set before the response is committed. Headers set after the response is committed will be ignored by the servlet container.
  • Servlet programmers are responsible for ensuring that the Content-Type header is appropriately set in the response object for the content the servlet is generating.
  • Servlet containers must not set a default content type when the servlet programmer does not set the type.
  • Containers use the X-Powered-By HTTP header to publish its implementation information. Eg: X-Powered-By: Servlet/2.4 JSP/2.0 (Tomcat/5.0 JRE/1.4.1)
  • The following convenience methods exist in the HttpServletResponse interface:
    • sendError
  • The sendRedirect method will set the appropriate headers and content body to redirect the client to a different URL.
  • It is legal to call this method with a relative URL path, however the underlying container must translate the relative path to a fully qualified URL for transmission back to the client. If a partial URL is given and, for whatever reason, cannot be converted into a valid URL, then this method must throw an IllegalArgumentException.
  • The sendError method will set the appropriate headers and content body for an error message to return to the client. An optional String argument can be provided to the sendError method which can be used in the content body of the error.
  • These methods will have the side effect of committing the response, if it has not already been committed, and terminating it. No further output to the client should be made by the servlet after these methods are called. If data is written to the response after these methods are called, the data is ignored.
  • Servlets should set the locale and the character encoding of a response.
  • The locale is set using the ServletResponse.setLocale method. The method can be called repeatedly; but calls made after the response is committed have no effect.
  • If the servlet does not set the locale before the page is committed, the container’s default locale is used to determine the response’s locale
  • If the servlet does not specify a character encoding before the getWriter method of the ServletResponse interface is called or the response is committed, the default ISO-8859-1 is used.
  • Containers must communicate the locale and the character encoding used for the servlet response’s writer to the client if the protocol in use provides a way for doing so. In the case of HTTP, the locale is communicated via the Content-Language header, the character encoding as part of the Content-Type header for text media types.
  • When a response is closed, the container must immediately flush all remaining content in the response buffer to the client.
  • The following events indicate that the servlet has satisfied the request and that the response object is to be closed:
    • The termination of the service method of the servlet.
    • The amount of content specified in the setContentLength method of the response has been written to the response.
    • The sendError method is called.
    • The sendRedirect method is called.
  • Each response object is valid only within the scope of a servlet’s service method, or within the scope of a filter’s doFilter method. Containers commonly recycle response objects in order to avoid the performance overhead of response object creation.


  • println() to a PrintWriter
  • PrintWriter writer = response.getWriter();
  • write() to a ServletOutputStream
  • ServletOutputStream out=response.getOutputStream();
  • setHeader() takes two string parameters

Servlet Lifecycle August 23, 2005

Posted by Coolguy in Servlets/Jsp.
add a comment


  • Servlet starts life when container finds the servlet class file.
  • This happens when container starts up.
  • Finding the class is the first step
  • Loading the class is second step
  • Loading happens on container startup or on first client use.
  • Web container instantiates the servlet and the default constructor of the servlet runs. Constructor makes only a object not servlet.
  • Container then initializes the servlet by calling init() on servlet.
  • The init() method is called only once in servlet’s lifecycle.
  • This happens only once after the servlet instance is created but before the servlet can service any requests.
  • init() method gives servlet access to ServletConfig and ServletContext objects
  • Initialization of servlet(getting db connections etc) can be done here.
  • Container calls service() to handle client requests.
  • Each request runs in a separate thread. There is only one instance of any servlet class
  • Service calls doGet() or doPost()
  • Container ends the servlet by calling destroy()
  • Container runs multiple threads to process multiple requests to a single servlet.
  • Its one thread per request. Not one per client.


  • A servlet is managed through a well defined life cycle that defines how it is loaded and instantiated, is initialized, handles requests from clients, and is taken out of service.
  • This life cycle is expressed in the API by the init, service, and destroy methods of the javax.servlet.Servlet interface that all servlets must implement directly or indirectly through the GenericServlet or HttpServlet abstract classes.
  • The servlet container is responsible for loading and instantiating servlets. The loading and instantiation can occur when the container is started, or delayed until the container determines the servlet is needed to service a request.
  • When the servlet engine is started, needed servlet classes must be located by the servlet container. The servlet container loads the servlet class using normal Java class loading facilities. The loading may be from a local file system, a remote file system, or other network services.
  • After the servlet object is instantiated, the container must initialize the servlet before it can handle requests from clients.
  • Initialization is provided so that a servlet can read persistent configuration data, initialize costly resources (such as JDBC™ API based connections), and perform other one-time activities.
  • The container initializes the servlet instance by calling the init method of the Servlet interface with a unique (per servlet declaration) object implementing the ServletConfig interface.
  • This configuration object allows the servlet to access name-value initialization parameters from the Web application’s configuration information.
  • The configuration object also gives the servlet access to an object (implementing the ServletContext interface) that describes the servlet’s runtime environment.
  • During initialization, the servlet instance can throw an UnavailableException or a ServletException.
  • In this case, the servlet must not be placed into active service and must be released by the servlet container. The destroy method is not called as it is considered unsuccessful initialization.
  • Developers should not assume a servlet is in an active container runtime until the init method of the Servlet interface is called.
  • A servlet should not try to establish connections to databases or Enterprise JavaBeans™ containers when only static (class) initialization methods have been invoked.
  • After a servlet is properly initialized, the servlet container may use it to handle client requests.
  • Requests are represented by request objects of type ServletRequest.
  • The servlet fills out response to requests by calling methods of a provided object of type ServletResponse. These objects are passed as parameters to the service method of the Servlet interface.
  • In the case of an HTTP request, the objects provided by the container are of types HttpServletRequest and HttpServletResponse.
  • It is strongly recommended that Developers not synchronize the service method (or methods dispatched to it) because of detrimental effects on performance.
  • A servlet may throw either a ServletException or an UnavailableException during the service of a request.
  • A ServletException signals that some error occurred during the processing of the request and that the container should take appropriate measures to clean up the request.
  • An UnavailableException signals that the servlet is unable to handle requests either temporarily or permanently.
  • If a permanent unavailability is indicated by the UnavailableException, the servlet container must remove the servlet from service, call its destroy method, and release the servlet instance. Any requests refused by the container by that cause must be returned with a SC_NOT_FOUND (404) response.
  • If temporary unavailability is indicated by the UnavailableException, the container may choose to not route any requests through the servlet during the time period of the temporary unavailability. Any requests refused by the container during this period must be returned with a SC_SERVICE_UNAVAILABLE (503) response status along with a Retry-After header indicating when the unavailability will terminate.
  • The container may choose to ignore the distinction between a permanent and temporary unavailability and treat all UnavailableExceptions as permanent, thereby removing a servlet that throws any UnavailableException from service.
  • Request and response objects should only be used within the scope of the request handling thread. References to the request and response objects should not be given to objects executing in other threads as the resulting behavior may be nondeterministic.
  • The servlet container is not required to keep a servlet loaded for any particular period of time. A servlet instance may be kept active in a servlet container for a period of milliseconds, for the lifetime of the servlet container (which could be a number of days, months, or years), or any amount of time in between.
  • When the servlet container determines that a servlet should be removed from service, it calls the destroy method of the Servlet interface to allow the servlet to release any resources it is using and save any persistent state. For example, the container may do this when it wants to conserve memory resources, or when it is being shut down.
  • Before the servlet container calls the destroy method, it must allow any threads that are currently running in the service method of the servlet to complete execution, or exceed a server-defined time limit.
  • Once the destroy method is called on a servlet instance, the container may not route other requests to that instance of the servlet. If the container needs to enable the servlet again, it must do so with a new instance of the servlet’s class.
  • After the destroy method completes, the servlet container must release the servlet instance so that it is eligible for garbage collection.
  • ServletConfig vs ServletContext
    ServletConfig :
  • One ServletConfig per servlet
  • Used to pass deploy-time info to servlet and configured in deployment descriptor
  • Used to access ServletContext
  • ServletContext:
  • One per webapp
  • Used to access webapp parameters configured in deployment descriptor
  • Application bulletin-board
  • Use to get server info

The Request Object August 23, 2005

Posted by Coolguy in Servlets/Jsp.
add a comment
  • The request object encapsulates all information from the client request. In the HTTP protocol, this information is transmitted from the client to the server in the HTTP headers and the message body of the request.
  • Request parameters for the servlet are the strings sent by the client to a servlet container as part of its request.
  • When the request is an HttpServletRequest object,the container populates the parameters from the URI query string and POST-ed data.
  • The parameters are stored as a set of name-value pairs. Multiple parameter values can exist for any given parameter name.
  • The following methods of the ServletRequest interface are available to access parameters:
    • getParameter
    • getParameterNames
    • getParameterValues
    • getParameterMap
  • The getParameterValues method returns an array of String objects containing all the parameter values associated with a parameter name.
  • The value returned from the getParameter method must be the first value in the array ofS tring objects returned by getParameterValues.
  • The getParameterMap method returns a java.util.Map of the parameter of the request, which contains names as keys and parameter values as map values.
  • Query string data is presented before post body data.
  • For example, if a request is made with a query string of a=hello and a post body of a=goodbye&a=world, the resulting parameter set would be ordered a=(hello,goodbye, world).
  • The following are the conditions that must be met before post form data will be populated to the parameter set:
    1. The request is an HTTP or HTTPS request.
    2. The HTTP method is POST.
    3. The content type is application/x-www-form-urlencoded.
    4. The servlet has made an initial call of any of the getParameter family of methods on the request object.
  • Attributes are objects associated with a request.
  • Attributes may be set by the container to express information that otherwise could not be expressed via the API, or may be set by a servlet to communicate information to another servlet (via theRequestDispatcher).
  • Attributes are accessed with the following methods of the ServletRequest interface:
    • getAttribute
    • getAttributeNames
    • setAttribute
  • Only one attribute value may be associated with an attribute name.
  • Attribute names beginning with the prefixes of “java.” and “javax.” are reserved.Similarly, attribute names beginning with the prefixes of “sun.”, and “com.sun.” are reserved for definition by Sun Microsystems.
  • A servlet can access the headers of an HTTP request through the following methodsof the HttpServletRequest interface:
    • getHeader
    • getHeaders
    • getHeaderNames
  • The getHeader method returns a header given the name of the header. There can be multiple headers with the same name, e.g. Cache-Control headers, in an HTTP request. If there are multiple headers with the same name, the getHeader method returns the first header in the request.
  • The getHeaders method allows access to all the header values associated with a particular header name, returning an Enumeration of String objects.
  • Headers may contain String representations of int or Date data. The following convenience methods of the HttpServletRequest interface provide access to header data in a one of these formats:
    • getIntHeader
    • getDateHeader
  • If the getIntHeader method cannot translate the header value to an int, a NumberFormatException is thrown.
  • If the getDateHeader method cannot translate the header to a Date object, an IllegalArgumentException is thrown.
  • The request path that leads to a servlet servicing a request is composed of manyimportant sections.
  • Context Path: The path prefix associated with the ServletContext that this servlet is a part of.
  • Servlet Path: The path section that directly corresponds to the mapping which activated this request.
  • PathInfo: The part of the request path that is not part of the Context Path or the Servlet Path.
  • If the context is not rooted at the root of the server’s name space, the context path starts with a’/’ character but does not end with a’/’ character.
  • Servlet Path starts with a’/’ character except in the case where the request is matched with the ‘/*’ pattern, in which case it is an empty string.
  • PathInfo is either null if there is no extra path, or is a string with a leading ‘/’.
  • The following methods exist in the HttpServletRequest interface to access this information:
    • getContextPath
    • getServletPath
    • getPathInfo
  • requestURI = contextPath + servletPath + pathInfo
  • E.g: SetupContext Path /catalogServlet Mapping Pattern: /lawn/*Servlet: LawnServletServlet Mapping Pattern: /garden/*Servlet: GardenServletServlet Mapping Pattern: *.jspServlet: JSPServletRequest Path : /catalog/lawn/index.html ContextPath: /catalogServletPath: /lawnPathInfo: /index.htmlRequest Path :/catalog/garden/implements/ ContextPath: /catalogServletPath: /gardenPathInfo: /implements/Request Path /catalog/help/feedback.jsp ContextPath: /catalogServletPath: /help/feedback.jspPathInfo: null
  • There are two convenience methods in the API which allow the Developer to obtain the file system path equivalent to a particular path. These methods are:
    • ServletContext.getRealPath
    • HttpServletRequest.getPathTranslated
  • The getRealPath method takes a String argument and returns a String representation of a file on the local file system to which a path corresponds.
  • The getPathTranslated method computes the real path of the pathInfo of the request.
  • The HttpServletRequest interface provides the getCookies method to obtain an array of cookies that are present in the request.
  • Typically, the only information that the client sends back as part of a cookie is the cookie name and thecookie value. Other cookie attributes that can be set when the cookie is sent to the browser, such as comments, are not typically returned.
  • If a request has been transmitted over a secure protocol, such as HTTPS, this information must be exposed via the isSecure method of the ServletRequest interface.
  • If there is an SSL certificate associated with the request, it must be exposed by the servlet container to the servlet programmer as an array of objects of type java.security.cert.X509Certificate and accessible via a ServletRequest attribute of javax.servlet.request.X509Certificate.
  • Clients may optionally indicate to aWeb server what language they would prefer the response be given in. This information can be communicated from the client using the Accept-Language header along with other mechanisms described in the HTTP/1.1 specification.
  • The following methods are provided in the ServletRequest interface to determine the preferred locale of the sender:
    • getLocale
    • getLocales
  • The getLocale method will return the preferred locale for which the client wants to accept content.
  • The getLocales method will return an Enumeration of Locale objects indicating, in decreasing order starting with the preferred locale, the locales that are acceptable to the client.
  • If no preferred locale is specified by the client, the locale returned by the getLocale method must be the default locale for the servlet container
  • The default encoding of a request the container uses to create the request reader and parse POST data must be “ISO-8859-1” if none has been specified by the client request.
  • If the client hasn’t set character encoding and the request data is encoded with a different encoding than the default as described above, breakage can occur. To remedy this situation, a new method setCharacterEncoding(String enc) has been added to the ServletRequest interface.
  • Developers can override the character encoding supplied by the container by calling this method. It must be called prior to parsing any post data or reading any input from the request. Calling this method once data has been read will not affect the encoding.
  • Each request object is valid only within the scope of a servlet’s service method, or within the scope of a filter’s doFilter method.
  • Containers commonly recycle request objects in order to avoid the performance overhead of request object creation.
  • getInputStream() could be used to get the raw bytes of everything that comes with a request
  • getRemotePort() gets the clients port
  • getServerPort() tells the port to which the request was originally sent
  • getLocalPort() tells on which port the request finally ended up.
  • Although all the requests are sent to a single port where the server is listening, server turns around and finds a different local port for each thread so that the app can handle multiple clients at the same time.

Simple MVC Example August 22, 2005

Posted by Coolguy in Java Frameworks.
add a comment

Simple MVC Example

HTML Form:

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
<meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1″>
<title>Insert title here</title>
<form method=”POST” action=”/BeerApp/SelectBeer.do”>
<body><strong>Selection Page<br></strong><br>
Select Characteristics
<select name=”colour”>
<option> Pale
<option> Brown
<option> Light
<option> Amber
<input type=”submit”>

<?xml version=”1.0″ encoding=”UTF-8″?>
<web-app id=”WebApp_ID”>

package com.example.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.example.model.BeerExpert;

public class BeerSelect extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
public BeerSelect() {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out= response.getWriter();
String selection=request.getParameter(“colour”);
out.println(“Colour you chose was: ” + selection);

BeerExpert be = new BeerExpert();
List c= be.getBrands(selection);

RequestDispatcher view= request.getRequestDispatcher(“result.jsp”);



package com.example.model;
import java.util.ArrayList;
import java.util.List;

public class BeerExpert

public List getBrands(String colour)
List brands = new ArrayList();
if (colour.equals(“light”))
return brands;


<%@ page language=”java” contentType=”text/html; charset=ISO-8859-1″ pageEncoding=”ISO-8859-1″%>
<%@ page import=”java.util.*” %>

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
<meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1″>
<title>Insert title here</title>
List styles = (List)request.getAttribute(“styles”);
Iterator it = styles.iterator();
out.println(“try ” + it.next());