You are on page 1of 16

J2EE 3-TIER ARCHITECTURAL MODEL:

Client Tier First Tier or Client Tier



Web Tier
Middle Tier or Business Logic Tier
Business Tier


EIS Tier Third Tier or Database Tier


COMPONENTS IN EACH LAYER:
Client-tier components run on the client machine.
Web-tier components run on the J2EE server.
Business-tier components run on the J2EE server.
Enterprise information system (EIS)-tier software runs on the EIS server.
Application clients and applets are client components.
Java Servlet and JavaServer Pages (JSP) technology components are web components.
Enterprise JavaBeans (EJB) components (enterprise beans) are business components.
Client Components:
A J2EE application can be web-based or non-web-based. An application client executes on the
client machine for a non-web-based J2EE application, and a web browser downloads web pages
and applets to the client machine for a web-based J2EE application.
Dynamic
HTML pages
JSP Pages
Enterprise
Beans
Database
Web Browsers:
The user's web browser downloads static or dynamic Hypertext Markup Language (HTML),
Wireless Markup Language (WML), or Extensible Markup Language (XML) web pages from
the web tier. Dynamic web pages are generated by servlets or JSP pages running in the web tier.
Applets:
A web page downloaded from the web tier can include an embedded applet. An applet is a small
client application written in the Java programming language that executes in the Java VM
installed in the web browser.
Web Components:
J2EE web components can be either JSP pages or servlets.
Business Components:
Business code, which is logic that solves or meets the needs of a particular business domain such
as banking, retail, or finance, is handled by enterprise beans running in the business tier.
FOLDER STRUCTURE:


html,jsp



.jar
.xml

.class
.java

Root
Web_Inf
lib
classes
Archieve Files Architecture:
EAR: An Enterprise Archive file represents a J2EE application that can be deployed in a Web
Sphere application server. EAR files are standard Java archive files and have the file extension
.ear. EAR file contain ejb, web or application client module. ear file is complete j2ee application
file that contain all(jar +war).
WAR: Web Archive (WAR) file is a Java archive file used to store jsp,servlets,classes,meta data
information,images and Sound and tag libraries etc. Its standard file extension is .war. WAR files
are used to package Web modules.
EAR = WAR(Web module) + JAR(business module)
JAR: Java Arcihve File contain all class file,image,sound and other files which will needed in
whole application. Computer users can create or extract JAR files using the jar command that
comes with the JDK. They can also use zip tools. The JavaTM Archive (JAR) file format enables
you to bundle multiple files into a single archive file. jar was designed mainly to facilitate the
packaging of java applets or applications into a single archive.
JAVA SERVLET TECHNOLOGY:
What is Web Application?
A web application is any application that uses a web browser as a client. A web
application is composed of web components like Servlet,jsp and HTML.The web components
execute in web server and respond to HTTP request.
What is a Servlet ?
Servlet is a server side programming language.Servlet technology is used to create web
application. It is a web component that is deployed on the server to create dynamic web pages.
Advantages and disadvantages of servlet:
Servlets are an integral part of any J2EE Web application. The key benefits of using Servlets in
our web applications are:

1. They are faster than CGI scripts because each CGI script produces an entirely new process
that takes a lot of time to execute, whereas a servlet creates only a new thread.
2. Servlet API is standard and available easily on the internet (like JSPs)
3. Servlets have the advantages like ease of development & platform independence (like Java)
4. They can access all the J2SE and J2EE APIs
5. Can take the full advantage & capabilities of the Java programming langauge .As you can
see, there are numerous advantages of using the Servlet & JSP technologies. This is exactly
why numerous organizations use them as a staple part of their J2EE application
developmentwork.

