hidden and output comments

hidden: <%-- --%> output:

implicit objects

request, response, pageContext, session, application, out, config, page, exception

64 kb limit

JVM has a 64kb limit on the size of the method and the entire JSP page is rendered as a single method. If a JSP page is greater than 64kb, this probably indicates poor implementation. When this method reaches its limit of 64kb it throws an error. This error can be overcome by splitting the JSP files and including them dynamically (i.e. using ) because the dynamic includes generate separate JSP Servlet for each included file.

static vs dynamic include

  • Static include: <%@ include %>, During the translation or compilation phase all the included JSP pages are compiled into a single Servlet.
  • Dynamic include: , The dynamically included JSP is compiled into a separate Servlet. It is a separate resource, which gets to process the request, and the content generated by this resource is included in the JSP response. Has run time performance overhead.
  • Use “static includes” when a JSP page does not change very often. For the pages, which change frequently, use dynamic includes.
  • The “dynamic include” (jsp:include) has a flush attribute. This attribute indicates whether the buffer should be flushed before including the new content.

JSP different scope values

Page: Available to the handling JSP page only. Request: Available to the handling JSP page or Servlet and forwarded JSP page or Servlet. Session: Available to any JSP Page or Servlet within the same session. Application: Available to all the JSP pages and Servlets within the same Web Application.

JSP Scripting Elements

SAD
  • Scripting Elements: embedded Java statements.
  • Declaration Element: is the embedded Java declaration statement, which gets inserted at the Servlet class level, so it is not thread safe. <%! %>
  • Expression Element: is the embedded Java expression, which gets evaluated by the service method. <%= %>
  • Scriptlet Elements: are the embedded Java statements, which get executed as part of the service method. <% %>
  • Action Elements: A JSP element that provides information for execution phase.
  • Directive Elements: A JSP element that provides global information for the translation phase.
<%@ page import=”java.util.Date” %> <%@ include file=”myJSP” %> <%@ taglib uri=”tagliburi” prefix=”myTag”%>

life cycle methods of a JSP

  • Pre-translated: Before the JSP file has been translated and compiled into the Servlet.
  • Translated: The JSP file has been translated and compiled as a Servlet.
  • Initialized: Prior to handling the requests in the service method the container calls the jspInit() to initialize the Servlet. Called only once per Servlet instance.
  • Servicing: Services the client requests. Container calls this method for each request.
  • Out of service: The Servlet instance is out of service. The container calls the jspDestroy() method.

URL mapping

http://localhost:8080/myApps/mine/test.do
  • web.xml
MyServlet< /servlet-name> myPath.MyServ let MyServlet< /servlet-name> mine/*.do
  • application.xml
............ m yAppsWeb.wa r< /web-u ri> myApps< /con text-root> < /module> ........ myEJB.jar < /module> .....

J2EE design pattern

Composite View: include sub views View Helper: JavaBean, Custom Tags Service Helper and Dispatcher View:

Core J2EE Patterns - Service to Worker revisit

Front Controller

  • Apply the common logic (security check, flow control), which is shared by multiple requests in the Front controller.
  • Separate the system processing logic from the view processing logic.
  • Provides a controlled and centralized access point for your system.

Declarative Security

PrivateAndSensitive /private/* executive admin FORM /login.jsp /error.jsp The user will be prompted for the configured login.jsp when restricted resources are accessed. The container also keeps track of which users have been previously authenticated.

Filter

  • A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses but typically do not themselves create responses.
  • Filters improve reusability by placing recurring tasks in the filter as a reusable unit.
  • The filters can be used for
    • caching and compressing content,
    • logging and auditing,
    • image conversions (scaling up or down etc),
    • authenticating incoming requests,
    • XSL transformation of XML content,
    • localization of the request and the response,
    • site hit count etc.
  • The filters are configured through the web.xml file as follows:
HitCounterFilter myPkg.HitCounterFilter HitCounterFilter /usersection/* ...
  • Servlet filters use the slightly modified version of the chain of responsibility design pattern.

Session replication

Session replication occurs when we replicate the information (ie session attributes) that are stored in your HttpSession. The container propagates the changes only when you call the setAttribute method. So mutating the objects in a session and without calling the setAttribute will not replicate the state change.

servlet clustering

  • Objects stored in a session should be serializable to support in-memory replication of sessions. Also consider the overhead of serializing very large objects. Test the performance to make sure it is acceptable.
  • Design for idempotence. Failure of a request or impatient users clicking again can result in duplicate requests being submitted. So the Servlets should be able to tolerate duplicate requests.
  • Avoid using instance and static variables in read and write mode because different instances may exist on different JVMs. Any state should be held in an external resource such as a database.
  • Avoid storing values in a ServletContext. A ServletContext is not serializable and also the different instances may exist in different JVMs.
  • Avoid using java.io.* because the files may not exist on all backend machines. Instead use
  • getResourceAsStream().

sendRedirect() vs. forward

sendRedirect
  • Sends a header back to the browser, which contains the name of the resource to be redirected to. The browser will make a fresh request from this header information.
  • Need to provide absolute URL path.
  • Has an overhead of extra remote trip.
  • but has the advantage of being able to refer to any resource on the same or different domain
  • also allows book marking of the page.
forward
  • Forward action takes place within the server without the knowledge of the browser.
  • No extra network trip.

RequestDispatcher

ServletContext sc = getServletContext(); RequestDispatcher rd = sc.getRequestDispatcher(url); rd.forward(request,response); rd.include(request, response);

Lazy loading servlet

  • By default the container does not initialize the servlets as soon as it starts up. It initializes a servlet when it receives a request for the first time for that servlet. This is called lazy loading.
  • The servlet deployment descriptor (web.xml) defines the element, which can be configured to make the servlet container load and initialize the servlet as soon as it starts up.

Thread Safe Servlet

  • A typical Servlet life cycle creates a single instance of each servlet and creates multiple threads to handle the service() method. The multithreading aids efficiency but the servlet code must be coded in a thread safe manner. The shared resources (e.g. instance variables, utility or helper objects etc) should be appropriately synchronized or should only use variables in a read-only manner.
  • Alternatively it is possible to have a single threaded model of a servlet by implementing SingleTreadModel.
  • The container will will use one of the following approaches to ensure thread safety:
    • Instance pooling: where container maintains a pool of servlets.
    • Sequential processing: where new requests will wait while the current request is being processed.
  • Best practice: It is best practice to use multi-threading and stay away from the single threaded model of the servlet unless otherwise there is a compelling reason for it.

HttpServlet vs GenericServlet

  • Generic Servlet: Protocol independent, service() method
  • HttpServlet: Protocol dependent, doGet(), doPost(), doHead() methods.