Unit 5: Servlets - PowerPoint PPT Presentation

1 / 69
About This Presentation
Title:

Unit 5: Servlets

Description:

Get a reference to the stream from the Response parameter ... Instructor Note: As a review, ask students how to get a reference to HttpSession in a servlet. ... – PowerPoint PPT presentation

Number of Views:302
Avg rating:3.0/5.0
Slides: 70
Provided by: jimdem
Category:
Tags: geta | servlets | unit

less

Transcript and Presenter's Notes

Title: Unit 5: Servlets


1
Unit 5 Servlets
Instructor Note To hide Instructor Notes, select
ViewComments
  • Building J2EE Applications in SilverStream

2
Section Objectives
  • Defining Servlets
  • Coding Servlets
  • Packaging Web Components
  • Deploying Web Components

3
What are they?
  • From the Servlet Specification
  • A servlet is a web component, managed by a
    container, that generates dynamic content.
    Servlets are small, platform independent Java
    classes compiled to an architecture neutral byte
    code that can be loaded dynamically into and run
    by a web server. Servlets interact with web
    clients via a request response paradigm
    implemented by the servlet container. This
    request-response model is based on the behavior
    of the Hypertext Transfer Protocol (HTTP).

4
Comparing Servlets
  • CGI
  • First Generation
  • Many different languages
  • Vendor neutral
  • ISAPI
  • Microsoft Standard
  • Faster than CGI
  • Proprietary
  • NSAPI
  • Netscape standard
  • Faster
  • Proprietary

5
Java Alternative Servlets
  • Faster than CGI
  • Vendor/platform neutral
  • All the advantages of Java

6
From the Browser
  • The browser issues a request to a particular URL
  • That request might include parameters

Instructor Note You can move through these
slides quickly if the class understands the
basics of HTTP.
HTML client
HTTP request
7
To the Servlet
  • The SilverStream Server has an integrated HTTP
    server that listens for HTTP requests.
  • When the request is received, the server
    interrogates the URL to determine the correct web
    application component

Server runningthe servlet
HTTP request
8
HTTP Requests
  • Get
  • Post
  • Put
  • Delete

Instructor Note A good way to check
understanding is to ask students how to issue a
Get and/or a Post from the browser
9
And Back to the Browser
  • The servlet generates the content dynamically and
    returns in a response to the browser.

Server runningthe servlet
HTML client
HTTP response
10
Section Objectives
  • Defining Servlets
  • Coding Servlets
  • Packaging Web Components
  • Deploying Web Components

11
Servlet Methods
  • init
  • service
  • doGet
  • doPost
  • destroy
  • getServletConfig
  • getServletInfo

12
service() Method
  • Early servlet specifications only included this
    method for the request handling.
  • Latest specifications include do methods for
    the different HTTP requests.
  • Most common HTTP requests
  • doGet
  • doPost
  • Request
  • Response
  • Session Management

13
Request Parameter
Entire query string
req parameter
Cookie info
?
Client user info
Session info
14
Retrieving Parameters
  • To get the parameter names, use
  • Enumeration getParameterNames()
  • To retrieve the values, use
  • String getParameter(String name)
  • Or
  • String getParameterValues(name)

15
Retrieving Headers
  • To get the clients address
  • String getRemoteAddr()
  • To get the clients domain
  • String getRemoteHost()
  • To determine HTTP or HTTPS
  • String getProtocol()

16
Retrieving Session Information
  • To get a reference to the clients session
  • HttpSession getSession()
  • To check is session is still valid
  • boolean isRequestedSessionIdValid()

17
Response Parameter
Set output file MIME-type
res parameter
Write to the output stream
Add cookies
18
Streaming Data to the Client
  • Use the ServletOutputStream or PrintWriter to
    send data back to the client
  • Get a reference to the stream from the Response
    parameter
  • ServletOutputStream out response.getOutputStream
    ()
  • Get a reference to the writer from the Response
    parameter
  • PrintWriter out response.getWriter()
  • Write the output to the stream
  • Out.println(ltHTMLgtHello Worldlt/HTMLgt)
  • Close the writer
  • out.close()