The Disadvantage would be that Servlets are a little difficult to learn and use.
The drawbacks of servlets are few, but they include:
1. You need a special "servlet container" to run servlets, and most web servers (and thus
most public hosting companies) don't include this.
2. You need a Java Runtime Environment on the server to run servlets. CGI is a completely
language independent protocol, so you can write CGIs in whatever languages you have
available (including Java if you want to).
3. Sometimes there are no Java interfaces to particular resources or devices. In this case
writing a CGI in a language which does have native support for access to these resources
or devices can be a lot simpler than setting up JNI to call through another language. And
it might not even be possible through JNI.
4. Although each CGI requst usually requires a process start (which can make them a lot
slower than servlets for short tasks) a CGI can be written in a fully compiled language
and use fully compiled and optimized low-level system calls, so complex, long, or
machine-dependent processing can be faster and simpler using CGIs
5. You can easily test a CGI on the command-line of the server: just set a few environment
variables and run it to see the output. This is not easy with servlets.
SERVLET LIFE CYCLE:
The following are the life cycle methods of a servlet instance:
init()
service()
destroy()
init()
This method is called once for a servlet instance. When first time servlet is called, servlet
container creates instance of that servlet and loaded into the memory. Future requests will be
served by the same instance without creating the new instance.init() method is used for
inilializing servlet variables which are required to be passed from the deployment descriptor
web.xml. ServletConfig is passed as the parameter to init() method which stores all the values
configured in the web.xml.
service()
This method is called for the each request. This is the entry point for the every servlet request
and here we have to write our businesslogic or any other processes. This method takes
HttpServletRequest and HttpServletresponseas the parameters. It is not mandatory to write this
method, normally developers are interested in writing doGet() or doPost() methods which is by
default called from the service() method.
destroy()
This method will be called once for a instance. It is used for releasing any resources used by the
servlet instance. Most of the times it could be database connections, Fill IO operations, etc.
destroy() is called by the container when it is removing the instance from the servlet container.
Servlet instance is deleted or garbage collected by the container only when the web server issues
shut down or the instance is not used for a long time.
SERVLET CLASSES:
Class Hierarchy
class java.lang.Object
class java.util.EventObject (implements java.io.Serializable)
class javax.servlet.ServletContextEvent
class javax.servlet.ServletContextAttributeEvent
class javax.servlet.ServletRequestEvent
class javax.servlet.ServletRequestAttributeEvent
class javax.servlet.GenericServlet (implements
java.io.Serializable, javax.servlet.Servlet,
javax.servlet.ServletConfig)
class java.io.InputStream
class javax.servlet.ServletInputStream
class java.io.OutputStream
class javax.servlet.ServletOutputStream
class javax.servlet.ServletRequestWrapper (implements
javax.servlet.ServletRequest)
class javax.servlet.ServletResponseWrapper (implements
javax.servlet.ServletResponse)
class java.lang.Throwable (implements java.io.Serializable)
class java.lang.Exception
class javax.servlet.ServletException
class javax.servlet.UnavailableException


Servlet Interfaces:

The central abstraction in the Servlet API is the Servlet interface. All servlets implement this
interface, either directly or, more commonly, by extending a class that implements it such as
HttpServlet.Servlets-->Generic Servlet-->HttpServlet-->MyServlet.The Servlet interface
declares, but does not implement, methods that manage the servlet and its communications with
clients.

ServletRequest interface
ServletRequest interface provides an abstraction of client request. The object of ServletRequest
is used to obtain the client request information such as request parameters, content type and
length, locale of the client, request protocol etc. Developers dont need to implement this
interface. The web container provides the implementation this interface. The web container
creates an instance of the implementation class and passes it as an argument when calling the
service() method.
ServletResponse interface
The ServletResponse interface assists a servlet in sending a response to the client. Developers
dont need to implement this interface. Servlet container creates the ServletResponse object and
passes it as an argument to the servlets service() method.
ServletConfig interface
The servlet container uses a ServletConfig object to pass initialization information to the servlet.
ServletConfig object is most commonly used to read the initialization parameters. Servlet
intialialization parameters are specified in deployment descriptor (web.xml) file. Servlet
container passes the ServletConfig object as an argument when calling servlets init() method.
ServletContext interface
ServletContext object is used to communicate with the servlet container. There is only one
ServletContext object per web application (per JVM). This is initialized when the web
application is started and destroyed only when the web application is being shutdown.
ServletContext object is most commonly used to obtain the MIME type of a file, dispatching a
request, writing to servers log file, share the data across application, obtain URL references to
resources etc.
SingleThreadModel Interface
SingleThreadModel is a marker interface. It is used to ensure that servlet handle only one request
at a time. Servlets can implement SingleThreadModel interface to inform the container that it
should make sure that only one thread is executing the servlets service() method at any given
moment.

