Session 2.1 J2EE Architecture Session 2.2 Http Basics & Servlet IETE
Session 2.1 J2EE Architecture
Session 2.2 Http Basics & Servlet
IETE
Objectives:
What is J2EE?
Why J2EE?
J2EE Tire Architecture.
MVC Architecture.
Http Basics
Servlet
IETE
What is J2EE?
Open and standard based platform for
developing, deploying and managing. n-tier, Web-enabled, server-centric, and component-
based enterprise applications.
It includes Java Standard Edition(J2SE) plus most of the other Java technologies including JavaMail, API for XML Binding, Servlets, JSP (Java Server Pages), JMS (Java Messaging Service), EJB (Enterprise Java Beans)……….
IETE
Why J2EE?
We can use all the properties of Java Technology….Platform Independence, Secure Code, Portability etc……
Simplifies the complexity of a building n-tier application.
Standardizes an API between components and application server container.
J2EE Application Server and Containers provide the framework services
IETE
J2EE ARCHITECTURE
Single Tier (Mainframe-based) Dumb terminals are directly
connected to mainframe
Centralized model (as opposed distributed model)
Presentation, business logic, and data access are intertwined in one application
Eg. FOXPRO
IETE
J2EE ARCHITECTURE (Cont.)
Single-Tier : Pros & Cons
Pros: – No client side management is required – Data consistency is easy to achieve
Cons: – Functionality (presentation, data model, business logic)
intertwined, difficult for updates and maintenance and code reuse
IETE
J2EE ARCHITECTURE (Cont.)
Two-Tier Clients talking to back end
database
– SQL queries sent, raw data
returned
Presentation, Business logic
and Data Model processing logic
in client application
•Client – Server systems
•Ex:- Unix, mainframes
IETE
J2EE ARCHITECTURE (Cont.)Two-Tier : Pros & Cons Pro:
– DB product independence (compared to single-tier model)
Cons:
– Presentation, data model, business logic are intertwined (at client side),
difficult for updates and maintenance
– Data Model is “tightly coupled” to every client: If DB Schema changes, all
clients break
– Updates have to be deployed to all clients making System maintenance
nightmare
– DB connection for every client, thus difficult to scale
– Raw data transferred to client for processing causes high network traffic
IETE
J2EE ARCHITECTURE (Cont.)
Three-Tier (RPC based) Thinner client: business & data
model separated from presentation
– Business logic and data access
logic reside in middle tier server
while client handles presentation
Middle tier server is now required to
handle system services
– Concurrency control, threading,
transaction, security, persistence,
multiplexing, performance, etc.
IETE
J2EE ARCHITECTURE (Cont.)
Three-Tier (RPC based) : Pros & Cons
Pro:– – Business logic can change more flexibly than 2-tier model
• Most business logic reside in the middle-tier server Cons:
– – Complexity is introduced in the middle-tier server– – Client and middle-tier server is more tightly coupled (than the three-tier
object based model)– – Code is not really reusable (compared to object model based)
IETE
J2EE ARCHITECTURE (Cont.)N-Tier
• N-Tiered architecture: Various components that make up the application are logically separated or distributed across network.
• Client Server Server Database• Eg.. ATM Application
IETE
J2EE ARCHITECTURE (Cont.)
Multi - Tier Architecture in J2EE
• Front end (Client):
• Viewed and manipulated by the users.
• It can live in a Web browser or a standalone application.
• Presents customized information to clients requirements.
• Servlets and JSP is used as Front end development.
IETE
J2EE ARCHITECTURE (Cont.)
Multi - Tier Architecture in J2EE
IETE
J2EE ARCHITECTURE (Cont.)
Multi - Tier Architecture in J2EE
• Middle:
• Contains business logic Ex: Discounts.
• It may contain two sub-tiers:
• Web Tier – It handles communication to client.
• EJB Tier – It manages business logic and access to corporate data.
• Backend (EIS):
• Provides access to various corporate data stores (Databases, E-Mail system,
Legacy systems…)
IETE
MVC ARCHITECTURE
Need for MVC
• J2EE designers were faced with a question of where to place the code in a
distributed environment.
• Reasonable solution: To divide the code and put them closer to their respective
tier.
• This approach reminds a popular, proven 20 year old application design pattern
called MVC.
• MVC is a design pattern for building maintainable applications, introduced by
Xerox researchers.
IETE
MVC ARCHITECTURE(Cont.) What is MVC?
• Technique aimed to make large applications flexible/simple during development and
maintenance.
• It is a design pattern for partitioning of labor into three layers.
• The "model" is the internal workings of the program (the algorithms), the "view" is
how the user sees the state of the model and the "controller" is how the user changes
the state or provides input.
IETE
MVC ARCHITECTURE(Cont.)
What is MVC? (Cont.)
• In this pattern, application flow is mediated by a central controller that
delegates requests to an appropriate handler.
• Controller is the means by which users interacts with web application.
Controller is responsible for input to the model.
• Ex: A pure GUI controller accepts input from the user and instructs the model to
create a view based on that input. If an invalid input is sent to the controller
from the view, model informs controller to direct the view that error occurred
and to tell it to try again.
IETE
MVC Example
IETE
IETE
Servlet & HTTP Basics
Servers
• A server is a computer that responds to requests from a client– Typical requests: provide a web page, upload or download a file, send
• A server is also the software that responds to these requests; a client could be the browser or other software making these requests
• Typically, your little computer is the client, and someone else’s big computer is the server– However, any computer can be a server– It is not unusual to have server software and client software running
on the same computer
IETE
Apache• Apache is a very popular server
– 66% of the web sites on the Internet use Apache• Apache is:
– Full-featured and extensible– Efficient– Robust– Secure (at least, more secure than other servers)– Up to date with current standards– Open source– Free
• Why use anything else?
IETE
Ports
• A port is a connection between a server and a client– Ports are identified by positive integers– A port is a software notion, not a hardware notion, so there may be
very many of them• A service is associated with a specific port
– Typical port numbers:• 21—FTP, File Transfer Protocol• 22—SSH, Secure Shell• 25—SMTP, Simple Mail Transfer Protocol• 53—DNS, Domain Name Service• 80—HTTP, Hypertext Transfer Protocol• 8080—HTTP (used for testing HTTP)• 7648, 7649—CU-SeeMe• 27960—Quake III
These are the ports of most interest to us
IETE
Common Gateway Interface (CGI)
• CGI stands for Common Gateway Interface• CGI is a standard programming interface to Web
servers that allows building dynamic and interactive Web sites
• CGI is not a programming language. – It is just a set of standards (protocols)– The standards specify how Web-applications can be
executed on the server-side
IETE
Dynamic Pages
Run CGI program………print $result
Return dynamically generated HTML file
Request service
<HEADER><BODY
</BODY> IETE
A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP, the Hyper Text Transfer Protocol. Servlet is an opposite of applet as a server-side applet. Applet is an application running on client while servlet is running on server.
Client Server
Request
Response
Servlet
IETE
What is java servlet ?
Servlets vs. CGI
• Servlet – Java-based CGI– Executed by servlets container
• Golden goals: "performance, flexibility, portability, simplicity and security"
• Faster and thinner– No fork-process execution like Perl– No need to initialize for each request– Only lightweight thread context switching– Built-in multithreading
IETE
Servlets vs. CGI
• Multi-threaded execution allows to:– share data across successive requests– share data between concurrent requests– use hidden fields, cookies, or sessions
• Java supports “write once, run anywhere” paradigm– Easier than unportable Perl
• Java provides enhanced security• Supports all HTTP request methods
– GET, POST, PUT, DELETE, and others
IETE
• Request-response model.
request
responseHTTP
HTML
HTTP Request
<html><head> <body>
…<html><head> <body>
…
Client
Server
Introduction – request-response model
IETE
HTTP Request HTTP Response
Key elements of a “request” stream:
HTTP method (action to be performed).
The page to access (a URL).
Form parameters.
Key elements of a “response” stream:
A status code (for whether the request was successful).
Content-type (text, picture, html, etc…).
The content ( the actual content).
Introduction – what is a request and response
IETE
Where does Servlet come into the picture?
Web ServerApplication
Helper Application
Web Server machine
I can serve only static HTML
pages
Not a problem. I can handle
dynamic requests.
“The Helper Application is nothing but a SERVLET”
Introduction – What is a Servlet
IETE
• What is a Web Container?
GET.…..
Web Server
ServletWeb Container
GET.…..
GET.…..
request
Client
Servlet Architecture -Web Container
IETE
• How does the Container handle a request?
Web Container
Servlet
Thread
Service()
doGet()
<Html> <Body> …….
</Body> </Html>
request
response
response
Web Server
Http request
Client
Servlet Architecture – Web Container
IETE
What is the role of Web Container ?
• Communication Support
• Lifecycle Management
• Multi-threading support
• Security
• JSP Support
The CONTAINER
S1
S3
S4
S2
JSP1
The container can contain multiple Servlets & JSPs within it
Servlet Architecture – Web Container
IETE
• How does the Container know which Servlet the client has requested for?
A Servlet can have 3 names
Client known URL name
Deployer known secret internal name
Actual file name
<web-app> ……… <servlet> <servlet-name>LoginServ</servlet-name> <servlet-class>com.Login</servlet-class> </servlet>
<servlet-mapping> <servlet-name>LoginServ</servlet-name> <url-pattern>/Logon</url-pattern> </servlet-mapping> ……….. ………..</web-app>
Web.xml
Servlet Architecture – Deployment Descriptor
IETE
• The Servlet lifecycle is simple, there is only one main state – “Initialized”.
Initialized
Does not exist
constructor()
init()destroy()
Service()
Servlet Lifecycle
IETE
GenericServlet
HttpServlet
Your Servlet
Servlet
Interface
Abstract class
Abstract class
Concrete class
If not overridden, implements init() method from the ‘Servlet’ interface,
If not overridden, implements service()method.
We implement the HTTP methods here.
Servlet Lifecycle - Hierarchy
IETE
Understanding Servlet API
Packages in the Java Servlet API 2.1
http://java.sun.com/products/servlet/2.1/servlet-2.1.pdfIETE
Understanding Servlet API (Contd.)
Packages in the Java Servlet API 2.1
http://java.sun.com/products/servlet/2.1/servlet-2.1.pdfIETE
When is it called
What it’s for Do you override it
init() The container calls the init() before the servlet can service any client requests.
To initialize your servlet before handling any client requests.
Possibly
service() When a new request for that servlet comes in.
To determine which HTTP method should be called.
No. Very unlikely
doGet() or doPost()
The service() method invokes it based on the HTTP method from the request.
To handle the business logic.
Always
Servlet Lifecycle – 3 big moments
IETE
Using the PrintWriter
• From here on, it’s just a matter of using our PrintWriter, named out, to produce the Web page
• First we create a header string:String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n";– This line is technically required by the HTML spec– Browsers mostly don’t care, but HTML validators do care
• Then use the println method of out one or more times out.println(docType + "<HTML>\n" + "<HEAD> ... </BODY></HTML>");
• And we’re done!
IETE
A “Hello World” servlet
public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n"; out.println(docType + "<HTML>\n" + "<HEAD><TITLE>Hello</TITLE></HEAD>\n" + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1>Hello World</H1>\n" + "</BODY></HTML>"); }} Don’t worry, we’ll take this a little at a time!
IETE
• The HTTP request method determines whether doGet() or doPost() runs.
GET (doGet()) POST (doPost())
HTTP Request
The request contains only the request line and HTTP header.
Along with request line and header it also contains HTTP body.
Parameter passing
The form elements are passed to the server by appending at the end of the URL.
The form elements are passed in the body of the HTTP request.
Size The parameter data is limited (the limit depends on the container)
Can send huge amount of data to the server.
Idempotency
GET is Idempotent POST is not idempotent
Usage Generally used to fetch some information from the host.
Generally used to process the sent data.
Request and Response – GET v/s POST
IETE
Request
Can the Servlet Serve the request?
Send resource
Yes
Does the Servlet knowWho can serve?
Error page
Send Redirect
Request Dispatcher
No
Yes
No
Request and Response – The response
IETE
Servlet 2Servlet 1 Servlet 3 JSP 1
Servlet Context
Servlet Config Servlet ConfigServlet Config Servlet Config
Being a Web Container – Servlet Config and Context
IETE
• What are init parameters?• Difference between Servlet Context and Config Init
parameters
Context Init Parameters Servlet Init Parameters
Scope Scope is Web Container Specific to Servlet or JSP
Servlet code
getServletContext() getServletConfig()
Deployment Descriptor
Within the <web-app> element but not within a specific <servlet> element
Within the <servlet> element for each specific servlet
Being a Web Container – init parameters
IETE
• What exactly, is an attribute?• Difference between Attributes and parameters
Attributes Parameters
TypesContextRequestSession
ContextRequest
Servlet Init
Method to set
setAttribute(String, Object)We cannot set Init parameters.
Return type Object String
Method to get
getAttribute(String)getInitParameter
(String)
Being a Web Container - Attributes
IETE
Q & A
IETE