Professional Documents
Culture Documents
J2EE Platform:
• Enterprise Architecture Styles
• Containers and Technologies
Servlet Programming:
• Overview of Java Servlet API Text book
• Servlet Implementation Professional Java Servler
• Servlet Configuration Programming
• Servlet Exceptions by Subrahmanyam Allamraju
• Servlet Life cycle,
• Request and Responses.
• Introduction to Web containers: Web Application Structure, Mapping requests to
Applications and Servlets, Securing web Applications and Deployment configuration
• Servlet Sessions, Context and Collaboration: Approaches to Session tracking,
Session Tracking with java servlet API, Servlet Context, Servlet Collaboration.
Applet
Application Container
ClientApp
(JAR file)
Application Container
Deployment
Descriptor
Main AppClass
Public static void main (String args[ ] )
Application
JD JA J J Java Packages,
B X A M Classes, Libraries
C P A S
S
15 of 99
J2EE Architecture
Middle Tier Container
Web Container
Manages execution of servlets and JSPs
Part of web or application server
Supports HTTP
EJB Container
Business Components that contain business logic or rules
Two types of EJBs
Session Beans – Logic Oriented and deal with handling client
requests and data processing
Entity Beand – Strongly coupled with data and deal with data
access and persistence
16 of 99
J2EE Architecture
E-Commerce Scenario
Shopping Cart
Application WEB Container
Catalog Servlet
OrderManager
Application Container Cart Servlet Application Supplier Server
Order WEB Container StockOrder
WEB Container Order Manager (XML)
ClientApp Process Servlet
Servlet
Static
Pages EJB Container
Order Manager
EJBApplication
WEB Container
Order EJB
Database
Cart Application
Catalog servlet gets product data from the database
Cart servlet keeps track of the customer purchase
Process servlet processes the order
Order Process Application
Processes customer order
Checks inventory levels (orders new parts from Suppliers)
Processes payments
Sends acknowledgement to the client
18 of 99
J2EE Architecture
E-Auctions
Applet Container
Client Tier Browser
PaymentApplet
WEB Container WEB Container WEB Container WEB Container WEB Container
Cluster
Middle Tier Sales/Auction Sales/Auction Sales/Auction
Sales & Auction Payment Payment Payment Cluster
WEB Container WEB Container WEB Container WEB Container WEB Container
Application Application Application Application Application
19 of 99
J2EE Architecture
E-Auctions – Container Ideas
Web Container
Auction Application
Payment Application Registration
Java Package
Post
Payment Search
Descriptor
Static
Deployment Descriptor
Deployment Bid Pages
Static
Pages Purchase
Java Package Offer
History
Payment
20 of 99
J2EE Architecture
E-Auctions
21 of 99
J2ee architecture-containers
• j2EE container is a runtime to manage application
components developed according to the API specifications,
and to provide access to the J2EE APIs.
• Diagram shows the architecture of J2EE in terms of
containers and APIs.
• Architecture shows four containers
1) Web container: for hosting java servlets and JSPs
2) EJB container: for hosting Enterprise javabean
components.
3) Applet container: for hosting java applets.
4) Application client container: for hosting standard java
applications.
INTERFACES CLASSES
Servlet ServletInputStream
ServletContext ServletOutputStream
ServletConfig ServletRequestWrapper
ServletRequest ServletResponseWrapper
ServletResponse ServletRequestEvent
ServletContextListener ServletContextEvent
RequestDispatcher ServletRequestAttributeEvent
SingleThreadModel ServletContextAttributeEvent
Filter ServletException
FilterConfig UnavailableException
FilterChain GenericServlet
ServletRequestListener
E.Swathi, CSE, CBIT
• Interfaces and classes are grouped together based on their purpose and usage.
Purpose Class/interface
Servlet Implementation Javax.servlet.Servlet
SingleThreadModel,GenericServlet,
Javax.servlet.http.HttpServlet
GenericServlet HttpServlet
init(ServletConfig);
doGet(HttpServletRequest,
service(ServletRequest,
HttpServletResponse);
ServletResponse);
doPost(HttpServletRequest,
HttpServletResponse);
destroy(); …….
Life cycle of servlet
➢ Life cycle of the servlet describes how and when a servlet is loaded,
initialized and able to handle the requests and destroyed.
➢ Servlets are reside in the java virtual machine after they are loaded
and continue until server stops.
➢ Web server has module called servlet container to load and run
servlets
➢ Servlets consists of three methods during the life cycle of the java
servlet.
Loaded
Startup init()
destroy()
Destroyed
E.Swathi, CSE, CBIT
Life cycle of servlets
➢ all these methods are in inteface javax.servlet.Servlet
1. loads the servlet class
2. create servlet instance
3. invokes init() method
4. Invokes service method
5. invokes destroy method
creation and initialization
➢ The servlets are created when a user first invokes a URL corresponding to
the servlet or servlets loaded when server starts up.
- loads servlet class
- create servlet instance
- initialize the servlet instance by calling the init() method
init() can be called only once in its life cycle by the following ways:
a) Through the ‘load-on-startup’ tag using the web.xml. This makes the servlet
to be loaded and initialized when the server starts.
b) Invoked only once before the service().
c) Initialize code like data base connections
➢ Servlet container invokes this method to process the request from client and
send back the formatted results to client
➢ Each request is serviced by a separate thread. The container calls the Service()
method of the servlet for every request.
➢ Service() method finds the HTTP request type and then calls
the appropriate request method such as doGet() or doPost().
- Public void doGet(HttpServletRequest req, HttpServletResponse res)throws
ServletException, IOException{ }
• <web-app>
<servlet>
<init-param>
<param-name>AdminEmail</param-name>
<param-value>zulfiqar_mca@yahoo.co.in</param-value>
</init-param>
•
<init-param>
<param-name>Address</param-name>
<param-value>Okhla</param-value>
</init-param>
•
<init-param>
<param-name>PhoneNo</param-name>
<param-value>9911217074</param-value>
</init-param>
•
<servlet-name>Zulfiqar</servlet-name>
<servlet-class>InitServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Zulfiqar</servlet-name>
<url-pattern>/InitServlet</url-pattern>
</servlet-mapping>
</web-app> E.Swathi, CSE, CBIT
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*; Getparameters.java
import java.util.*;
public class InitServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter pw = response.getWriter();
while(enumeration.hasMoreElements()){
PrintWriter pw = response.getWriter();
while(enumeration.hasMoreElements()){
Method Description
public String getParameter(String name) Return value of a specified parameter
public String[] getParameterValues(String Returns array containing parameter values
key) Ex: checkbox
public Enumeration getParameterName() Enumeration of all the parameter names for
the request.
public Object getAttribute(String name) Value of named attribute
public Enumeration getAttributeNames() Enumeration of all the atrributes in the
request
public void setAttribute(String n, Object x) set named attribute
public void removeAttribute(String n) removes the named attribute from the
request
p ServletInputStream getInputStream() Access body of the request using
throws java.io.IOException ServletInputStream object
E.Swathi, CSE, CBIT
HttpServletReques Interface
• Provides methods to access request parameters
• public interface HttpServletRequest extends ServletRequest
method Description
public String getPathInfo() any extrea path information associate with
the request URL.
public String getPathTranslated() Extra path info into a real path
public String getQueryString() Query string associated with the request
public String getRequestURI URI path /myProject/myServlet/apress
public StringBuffer getRequestURL() protocol, server name, port and server path
public String getServletPath() Returns URI path associated with Servlet
public String getHeader(String name) Value of the named header from the HTTP
request
public String getMethod() Type of the HTTP Request method
69
E.Swathi, CSE, CBIT
✓Follow the steps which are described in the gengreeting
example and then
1.Start Tomcat (if it is not already running)
2.Display the Web page (ColorGet.html) in a browser
3.Select a color
70
E.Swathi, CSE, CBIT
4.Submit the Web page. The browser will display the
response that is dynamically generated by the servlet
71
E.Swathi, CSE, CBIT
✓Parameters for an HTTP GET request are included as part
of the URL that is sent to the Web server
74
E.Swathi, CSE, CBIT
3.Select a color
75
E.Swathi, CSE, CBIT
✓Parameters for an HTTP POST request are not included as
part of the URL that is sent to the Web server
76
E.Swathi, CSE, CBIT
Servlet Sessions, Context and Collaboration:
Approaches to Session tracking,
Session Tracking with java servlet API,
Servlet Context,
Servlet Collaboration.
ServletContext Interface
1. For every web application web container creates one
ServletContext object to hold application level configuration
information such as request dispatcher, servlet API version, servler
version.
2. ServletContext created at time of application deployment and
destroyed at time of application undeployment
3. ServletContext object create by calling below methods
ServletContex context= config.getServletContext(); or
ServletContex context= getServletContext();
USE CASE
- when servlet in an web application required to access a database by
using username and password. Provide this information in web.xml
rather than in every servlet program.
To send the session-id to the client side we have the following ways
1. Cookies
2. URL rewriting
3. HTTP session
4. Hidden form field.
2.Cookies
3. URL Rewriting
5. HTTP Session.
above methods are differ in implementation details
1. User Authentication
▪ User must be authorized first.
▪ When user want to access the web site he must provide user name and
password on login page.
▪ Based on authentication details server maintains the session.
▪ Doesn’t work well if user logged in from different browsers.
E.Swathi, CSE, CBIT
Cookies: A cookie is a concatenation of name, value pairs separated by
semicolon(;) and as optional attributes like comments, domain qualifiers ,
maximum age and its version.
EX:
if the session-id is 35248972
The cookie looks as follows
Jsessionid=35248972; encryption=false; expiry=30
String n=request.getParameter("userName");
out.print("Welcome "+n);
}catch(Exception e){System.out.println(e);}
}
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
➢In this case Hidden form field is used to maintain the state of the user.
➢This is not secure, User can viewed using view source option from the
browsers .
➢Not able to maintain the state of an end user when it encounters a
static document.
</form>
Reload page
Response of first servlet is not displayed on browser only second servelt response is
send to client
E.Swathi, CSE, CBIT
2. public void include(ServletRequest
request,ServletResponse response)throws
ServletException,java.io.IOException:
Includes the content of a resource (servlet, JSP page, or HTML
file) in the response.
response of second servlet is included in the response of the first servlet that is being
sent to the client.
</form>
import javax.servlet.ServletException;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name=request.getParameter(“name”);
out.print("welcome to “+name);
out.close();
}
}
<servlet-mapping>
<servlet-name>AdminServlet</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
</web-app>
E. Swathi, CSE, CBIT
References
• https://way2java.com/java-general/introduction-to-2-tier-and-
3-tier-architecture/
• https://way2java.com/
• https://www.studytonight.com/servlet/servlet-api.php