J2EE Servlets - PowerPoint PPT Presentation

About This Presentation
Title:

J2EE Servlets

Description:

J2EE Servlets Ch. 10 (Architecture) Ch. 12 (21 Days) Getting a Session Import java.io.*; import javax.servlet.*; import javax.servlet.http.*; publc class HtmlPage ... – PowerPoint PPT presentation

Number of Views:251
Avg rating:3.0/5.0
Slides: 44
Provided by: EVON11
Category:
Tags: j2ee | servlet | servlets

less

Transcript and Presenter's Notes

Title: J2EE Servlets


1
J2EE Servlets
  • Ch. 10 (Architecture)
  • Ch. 12 (21 Days)

2
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

3
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

4
Servlet Features
  • Tailored to interact with Web Server
  • Server and platform independent
  • Efficient and scalable
  • Container provides additional functionality
  • (i.e., authentication, cookies, etc.)

5
Interacting with HTML Forms
  • Get Request information from web server
  • Simple
  • http//www.byui.edu/j2ee?NameFredtel3565132
  • Post Send data to the server
  • Submit button, etc.
  • Data is sent in body of message
  • Safer than Get

6
HTML Forms (Cont.)
  • Put Place a file on the server
  • Delete Remove a web page from server

7
Servlet Class Diagram
8
Servlet Life Cycle
init()
doGet(), doPost,
State Resident
ProcessingRequest
destroy()
9
Servlet Sequence Diagram
Fig. 12-15
10
Model 1 - Servlets only
Model/View/Control
Servlet
WebServer
Generate HTML
Data
11
Servlets in the Enterprise
View/Control
Model
WebServer
EJBEntityBean
Servlet
Input Control Output
Data
12
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)
. Business logic .
PrintWriter out response.getWriter()
out.println(ltHTMLgt)
out.println(ltHEADgtltTITLEgtFirst
Servletlt/TITLEgtlt/HEADgt)
out.println(ltBODYgt)
out.println(ltH1gtHello name , Telephone
telephone lt/H1gt)
out.println(lt/BODYgt)
out.println(lt/HTMLgt) public void
doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException
doGet(request, response)
13
Model 2 Architecture
Model
View
Control
WebServer
Data Access ObjecsltltEntityEJBgtgt
Servlet
Business MethodsltltSessionEJBgtgt
input
Data
JSPpage
output
14
Web Development Life CycleModel 2 Architecture
JSP
Servlet
Determine and call business function
Determine next view
Get request Parameters
Build view
15
Web Development Life Cycle
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException String username
request.getParameter("username") String
password request.getParameter("password") tr
y InitialContext context new
InitialContext() BusinessRulesRemote
businessRules (BusinessRulesRemote)
context.lookup(BusinessRules.REMOTE_JNDI_NAME)
Long personId businessRules.login(username,passw
ord) catch (Exception e) e.printStackTrace
() HttpSession session
request.getSession() session.setAttribute("perso
nid", personId) RequestDispatcher dispatcher
request.getRequestDispatcher("index.jsp") disp
atcher.forward(request, response)
16
Web Development Life CycleJSP page
ltdiv id"login"gt ltspan class'highlight'gtWelc
ome to Home Town Bank!lt/spangt ltbrgt
lta id'logout' href""gtLogoutlt/agt lt/divgt
17
How to use HTTPServlet
Contains Request Info (Input)
Handles Response (Output)
18
RequestResponse Interface
Forwarding a Response
19
RequestResponse Interface
Including other Web Components
20
Deployment of Servlets
  • All Servlet files zipped together into a web
    archive (war) file
  • Requires specific directory structure
  • Deployment Descriptor (WSDL)

21
Deployment Descriptor
lt?xml version1.0 encodingUTF-8?gtlt!DOCTYPE
web-app PUBLIC -//Sun Microsystems, Inc.//DTD
Web Application 2.3//EN http//java.sun.co
m/dtd/web-app_2_3.dtdgtltweb-appgt
ltdisplay-namegtA Simple Applicationlt/display-namegt
ltservletgt ltservlet-namegtVerify
Datalt/servlet-namegt ltservlet-classgtVerif
yDatalt/servlet-classgt ltinit-paramgt
ltparam-namegtmaxValuelt/param-namegt
ltparam-valuegt25lt/param-valuegt
lt/init-paramgt lt/servletgt
ltservlet-mappinggt ltservlet-namegtVerify
Datalt/servlet-namegt lturl-patterngt/verify
datalt/url-patterngt lt/servlet-mappinggt
ltsession-configgt ltsession-timeoutgt30lt/se
ssion-timeoutgt lt/session-configgt
lterror-pagegt lterror-codegt404lt/error-code
gt ltlocationgt/error404.htmllt/locationgt
lt/error-pagegtlt/web-appgt
22
Customizing Deployment
  • Define initialization parameters
  • Context parameters
  • Apply to entire web application
  • Servlet parameters
  • Apply to a specific servlet

23
Deployment Descriptor
lt?xml version1.0 encodingUTF-8?gtlt!DOCTYPE
web-app PUBLIC -//Sun Microsystems, Inc.//DTD
Web Application 2.3//EN http//java.sun.co
m/dtd/web-app_2_3.dtdgtltweb-appgt
ltdisplay-namegtA Simple Applicationlt/display-namegt
ltcontext-paramgt
ltparam-namegtlocationlt/param-namegt
ltparam-valuegtBYU-Idaholt/param-valuegt
ltdescriptiongtSite Locationlt/descriptiongt
lt/context-paramgt ltservletgt
ltservlet-namegtVerify Datalt/servlet-namegt
ltservlet-classgtVerifyDatalt/servlet-classgt
ltinit-paramgt
ltparam-namegtmaxValuelt/param-namegt
ltparam-valuegt25lt/param-valuegt
lt/init-paramgt lt/servletgt
ltservlet-mappinggt ltservlet-namegtVerify
Datalt/servlet-namegt lturl-patterngt/verify
datalt/url-patterngt lt/servlet-mappinggt
ltsession-configgt ltsession-timeoutgt30lt/se
ssion-timeoutgt lt/session-configgt
lterror-pagegt lterror-codegt404lt/error-code
gt ltlocationgt/error404.htmllt/locationgt
lt/error-pagegtlt/web-appgt
Context Intialization Parameter
Servlet Intialization Parameter
24
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")

25
Handling Errors
  • HTTP Error Codes
  • Http Status code set error code
  • Error page set default error page
  • Send Redirect redirect to another page
  • Servlet Exceptions catch and handle all servlet
    exceptions

26
Set HTTP Status Code
  • Sets the error status code on default error page

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() lt 1)
response.sendError(9001, Invalid name)
27
Default HTTP Error Page
Deployment Descriptor
lt?xml version1.0 encodingUTF-8?gtltlt!DOCTYPE
web-app PUBLIC -//Sun Microsystems, Inc.//DTD
Web Application 2.3//EN http//java.sun.co
m/dtd/web-app_2_3.dtdgtltweb-appgtltdisplay-namegtA
Simple Applicationlt/display-namegtltservletgt
ltservlet-namegtVerify datalt/servlet-namegt
ltservlet-classgtVerifyDatalt/servlet-classgt
ltinit-paramgt ltparam-namegtmaxValuelt/param
-namegt ltparam-valuegt25lt/param-valuegt
lt/init-paramgtlt/servletgt ltservlet-mappinggt
ltservlet-namegtverifyDatalt/servlet-namegt
lturl-patterngt/verifyDatalt/url-patterngtlt/serv
let-mappinggtltsession-configgt
ltsession-timeoutgt30lt/session-timeoutgtlt/session-co
nfiggtlterror-pagegt lterror-codegt9001lt/err
or-codegt ltlocationgt/error9001.htmllt/loca
tiongtlt/error-pagegtlt/web-appgt
28
Send Redirect
  • Redirect to another page to handle error

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() lt 1)
response.sendRedirect(/Servlets/invalidNamePage)