Methods of Servlet interface
1. void init(ServletConfig config)throws ServletException
Called by the servlet container to indicate to a servlet that the servlet is being placed into service.
2. ServletConfig getServletConfig()
Returns a ServletConfig object, which contains initialization and startup parameters for this
servlet. The ServletConfig object returned is the one passed to the init method.
3. void service(ServletRequest req, ServletResponse res)throws ServletException,
IOException
Called by the servlet container to allow the servlet to respond to a request.This method is only
called after the servlet's init() method has completed successfully
4. String getServletInfo()
Returns information about the servlet, such as author, version, and copyright
5. void destroy()
Called by the servlet container to indicate to a servlet that the servlet is being taken out of
service.

What is Generic servlet anh HTTP servlet & whats is their difference?

Generic servlet is the class which implements servelt interface directly.This is not
particualr for one protocol.If we want to design our own servelt whcih not particular any
protocol.
Httpservlet is the child class of Generic servlet.it is particular to HTTP protcol.If we want
to design HTTP based servlet we can extend the Httpservelt class.
Generic servlet is protocal independent cannot support cookies httpsession and url
writing it does not send large data .Http servlet sends large data and its protocol
independent support cookies sessions.
HttpServlet is used to handle only http request & response but whereas Generic servlet
can be used to handle any type of requests and responses , such as FTP.
Generic servlet doesnt maintain client session where as httpservlet maintains session.
Generic servlet is the servlet which serves all kind of request but http servlet serves only
http servlet.
Web.xml(deployment descriptor file):
The web.xml file defines each servlet and JSP page within a Web Application.
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 the WEB-INF/ directory. web.xml is part of
the servlet standard for web applications.
Here is a simple web.xml
<web-app >
<servlet>
<servlet-name>name of the servlet</servlet-name>
<servlet-class>class name</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>name of the servlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
PASSING INPUT TO SERVLET:
Example:Welcome program in servlet:
Dynamic.java:
import java.io.PrintWriter;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;

public class Dynamic extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws IOException,ServletException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
pw.println("<html>");
pw.println("<title>");
pw.println("Hello");
pw.println("</title>");
pw.println("<body>");
pw.println("welcome to servlet program");
pw.println("welcome to servlet program");

pw.println("</body>");
pw.println("</html>");
}
}

