jump to navigation

Attributes August 24, 2005

Posted by Coolguy in Servlets/Jsp.
add a comment
  • Attribute is a object bound to other servlet API objects like ServletContext,HttpServletRequest,HttpSession
  • Types:
    Application
    Request
    Session
  • To set an attribute :
    setAttribute(String name,Object value)
  • Method to get:
    getAttribute(String name)
  • Return type:
    Object
  • Scope of attribute:
    Context,
    Session ,
    Request
  • Three attribute scopes Context,Session,Request are handled by ServletContext,ServletRequest,HttpSession interfaces
  • Methods are:
    getAttribute(String)
    setAttribute(String,Object)
    removeAttribute(String)
    getAttributeNames()
  • Context scope attributes are not thread-safe
  • Session scope attributes are not thread-safe as its one thread per request not one per session.
  • To make them thread safe synchronize ServletContext and HttpSession respectively
  • Request variables and local variables are thread safe
  • Instance variables are also not thread safe
Advertisements

Servlet Listeners August 24, 2005

Posted by Coolguy in Servlets/Jsp.
add a comment
  • Attribute added,removed or replaced: ServletContextAttributeListener
  • Tracking active sessions: HttpSessionListener
  • Log each request: ServletRequestListener
  • Request attribute added,removed or replaced: ServletRequestAttributeListener
  • Attributes added to session: HttpSessionBindingListener
  • Session attribute added,removed or replaced: HttpSessionAttributeListener
  • Context created or destroyed: ServletContextListener
  • Attributes notified when the session is migrating to another JVM:HttpSessionActivationListener


HttpSessionAttributeListener

  • This class knows when any type of attribute has been added,removed or replaced in a session


