0% found this document useful (0 votes)
17 views

Java Unit 1

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Java Unit 1

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

PUNIT-II

**J2EE

J2EE stands for Java 2 Platform, Enterprise Edition. J2EE is the standard platform for
developing applications in the enterprise and is designed for enterprise applications that run on servers.
J2EE provides APIs that let developers create workflows and make use of resources such as databases or
web services. J2EE consists of a set of APIs. Developers can use these APIs to build applications for
business computing.

A J2EE application server is software that runs applications built with J2EE APIs and lets you run multiple
applications on a single computer. Developers can use different J2EE application servers to run
applications built with J2EE APIs.

In another words this means that the “wrights ones run anywhere. When we compile java program than
class file is developed.

J2EE Architecture:-
The JEE platform provides the environment to develop enterprise applications / services using multitier
architecture.
- The highly intensified technology made the need for scalable, efficient, faster solutions for information
management.
- The JEE technology is rightly apt for meeting these requirements.
- JEE provides a programming development environment which improves the productivity of
development, standards for hosting / deploying enterprise applications.
- The following are the tiers in JEE application

Client Tier:
- The client tier includes the web components such as Servlets, JSP or standalone Java Desktop
applications.
- This tier provides dynamic interfaces to the middle tier.

Middle Tier:
- This is also called as the server tier.
- In the middle tier enterprise beans and web services encapsulate distributable business logic for the
applications which are reusable.
- The JEE application server contains the server-tier components which provides the platform for these
web components for actions to be performed and data to be stored / persisted.

Enterprise data tier :


- The enterprise level data is stored / persisted preferably or typically in a relational database.
- In this tier, the JEE applications comprises of components, containers and services.

- All
the web components (Servlets, JSP) provide dynamic requests and responses from a web page.
- The EJB components contain the server-side business logic for enterprise applications.

**J2EE API’S:- J2EE API’S means a technology or a facility given by enterprise of java.
1) Java Servlet:- The java servlet provide object oriented programming for built dynamic
web application. Servlets are server side component which is platform independent and
give high performance.
2) Java Server Pages:- The java server pages are an extension of servlet API. JSP will work
web page as well dynamic connectivity with JDBC.
3) Enterprise Java Beans:- EJB are Distributed component base framework.It provide
environment for handling server side powerful and flexible java application.
4) Java Data base Connectivity:- JDBC provide platform independent access for SQL
command. Using JDBC we can permanent store the data in selected database.
5) Java Message Service:- JMS will provide message passing service in object oriented
distributed database. JMS is a standard for interacting whole application.
6) Java Mail:- This API provide platform and protocol independent frame work. Java mail
depend an E-mail server for sending and receiving E-mail for your application.
7) Java Beans Activation Framework:- A JAF is work with java mail to provided a facility to
interact with client to WWW. JAF is Intermediate between client and server.
8) JNDI:- Java naming and directory interface is an application to access different services
provide by other provider like Microsoft. JNDI is actually not a part of J2EE but it is part
of J2SE

**J2EE Containers
The Application Server Which Controls And Provides Services Through An Interface Is Called
A Container. The J2EE Container Helps In The Deployment And Execution Of Java Enterprise Edition
(J2EE) Components. In J2EE There Are 5 Containers Types Three Of These Are Server-Side Containers:
 The Server, Which Provides The Java Enterprise Edition(J2EE) Platform.
 An EJB Container Contains (Enterprise Java Bean) EJB Components.
 A Web Container That Manages Servlets.
The Other Two Containers Are User-Side:
 An Application Container Contains Standalone Graphical User Interface(GUI) And Batch-Type
Programs.
 An Applet Container That Contains a Java Plugin.

Application Client Container:


This Container Contains A Host Application Component, It Runs On The User Computer And It Can
Interact With Its Other Components. In Java It Helps To Build Robust Applications, These Applications
Can Also Interact With Data Resources. This Container Maintains The Execution Of Application Client
Components. This Server Can Handle All Application Operations Between Users And Databases.

Web Container:
This Container Contains A Component That Works On The Server-Side. A Web Application Executes
Within A Web Container Of A Web Server Which Is Also Known As Servlet Container. This Container
Provides The Runtime Environment Through Components. Web Container Manages The Execution Of
The JSP Page And Servlet Components For Java Enterprise Edition(J2EE) Applications.