19
Setting MIME Type and Status
  • When interacting directly with a browser, you
    must identify the type of data generated.
  • response.setContentType(text/html)
  • response.setContentType(application/pdf)
  • You can also control the HTTP status codes.
  • For example, 404 Resource Not Found
  • response.setStatus()

Segue Now that weve talked about the methods
and parameters, lets look at some examples
20
doGet Example
  • An HTTP Get request
  • lta hrefdisplayName.html?nameSolomongtDisplay
    Solomonlt/agt
  • Appearance in the browser

Display Solomon
21
doGet Code Example
  • public void doGet(HttpServletRequest req,
    HttpServletResponse res) String inName
    req.getParameter("name")
  • PrintWriter out res.getWriter()
  • res.setContentType("text/html")
  • out.println("lthtmlgtltcentergtlth1gtYour name
    is")
  • out.println(inName)
  • out.println("lt/centergtlt/h1gtlt/htmlgt")
    out.close()
  • The servlet output

Your name is Solomon
22
doPost Example
23
Post HTML Source
lthtmlgt ltbody bgcolor"FFFFFF"gt ltform
action"DisplayName.html" method"post" gt
ltpgtPlease enter your namelt/pgt ltpgt ltinput
type"text" name"nameField"gt lt/pgt ltpgt
ltinput type"submit" name"Submit"
value"Submit"gt ltinput type"reset"
name"Reset" value"Reset"gt lt/pgt lt/formgt lt/bodygt
lt/htmlgt
24
doPost Code Example
  • public void doPost(HttpServletRequest req,
    HttpServletResponse res) String inName
    req.getParameter("nameField")
  • PrintWriter out res.getWriter()
  • res.setContentType("text/html")
  • out.println("lthtmlgtltcentergtlth1gtThe name is
    ")
  • out.println(inName)
  • out.println("lt/centergtlt/h1gtlt/htmlgt")
    out.close()
  • The servlet output

The name is David
25
Putting it Together
  • import java.io.
  • import java.servlet.
  • import java.servlet.http.
  • public class NameServlet extends HttpServlet
  • public void doGet(HttpServletRequest req,
    HttpServletResponse res)
  • //code from previous example
  • public void doPost(HttpServletRequest req,
    HttpServletResponse res) //code from previous
    example

26
Session Management
  • Session tracking mechanisms
  • Methods of HttpSession

27
Session Tracking Mechanisms
  • URL Rewriting
  • http//localhost/dir/index.htmljsessionid1234
  • Cookies
  • SSL Sessions

28
Methods of HttpSession
Instructor Note As a review, ask students how
to get a reference to HttpSession in a servlet.
  • To place values in the session
  • setAttribute(name, value)
  • To retrieve values from the session
  • getAttribute(name)
  • To remove the value from the session
  • removeAttribute(name)
  • To determine attribute names
  • getAttributeNames()

29
Servlet Lab 1 - Build a Servlet to Retrieve Data
30
Section Objectives
  • Defining Servlets
  • Coding Servlets
  • Packaging Web Components
  • Deploying Web Components

31
web.xml
  • Deployment descriptor that describes how the
    components in the web archive operate.
  • For example, what URLs a servlet listens on
  • Created by both the component developer and
    application assembler.
  • The web.xml file needs to be located in the
    WEB-INF directory.

32
web.xml (2)
  • web.xml contents
  • Session parameters
  • Servlet and servlet mapping
  • Designating home and error pages
  • Context parameters and environment entries
  • Resource and EJB references
  • Security authorization and authentication
  • JSP tag libraries
  • MIME-type mapping

33
web.xml (3)
lt?xml version"1.0" encoding"Cp1252"?gt ltweb-appgt
ltdisplay-namegtSome Namelt/display-namegt ltdescript
iongtsome descriptionlt/descriptiongt lticongt ltsmal
l-icongtsmall.giflt/small-icongt ltlarge-icongtlarge.
giflt/large-icongt ...other sections... lt/web-appgt
34
Home and Error Pages
  • Welcome FilesWeb page that is displayed if a
    user specifies a URL that is a directory.
  • Error PagesWeb page that is displayed if either
  • A Web server returns a HTTP error code
  • A Java Exception is thrown

35
Home and Error Pages
ltwelcome-file-listgt ltwelcome-filegtindex.htmllt/wel
come-filegt lt/welcome-file-listgt lterror-pagegt lter
ror-codegt404lt/error-codegt ltlocationgtoops.htmllt/lo
cationgt lt/error-pagegt lterror-pagegt ltexception-ty
pegt java.lang.NullPointerException lt/exception-
typegt ltlocationgt/nullpointer.htmllt/locationgt lt/er
ror-pagegt
36
Session Configuration
  • Can specify how long a sessions timeout value is
    (in minutes)

ltsession-configgt ltsession-timeoutgt30lt/session
-timeoutgt lt/session-configgt
37
Servlets
  • Need to place information about the servlets into
    the web.xml including
  • Required Information
  • Class file to associate to a servlet
  • URL mapping to servlets
  • Optional Information
  • Whether to load servlet on startup
  • Servlet initialization parameters

38
Servlets (2)
ltservletgt ltdescriptiongtServlet
Lablt/descriptiongt ltservlet-namegtcustomerservletlt/
servlet-namegt ltservlet-classgtCustomerServletlt/ser
vlet-classgt lt/servletgt ltservlet-mappinggt ltservle
t-namegtcustomerservletlt/servlet-namegt lturl-patter
ngtcustomerlisting.htmllt/url-patterngt lt/servlet-map
pinggt
39
Parameters
  • context-parameters
  • For the servlet/JSP container runtime environment
  • Developers gain access via getServletContext()
  • environment entries
  • Application constants
  • Values can be changed at deployment time
  • Developers gain access via JNDI
  • Environment entries are stored at javacomp/env
    in the JNDI tree

40
EJB and External Resources
  • Your Web application may use
  • Enterprise JavaBeans
  • JDBC Data Sources
  • Java Mail
  • JMS
  • URLs
  • Others...
  • ...But you wont necessarily know the location of
    the resources at development time.
  • You can specify a location internally that can be
    changed at deployment time without affecting your
    component.

41
EJB and External Resources (2)
  • External resources in J2EE terminology are called
    Resource References.
  • When specifying a resource reference you must
    identify the Java class representing the
    resource.
  • javax.sql.DataSource
  • javax.mail.Session
  • java.net.URL
  • javax.jms.QueueConnectionFactory
  • javax.jms.TopicConnectionFactory

42
EJB and Resource References
Instructor Note Mention to the students that we
changed the heading from External Resources to
Resource References because we all want to be
J2EE-proper
ltresource-refgt ltdescriptiongtMy
DataSourcelt/descriptiongt ltres-ref-namegtjdbc/myJDB
Clt/res-ref-namegt ltres-typegtjavax.sql.DataSourcelt/
res-typegt ltres-authgtContainerlt/res-authgt lt/resour
ce-refgt
43
Security
  • With a Web application there are two types of
    security
  • Authentication
  • Authorization
  • Authentication can either be done by the
    container or by one of our web pages
  • In the development of our Web apps we think of
    security logically
  • Developers dont specify a real user or group
    name
  • Instead we think of roles that are mapped to user
    or group at deployment time

44
Security (2)
  • Within the web.xml we need to identify
  • How a login box is displayed (browser or custom
    form)
  • What resources are protected
  • What logical security roles there are
  • Which roles can access protected resources

45
Security (3)
ltlogin-configgt ltauth-methodgtFormlt/auth-methodgt lt
realm-namegtSilverStreamlt/realm-namegt ltform-login-
configgt ltform-login-pagegt somepage.html lt/f
orm-login-pagegt ltform-error-pagegt somepage.ht
ml lt/form-error-pagegt lt/form-login-configgt lt/lo
gin-configgt ltsecurity-rolegt ltdescriptiongtlt/descr
iptiongt ltrole-namegtmyrolelt/role-namegt lt/security-
rolegt
46
SecuritySide Note
  • Normally when you attempt to access a secure
    resource, SilverStream will send a 401 error
    which informs the browser to popup a login
    window.
  • You can have a custom Web page that handles the
    login process.
  • The page must have a html form
  • Form method must be POST
  • Action must be j_security_check
  • Need an input field named j_username
  • Need an input field named j_password

47
SecuritySide Note (2)
lthtmlgt ltbodygt ltform method"POST"
action"j_security_check"gt ltinput type"TEXT"
name"j_username"gt ltinput type"TEXT"
name"j_password"gt ltinput type"SUBMIT"gt lt/formgt lt
/bodygt lt/htmlgt
48
Security
ltsecurity-constraintgt ltweb-resource-collectiongt
ltweb-resource-namegt somename lt/web-resource-
namegt ltdescriptiongtlt/descriptiongt lturl-pattern
gtpageslt/url-patterngt lthttp-methodgtGETlt/http-met
hodgt lthttp-methodgtPOSTlt/http-methodgt lt/web-reso
urce-collectiongt ...continues...
49
Security
ltauth-constraintgt ltdescriptiongtlt/descriptiongt
ltrole-namegtsomerolelt/role-namegt
lt/auth-constraintgt ltuser-data-constraintgt ltde
scriptiongtlt/descriptiongt lttransport-guaranteegt
NONE lt/transport-guaranteegt lt/user-data-const
raintgt lt/security-constraintgt
50
MIME Mappings
  • There needs to be a MIME mapping for each type of
    data that your Web application will send back to
    the client
  • Most common MIME mappings are defined for you
  • Text files
  • HTML
  • Graphic formats (gif, jpeg, png, etc)

51
Sample web.xml
lt?xml version"1.0"?gt ltweb-appgt ltdisplay-namegtJ2E
E Sample Applt/display-namegt ltsession-configgt lt
session-timeoutgt30lt/session-timeoutgt lt/session-co
nfiggt ltwelcome-file-listgt ltwelcome-filegtwel
come.htmllt/welcome-filegt lt/welcome-file-listgt
lterror-pagegt lterror-codegt404lt/error-codegt ltloc
ationgt/oops.htmllt/locationgt lt/error-pagegt
52
Sample web.xml (2)
ltservletgt ltdescriptiongtServlet
Lablt/descriptiongt ltservlet-namegtcustomerservletlt/
servlet-namegt ltservlet-classgtCustomerServletlt/ser
vlet-classgt lt/servletgt ltservlet-mappinggt ltservle
t-namegtcustomerservletlt/servlet-namegt lturl-patter
ngtcustomerlisting.htmllt/url-patterngt lt/servlet-map
pinggt ltresource-refgt ltdescriptiongtMy Data
Sourcelt/descriptiongt ltres-ref-namegtjdbc/myJDBClt/r
es-ref-namegt ltres-typegtjavax.sql.DataSourcelt/res-
typegt ltres-authgtContainerlt/res-authgt lt/resource-r
efgt
53
Servlet Lab 2 Packaging Web Components Package
the Servlet
54
Section Objectives
  • Defining Servlets
  • Coding Servlets
  • Packaging Web Components
  • Deploying Web Components

55
Deploying Web Components
  • Once a web application has been properly
    packaged, the deployer will deploy the
    application.
  • The deployer resolves dependencies and vendor
    specific constructs in a deployment plan
  • SilverStreams deployment plan for web components
    is an XML file
  • Based on deploy_war.dtd
  • SilverStreams deployment tool is SilverCmd

56
SilverCmd
  • Command-line interface
  • SILVERSTREAM_HOME/bin/SilverCmd.exe
  • Standard format
  • SilverCmd command arguments
  • Day-to-day administration, and deployment
  • Example
  • SilverCmd DeployWar localhost SilverBooksBegin
    myapp.war
  • -f myapp-deployment.xml v5

57
Deploying Web Components (2)
  • The deployer will review the deployment
    descriptor (web.xml) to determine what is needed
    in the deployment plan
  • Once a deployment plan is written, SilverCmd is
    used to deploy the web component into the server.
  • If there are any unresolved dependencies,
    SilverCmd will report an error

58
Deploying Web Components (3)
  • What happens when you deploy?
  • Dependencies get resolved
  • New JNDI names get created
  • JSP pages get compiled into servlets

59
War Deployment Plan
  • Basic War Deployment Plan

ltwarJarOptions isObjecttruegt ltwarJar
isObjecttruegt ltsessionTimeoutgt300lt/sessionTi
meoutgt ltURLgt/myapplt/URLgt lt/warJargt lt/warJarOpt
ionsgt
60
War Deployment Plan Options
  • Environment Entries
  • Bean References

61
War Deployment Plan Options (2)
  • Resource References Options

ltresourceReferenceList isObjecttruegt ltresource
Reference isObjecttruegt ltnamegtjdbc/myJDBClt/na
megt lttypegtjavax.sql.DataSourcelt/typegt ltdataSou
rcegtSilverBooksBeginlt/dataSourcegt lt/resourceRefer
encegt lt/resourceReferenceListgt
62
War Deployment Plan Options (3)
  • Security Role Map Options

ltobj_roleMapgt ltobj_roleMappinggt ltnamegtname_as_i
n_war.xmllt/namegt ltuserOrGroupNamegt some-user-
or-group lt/userOrGroupNamegt lt/obj_roleMappinggt
lt/obj_roleMapgt
63
Sample War Deployment Plan
lt?xml version"1.0"?gt ltwarJarOptions
isObjecttruegt ltwarJar isObjecttruegt
ltsessionTimeoutgt300lt/sessionTimeoutgt
ltURLgt/myapplt/URLgt ltresourceReferenceList
isObjecttruegt ltresourceReference
isObjecttruegt ltnamegtjdbc/myJDBClt/namegt
lttypegtjavax.sql.DataSourcelt/typegt
ltdataSourcegtSilverBooksBeginlt/dataSourcegt
lt/resourceReferencegt lt/resourceReferenceListgt
lt/warJargt lt/warJarOptionsgt
64
SilverCmd DeployWAR
SilverCmd DeployWAR serverport
database warJar-f deploymentPlan
options Options include -o overwrite -i
ignore errors -U userid -P password -v verbose
65
SilverCmd QuickDeployWAR
SilverCmd QuickDeployWAR serverport
database warJar-f deploymentPlan -s
rootdirectory options Options include -o
overwrite -i ignore errors -U userid -P
password -v verbose
66
Servlet Lab 3 Deploying Web Components Deploy
the Servlet
67
Servlet Lab 4 Configure Servlet Look at
Deployment
68
Unit Summary
  • What is the benefit of servlets over similar
    technologies?
  • What two methods contain most of the code for a
    servlet?
  • What must be defined in the web.xml file for a
    servlet?
  • What is the difference between DeployWar and
    QuickDeployWar?

Instructor Note -- Faster than CGI, more open
than ISAPI or NSAPI -- doGet( ) and doPost( ) --
The servlet name, implementation class, and
URL -- QuickDeployWar looks for changed JSPs and
only deploys those
69
Unit Summary
  • Defining Servlets
  • Coding Servlets
  • Packaging Web Components
  • Deploying Web Components
Write a Comment
User Comments (0)
About PowerShow.com