0% found this document useful (0 votes)
60 views43 pages

Serv Lets

This document provides an overview of Java servlets, including their history, features, lifecycle, and deployment. It discusses how servlets provide a standard interface for interacting with web servers and implementing dynamic web applications. Early servlets implemented all logic in one class, but it is now considered better practice to separate concerns using the MVC pattern. The document also covers servlet configuration using a deployment descriptor and initialization parameters, as well as error handling.

Uploaded by

Mohamed Sami
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views43 pages

Serv Lets

This document provides an overview of Java servlets, including their history, features, lifecycle, and deployment. It discusses how servlets provide a standard interface for interacting with web servers and implementing dynamic web applications. Early servlets implemented all logic in one class, but it is now considered better practice to separate concerns using the MVC pattern. The document also covers servlet configuration using a deployment descriptor and initialization parameters, as well as error handling.

Uploaded by

Mohamed Sami
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

J2EE Servlets

Ch. 10 (Architecture)
Ch. 12 (21 Days)
History of Interactive Web
➢ Applets
 Long download times
 Code on client machines (maintenance)

➢ CGI
 Custom code to interact with web server
 Security hole
 Resource hog for large sites

➢ Java Servlets
 Standard, easy interface to web server
 Security/authentication
 Implements sessions
History (cont.)
➢ Early use of Servlets
 Simple, easy to use for web applications
 MVC all implemented in one big servlet
• Very complex
• Difficult to maintain
• Not scalable

➢ Current state of Servlet use


 Smaller is better.
 Used only for:
• Gathering and validating data input from the user
• Coordinating output
• Minimal business logic
• Web page forwarding
Servlet Features
➢ Tailored to interact with Web Server
➢ Server and platform independent
➢ Efficient and scalable
➢ Container provides additional functionality
(i.e., authentication, cookies, etc.)
Interacting with HTML Forms
➢ Get– Request information from web
server
 Simple
http://www.byui.edu/j2ee?Name=Fred+&tel=3565132

➢ Post – Send data to the server


 Submit button, etc.
 Data is sent in body of message
 Safer than Get
HTML Forms (Cont.)
➢ Put – Place a file on the server

➢ Delete – Remove a web page from server


Servlet Class Diagram
Class Diagram
Servlet Life Cycle
Class Diagram
START

init()

doGet(),
doPost, … Processing
State: Resident
Request

destroy()

END
Servlet Sequence Diagram

Fig. 12-15
Model 1 - Servlets only
Model/View/Control
submit

Servlet
doGet/doPost
Generate Data
webpage HTML Data
base
WebServer
Servlets in the Enterprise
submit
View/Control Model

doGet/doPost Servlet
Input EJB
Control Data Entity
WebServer webpage
Output Bean

Performance
and
Flexibility Issues
Example Servlet
publc class HtmlPage extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException
{
String name = request.getParameter(“name”);
String telephone = request.getParameter(“tel”);
response.setContentType(“text/html”);
Get value of form parameters
…. Business logic ….
PrintWriter out = response.getWriter():
out.println(“<HTML>”);
out.println(“<HEAD><TITLE>First Servlet</TITLE></HEAD>”); Sent output to web
out.println(“<BODY>”); browser
out.println(“<H1>Hello “ + name + “, Telephone “ + telephone + “</H1>”);
out.println(“</BODY>”);
out.println(“</HTML>”);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException
{
doGet(request, response);
}
}
Model 2 Architecture
submit

View Control Model

doGet/doPost Servlet
input Business Data
Methods Data Access
<<forward>>
WebServer <<SessionEJB>> Objecs
<<EntityEJB>>
JSP
webpage
page
output
Web Development Life Cycle
Model 2 Architecture

Servlet JSP

Determine
Get request and call Determine
next view Build view
Parameters business
function
Web Development Life Cycle
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String username = request.getParameter("username");


String password = request.getParameter("password");
1. Get request parameters

try {
InitialContext context = new InitialContext();
BusinessRulesRemote businessRules =
(BusinessRulesRemote) context.lookup(BusinessRules.REMOTE_JNDI_NAME);
Long personId = businessRules.login(username,password); 2.Call business
} catch (Exception e) { function
e.printStackTrace();
}