Therefore, This Web Container Provides The Same Services As A Java Server Page(JSP) Container. Web
Components And Their Container Run On The Java Enterprise Edition(J2EE) Server. Web Server Is A
Server That Handles HTTP Requests Sent By A User And Responds With A HTTP Response.

How container handles Request/Response:

HTTP http servlet Request

Client CPU
Container Servlet

HTTP

http servlet Respose

**Web Applications:
Web applications are distributed applications by nature. This means that any program that runs
on more than one computer and communicates using the network and server. Web applications are
accessed using a web browser so they are very popular for the ease of using the browser as a user client.
The ability to update and maintain web applications without installing any software on thousands of
client computers becomes a key reason for the demand.
Using many components web applications are created, some of which have a user interface and
some of which do not require a graphical user interface (GUI). In addition, web applications frequently
require an additional markup or scripting language, such as HTML, CSS, or JavaScript programming
language. Many applications use only the Java programming language, which is ideal because of its
versatility.
The Java technologies used to create web applications are part of the Java EE platform. In order
for these technologies to work on a server, the server must have a container, or web server, installed
that recognizes and runs the classes you create.

Java Web Application types:

1) Standalone Application:- -Need to install in your system.


-Require Operating System services to work
- Does not require internet
Ex- Ms office, Power point
2) Web Application:- This is software program store a Server.

C1 C2 C3

Web Application

C4 C5 CN

Web Applications using Languages:-

 Client Side scripting Language:- HTML, CSS, Java Script


 Server Side scripting Language:- Php, ASP
Ex:- Gmail, Facebook, Netfix, etc

Display Application
Brower Server

Transform data with business logic

Client

http request &response


Database
Advantages of Web Applications
 Any typical web application can run or accessible on any operating system such as the Windows,
Mac, Linux as long as the browser is compatible.
 A web application is usually not required to install in the hard drive of the computer system,
thus it eliminates all the issues related to the space limitation.
 All the users are able to access the same version of the web application, which eliminates all
compatibility issues.
 It also reduces software piracy in subscription-based web applications, for example, SAAS (or
Software as a service).
 They also reduce the expense for end-users, business owners because the maintenance needed
by the business is significantly less.
 Web applications are flexible. A user can work from any geographical location as long as he has
a working internet connection.

Disadvantages of the Web Applications

 Internet connection is necessary to access any web application, and without an internet
connection, anyone can't use any of the web applications. It is very typical to get an internet
connection in our modern cities, still rural area internet connectivity not so well.
 Several people in business believe that their data on the cloud environment is no that secure
and likes to stick with old methods; they even don't want to use new methods.
 As we all know that many users like to use different web browsers according to their needs and
choices. So while creating a web application, you must remember that your application must
support several web browsers, including new and old versions of browsers.
 Speed-related issues are also affecting the web application's performance because there are
several factors on which the performance of a web application depends, and these all factors
affect the performance of the web application in their own way.
 If a user's web application faces any kind of issues, or if he does not have a good quality
corporate website, his web application will not be going to run correctly, smoothly.

**Web Application Architecture:-

There is a difference between websites and web applications. The web application is a program that
runs on a browser and it has mainly three formal characteristics.

 Addresses a particular problem, even if it’s simply finding some information


 As interactive as a desktop application
 Works with Content Management System.

Web Application Three Tier Architecture Layers


Web application architectural patterns are separated into many different layers or tiers which are called
Multi- or Three-Tier Architecture. You can easily replace and upgrade each layer independently.
Presentation Layer: This layer is accessible to the client via a browser and it includes user interface
components and UI process components. As we have already discussed that these UI components are
built with HTML, CSS, and JavaScript (and its frameworks or library) where each of them plays a different
role in building the user interface.

Business Layer: It is also referred to as a Business Logic or Domain Logic or Application Layer. It accepts
the user’s request from the browser, processes it, and regulates the routes through which the data will
be accessed. The whole workflow is encoded in this layer. You can take the example of booking a hotel
on a website. A traveler will go through a sequence of events to book the hotel room and the whole
workflow will be taken care of by the business logic.