29
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?sessionid9982345
  • 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

30
Creating Cookies
  • Implement transactions with Cookies
  • Store state data in Cookie

31
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(to
talQuantity) catch
(RemoteException remex)
response.sendError(response.SC_INTERNAL_SERVER_
ERROR)
32
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 i0 i lt cookies.length i)
cookie
cookiesi if
(cookie.getName().equals(userAddress))

String urlAddress cookie.getValue()
break

catch
(RemoteException remex)
response.sendError(response.SC_INTERNAL_SERVER_
ERROR)
33
Sessions
  • Implement transactions with a HttpSession
  • Retains state of data between page request

34
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_ERR
OR)
35
Filter Servlets
  • Acts as preprocessor to request/response for
    target servlet

HttpPage
VerifyData
36
Filter Servlet
Import java.io.import javax.servlet.import
javax.servlet.http.publc class PageHits
extends HttpServlet implements Filter
private FilterConfig filterConfig null
public void init(FilterConfig filterConfig)
throws ServletException
this.filterConfig filterConfig
public void destroy(
this.filterConfig null
37
Filter Servlet (cont.)
public void doFilter(HttpServletRequest
request, HttpServletResponse response,
FilterChain chain)
throws IOException, ServletException
if (filterConfig null) return
synchronized (this)
Integer counter (Integer) filterConfig.getServlet
Context().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("Cou
nter", counter)
chain.doFilter(req, resp)
38
Modify Deployment Descriptor
lt?xml version1.0 encodingUTF-8?gtltlt!DOCTYPE
web-app PUBLIC -//Sun Microsystems, Inc.//DTD
Web Application 2.3//EN http//java.sun.co
m/dtd/web-app_2_3.dtdgtltweb-appgt
ltdisplay-namegtA Simple Applicationlt/display-namegt
ltservletgt ltservlet-namegtVerifyDatalt
/servlet-namegt ltservlet-classgtVerifyData
lt/servlet-classgt ltinit-paramgt
ltparam-namegtmaxValuelt/param-namegt
ltparam-valuegt25lt/param-valuegt
lt/init-paramgt lt/servletgt
ltservlet-mappinggt ltservlet-namegtVerify
Datalt/servlet-namegt lturl-patterngt/verify
Data/lt/url-patterngt lt/servlet-mappinggt
ltfiltergt ltfilter-namegtPage
Hitslt/filter-namegt ltdisplay-namegtPage
Hitslt/display-namegt ltdescriptiongtCount
page hitsltdescriptiongt
ltfilter-classgtPageHitslt/filter-classgt
lt/filtergt ltfilter-mappinggt
ltfilter-namegtPageHitslt/filter-namegt
ltservlet-namegtVerifyDatalt/servlet-namegt
lt/filter-mappinggt lt/web-appgt
39
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
40
Create Listener Servlet
Import java.io.import javax.servlet.import
javax.servlet.http.publc class Listener
extends HttpServlet implements ServletContextListe
ner private ServletContext context
null public void contextIntialized(ServletC
ontextEvent event) context
event.getServerContext() Integer
counter new Integer(0)
context.setAttribute(Counter, counter)
context.log(Created Counter)
public void contextDestroyed(ServletContextEvent
event) event.getServletContext(
).removeAttribute(Counter)
41
Modify Deployment Descriptor
lt?xml version1.0 encodingUTF-8?gtltlt!DOCTYPE
web-app PUBLIC -//Sun Microsystems, Inc.//DTD
Web Application 2.3//EN http//java.sun.co
m/dtd/web-app_2_3.dtdgtltweb-appgt
ltdisplay-namegtA Simple Applicationlt/display-namegt
ltservletgt ltservlet-namegtVerify
datalt/servlet-namegt ltservlet-classgtVerif
yDatalt/servlet-classgt ltinit-paramgt
ltparam-namegtmaxValuelt/param-namegt
ltparam-valuegt25lt/param-valuegt
lt/init-paramgt lt/servletgt
ltservlet-mappinggt ltservlet-namegtVerify
Datalt/servlet-namegt lturl-patterngt/verify
Data/lt/url-patterngt lt/servlet-mappinggt
ltfiltergt ltfilter-namegtPage
Hitslt/filter-namegt ltdisplay-namegtPage
Hitslt/display-namegt ltdescriptiongtCount
page hitsdescriptiongt
ltfilter-classgtPageHitslt/filter-classgt
lt/filtergt ltfilter-mappinggt
ltfilter-namegtPageHitslt/filter-namegt
ltservlet-namegtVerify datalt/servlet-namegt
lt/filter-mappinggt ltlistenergt lt
listener-classgtListenerlt/ listener -classgt
lt/listenergtlt/web-appgt
42
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().getAttri
bute(Counter) if (counter
null) counter new
Integer(1) counter new
Integer(counter.intValue()1)
filterConfig.getServletContext().log(Number of
hits is counter)
filterConfig.getServletContext().setAttribute(Cou
nter, counter) counter)
chain.doFilter(request, response)
43
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().getAttri
bute(Counter) counter
new Integer(counter.intValue()1)
filterConfig.getServletContext().log(Number
of hits is counter)
filterConfig.getServletContext().setAttribute(Cou
nter, counter) counter)
chain.doFilter(request, response)
Write a Comment
User Comments (0)
About PowerShow.com