HttpSessionBindingListener

  • Attribute itself can find out when it has been added to or removed from a session
  • E.g:
    import javax.servlet.http.*;public class Dog implements HttpSessionBindingListener
    {
    private String breed;

    public Dog(String breed)
    {
    this.breed=breed;
    }
    public String getBreed()
    {
    return breed;
    }
    public void valueBound(HttpSessionBindingEvent arg0)
    {
    // TODO Auto-generated method stub
    }
    public void valueUnbound(HttpSessionBindingEvent arg0)
    {
    // 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:
    <init-param>
    <description>test parameter
    <param-name>myname
    <param-value>DummyValue
    </init-param>
    String name=ServletConfig.getInitParameter(“myname”);
    Enumeration e= getServletConfig().getInitParameterNames();

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

Nutshell

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

Detail

  • 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:

    <servlet>
    <display-name>InitParamTest</display-name>
    <servlet-name>InitParamTest</servlet-name>
    <servlet-class>
    test.InitParamTest</servlet-class>
    <init-param>
    <description>test parameter</description>
    <param-name>myname</param-name>
    <param-value>DummyValue</param-value>
    </init-param>
    </servlet>

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

ServletContext:

  • 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>
    <param-name>myname</param-name>
    <param-value>DummyValue</param-value>
    </context-param
    getServletContext.getInitParameter(“myname”);

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

The Response Object August 23, 2005

Posted by Coolguy in Servlets/Jsp.
Tags:
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:
    setHeader
    addHeader
  • 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:
    setIntHeader
    setDateHeader
    addIntHeader
    addDateHeader
  • 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:
    sendRedirect
    • 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.

Gotchas

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

Servlet Lifecycle August 23, 2005

Posted by Coolguy in Servlets/Jsp.
add a comment

Nutshell

  • 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.

Detailed

  • 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.
Tags:
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.

Core Syntax August 22, 2005

Posted by Coolguy in Servlets/Jsp.
add a comment

Core Syntax

  • A JSP page defines a JSP page implementation class that implements the semantics of the JSP page.
  • This class implements the javax.servlet.Servlet Interface
  • At request time a request intended for the JSP page is delivered to the JSP page implementation object for processing.
  • HTTP is the default protocol for requests and responses. Additional request/ response protocols may be supported by JSP containers.
  • A JSP container is a system-level entity that provides life-cycle management and runtime support for JSP pages and servlet components.
  • Requests sent to a JSP page are delivered by the JSP container to the appropriate JSP page implementation object.
  • A traditional application domain of the JSP technology is HTML content.
  • An increasingly important application domain for JSP technology is dynamic XML content using formats like XHTML.
  • A JSP container manages two phases of a JSP page’s lifecycle.
  • In the translation phase, the container validates the syntactic correctness of the JSP pages and tagfiles and determines a JSP page implementation class that corresponds to the JSP page.
  • During the translation phase the container locates or creates the JSP page implementation class that corresponds to a given JSP page. This process is determined by the semantics of the JSP page.
  • In the execution phase the container manages one or more instances of this class in response to requests and other events.


Events in JSP Pages

  • A JSP page may indicate how some events are to be handled.
  • init and destroy events can be described in the JSP page.
  • When the first request is delivered to a JSP page, a jspInit() method, if present, will be called to prepare the page.
  • Similarly, a JSP container invokes a JSP’s jspDe-stroy() method to reclaim the resources used by the JSP page at any time when a request is not being serviced.

JSP Configuration

  • JSP pages may be extended with configuration information that is delivered in the JSP configuration portion of the web.xml deployment description of the web application.
  • The JSP configuration information includes interpretation for the tag libraries used in the JSP files and different property information for groups of JSP files.

Naming Conventions for JSP Files

  • By default the extension .jsp means a top-level JSP file.
  • JSP documents, that is, JSP pages that are delivered as XML documents, use the extension .jspx by default.
  • The jsp-property-group element of web.xml can be used to indicate that some group of files, perhaps not using either of the extensions above, are JSP pages, and can also be used to indicate which ones are delivered as XML documents.

Compiling JSP Pages

  • A JSP page may be compiled into its implementation class plus deployment information during development
  • The benefits of this approach include: • Removal of the start-up lag that occurs when a container must translate a JSP page upon receipt of the first request.
    • Reduction of the footprint needed to run a JSP container, as the Java compiler is not needed.

Relative URL’s

  • A context-relative path is a path that starts with a slash (/).It is to be interpreted as relative to the application to which the JSP page or tag file belongs.
  • A page relative path is a path that does not start with a slash (/). It is to be interpreted relative to the current JSP page, or the current JSP file or tag file,

Elements

  • There are three types of elements:
  • directive elements,
  • scripting elements,
  • action elements.

Directives

  • Directives provide global information that is conceptually valid independent of any specific request received by the JSP page.
  • They provide information for the translation phase.
  • Directive elements have a syntax of the form <%@ directive…%>.

Actions

  • Actions provide information for the request processing phase.
  • The interpretation of an action may, and often will, depend on the details of the specific request received by the JSP page.
  • An Actions can either be standard, or custom (that is, provided via the portable tag extension mechanism).
  • Action elements follow the syntax of an XML element. They have a start tag including the element name, and may have attributes, an optional body, and a matching end tag, or may be an empty tag, possibly with attributes:

<mytag attr1=”attribute value”…>body</mytag>
<mytag attr1=”attribute value”…/>
<mytag attr1=”attribute value” …></mytag>

Scripting Elements

  • Scripting elements provide “glue” around template text and actions.
  • JSP 2.0 has a simple Expression Language (EL) that can be used to simplify accessing data from different sources.
  • EL expressions use the syntax ${expr};
  • Other language-based types of scripting elements are: declarations, scriptlets, and expressions.
  • Declarations follow the syntax <%! … %>.
  • Scriptlets follow the syntax <% … %>.
  • Expressions follow the syntax<%= … %>.

JSP Documents

  • A JSP Document is a JSP page that is also an XML document.
  • When a JSP document is encountered by the JSP container, it is interpreted as an XML document first and after that as a JSP page.
  • Among the consequences of this are:
    • The document must be well-formed
    • Validation, if indicated
    • Entity resolution will apply, if indicated

Error Handling

  • Errors may occur at translation time or at request time.
  • The translation of a JSP page source into a corresponding JSP page implementation class by a JSP container can occur at any time between initial deployment of the JSP page into the JSP container and the receipt and processing of a client request for the target JSP page.
  • In all cases, fatal translation failures shall result in the failure of subsequent client requests for the translation target with the appropriate error specification: For HTTP protocols the error status code 500 (Server Error) is returned.
  • During the processing of client requests, errors can occur in either the body of the JSP page implementation class, or in some other code (Java or other implemen-tation programming language) called from the body of the JSP page implementation class.
  • These exceptions may be caught and handled (as appropriate) in the body of the JSP page implementation class.
  • Any uncaught exceptions thrown in the body of the JSP page implementation class result in the forwarding of the client request and uncaught exception to the errorPage URL specified by the JSP page
  • A JSP is considered an Error Page if it sets the page directive’s isErrorPage attribute to true.
  • If a page has isErrorPage set to true, then the “exception” implicit
    scripting language variable of that page is initialized.
  • The variable is set to the value of the javax.servlet.error.exception request attribute value if present

Comments

  • There are two types of comments in a JSP page
  • Comments to the JSP page itself, documenting what the page is doing
  • Comments that are intended to appear in the generated document sent to the client.
  • In order to generate comments that appear in the response output stream to the requesting client, the HTML and XML comment syntax is used, as follows:
    <!– comments … –>
  • A JSP comment is of the form
    <%– anything but a closing –%> … –%>