HttpSession session = request.getSession();


session.setAttribute("personid", personId);

RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp"); 3. Determine next view


dispatcher.forward(request, response);

}
Web Development Life Cycle
JSP page

<div id="login">
<span class='highlight'>Welcome to Home Town Bank!</span>
<br> 4.Build next
<a id='logout' href="">Logout</a> view
</div>
How to use HTTPServlet
HttpServlet

doGet(request HttpServletRequest , response:HttpServletResponse)


doPost(request HttpServletRequest, response:HttpServletResponse)
doPut(request HttpServletRequest , response:HttpServletResponse)
doDelete(request HttpServletRequest , response:HttpServletResponse)

HttpServletRequest HttpServletResponse

Contains Request Info (Input) Handles Response (Output)


RequestResponse Interface
Forwarding a Response
RequestResponse Interface
Including other Web Components
Deployment of Servlets
➢ AllServlet files zipped together into a web
archive (“war”) file

➢ Requires specific directory structure

➢ Deployment Descriptor (WSDL)


Deployment Descriptor
<?xml version=“1.0” encoding=“UTF-8:?>
<!DOCTYPE web-app PUBLIC ‘-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN’
‘http://java.sun.com/dtd/web-app_2_3.dtd’>
<web-app>
<display-name>A Simple Application</display-name>
<servlet>
<servlet-name>Verify Data</servlet-name>
<servlet-class>VerifyData</servlet-class>
<init-param>
<param-name>maxValue</param-name>
<param-value>25</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Verify Data</servlet-name>
<url-pattern>/verifydata</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<error-page>
<error-code>404</error-code>
<location>/error404.html</location>
</error-page>
</web-app>
Customizing Deployment
➢ Define initialization parameters
 Context parameters
• Apply to entire web application

 Servlet parameters
• Apply to a specific servlet
Deployment Descriptor
<?xml version=“1.0” encoding=“UTF-8:?>
<!DOCTYPE web-app PUBLIC ‘-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN’
‘http://java.sun.com/dtd/web-app_2_3.dtd’>
<web-app>
<display-name>A Simple Application</display-name>
<context-param>
<param-name>location</param-name> Context
<param-value>BYU-Idaho</param-value> Intialization
<description>Site Location</description> Parameter
</context-param>
<servlet>
<servlet-name>Verify Data</servlet-name>
<servlet-class>VerifyData</servlet-class>
<init-param> Servlet
<param-name>maxValue</param-name> Intialization
<param-value>25</param-value> Parameter
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Verify Data</servlet-name>
<url-pattern>/verifydata</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<error-page>
<error-code>404</error-code>
<location>/error404.html</location>
</error-page>
</web-app>
Retrieving Init. Parameters

public void init() throws ServletException


{
super.init();
ServletContext context = this.getServletContext();
String location = context.getInitParameter(“location");

if (maxValue == null)
{
int maxValue = Integer.parseInt(this.getInitParameter(“maxValue");
}


}
Handling Errors
➢ HTTP Error Codes
 Http Status code – set error code
 Error page – set default error page

➢ Send Redirect – redirect to another page

➢ ServletExceptions – catch and handle all


servlet exceptions
Set HTTP Status Code
➢ Sets the error status code on default error page
HttpServletResponse

public void sendError(int statusCode)


public void sendError(int statusCode, String msg))
….
public void sendRedirect(String url);

Import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
publc class HtmlPage extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException
{
String name = request.getParameter(“name”);
if (name.length() < 1)
response.sendError(9001, “Invalid name”);
}
}
Default HTTP Error Page
Deployment Descriptor
<?xml version=“1.0” encoding=“UTF-8:?>
<<!DOCTYPE web-app PUBLIC ‘-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN’
‘http://java.sun.com/dtd/web-app_2_3.dtd’>
<web-app>
<display-name>A Simple Application</display-name>
<servlet>
<servlet-name>Verify data</servlet-name>
<servlet-class>VerifyData</servlet-class>
<init-param>
<param-name>maxValue</param-name>
<param-value>25</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>verifyData</servlet-name>
<url-pattern>/verifyData</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<error-page> Define output error
<error-code>9001</error-code> page for error code
<location>/error9001.html</location>
</error-page>
Send Redirect
➢ Redirect to another page to handle error
HttpServletResponse

public void sendError(int statusCode)


public void sendError(int statusCode, String msg))
….
public void sendRedirect(String url);