Persistence Layer: It is also referred to as a storage or data access layer. This layer collects all the data
calls and provides access to the persistent storage of an application. The business layer is closely
attached to the persistence layer, so the logic knows which database to talk to and the process of
retrieving data becomes more optimized. A server and a data base management system software exist
in data storage infrastructure which is used to communicate with the database itself, applications, and
user interfaces to retrieve data and parse it. You can store the data in hardware servers or in the cloud.
Some other parts of the web application which is separated from the main layers that exist in the
architecture are…
 Cross-cutting code: This part handles communications, operational management, and security. It
affects all parts of the system but should never mix with them.
 Third-party integrations: Using third-party APIs we can integrate payment gateways, social logins,
GDSs in travel websites, etc.

How Does Web Application Architecture Work?

Web Application Architecture Components

Web application architecture works on various components. These components can be divided into two
areas.
1. User Interface App Components: As the name suggests this category is much more related to
the user interface/experience. In this category, the role of the web page is related to the display,
dashboards, logs, notifications, statistics, configuration settings, etc and it has nothing to do
with the functionality or working of the web application.

2. Structural Components: This category is mainly concerned with the functionality of the web
application with which a user interacts, the control, and the database storage. As the name suggests
it is much more about the structural part of the web application. This structural part comprises…
 The web browser or client
 The web application server
 The database server

**Servlet
A servlet is a class of Java programming language. You can use it to increase the functionality of
servers that host applications based on the programming model, i.e., request-response. Servlets can
react to any request, but they are frequently used to expand the functionality of web server-hosted
applications. Java Servlet technology creates HTTP-specific servlet classes for these applications.
There are classes and interfaces for writing servlets in the javax.servlet and javax.servlet.http packages.
The Servlet Lifecycle methods are defined by the Servlet interface, which all servlets must implement.
You can take the help of Java Servlet API to extend the GenericServlet class for developing a generic
service. For dealing with services related to HTTP, the HttpServlet class offers methods like doGet and
doPost.

o Servlet is a technology which is used to create a web application.


o Servlet is an API that provides many interfaces and classes including documentation.
o Servlet is an interface that must be implemented for creating any Servlet.
o Servlet is a class that extends the capabilities of the servers and responds to the incoming
requests. It can respond to any requests.
o Servlet is a web component that is deployed on the server to create a dynamic web page.
CGI (Common Gateway Interface ):- CGI is actually an external application that is written by
using any of the programming languages like C or C++ and this is responsible for processing client
requests and generating dynamic content.

In CGI application, when a client makes a request to access dynamic Web pages, the Web server
performs the following operations.

It first locates the requested web page i.e the required CGI application using URL.

It then creates a new process to service the client’s request.

Invokes the CGI application within the process and passes the request information to the application.

Collects the response from the CGI application

Destroys the process, prepares the HTTP response, and sends it to the client.

So, in CGI server has to create and destroy the process for every request. It’s easy to understand that
this approach is applicable for handling few clients but as the number of clients increases, the workload
on the server increases and so the time is taken to process requests increases.

Difference between Servlet and CGI

Servlet CGI(Common Gateway Interface)

Servlets are portable and efficient. CGI is not portable


In Servlets, sharing data is possible. In CGI, sharing data is not possible.

Servlets can directly communicate with the CGI cannot directly communicate with the
webserver. webserver.

Servlets are less expensive than CGI. CGI is more expensive than Servlets.

Servlets can handle the cookies. CGI cannot handle the cookies.

Servlets API’s:
Servlets are build from two packages:
 javax.servlet(Basic)
 javax.servlet.http(Advance)

Various classes and interfaces present in these packages are:

Component Type Package


Servlet Interface javax.servlet.*

ServletRequest Interface javax.servlet.*

ServletResponse Interface javax.servlet.*

GenericServlet Class javax.servlet.*

HttpServlet Class javax.servlet.http.*

HttpServletRequest Interface javax.servlet.http.*

HttpServletResponse Interface javax.servlet.http.*

Filter Interface javax.servlet.*

ServletConfig Interface javax.servlet.*

Advantages of Servlet:-

There are many advantages of Servlet over CGI. The web container creates threads for handling
the multiple requests to the Servlet. Threads have many benefits over the Processes such as they share
a common memory area, lightweight, cost of communication between the threads are low. The
advantages of Servlet are as follows:

