Category Archives: J2EE

Servlets and JSP

Why Servlets?

Servlets play the role of a helper app in the web server. It is preferred because of performance where server has to launch a heavy-weight process for each and every request for that resource.


  • Servlets should be deployed to Web Container (Servlet Container e.g. Tomcat)

Web Container (Servlet Container)

  • Responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights

Servlet Lifecycle

  • There is single instance of Servlet per JVM instance. The classes are loaded and servlet object is created during container boot up which lives during the whole JVM lifecycle
  • init method is called by container to initialize servlet instance. ServletConfig can be passed to customize servlet at run time. init method can be used to costly operations e.g. create JDBC connection or anything that need to be performed one time.
  • For every request, container creates new HTTPServletRequest/HTTPServletResponse (in case of HTTPServlet) and every request do have separate thread
  • service method is responsible for calling doGet/doPost methods (HTTPServlet)
  • destroy method is called when servlet object is destroyed

Servlet API

  • Servlet API contained in the Java package hierarchy javax.servlet
  • The package javax.servlet.http defines HTTP-specific subclasses of the generic servlet elements


Secure wsdl client artifacts using wsimport and jax ws client

Q: How to create client artifacts (value objects and other service class methods etc) of secure resource (WSDL) using wsimport?

Solution: Use following command to generate artifacts in given directory. Make sure to put authFile.txt file at current path.

wsimport -keep -d <DirectoryName> -verbose -Xnocompile -Xauthfile authFile.txt <WSDL_URL>

Content of authFile.txt




Q: How to create JAX WS client where WSDL is secure and API is also secure? 

Solution: There will be authentication at two layers.

1) HTTP Layer
2) Method Layer (API)

Here is the sample.

public class JaxWsClientSample {

