Upload
ankita-bajaj
View
214
Download
0
Embed Size (px)
Citation preview
7/27/2019 unit-1_ECJ
1/48
UNIT-1
7/27/2019 unit-1_ECJ
2/48
Introduction
Enterprise computing is all about combiningseparate applications, services, and processes intoa unified system that is greater than the sum of itsparts.
J2EE, introduced in 1998, defines a multi-tierarchitecture for enterprise information systems(EIS). By defining the way in which multi-tierapplications should be developed, J2EE reduces thecosts, in both time and money, of developing large-scale enterprise systems.
7/27/2019 unit-1_ECJ
3/48
Why j2ee?
Client side java has problems like:
Slow speed of user interfaces
Inconsistency with user interfaces b/w platforms
Wrong version of jvm
Java is convenient to write sever side componentsbcoz,
Server side market is dominated by unix machinesand mainframes where a developer can write acomponent once and deploy it on customersexisting server side environment.
To enable serer side computing in java, sun has
produced complete development platform j2ee.
j2EE provides a platform independent, portable,multiuser secure platform for server sidedeployments written in java.
7/27/2019 unit-1_ECJ
4/48
J2EEarchitecture
J2EE multi-tiered applicationsare generally considered to bethree-tiered applicationsbecause they are distributedover three different locations
client machines
the J2EE server machine
the database or legacymachines at the back end
7/27/2019 unit-1_ECJ
5/48
Three-tiered applications that run in
this way extend the standard two-tiered client and server model byplacing a multithreaded applicationserver between the client applicationand back-end storage
7/27/2019 unit-1_ECJ
6/48
J2EEContainers
The application server maintains control andprovides services through an interface orframework known as a container
There are five defined container types in the J2EEspecification
7/27/2019 unit-1_ECJ
7/48
J2EEContainers
Three of these are server-sidecontainers:
The server itself, which provides theJ2EE runtime environment
An EJB container to manage EJBcomponents
A Web container to manage Servlets
and JSP pages
The other two container types areclient-side:
An application container for stand-
alone GUIs, console An applet container, meaning a
browser, usually with the Java Plug-in
7/27/2019 unit-1_ECJ
8/48
J2EEComponents
AJ2EE componentis a self-contained functional
software unit that is assembled into a J2EEapplication with its related classes and files andthat communicates with other components
7/27/2019 unit-1_ECJ
9/48
Components
Client components run on the client machine,
which correlate to the client containers Web components -servlets and JSP pages
EJB Components
7/27/2019 unit-1_ECJ
10/48
PackagingApplicationsandComponents Under J2EE, applications and components reside in
Java Archive (JAR) files
These JARs are named with different extensions todenote their purpose, and the terminology isimportant
7/27/2019 unit-1_ECJ
11/48
Various Filetypes
Enterprise Archive (EAR) files represent theapplication, and contain all other server-side
component archives that comprise the application Client interface files and EJB components reside in
JAR files
Web components reside in Web Archive (WAR) files
7/27/2019 unit-1_ECJ
12/48
DeploymentDescriptors
Deployment descriptors are included in theJARs, along with component-relatedresources
Deployment descriptors are XML documentsthat describe configuration and other
deployment settings (remember that theJ2EE application server controls manyfunctional aspects of the services it provides)
The statements in the deployment descriptorare declarative instructions to the J2EE
container; for example, transactional settingsare defined in the deployment descriptor andimplemented by the J2EE container
7/27/2019 unit-1_ECJ
13/48
DeploymentDescriptors
Most J2EE Web Services vendorsprovide a GUI tool for generatingdeployment descriptors andperforming deployment becausecreating manual entries is tedious
and error prone
The deployment descriptor for anEJB component must be namedejb-jar.xml, and it resides in theMETA-INF directory inside the EJBJAR file
7/27/2019 unit-1_ECJ
14/48
EJBComponents
EJB components are server-side,
modular, and reusable, comprisingspecific units of functionality
They are similar to the Java classeswe create every day, but are
subject to special restrictions andmust provide specific interfaces forcontainer and client use and access
We should consider using EJBcomponents for applications thatrequire scalability, transactionalprocessing, or availability tomultiple client types
7/27/2019 unit-1_ECJ
15/48
EJBComponents- Major Types
Session beans These may be either statefulor stateless and are
primarily used to encapsulate business logic, carry out
tasks on behalf of a client, and act as controllers ormanagers for other beans
Entity beans Entity beans represent persistent objects or business
concepts that exist beyond a specific application'slifetime; they are typically stored in a relational database
7/27/2019 unit-1_ECJ
16/48
The homeand
componentinterface
A bean's home interface specifiesmethods that allow the client to create,remove, and find objects of the sametype
The home interface provides bean
management and life cycle methods EJB functionality is obtained through the
bean's component interface, whichdefines the business methods visible to,and callable by, the client
The developer writes the componentinterface, and the container creates theimplementation for client interaction
7/27/2019 unit-1_ECJ
17/48
Working withthe Model-View-Controller
The MVC paradigm provides a pattern for separatingthe presentation logic (view), business logic (control),and data objects (model). J2EEs architecture mapsonto the MVC nicely. Typically, entity beans are usedto provide the model logic, while a mix of entity
beans and session beans are used to provide thecontrol logic, and Web components are used toimplement both control and presentation logic. Inpractice, however, the separation of the three typesof logic is not as distinct, and additional patterns areoften needed to support the development cycle.
Figure
7/27/2019 unit-1_ECJ
18/48
MVC Pattern
7/27/2019 unit-1_ECJ
19/48
The Model
It refers to the data object model. For example, inan airline ticketing service you may have theconcept of a booking, which in the real world isrepresented by a paper ticket. The model deals
with issues such as how the booking is representedwithin the software system, where it is persisted,and how it is accessed. For example, the bookingmay be held within a relational database withinDestinationCity, travelDate, and DepartureTime.This data may be accessed via JDBC using Entity
Beans
7/27/2019 unit-1_ECJ
20/48
The view
The view is responsible for presentation issues. Ithandles how the client will see the application,and so HTML issues are usually dealt with here.However, other markup languages such asWireless Markup Language (WML) andExtensible Markup Language (XML) are
increasingly being used to support more variedtypes of clients. The Booking example may bedisplayed in various ways. For example, on awireless device only the most relevantinformation might be displayed due to thelimited screen size. In fact, the term view may be
misleading, implying that it is meant for visualdisplay only; the view may also be used topresent the model via an audio interface if desired. The method in which the model ispresented is abstracted from the underlyingdata.
7/27/2019 unit-1_ECJ
21/48
The control
The control part of the paradigm deals with thebusiness logic of the application. It handles howand when a client interacting with the view is ableto access the model. The control layer usuallyinteracts with authorization and authenticationservices, other J2EE services, and external systemsto enforce the business rules to be applied to theapplication. In our Booking example, the control
would determine whether the view can actuallydisplay the model. This may be based on whetherthe user is logged in, if he or she has appropriateauthorization and so on. It would also hold thebusiness logic of what to do if the user attempts toview a booking that no longer existsfor example,should an error be presented to the user? Should
the user be prompted with a screen asking foradditional information? These are rules thatchange within the business but they do notnecessarily force a change on the view or model.
7/27/2019 unit-1_ECJ
22/48
Java Servlets
7/27/2019 unit-1_ECJ
23/48
What is aservlet?
A servlet is a special Java class that can be loadedby a servlet enabled web server to respond to an
HTTP request with an HTTP response. Servlets usually execute in a multi-threaded
environment inside a servlet container that is partof the web server.
7/27/2019 unit-1_ECJ
24/48
Comparisonwith CGI
Servlets are much more efficient than CGI scripts.
Once a servlet is loaded it can efficiently respond tomany requests. Each is a separate thread(lightweight process)
In CGI each request causes a separate external
process to be started in the operating system.
In CGI server talks with an external program but inservlet it resides in jvm only Because they are in thesame JVM(different servlets), servlets canefficiently share data with each other,.
Servlet does not need java enabled browser but CGIdoes.
7/27/2019 unit-1_ECJ
25/48
Comparisonwith CGI
Servlets have built-in object-oriented functionalityfor dealing with the HTTP request and theassociated list of name-value pairs resulting from aform or url submission
They have support for cookies
They have support for session management
They are essentially part of the Web server ratherthan separate processes.
7/27/2019 unit-1_ECJ
26/48
Servlet Life-cycle
Servlet
Servlet
Container
Servlet
Servlet
Servlet Life-cycle
1. Server loadsservlet: creates
an instance
2. init method is
called
3. Servlet instance
accepts 0 or moreclient requests
4. Server calls
destroy method
and unloads
servlet
A servlet is a class that extends the
HttpServlet class
7/27/2019 unit-1_ECJ
27/48
Types ofservlet Generic servlet : This class is used for servlets thatdont implement any communication protocol.
7/27/2019 unit-1_ECJ
28/48
Genericservlet
import javax.servlet.*;import java.io.*;
public class BasicServlet extends GenericServlet
{
public void service(ServletRequest req,
ServletResponse resp)throws ServletException, IOException
{
resp.setContentType("text/plain");
PrintWriter out = resp.getWriter( );
out.println("Hello.");}
}
7/27/2019 unit-1_ECJ
29/48
HTTP Servlet
The HttpServlet class is an extension of GenericServlet that includes methods for handlingHTTP-specific data.[*] HttpServlet provides anumber of methods, such as doGet( ), doPost( ),
and doPut( ), to handle particular types of HTTPrequests (GET, POST, and so on). These methodsare called by the default implementation of theservice( ) method, which figures out what kind ofrequest is being made and then invokes theappropriate method.
7/27/2019 unit-1_ECJ
30/48
HTTP Servlet
import java.io.*;import javax.servlet.*;import javax.servlet.http.*;
public class HelloWorld extends HttpServlet{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws IOException, ServletException
{response.setContentType("text/html");PrintWriter out = response.getWriter();
out.println("\n" +"\n" +"Hello World\n" +"\n" +"\n" +"Hello World\n" +"This html document was " +"produced by a servlet.\n" +"\n" +"\n"
);
out.close();
7/27/2019 unit-1_ECJ
31/48
Session
trackingtechniques
User authorization
Hidden fields
URL rewriting Cookies
Session tracking API
7/27/2019 unit-1_ECJ
32/48
Userauthorization
Users can be authorized to use the web application
in different ways. Basic concept is that the user willprovide username and password to login to theapplication. Based on that the user can beidentified and the session can be maintained.
7/27/2019 unit-1_ECJ
33/48
Hidden fields
Hidden fields like the above can be inserted in thewebpages and information can be sent to the
server for session tracking. These fields are notvisible directly to the user, but can be viewed usingview source option from the browsers. This typedoesnt need any special configuration from thebrowser of server and by default available to use forsession tracking.
7/27/2019 unit-1_ECJ
34/48
Working withcookies
Cookies allow a web server to store small amountsof data on client systems. Cookies are generally
used to store basic user identification orconfiguration information. Because a cookie's valuecan uniquely identify a client, cookies are oftenused for session tracking.
The Servlet API includes a class,javax.servlet.http.Cookie, that abstracts cookie
syntax and makes cookies easy to work with. Inaddition, HttpServletResponse provides anaddCookie( ) method and HttpServletRequestprovides a getCookies( ) method to aid in writingcookies to and reading cookies from the HTTPheaders, respectively.
Disadvantage is that, the users can opt to disablecookies using their browser preferences. In suchcase, the browser will not save the cookie at clientcomputer and session tracking fails.
7/27/2019 unit-1_ECJ
35/48
Creation ofcookies
String userid = createUserID( ); // Create a unique ID
Cookie c = new Cookie("userid", userid);
resp.addCookie(c);
// Add the cookie to the HTTP headers
7/27/2019 unit-1_ECJ
36/48
Read cookie
To find a particular cookie, a servlet needs to read theentire collection of values and look through it:
Cookie[ ] cookies;
cookies = req.getCookies( );
String userid = null;
for (int i = 0; i < cookies.length; i++)
if (cookies[i].getName( ).equals("userid"))
userid = cookies[i].getAttribute( );
The Servlet API provides classes and methods
7/27/2019 unit-1_ECJ
37/48
Sessiontracking
The Servlet API provides classes and methodsspecifically designed to handle session tracking . Aservlet can use the session-tracking API to delegatemost of the user-tracking functions to the server.The first time a user connects to a session-enabled
servlet, the servlet simply creates ajavax.servlet.http.HttpSession object. The servletcan then bind data to this object, so subsequentrequests can read the data. After a certain amountof inactive time, the session object is destroyed.
A servlet uses the getSession( ) method of
HttpServletRequest to retrieve the current sessionobject. This method takes a single booleanargument. If you pass TRue and there is no currentsession object, the method creates and returns anew HttpSession object. If you pass false, themethod returns null if there is no current session
object. For example:
HttpSession thisUser = req.getSession(true);
7/27/2019 unit-1_ECJ
38/48
Sessiontracking_1
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Date;import java.text.DateFormat;
import java.util.Enumeration;
public class SessionDisplay extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
java.io.IOException{
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter( );
HttpSession session = request.getSession( );
Date creationTime = new Date(session.getCreationTime( ));
Date lastAccessed = new Date(session.getLastAccessedTime( ));
Date now = new Date( );
DateFormat formatter =
DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
DateFormat.MEDIUM);
7/27/2019 unit-1_ECJ
39/48
Sessiontracking_2
out.println("");
out.println("");
out.println( "Displaying the Session Creation and "+
"Last-Accessed Time");
out.println("");
out.println("");
out.println("Session Creation and Last-Accessed
Time");
out.println( "The time and date now is: " +
formatter.format(now) + "
");out.println("The session creation time: "+
"HttpSession.getCreationTime( ): " +
formatter.format(creationTime) + "
");
out.println("The last time the session was accessed: " +
HttpSession.getLastAccessedTime( ): " +
formatter.format(lastAccessed) );
out.println("");out.println("");
}
7/27/2019 unit-1_ECJ
40/48
URLrewriting
If your browser does not support cookies, URLrewriting provides you with another sessiontracking alternative. URL rewriting is a method inwhich the requested URL is modified to include asession ID.
There are several ways to perform URL rewriting.You are going to look at one method that is
provided by the Servlet API. Original URL:
http://server:port/servlet/ServletNameRewritten URL:http://server:port/servlet/ServletName?sessionid=7456
The advantage of URL rewriting over hidden formfields is the capability to include session trackinginformation without the use of forms.
import javax.servlet.*;
7/27/2019 unit-1_ECJ
41/48
Program forurl rewriting
p j ;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class URLRewritingServlet
extends HttpServlet {
//Initialize global variablespublic void init(ServletConfig
config)
throws ServletException {
super.init(config);
}
//Process the HTTP Get requestpublic void
doGet(HttpServletRequest
request,
HttpServletResponse response)
throws ServletException,
IOException {
response.setContentType("text/html");
PrintWriter out =
response.getWriter();
out.println("");
out.println("URL
Rewriting");
out.println("");
// Encode a URL string with the
session id appended
// to it.String url =
response.encodeRedirectURL(
"http://localhost:8000/servlet/ch
eckout?sid=5748");
// Redirect the client to the new
URL
response.sendRedirect(url);out.println("");
out.close();
}
//Get Servlet informationpublic
String getServletInfo() {
return "URLRewritingServlet
Information";
}
}
7/27/2019 unit-1_ECJ
42/48
Servletconfiguration
Sometimes it is necessary to provide initialconfiguration information for Servlets.Configuration information for a Servlet may consist
of a string or a set of string values included in theServlet's web.xml declaration. This functionalityallows a Servlet to have initial parameters specifiedoutside of the compiled code and changed withoutneeding to recompile the Servlet.
ServletContext Defines a set of methods that a
7/27/2019 unit-1_ECJ
43/48
Servletcontext andservlet config
ServletContext Defines a set of methods that aservlet uses to communicate with its servletcontainer.ServletConfig is a servlet configuration object usedby a servlet container used to pass information to a
servlet during initialization. All of its initializationparameters can ONLY be set in deploymentdescriptor.
The ServletContext object is contained within theServletConfig object, which the Web serverprovides the servlet when the servlet is initialized.
You can specify param-value pairs forServletContext object in tags inweb.xml file.
The ServletConfig parameters are specified for aparticular servlet and are unknown to other
servlets.
The ServletContext parameters are specified for anentire application outside of any particular servletand are available to all the servlets within thatapplication.
7/27/2019 unit-1_ECJ
44/48
Servletcontext
For ex: If you want the name of your company oryour E-mail address appear in all the pages of yourweb application then you use ServletContext.
// use this in web.xml
// use this in servlet code
String s =
getServletContext.getInitParameter("Developer");
7/27/2019 unit-1_ECJ
45/48
ServletConfig
Lets consider you need to have a String value whichtells you what a particular servlet does. RememberServletConfig is for a particular servlet and not forthe entire Application.
The web.xml file may look like this:
SelectSelect
About the ServletThis Servlet gives you a list of
colors to select from
// use this in servlet code
String s =getServletContext.getInitParameter(About theServlet");
7/27/2019 unit-1_ECJ
46/48
ServletCollaboration
Servlet collaboration is all about sharinginformation among the servlets. Collaboratingservlets is to pass the common information that isto be shared directly by one servlet to anotherthrough various invocations of the methods. Toperform these operations, each servlet need toknow the other servlet with which it is collaborated.
The collaboration can be done by redirecting aservlet from another or loading the servlets fromthe ServletContext access methods. This can alsobe achieved by the methods forward() and include()ofRequestDispatcher or by sendRedirect()
method.
7/27/2019 unit-1_ECJ
47/48
requestDispatcher()
A Request Dispatcher is all about dispatching arequest to an another resource. Requestdispatching is done using two different mechanism
Include
Forward
\\Forward
RequestDispatcher rd ==req.getRequestDispatcher("servlet2");
rd.forward(req, resp);
\\ Include
rd.include(req, resp);
7/27/2019 unit-1_ECJ
48/48
sendRedirect()
The sendredirect method of Httpservletresponseinterface can be used to redirect your response toanother servlet, jsp or html file.
It can accept relative URL.
Can be used inside or outside the server.
Response. Send Redirect(http://www.google.com)