Servlet Config vs. Servlet Context


The ServletConfig parameters are for a particular Servlet.
HttpServlet extends GenericServlet implements ServletConfig, myServlet.getInitParameter(paramName)
<servlet>
<servlet-name>MyServlet1</servlet-name>
<servlet-class>com.MyServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/config/config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
The ServletContext parameters are specified for the entire Web application.

In the case of a web application marked "distributed" in its deployment descriptor, there will be one context instance for each virtual machine. In this situation, the context cannot be used as a location to share global information (because the information won't be truly global). Use an external resource like a database instead. The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized. Servlet.getServletConfig(), ServletConfig.getServletContext()

<context-param>
<param-name>GlobalClassName</param-name>
<param-value>MyWebAppClass</param-value>
</context-param>

web structure

  • A public resource directory (document root): The document root is where JSP pages, client-side classes and archives, and static Web resources are stored.
  • A private directory called WEB-INF: which contains following files and directories:
    • web.xml : Web application deployment descriptor.
    • *.tld : Tag library descriptor files.
    • classes : A directory that contains server side classes like servlets, utility classes, JavaBeans etc.
    • lib : A directory where JAR (archive files of tag libraries, utility libraries used by the server side classes) files are stored.
  • Note: JSP resources usually reside directly or under subdirectories of the document root, which are directly accessible to the user through the URL. If you want to protect your Web resources then hiding the JSP files behind the WEB-INF directory can protect the JSP files from direct access.

Servlet Reload

  • Development/Test: deployed to  $server_root/servlets and timestamp comparison for each request comes in and a new custom classloader is created for reloading the new servlet.
  • Production: deployed to $server_root/classes
When a server dispatches a request to a servlet, the server first checks if the servlet's class file has changed on disk. If it has changed, the server abandons the class loader used to load the old version and creates a new instance of the custom class loader to load the new version. Old servlet versions can stay in memory indefinitely (so the effect is the other classes can still hold references to the old servlet instances, causing odd side effects, but the old versions are not used to handle any more requests. Servlet reloading is not performed for classes found in the server's classpath because the core, primordial class loader, loads those classes. These classes are loaded once and retained in memory even when their class files change.

Life cycle of a servlet

  • instantiate and init(): ready state
  • service(): spawn thread
  • destroy: for gc

Maintain state for stateless HTTP

HTTP Session: no size limit, need to remove session, set time out, serialize. Hidden field: no size limit, expose private Cookie: size limit, expose private, might be turned off. URL rewriting: size limit, expose private

CGI vs Servlet

  • CGI Common Gateway Interface, creates a heavy weight process to handle each http request. N number of copies of the same traditional CGI programs is copied into memory to serve N number of requests.
  • Servlet: Spawns a lightweight Java thread to handle each http request. Single copy of a type of servlet but N number of threads (thread sizes can be configured in an application server). In MVC, servlets process requests and select JSP views. So servlets act as controller.

web.xml

display-name
context-param
servlet: servlet-name, servlet-class, init-param
servlet-mapping: servlet-name, url-pattern
error-page: error-code, location
taglib: tablig-uri, taglib-location
security-constraint: web-resource-collection, auth-constraint
login-config: auth-method, realm-name, form-login-config
security-role

EJB classloader vs. WAR classloader

  • EJB jars in the application share the same EJB class loader.
  • WAR files get their own class loader.
This is because the EJBs have inherent relationship between one another (ie EJB-EJB communication between EJBs in different applications but hosted on the same JVM) but the Web modules do not. Every WAR file should be able to have its own WEB-INF/lib third party libraries and need to be able to load its own version of converted logon.jsp Servlet so each WEB module is isolated in its own class loader.

So if two different WEB modules want to use two different versions of the same EJB then we need to have two different ear files. In Java section the class loaders use a delegation model where the child class loaders delegate the loading up the hierarchy to their parent before trying to load it itself only if the parent can’t load it. But with regards to WAR class loaders, some application servers provide a setting to turn this behaviour off (DelegationMode=false). This delegation mode is recommended in the Servlet 2.3 specification. 

J2EE classloader

  • Above System-Classpath classloader: Children can see parent.
  • Below System-Classpath classloader: Children can see parent only if it is mentioned in MANIFEST.MF
J2EE application specific class loaders are children of the System-Classpath classloader. This class loader is responsible for loading all the dependency jar files (log4j, util.jar, common.jar), which are shared by both WEB and EJB modules. So if EJB.jar wants to refer to Common.jar and Util.jar we need to add them (space delimited) to class-path in EJB.jar’s manifest file MANIFEST.MF.
As a general rule classes should not be deployed higher in the hierarchy than they are supposed to exist. This is because if you move one class up the hierarchy then you will have to move other classes up the hierarchy as well. This is because classes loaded by the parent class loader can’t see the classes loaded by its child class loaders (uni-directional bottom-up visibility).

ejb_jar.xml

enterprise-beans
  • session: ejb-name, home, remote, ejb-class, session-type, transaction-type
  • entity: ejb-name, home, remote, ejb-class, persistence-type, prim-key-class, reentrant, cmp-field
assembly-descriptor
  • security-role
  • method-permission
  • container-transaction

application.xml

  • EJB jar modules, WEB war modules, <security-role> etc.
  • Also since EJB jar modules are packaged as jars the same way dependency libraries like log4j.jar, commonUtil.jar etc are packaged, the application.xml descriptor will distinguish between these two jar files by explicitly specifying the EJB jar modules.

Web Server vs. App Server

Web Server:
  • Supports HTTP protocol. When the Web server receives an HTTP request, it responds with an HTTP response, such as sending back an HTML page (static content) or delegates the dynamic response generation to some other program such as CGI scripts or Servlets or JSPs in the application server.
  • Uses various scalability and fault-tolerance techniques.
App Server:
  • Exposes business logic and dynamic content to the client through various protocols such as HTTP, TCP/IP, IIOP, JRMP etc.
  • Uses various scalability and fault-tolerance techniques. In addition provides resource pooling, component life cycle management, transaction management, messaging, security etc.
  • Provides services for components like Web container for servlet components and EJB container for EJB components.
With the advent of XML Web services the line between application servers and Web servers is not clear-cut. By passing XML documents between request and response the Web server can behave like an application server.

J2EE Design Patterns

http://java.sun.com/blueprints/patterns/catalog.html Filter, Front Controller, View Helper, Composite View, Dispatcher View, Service To Worker, Business Delegate, Session Facade, Service Locator, Transfer Object Assembler, Value List Handler, Composite Entity, Transfer Object, DAO, Service Activator.

Structure of ear file

App.ear
  • META-INF
    • MANIFEST.MF
    • application.xml
  • EJB.jar
    • META-INF
      • MANIFEST.MF
      • ejb-jar.xml
    • ejb classes, non-ejb classes
  • Web.war
    • META-INF
      • MANIFEST.MF
    • WEB-INF
      • web.xml
      • lib
      • classes
    • JSP, HTML, CSS, JS
  • Common.jar, Util.jar
  • 3Party.jar

how classes are found

 

jar shared by web and EJB modules

MANIFEST.MF files Manifest-Version: 1.0 Created-By: Apache Ant 1.5 Class-Path: myAppsUtil.ja

MVC 2

Model (EJB, Plain Java Classes)
  • Encapsulates business logic and application state.
View (JSP, JavaBeans, SWING, Custom Tags, etc )
  • Renders the model & has only display logic.
  • Sends user actions to the controller
  • Allows controller to select a view.
Controller (Servlet, Struts Action etc)
  • controls application behavior
  • Maps user actions to model.
  • selects view for response.
  • usually one for each functionality.

MVC

  • A model represents the core business logic and state. A model commonly maps to data in the database and will also contain core business logic.
  • A View renders the contents of a model. A view accesses the data from the model and adds display logic to present the data.
  • A Controller acts as the glue between a model and a view. A controller delegates the request to the model for application logic and state and also centralises the logic for dispatching the request to the next view based on the input parameters from the client and the application state. A controller also decouples JSP pages and the Servlet by handling the view selection.

Key benefits of multitier J2EE

  • Manageability: Each tier can be monitored, tuned and upgraded independently and different people can have clearly defined responsibilities.
  • Scalability: More hardware can be added and allows clustering (i.e. horizontal scaling).
  • Maintainability: Changes and upgrades can be performed without affecting other components.
  • Availability: Clustering and load balancing can provide availability.
  • Extensibility: Additional features can be easily added.

Multitier

  • Client tier represents Web browser, a Java or other application, Applet, WAP phone etc. The client tier makes requests to the Web server who will be serving the request by either returning static content if it is present in the Web server or forwards the request to either Servlet or JSP in the application server for either static or dynamic content.
  • Presentation tier encapsulates the presentation logic required to serve clients. A Servlet or JSP in the presentation tier intercepts client requests, manages logons, sessions, accesses the business services, and finally constructs a response, which gets delivered to client.
  • Business tier provides the business services. This tier contains the business logic and the business data. All the business logic is centralised into this tier as opposed to 2-tier systems where the business logic is scattered between the front end and the backend. The benefit of having a centralised business tier is that same business logic can support different types of clients like browser, WAP, other stand-alone applications etc.
  • Integration tier is responsible for communicating with external resources such as databases, legacy systems, ERP systems, messaging systems like MQSeries etc. The components in this tier use JDBC, JMS, J2EE Connector Architecture (JCA) and some proprietary middleware to access the resource tier.
  • Resource tier is the external resource such as a database, ERP system, Mainframe system etc responsible for storing the data. This tier is also known as Data Tier or EIS (Enterprise Information System) Tier.

advantage of multitier artchitecture

The advantages of the multi-tier architecture are:
  • Forced separation of user interface logic and business logic.
  • Business logic sits on small number of centralized machines (may be just one).
  • Easy to maintain, to manage, to scale, loosely coupled etc.

J2EE API

Component model technology: Java Servlet, JavaServer Pages(JSP), Enterprise JavaBeans(EJB).
Web services technology:
  • JAXP (Java API for XML Processing),
  • JAXR (Java API for XML Registries),
  • SAAJ (SOAP with attachment API for Java),
  • JAX-RPC (Java API for XML-based RPC),
  • JAX-WS (Java API for XML-based Web Services).
Other:
  • JDBC (Java Database Connectivity),
  • JNDI (Java Naming and Directory Interface),
  • JMS (Java Messaging Service),
  • JCA (J2EE Connector Architecture),
  • JTA (Java Transaction API), JavaMail,
  • JAF (JavaBeans Activation Framework – used by JavaMail),
  • JAAS (Java Authentication and Authorization Service),
  • JMX (Java Management eXtenstions).

Protocols

Protocols are used for access to Internet services. J2EE platform supports:
  • HTTP (HyperText Transfer Protocol),
  • TCP/IP (Transmission Control Protocol / Internet Protocol),
  • RMI (Remote Method Invocation),
  • SOAP (Simple Object Access Protocol) and
  • SSL (Secured Socket Layer) protocol.

J2EE server

A J2EE server provides system level support services such us security, transaction management, JNDI lookups, remote access etc. J2EE architecture provides configurable and nonconfigurable services. The configurable service enables the J2EE components within the same J2EE application to behave differently based on where they are deployed. For example the security settings can be different for the same J2EE application in two different production environments. The non-configurable services include enterprise bean (EJB) and servlet life cycle management, resource pooling etc.

J2EE container

Containers (Web & EJB containers) are the interface between a J2EE component and the low level platform
specific functionality that supports J2EE components. Before a Web, enterprise bean (EJB), or application client
component can be executed, it must be assembled into a J2EE module (jar, war, and/or ear) and deployed into its
container.

component vs service

A component is an application level software unit. All the J2EE components depend on the container for the system
level support like transactions, security, pooling, life cycle management, threading etc. A service is a component
Enterprise Java that can be used remotely through a remote interface either synchronously or asynchronously (e.g. Web service, messaging system, sockets, RPC etc).

J2EE component

A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with its
related classes and files and communicates with other components. The J2EE specification defines the following
J2EE components: Applet, Web component (Servlet, JSP), EJB (Session, Entity, Message), Enterprise application, Resource adapters.

What is J2EE

J2EE is an environment for developing and deploying enterprise applications. The
J2EE platform consists of J2EE components, servicesAPIs and protocols
that provide the functionality for developing multi-tiered and distributed Web based applications.

Core Dump

The JVM is a process like any other and when a process crashes a core dump is created. A core dump is a memory map of a running process. This can happen due to one of the following reasons:
  • Using JNI (Java Native Interface) code, which has a fatal bug in its native code. Example: using Oracle OCI drivers, which are written partially in native code or jdbc-odbc bridge drivers, which are written in non Java code. Using 100% pure Java drivers (communicates directly with the database instead of through client software utilizing the JNI) instead of native drivers can solve this problem. We can use Oracle thin driver, which is a 100% pure Java driver.
  • The operating system on which your JVM is running might require a patch or a service pack.
  • The JVM implementation you are using may have a bug in translating system resources like threads, file handles, sockets etc from the platform neutral Java byte code into platform specific operations. If this JVM’s translated native code performs an illegal operation then the operating system will instantly kill the process and mostly will generate a core dump file, which is a hexadecimal file indicating program’s state in memory at the time of error. The core dump files are generated by the operating system in response to certain signals. Operating system signals are responsible for notifying certain events to its threads and processes. The JVM can also intercept certain signals like SIGQUIT which is kill -3 <> from the operating system and it responds to this signal by printing out a Java stack trace and then continue to run. The JVM continues to run because the JVM has a special built-in debug routine, which will trap the signal -3. On the other hand signals like SIGSTOP (kill -23 ) and SIGKILL (kill -9 ) will cause the JVM process to stop or die. The following JVM argument will indicate JVM not to pause on SIGQUIT signal from the operating system. Java –Xsqnopause

Reasons to cause OutOfMemoryError

  • JVM may have a memory leak due to a bug in its internal heap management implementation. But this is highly unlikely because JVMs are well tested for this.
  • The application may not have enough heap memory allocated for its running. You can allocate more JVM heap size (with –Xmx parameter to the JVM) or decrease the amount of memory your application takes to overcome this. To increase the heap space: Java -Xms1024M -Xmx1024M Care should be taken not to make the –Xmx value too large because it can slow down your application. The secret is to make the maximum heap size value the right size.
  • Another not so prevalent cause is the running out of a memory area called the “perm” which sits next to the heap. All the binary code of currently running classes is archived in the “perm” area. The ‘perm’ area is important if your application or any of the third party jar files you use dynamically generate classes. For example: “perm” space is consumed when XSLT templates are dynamically compiled into classes, J2EE application servers, JasperReports, JAXB etc use Java reflection to dynamically generate classes and/or large amount of classes in your application. To increase perm space: Java -XX:PermSize=256M -XX:MaxPermSize=256M
  • you may have a memory leak in your application.

OutOfMemoryError

Any problem in pure Java code throws a Java exception or error. Java exceptions or errors will not cause a core dump (on UNIX systems) or a Dr.Watson error (on WIN32systems). Any serious Java problem will result in an OutOfMemoryError thrown by the JVM with the stack trace and consequently JVM will exit. These Java stack traces are very useful for identifying the cause for an abnormal exit of the JVM. So is there a way to know that OutOfMemoryError is about to occur? The Java JDK 1.5 has a package called java.lang.management which has useful JMX beans that we can use to manage the JVM. One of these beans is the MemoryMXBean.

Key Points

Minimising memory leaks

  • Design applications with an object’s life cycle in mind, instead of relying on the clever features of the JVM. Letting go of the object’s reference in one’s own class as soon as possible can mitigate memory problems. Example: myRef = null;
  • Unreachable collection objects can magnify a memory leak problem. In Java it is easy to let go of an entire collection by setting the root of the collection to null. The garbage collector will reclaim all the objects (unless some objects are needed elsewhere).
  • Use weak references if you are the only one using it. The WeakHashMap is a combination of HashMap and WeakReference. This class can be used for programming problems where you need to have a HashMap of information, but you would like that information to be garbage collected if you are the only one referencing it.
  • Free native system resources like AWT frame, files, JNI etc when finished with them. Example: Frame, Dialog, and Graphics classes require that the method dispose() be called on them when they are no longer used, to free up the system resources they reserve.

Detect memory leaks

  • Use tools like JProbe, OptimizeIt etc to detect memory leaks.
  • Use operating system process monitors like task manager on NT systems, ps, vmstat, iostat, netstat etc on UNIX systems.
  • Write your own utility class with the help of totalMemory() and freeMemory() methods in the Java Runtime class.
  • An even better approach than a utility class is using dynamic proxies or Aspect Oriented Programming (AOP) for pre and post memory recording where you have the control of activating memory measurement only when needed.

Performance Tips

  • Use ArrayLists, HashMap etc as opposed to Vector, Hashtable etc where possible. This is because the methods in ArrayList, HashMap etc are not synchronized.Even better is to use just arrays where possible.
  • Set the initial capacity of a collection (e.g. ArrayList, HashMap etc) and StringBuffer/StringBuilder appropriately. This is because these classes must grow periodically to accommodate new elements. So, if you have a very large ArrayList or a StringBuffer, and you know the size in advance then you can speed things up by setting the initial size appropriately.
  • Minimise the use of casting or runtime type checking like instanceof in frequently executed methods or in loops. The “casting” and “instanceof” checks for a class marked as final will be faster. Using “instanceof” construct is not only ugly but also unmaintainable. Look at using visitor pattern.
  • Do not compute constants inside a large loop. Compute them outside the loop. For applets compute it in the init() method.
  • Exception creation can be expensive because it has to create the full stack trace. The stack trace is obviously useful if you are planning to log or display the exception to the user. But if you are using your exception to just control the flow, which is not recommended, then throw an exception, which is precreated. An efficient way to do this is to declare a public static final Exception in your exception class itself.
  • Avoid using System.out.println and use logging frameworks like Log4J etc, which uses I/O buffers
  • Minimize calls to Date, Calendar, etc related classes.
  • Minimize JNI calls in your code.

Minimize the creation of objects

  • If repeating code within a loop, avoid creating new objects for each iteration. Create objects before entering the loop (i.e. outside the loop) and reuse them if possible.
  • For complex objects that are used frequently, consider creating a pool of recyclable objects rather than always instantiating new objects. This adds additional burden on the programmer to manage the pool, but in select cases can represent an order of magnitude performance gain.
  • Use lazy initialization when you want to distribute the load of creating large amounts of objects.

Performance

  • Pool valuable system resources like threads, database connections, socket connections etc. Emphasis on reuse of threads from a pool of threads. Creating new threads and discarding them after use can adversely affect performance. Also consider using multi-threading in your single-threaded applications where possible to enhance performance. Optimze the pool sizes based on system and application specifications and requirements.
  • Optimize your I/O operations: use buffering when writing to and reading from files and/or streams. Avoid writers/readers if you are dealing with only ASCII characters. You can use streams instead, which are faster. Avoid premature flushing of buffers. Also make use of the performance and scalability enhancing features such as non-blocking and asynchronous I/O, mapping of file to memory etc offered by the NIO (New I/O).
  • Minimize network overheads by retrieving several related items simultaneously in one remote invocation if possible. Remote method invocations involve a network round-trip, marshalling and unmarshalling of parameters, which can cause huge performance problems if the remote interface is poorly designed.
  • Establish whether you have a potential memory problem and manage your objects efficiently: remove references to the short-lived objects from long-lived objects like Java collections etc to minimise any potential memory leaks. Also reuse objects where possible. It is cheaper to recycle objects than creating new objects each time. Avoid creating extra objects unnecessarily. For example use mutable StringBuffer/StringBuilder classes instead of immutable String objects in computation expensive loops. Automatic garbage collection is one of the most highly touted conveniences of Java. However, it comes at a price. Creating and destroying objects occupies a significant chunk of the JVM's time.

Call Web Server from Java

URLConnection (HttpURLConnection and JarURLConnection.) or HttpClient (browser). They both Supports HEAD, GET, POST, PUT, DELETE, TRACE and OPTIONS, but not cookies.

Socket

  • A socket is a communication channel, which facilitates inter-process communication (For example communicating between two JVMs, which may or may not be running on two different physical machines).
  • There are two kinds of sockets: The connectionless communication protocol of the Internet is called UDP (datagram sockets). The connection-oriented communication protocol of the Internet is called TCP.
  • Each socket is uniquely identified on the entire Internet with two numbers: 128-bit integer called the Internet Address (or IP address) and a 16-bit integer called the port of the socket.
  • The port numbers 0 to 1023 are reserved for standard services such as e-mail, FTP, HTTP etc.
  • The lifetime of the socket is made of 3 phases: Open Socket-->Read and Write to Socket-->Close Socket. In Java you can use the Socket (client side) and ServerSocket (Server side) classes.

Singleton & Factory

Another important aspect to consider when writing your factory class is that, it does not make sense to create a new factory object for each invocation you can incorporate the singleton design pattern into your factory pattern code. The singleton design pattern will create only a single instance of your SimpleShapeFactory class. Since an abstract factory pattern is unlike factory pattern, where you need to have an instance for each of the two factories (i.e.SimpleShapeFactory and ComplexShapeFactory) returned, you can still incorporate the singleton pattern as an access point and have an instance of a HashMap, store your instances of both factories. Now your calling method uses a static method to get the same instance of your factory, hence conserving memory and promoting object
reuse:
ShapeFactory factory = ShapeFactory. GetFactoryInstance();
factory.getShape(1);

Benefits of Factory Pattern

  • The factory pattern decoupling or the dependencies between the calling code and called objects like Circle, Square etc. Factory pattern returns an instance of several (product hierarchy) subclasses (like Circle, Square etc), but the calling code is unaware of the actual implementation class. The calling code invokes the method on the interface (for example Shape) and using polymorphism the correct draw() method gets invoked.
  • You do not have to create a new Circle or a new Square on each invocation as shown in the sample code, which is for the purpose of illustration and simplicity. In future, to conserve memory you can decide to cache objects or reuse objects in your factory with no changes required to your calling code. You can also load objects in your factory based on attribute(s) read from an external properties file or some other condition.
  • Another benefit going for the factory is that unlike calling constructors directly, factory patterns have more meaningful names like getShape(…), getInstance(…) etc, which may make calling code more clear.

Factory Method/Abstract Factory

A Factory method pattern (aka Factory pattern) is a creational pattern. The creational patterns abstract the
object instantiation process by hiding how the objects are created and make the system independent of the object
creation process. An Abstract factory pattern is one level of abstraction higher than a factory method pattern,
which means it returns the factory classes.
 
Factory pattern returns one of the several product subclasses. You should use a factory pattern If you have a super class and a number of subclasses,and based on some data provided, you have to return the object of one of the subclasses.
An Abstract factory pattern is one level of abstraction higher than a factory method pattern, which means the abstract factory returns the appropriate factory classes, which will later on return one of the product subclasses.