	// HTTP Authentication
	static { {

			protected getPasswordAuthentication() {
				return new"username",

	public static void main(String[] args) {

		// Create service object and get port
		// Note: TestBean_Service is service class that can be found in 
// generated client artifacts and name may be different in your case
		TestBean_Service service = new TestBean_Service();
		TestBean port = service.getTestBeanPort();

		//Use BindingProvider API to provide credentials for API security
		BindingProvider prov = (BindingProvider) port;
		Map<String, Object> reqCtx = prov.getRequestContext();

		// API credentials
		reqCtx.put(BindingProvider.USERNAME_PROPERTY, "username");
		reqCtx.put(BindingProvider.PASSWORD_PROPERTY, "password");

		// Invoke webservice method through port
		Response response = port.doSomething(request);




Java EE Interceptors

Java EE Interceptors

Technology to do method call intercept. Common uses of interceptors are logging, auditing, and profiling.

Java EE Interceptor

Java EE Interceptor


target class – class in which Interceptors are defined. Interceptor methods are invoked in conjunction with the methods (of target class) or lifecycle events of the target class.
interceptor method –  methods which handles the interceptor invocation. It could be defined in target class as interceptor method or defined in separate class called interceptor class.
interceptor class – contains interceptor methods


Interceptor Metadata Annotations

Interceptor Metadata Annotation Description
javax.interceptor.AroundInvoke Designates the method as an interceptor method.
javax.interceptor.AroundTimeout Designates the method as a timeout interceptor, for interposing on timeout methods for enterprise bean timers.
javax.annotation.PostConstruct Designates the method as an interceptor method for post-construct lifecycle events.
javax.annotation.PreDestroy Designates the method as an interceptor method for pre-destroy lifecycle events.



Java XML – JAXB – Java Architecture for XML Binding

Java XML – JAXB – Java Architecture for XML Binding

What is JAXB?

  • Provides API, tools & framework that automate the mapping between XML documents and Java objects
  • Provides compiler that compiles XML schema to Java Classes


  • Provides efficient and standard way of mapping between XML and Java Code
  • JAXB is a high level language while JAXP, SAX, DOM are assembly language for XML document management
  • Easy to use, Customizable, portable

In JAXB, you are going to create Java classes from XML schema

How to use JAXB?

 JAXB Architecture

JAXB Architecture


  • JAXB Binding Compiler is basically xjc: %JAVA_HOME%/bin/xjc
  • Binding Declaration: Binding Customization File
  • XJC creates Java classes from schema
  • Java code reads xml document instance & create into java object (Unmarshal) & object can be them manipulated
  • Java object could be write down to XML document (Marshal)


Other Java/XML technologiesSAX, DOM, JAXP



– JAXB Entity

– Marshalling

– Unmarshalling


– Schema


– schema vs xml


– Binding


Web Services JAXB Basics – Youtube Video



java persistence api

Java Persistence API – JPA

Java Persistence API

API specification that describes the management of relational data.

  • It is a standard API that provides functionalities to access, manage, persist data between Java Objects (POJO) and relational database in Java EE
  • It  uses annotations or XML to map objects to database. These objects are called Entities
  • It allows querying and retrieval of data using JPQL (Java Persistence Query Language)

Why Java Persistence API?

Because it is strict standard, portable, simple and  supports Persistence Mechanisms for:

  • Java Objects
  • Advanced OO Concepts
  • Transactional Integrity
  • Concurrency
  • Large Data Sets
  • Existing Schema
  • Queries

 Persistence in this context covers three areas:

  • the API itself, defined in the javax.persistence package
  • the Java Persistence Query Language (JPQL)
  • object/relational metadata

Persistence Enitity / JPA Entity Class

Persistence Entity is a lightweight Java class whose state is typically persisted to a table in a relational database. Each row in the table corresponds to an instance of an entity. It is a POJO (Plain Old Java Object) class that is marked (annotated @Entity) as having the ability to represent objects in the database.

Requirements for Entity class

  • Marked with javax.persistence.Entity annotation
  • Must have public or protected no argument constructor
  • class, methods or persistent instance variables cannot be marked final
  • class must implement Serializable interface

In JPA a database connection is represented by the EntityManager interface. Therefore, in order to manipulate an database we need an EntityManager instance. Operations that modify database content also require an EntityTransaction instance.

JPA Implementation

  • Hibernate – Hibernate provides an open source object-relational mapping framework for Java. Versions 3.2 and later provide an implementation for the Java Persistence API
  • EclipseLink
  • OpenJPA
  • DataNucleus, more…

RESOURCE_LOCAL persistence contexts vs JTA persistence contexts

RESOURCE_LOCAL persistence contexts JTA persistence context
  • <persistence-unit transaction-type=”RESOURCE_LOCAL“>
  • <persistence-unit transaction-type=”JTA“>
  • You are responsible for EntityManager (PersistenceContext/Cache) creating and tracking
  • container will do EntityManager (PersistenceContext/Cache) creating and tracking
  • Use EntityManagerFactory to create EntityManager (PersistenceContext)
  • You cannot use the EntityManagerFactory to get an EntityManager
  • You can only get an EntityManager supplied by the container
  • An EntityManagerFactory can be injected via the @PersistenceUnit annotation only (not @PersistenceContext)
  • An EntityManager can be injected via the @PersistenceContext annotation only (not @PersistenceUnit)
  • You are not allowed to use @PersistenceContext to refer to a unit of type RESOURCE_LOCAL
  • You are not allowed to use @PersistenceUnit to refer to a unit of type JTA
  • You must use the EntityTransaction API to begin/commit around every call to your EntityManger
  • The EntityManager given by the container is a reference to the PersistenceContext/Cache associated with a JTA Transaction.
  • If no JTA transaction is in progress, the EntityManager cannot be used because there is no PersistenceContext/Cache.
  • Everyone with an EntityManager reference to the same unit in the same transaction will automatically have a reference to the same PersistenceContext/Cache
  • The PersistenceContext/Cache is flushed and cleared at JTA commit time
  • With a RESOURCE_LOCAL unit and an EntityManagerFactory you should create and use exactly one EntityManager instance in your transaction to ensure there is only one active PersistenceContext/Cache for the given set of data active against the current transaction.
  • In any given transaction you want exactly one PersistenceContext/Cache for a given set of data. Using a JTA unit with an EntityManager created by the container will always guarantee that this is the case.
1 1
1 1
1 1
1 1


  1. JPA Concepts –
  2. Java Persistence API Basics
  3. Obtaining a JPA Database Connection
  4. Why Java Persistence API
  5. Basic Java Persistence API Best Practices
  6. Difference between Java Persistence API vs Hibernate ( JPA Specification vs JPA Implementation)
  7. JPA performance Benchmark – Comparison of JPA providers [ Comparison ]
  8. persistence.xml configurations for major databases and jpa providers

web.xml Deployment Descriptor

web.xml Deployment Descriptor

Java web applications use a deployment descriptor file to determine how URLs map to servlets, which URLs require authentication, and other information. This file is named web.xml, and resides in the app’s WAR under theWEB-INF/ directory. web.xml is part of the servlet standard for web applications.


Web.xml Metawerx Wiki
The Deployment Descriptor: web.xml – Google

JAX WS - Java API for XML Web Services

JAX WS – Java API for XML Web Services

JAX WS – Java API for XML Web Services

  • Simpler way to develop/deploy Web Services
  • Server & clients communicate using XML
  • Can be invoked by XML-based protocol (e.g. SOAP) & messages (xml) can be transported over HTTP

service endpoint interface or service endpoint implementation (SEI) is a Java interface or class, respectively, that declares the methods that a client can invoke on the service. An interface is not required when building a JAX-WS endpoint. The web service implementation class implicitly defines an SEI.

JAX-WS client programming model 

  1. Dispatch client: work at the XML message level; work without any generated artifacts at the JAX-WS level.
  2. Dynamic Proxy client: invoke a web service based on a service endpoint interface.

wsimport tool

The wsimport tool generates JAX-WS portable artifacts, such as:

  • Service Endpoint Interface (SEI)
  • Service
  • Exception class mapped from wsdl:fault (if any)
  • Async Reponse Bean derived from response wsdl:message (if any)
  • JAXB generated value types (mapped java classes from schema types)


  • How to generate JAX-WS artifacts of secure WSDL using wsimport?

Following command will generate the webservice artifacts of the given wsdl and copy into directory (directoryName)

wsimport -keep -d directoryName -verbose -Xnocompile -Xauthfile authFile.txt <WSDL URL>

Content of authFile.txt



  1. JAX WS official site
  2. JAX-WS Release Documentation 2.2.8  (PDF, HTML)
  3. Building Web Services with JAX-WS (javaee 6)
  4. wsimport tool documentation