Web.xml:
<web-app>
<servlet>
<servlet-name>Dyn</servlet-name>
<servlet-class>Dynamic</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Dyn</servlet-name>
<url-pattern>/res/*</url-pattern>
</servlet-mapping>
</web-app>
Steps to compile and run a servlet program:
Step 1: Create a Directory Structure under Tomcat
Go to C:\Program Files\Apache Software Foundation\Tomcat 5.5








Dynamic.java
Web.xml
webapps
WEB_INF
classes
Step 2: Write the Servlet Source Code
For example Dynamic.java given above.
Step 3: Compile Your Source Code
C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\first\WEB-
INF\classses>javac Dynamic.java
Step 4: Create the Deployment Descriptor(web.xml)
For example web.xml given above
Step 5: Run Tomcat
Go to C:\Program Files\Apache Software Foundation\Tomcat 5.5\bin and run tomcat.
Step 6: Call Your Servlet from a Web Browser
The URL for that servlet has the following format:
http:/localhost:port number/rootfolder name/url-pattern name
For the above program: http://localhost:8080/first/res
Typing the URL in the Address or Location box of your web browser will give you the string
"welcome to the servlet program


Initparam:
Getting and Setting Initialization Parameters for a Servlet
The servlet container supports the ability to store startup and configuration information for a servlet.
After the container instantiates the servlet, it makes this information available to the servlet instance.
This example demonstrates a servlet that retrieves some initialization parameters in its init() method:
Initparam.java:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class InitParam extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException,ServletException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
ServletContext con = getServletContext();
String str = con.getInitParameter("Link");
ServletConfig strconfig = getServletConfig();
//getServletConfig() :Returns a ServletConfig object, which contains initialization and startup
parameters for this servlet.
String email = strconfig.getInitParameter("Email");
String phone = getInitParameter("Phone");
pw.println("<html>");
pw.println("<title>");
pw.println("Link1");
pw.println("</title>");
pw.println("<body>")
pw.println("contact us on Email:"+email);
pw.println("<br>");
pw.println("contact us on phone number:"+phone);
pw.println("<br>");
pw.println("Welcome to Link1 using context param");
//String str="http://localhost:7001/shan/";
pw.println("<a href=\""+str+"InitParam1\">Next</a> ");
pw.println("<br>");
pw.println("</body>");
pw.println("</html>");
}
}
Initparam1.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class InitParam1 extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException,ServletException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
ServletContext con = getServletContext();
ServletConfig strconfig = getServletConfig();
String str = con.getInitParameter("Link");
String email = strconfig.getInitParameter("Email");
String phone = getInitParameter("Phone");
pw.println("<html>");
pw.println("<title>"+"INIT PARAM"+"</title>");
pw.println("<body>");
pw.println("contact us on Email:"+email);
pw.println("<br>");
pw.println("contact us on phone number:"+phone);
pw.println("<br>");
pw.println("Welcome to Link1 using context param");
//String str="http://localhost:7001/shan/";
pw.println("<a href=\""+str+"InitParam\">Next</a> ");
pw.println("<br>");
pw.println("</body>");
pw.println("</html>");
}
}
// two way of getting information from web.xml
// 1. servletconfig obj
//2. getInitParameter
getInitParameter
public java.lang.String getInitParameter(java.lang.String name)
Returns a String containing the value of the named initialization parameter, or null if the
parameter does not exist. See ServletConfig.getInitParameter(java.lang.String).
This method is supplied for convenience. It gets the value of the named parameter from
the servlet's ServletConfig object.
Specified by:
getInitParameter in interface ServletConfig
Parameters:
name - a String specifying the name of the initialization parameter
Returns:
String a String containing the value of the initalization parameter
The initialization parameters for the servlet are specified in the deployment descriptor (i.e., web.xml
file). Here is an example of a deployment descriptor that specifies two initialization parameters:
Web.xml
<web-app>
<context-param>
<param-name>Link</param-name>
<param-value>http://localhost:8086/initparam/</param-value>
</context-param>
<servlet>
<servlet-name>InitParam</servlet-name>
<servlet-class>InitParam</servlet-class>
<init-param>
<param-name>Email</param-name>
<param-value>candid@gmail.com</param-value>
</init-param>
<init-param>
<param-name>Phone</param-name>
<param-value>456745678</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>InitParam1</servlet-name>
<servlet-class>InitParam1</servlet-class>

<init-param>
<param-name>Email</param-name>
<param-value>mathanlal@gmail.com</param-value>
</init-param>
<init-param>
<param-name>Phone</param-name>
<param-value>456745678333333333333</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>InitParam</servlet-name>
<url-pattern>/InitParam/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>InitParam1</servlet-name>
<url-pattern>/InitParam1/*</url-pattern>
</servlet-mapping>
</web-app>
Servlet Chaining:

You might also like