1. Platform Independent : The biggest advantages of servlet is that is platform independent


because it is completely written in java. It can run on any platform.
2. Better performance: because it creates a thread for each request, not process.
3. Portability: Servlet is very portable because servlet programs are written in java. Being portable
we can run it on any platform .
4. Robust: JVM manages Servlets, so we don't need to worry about the memory leak, garbage
collection, etc.
5. Secure: Server is a server side component, so web server provides security to it and java also
provides security to it.
6. Performance: The speed of java servlet is very high as compared to CGI because CGI programs
take a lot of time to execute java servlet is fast because they run in web servers.
7. Power full features: Power full features like garbage collection and exception handling are
available in servlet.

The Servlet Container


Servlet container also known as Servlet engine is an integrated set of objects that provide a run
time environment for Java Servlet components.
In simple words, it is a system that manages Java Servlet components on top of the Web server
to handle the Web client requests.
Services provided by the Servlet container :

 Network Services: Loads a Servlet class. The loading may be from a local file system, a
remote file system or other network services. The Servlet container provides the network
services over which the request and response are sent.
 Decode and Encode MIME-based messages: Provides the service of decoding and encoding
MIME-based messages.
 Manage Servlet container: Manages the lifecycle of a Servlet.
 Resource management: Manages the static and dynamic resources, such as HTML files,
Servlets, and JSP pages.
 Security Service: Handles authorization and authentication of resource access.
 Session Management: Maintains a session by appending a session ID to the URL path.

Life Cycle of Servlet:- Client N no of request

Loadand Instantiate Init()


Request Response
Destroy()

Calls init() method for servlet


initiatization

Service() method get called Service()


for processing the request.

The entire life cycle of servlet is managed by servlet container which uses
the javax.serlet Servlet interface to understand the servlet object and manage it.

 Stage of Servlet life cycle


1. Servlet class is loaded
2. Servlet method is invoked
3. Initialized method is invoked
4. Service method is invoked
5. Destroy method is invoked

1. Sevlet class is loaded:- The first stage of the servlet life cycle invoked loading &
initializing the servlet by the servlet container.

2. Servlet instance is created:-The web container created the initance of a servlet after
loading the servlet class. The servlet initance is created only once is the servlet life cycle.

3. init method:- The init method is used to initialize the servlet. It is the life cycle methos
of java.servlet.Servlet interface. (using servlet.init(servlet.configuration info)

4. Service Method:- The web container/calls the service method each time when request
for the servlet is received. Servlet is not initialized first 3 stape are done then comes
back to service method. Else if servlet is inititize it calls the service method.
Syntax :- ( servlet request.responce)
5. Destroy Method:- Before removing the servlet instance from the service. It give the
servlet an opportunity to clear up any resource Ex- Memory, thread etc

Public void destroy()


{
}
Steps to create a servlet example
There are given 6 steps to create a servlet example. These steps are required for all the servers.
The servlet example can be created by three ways:
1. By implementing Servlet interface,
2. By inheriting GenericServlet class, (or)
3. By inheriting HttpServlet class

The mostly used approach is by extending HttpServlet because it provides http request specific
method such as doGet(), doPost(), doHead() etc.

Here, we are going to use apache tomcat server in this example. The steps are as follows:

4. Create a directory structure


5. Create a Servlet
6. Compile the Servlet
7. Create a deployment descriptor
8. Start the server and deploy the project
9. Access the servlet

1)Create a directory structures

The directory structure defines that where to put the different types of files so that web
container may get the information and respond to the client.

The Sun Microsystem defines a unique standard to be followed by all the server vendors. Let's
see the directory structure that must be followed to create the servlet.
As you can see that the servlet class file must be in the classes folder. The web.xml file must be
under the WEB-INF folder.

2)Create a Servlet
There are three ways to create the servlet.

1. By implementing the Servlet interface

2. By inheriting the GenericServlet class


3. By inheriting the HttpServlet class

The HttpServlet class is widely used to create the servlet because it provides methods to
handle http requests such as doGet(), doPost, doHead() etc.

In this example we are going to create a servlet that extends the HttpServlet class. In this
example, we are inheriting the HttpServlet class and providing the implementation of the
doGet() method. Notice that get request is the default request.