Import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
publc class HtmlPage extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException
{
String name = request.getParameter(“name”);
if (name.length() < 1)
response.sendRedirect(“/Servlets/invalidNamePage”);
}
}
Servlet Session Management
➢ Hidden fields in form
 Visible to client in source (not secure)
 Limited amount of data

➢ URL rewritting
http://www.byui.edu/j2ee?sessionid=9982345

➢ Cookies
 Store on client browser
 May be disabled by some users

➢ Server side session object


 Session info stored on Server
• Unlimited amount of space
• More secure
 Automatic management
Creating Cookies
➢ Implement transactions with Cookies
 Store state data in Cookie

HttpServletResponse Cookie

… public void setValue(String value)


public void addCookie(Cookie c) public String getName()
public Cookie[ ] getCookies() public String getValue()
…. ….
Creating a Cookie
Import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
publc class HtmlPage extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException
{
try
{
Cookie cookie = new Cookie(“userAddress”, null);
String url = this.getRequextURI();
cookie.addValue(url);
response.addCookie(cookie);

double quantity = Double.parseDouble(request.getParameter(“quantity”));


double totalQuantity += (Double) session.getAttribute(“totalQuantity”);
}
catch (RemoteException remex)
{
response.sendError(response.SC_INTERNAL_SERVER_ERROR);
}
}
}
Retrieving a Cookie
publc class HtmlPage extends HttpServlet
{
String userUrl = new UniqueID();
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException
{
try
{
Cookie cookie = null;
Cookie[] cookies = response.getCookies();
if (cookies != null)
{
for (int i=0; i < cookies.length; i++)
{
cookie = cookies[i];
if (cookie.getName().equals(“userAddress”))
{
String urlAddress = cookie.getValue();
break;
}
}
}
}
catch (RemoteException remex)
{
response.sendError(response.SC_INTERNAL_SERVER_ERROR);
}
}
Sessions
➢ Implement transactions with a HttpSession
 Retains state of data between page request

HttpSession

HttpServletRequest public long getId()


public long getLastAccessedTime()
… public long getCreationTime()
public HttpSession getSession() public long getMaxInactiveInterval()
…. public Object getAttribute()
public boolean isNew()
….
Getting a Session
Import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
publc class HtmlPage extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException
{
try
{
HttpSession session = request.getSession();
if (session.isNew())
{
Long personId = (Long) session.getAttribute(“personId”);
}
double quantity = Double.parseDouble(request.getParameter(“quantity”));
session.setAttribute(“quantity”);
}
catch (RemoteException remex)
{
response.sendError(response.SC_INTERNAL_SERVER_ERROR);
}
}
}
Filter Servlets
➢ Acts as preprocessor to request/response
for target servlet

…HttpPage PageHits
HttpPage
Filter
Servlet
Authenticate Servlet
Filter
Servlet
…VerifyData
VerifyData
Servlet
Filter Servlet
Import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
publc class PageHits extends HttpServlet implements Filter Must implement
{ Filter Interface
private FilterConfig filterConfig = null;

public void init(FilterConfig filterConfig) throws ServletException


{ Must override init.
this.filterConfig = filterConfig; method
}

public void destroy(


Must override destroy
{
method
this.filterConfig = null;
}
Filter Servlet (cont.)

public void doFilter(HttpServletRequest request, HttpServletResponse response, Must override


FilterChain chain) throws IOException, ServletException doFilter method
{
if (filterConfig == null)
return;
synchronized (this)
{
Integer counter =(Integer) filterConfig.getServletContext().getAttribute("Counter");

if (counter == null)
counter = new Integer(0);
counter = new Integer(counter.intValue()+1);
filterConfig.getServletContext().log("Number of hits is " + counter);
filterConfig.getServletContext().setAttribute("Counter", counter);
}

chain.doFilter(req, resp)
}
Modify Deployment Descriptor
<?xml version=“1.0” encoding=“UTF-8:?>
<<!DOCTYPE web-app PUBLIC ‘-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN’
‘http://java.sun.com/dtd/web-app_2_3.dtd’>
<web-app>
<display-name>A Simple Application</display-name>
<servlet>
<servlet-name>VerifyData</servlet-name>
<servlet-class>VerifyData</servlet-class>
<init-param>
<param-name>maxValue</param-name>
<param-value>25</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Verify Data</servlet-name>
<url-pattern>/verifyData/</url-pattern>
</servlet-mapping>

<filter>
<filter-name>Page Hits</filter-name>
<display-name>Page Hits</display-name>
<description>Count page hits<description>
<filter-class>PageHits</filter-class>
</filter>
<filter-mapping>
<filter-name>PageHits</filter-name>
<servlet-name>VerifyData</servlet-name>
</filter-mapping>

</web-app>
Listener Servlet
➢ Servlet is automatically executed when
some external event occurs

HTTPSessionActivationListener Session is activated/passivated


HTTPSessionAttributeListener Session attribute is added/removed
HTTPSessionListener Session attribute is created/destroyed
HTTPSessionContextAttributeListener Servlet contextattribute is
added/removed
HTTPSessionContextListener Servlet context changes
Create Listener Servlet
Import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
publc class Listener extends HttpServlet implements ServletContextListener Must implement
{ Listner Interface
private ServletContext context = null;

public void contextIntialized(ServletContextEvent event)


Must override
{ contextInitialized
context = event.getServerContext(); method
Integer counter = new Integer(0);
context.setAttribute(“Counter”, counter);
context.log(“Created Counter”);
}

public void contextDestroyed(ServletContextEvent event) Must override


{ contextInitialized
event.getServletContext().removeAttribute(“Counter”); method
}

}
Modify Deployment Descriptor
<?xml version=“1.0” encoding=“UTF-8:?>
<<!DOCTYPE web-app PUBLIC ‘-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN’
‘http://java.sun.com/dtd/web-app_2_3.dtd’>
<web-app>
<display-name>A Simple Application</display-name>
<servlet>
<servlet-name>Verify data</servlet-name>
<servlet-class>VerifyData</servlet-class>
<init-param>
<param-name>maxValue</param-name>
<param-value>25</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Verify Data</servlet-name>
<url-pattern>/verifyData/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>Page Hits</filter-name>
<display-name>Page Hits</display-name>
<description>Count page hitsdescription>
<filter-class>PageHits</filter-class>
</filter>
<filter-mapping>
<filter-name>PageHits</filter-name>
<servlet-name>Verify data</servlet-name>
</filter-mapping>
<listener>
< listener-class>Listener</ listener -class>
</listener>
</web-app>
Modify Filter Servlet

public void doFilter(HttpServletRequest request, HttpServletResponse response,


FilterChain chain) throws IOException, ServletException
{
if (filterConfig == null)
return;
synchronized (this)
{
Integer counter =( Integer) filterConfig.getServletContext().getAttribute(“Counter”);
if (counter = null)
counter = new Integer(1); No longer needed
counter = new Integer(counter.intValue()+1);
filterConfig.getServletContext().log(“Number of hits is “ + counter);
filterConfig.getServletContext().setAttribute(“Counter”, counter); counter);

}
chain.doFilter(request, response);
}
}
Modified Filter Servlet

public void doFilter(HttpServletRequest request, HttpServletResponse response,


FilterChain chain) throws IOException, ServletException
{
if (filterConfig == null)
return;
synchronized (this)
{
Integer counter =( Integer) filterConfig.getServletContext().getAttribute(“Counter”);
counter = new Integer(counter.intValue()+1);
filterConfig.getServletContext().log(“Number of hits is “ + counter);
filterConfig.getServletContext().setAttribute(“Counter”, counter); counter);

}
chain.doFilter(request, response);
}
}

You might also like