DemoServlet.java

import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServlet extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");//setting the content type
PrintWriter pw=res.getWriter();//get the stream to write the data

//writing html in the stream


pw.println("<html><body>");
pw.println("Welcome to servlet");
pw.println("</body></html>");

pw.close();//closing the stream


}}

3)Compile the servlet


For compiling the Servlet, jar file is required to be loaded. Different Servers provide different jar
files:
Jar file Server

1) servlet-api.jar Apache Tomcat


2) weblogic.jar Weblogic
3) javaee.jar Glassfish
4) javaee.jar JBoss

Two ways to load the jar file


1. set classpath
2. paste the jar file in JRE/lib/ext folder

Put the java file in any folder. After compiling the java file, paste the class file of servlet in WEB-
INF/classes directory.

4)Create the deployment descriptor (web.xml file)

The deployment descriptor is an xml file, from which Web Container gets the information about
the servet to be invoked.
The web container uses the Parser to get the information from the web.xml file. There are
many xml parsers such as SAX, DOM and Pull.

There are many elements in the web.xml file. Here is given some necessary elements to run the
simple servlet program.

web.xml file

<web-app>

<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>

</web-app>

Description of the elements of web.xml file

There are too many elements in the web.xml file. Here is the illustration of some elements that
is used in the above web.xml file. The elements are as follows:

<web-app> represents the whole application.

<servlet> is sub element of <web-app> and represents the servlet.

<servlet-name> is sub element of <servlet> represents the name of the servlet.

<servlet-class> is sub element of <servlet> represents the class of the servlet.

<servlet-mapping> is sub element of <web-app>. It is used to map the servlet.

<url-pattern> is sub element of <servlet-mapping>. This pattern is used at client side


to invoke the servlet.

5)Start the Server and deploy the project

To start Apache Tomcat server, double click on the startup.bat file under apache-tomcat/bin
directory.
One Time Configuration for Apache Tomcat Server

You need to perform 2 tasks:

1. set JAVA_HOME or JRE_HOME in environment variable (It is required to start server).


2. Change the port number of tomcat (optional). It is required if another server is running on same
port (8080).

1) How to set JAVA_HOME in environment variable?

To start Apache Tomcat server JAVA_HOME and JRE_HOME must be set in Environment variables.

Go to My Computer properties -> Click on advanced tab then environment variables -> Click on the new
tab of user variable -> Write JAVA_HOME in variable name and paste the path of jdk folder in variable
value -> ok -> ok -> ok.

Go to My Computer properties:

Click on advanced system settings tab then environment variables:


Write JAVA_HOME in variable name and paste the path of jdk folder in variable value:
There must not be semicolon (;) at the end of the path.

After setting the JAVA_HOME double click on the startup.bat file in apache
tomcat/bin.

Note: There are two types of tomcat available:

1. Apache tomcat that needs to extract only (no need to install)


2. Apache tomcat that needs to install
It is the example of apache tomcat that needs to extract only.
Now server is started successfully.

2) How to change port number of apache tomcat

Changing the port number is required if there is another server running on the same
system with same port number.Suppose you have installed oracle, you need to change
the port number of apache tomcat because both have the default port number 8080.

Open server.xml file in notepad. It is located inside the apache-tomcat/conf directory .


Change the Connector port = 8080 and replace 8080 by any four digit number instead
of 8080. Let us replace it by 9999 and save this file.

5) How to deploy the servlet project

Copy the project and paste it in the webapps folder under apache tomcat.
But there are several ways to deploy the project. They are as follows:

o By copying the context(project) folder into the webapps directory


o By copying the war folder into the webapps directory
o By selecting the folder path from the server
o By selecting the war file from the server

Here, we are using the first approach.

You can also create war file, and paste it inside the webapps directory. To do so, you need to use jar tool
to create the war file. Go inside the project directory (before the WEB-INF), then write:

1. projectfolder> jar cvf myproject.war *

Creating war file has an advantage that moving the project from one location to another takes less time.

6) How to access the servlet

Open broser and write http://hostname:portno/contextroot/urlpatternofservlet. For example:

1. http://localhost:9999/demo/welcome

You might also like