Servlets and Web Applications WARs - PowerPoint PPT Presentation

1 / 94
About This Presentation
Title:

Servlets and Web Applications WARs

Description:

Servlets & Web Apps. 1. Enterprise. Java. Servlets. and. Web Applications (WARs) ... Servlets & Web Apps. 4. Enterprise. Java. HTML ... – PowerPoint PPT presentation

Number of Views:219
Avg rating:3.0/5.0
Slides: 95
Provided by: apl3
Category:

less

Transcript and Presenter's Notes

Title: Servlets and Web Applications WARs


1
Servletsand Web Applications (WARs)
  • HTML, Servlets, and Web Applications

2
Topics
  • HTML Review
  • Servlets
  • Web Applications
  • Resources
  • References

3
HTML
  • Basic Document Structure
  • Hyper-Text Transport Protocol (HTTP)
  • Forms

4
HTML
  • Regular text with markup elements specifying
    the desired appearance and layout of the
    information
  • Style sheets can also be specified
  • Tag Format
  • ltTAG ATTRoptionalgtValuelt/TAGgt

5
HTML Example
  • lt!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 3.2//ENgt
  • ltHTMLgt
  • ltHEADgt
  • ltTITLEgtExample Pagelt/TITLEgt
  • lt/HEADgt
  • ltBODY BGCOLOR "WHITE"gt
  • ltBLOCKQUOTEgt
  • ltH3gtBonus Calculationlt/H3gt
  • lt/BLOCKQUOTEgt
  • lt/BODYgt
  • lt/HTMLgt

6
HTML Structure
  • lt!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 3.2//ENgt
  • ltHTMLgt
  • ltHEADgt
  • ltTITLEgtThis is the titlelt/TITLEgt
  • lt/HEADgt
  • ltBODYgt
  • ltH1gtHeadinglt/H1gt
  • Other elements
  • lt/BODYgt
  • lt/HTMLgt

7
Example Tags
  • ltHTMLgtltHEADgtltBODYgt
  • Main document sections
  • Headings ltH1gtltH2gt . ltH6gt
  • Paragraph ltPgt (lt/Pgt is optional)
  • Lists
  • Numbered List ltOLgtltLIgt .. lt/OLgt
  • Bulleted Lists ltULgtltLIgt .. lt/ULgt

8
Other Capabilities
  • Character Display
  • Bold ltBgt, Italic ltIgt, Font ltFgt, etc.
  • Hyperlinks ltA HREFurlgtClicklt/Agt
  • Tables
  • Forms
  • Frames
  • Scripting

9
HTTP
  • Simple, socket-based protocol used between web
    browsers and web servers
  • Defaults to port 80
  • Client Request
  • Server Response

10
HTTP Client Request
  • Request message consists of four parts
  • Request Line
  • Request Header(s)
  • Blank Line
  • Additional Data (Optional)
  • Example
  • GET / HTTP/1.0
  • Accept /
  • Blank Line

11
Request Line
  • Request Line
  • Example
  • GET /test.html HTTP/1.1
  • Request Type (GET, POST, HEAD, PUT, DELETE)
  • Document Address
  • Uniform Resource Identifier (URI)
  • URL with no protocol, host, or port
  • http//java.sun.com/test.html gt /test.html
  • HTTP Version

12
Request Methods
  • GET (HTTP 1.0)
  • Used by browsers for normal document requests
  • Additional info can be sent after URI
  • GET /test.html?field1value HTML/1.0
  • Use for repeatable (bookmarkable) actions
  • POST (HTTP 1.0)
  • Additional info sent after blank line (not after
    URI)
  • Can transmit more information than GET
  • Use for non-repeatable (non-bookmarkable) actions
  • HEAD (HTTP 1.0)
  • Server only returns response headers
  • Used to verify links or obtain server information
    without receiving documents

13
Request Methods (cont.)
  • PUT (HTTP 1.1)
  • Client can supply document for storage on the
    server
  • DELETE (HTTP 1.1)
  • Client can delete a URI from the server
  • OPTIONS (HTTP 1.1)
  • Query for supported options on the server
  • TRACE (HTTP 1.1)
  • Have server echo back passed document unchanged

14
Request Headers
  • Additional, optional information for server
  • Examples
  • Accept - MIME types client will accept in
    preference order
  • Accept / - client is willing to accept anything
  • Authorizationauth-schemecredentials
  • provides no privacy alone - can be combined with
    SSL
  • Connection Keep-Alive
  • do not close connection between server
    interactions
  • Content-Length - data length (POST)
  • Cookienamevalname2val2
  • Referrer - URL of referring page
  • Host - host and port from original URL

15
Request Example
  • GET /test.html?nameDan HTTP/1.1
  • Accept image/gif, image/jpeg, /
  • Accept-Language en
  • Host www.sun.com80
  • Content-Length20 required if request was POST
  • (Blank Line)
  • if request was POST, additional data here

16
HTTP Server Response
  • Example
  • HTTP/1.0 200 Document Follows
  • Content-Type text/html
  • Content-Length 2908
  • lt/!DOCTYPE .gt
  • ltHTMLgt
  • lt/HTMLgt

17
Server Response (Cont)
  • Consists of
  • Status Line
  • HTTP/Version status-code message
  • Success 200-299, File Moved 300-399, Client error
    400-499, Server Error 500-599
  • Response Header(s)
  • Blank Line
  • Referenced Document

18
HTTP Response Headers
  • Examples
  • Content-Length - File length
  • Content-Type - MIME Type
  • text/html, audio/x-proprietary
  • Last-Modified - date/time of document
    modification
  • Set-Cookie
  • WWW-Authenticate

19
Response Header Example
  • HTTP/1.0 200 OK
  • Date Fri, 29 Feb 2000 173120 GMT
  • Set-Cookie user-id123 secure
  • Content-Length 124
  • Content-Encoding x-compress
  • Content-Type text/html
  • ltBlank Linegt
  • HTML document

20
Dynamic Page Generation
  • Web Servers were built to distribute web pages.
  • HTML page can be marked-up for processing by
    the server
  • Active Server Pages (ASP),
  • Java Server Pages (JSP)
  • Web Server can be configured to route specific
    URI requests to user code
  • Common Gateway Interface (CGI)
  • Servlets

21
HTML Forms
  • Gathers user information and submits to
    CGI/Servlet programs
  • GET
  • Form parameters appended to end of URI
  • Simple, but limited in length and security
  • POST
  • FORM parameters sent in message body

22
Form Example
  • lt!doctype html public "-//w3c//dtd html 4.0
    transitional//en"gt
  • lthtmlgt
  • ltheadgt
  • lttitlegtForm Examplelt/titlegt
  • lt/headgt
  • ltbodygt
  • ltform method"GET" action"BonusAlias"gt
  • ltpgtEnter social security number
  • ltpgtltinput type"TEXT" name"SOCSEC"gtlt/inputgt
  • ltpgtEnter multiplier
  • ltpgtltinput type"TEXT" name"MULTIPLIER"gtlt/inputgt
  • ltpgt
  • ltinput type"SUBMIT" name"Multiply"
    value"Multiply"gtlt/inputgt
  • ltinput type"RESET" name"Reset" value"Reset"gt
  • lt/formgt
  • lt/bodygt
  • lt/htmlgt

23
Form Display
24
Form Structure
  • Form Header
  • ltFORM MethodGET ACTIONurlgt
  • Attributes
  • Action - URL of processing script
  • Method - HTTP method (GET or POST)
  • Input Field(s)
  • ltINPUT TYPEtype NAMEnamegtlt/INPUTgt
  • Action Button(s)
  • ltINPUT TYPEtype NAMEname VALUEvaluegtlt/INPUTgt

25
Input Fields
  • GUI controls for entering information
  • Types
  • Text Box ltINPUT TYPETEXTgt
  • Password Box ltINPUT TYPEPASSWORDgt
  • Checkbox ltINPUT TYPECHECKBOXgt
  • Radio Button ltINPUT TYPERADIOgt
  • Hidden Field ltINPUT TYPEHIDDENgt
  • Images ltINPUT TYPEIMAGEgt
  • File ltINPUT TYPEFILEgt
  • Text Window ltTEXTAREAgtlt/TEXTAREAgt
  • Menu ltSELECTgtltOPTIONgtlt/SELECTgt

26
Menu Example
lt!doctype html public "-//w3c//dtd html 4.0
transitional//en"gt lthtmlgt ltheadgt lttitlegtMenu
Examplelt/titlegt lt/headgt ltbodygt ltform method"GET"
action"PurchaseAlias"gt ltpgtChose Product to
Purchase ltselect name"Product" size2gt ltoption
value"ID_1"gtOffer 1 Desclt/optiongt ltoption
value"ID_8"gtOffer 8 Desclt/optiongt lt/selectgt ltpgt lt
input type"SUBMIT" name"BUYCMD"
value"BUY"gtlt/inputgt ltinput type"SUBMIT"
name"CANCELCMD" value"CANCEL"gtlt/inputgt lt/formgt lt
/bodygt lt/htmlgt
27
Menu Display
28
Form Submission
  • Parameters are encoded and sent to the Action URL
    using GET or POST
  • application/x-www-form-urlencoded
  • name1val1name2val2namexvalx
  • space gt
  • non-alphanumeric gt xx
  • becomes 7E
  • / becomes 2F

29
Form Submission Examples
30
Form Submission (Cont)
  • Web Server makes parameters available via the
    environment for CGI programs
  • Perl and Java are common implementation languages
  • Utility Libraries for decoding parameters
  • Parameters are made available to servlets via the
    HttpRequest object

31
Forms Summary
  • Forms provide a simple mechanism to gather user
    input and submit to server-side programs
  • For more complex user interfaces, consider a Java
    applet/program
  • presents user interface and gathers input
  • opens socket to web server
  • sends HTTP formatted GET/POST message

32
Servlets
33
Servlet Definition
  • Web component, managed by a container, that
    generates dynamic content
  • Request-Response mechanism modeled after HTTP
  • Required by J2EE v1.2 specification
  • Web Server configured to invoke servlets when
    specified URLs are accessed (servlet mapping)
  • HTML Forms
  • Java programs

34
Servlet Benefits
  • Efficiency
  • run as threads vs. CGI processes
  • Written in Java
  • can use any Java API such as JDBC, EJB, RMI, etc.
  • Portability
  • supported by many web/application servers
  • Simplicity
  • Provides support for common operations including
    session management

35
Servlet Container
  • Provides the execution environment for a servlet
  • Must support HTTP as the request/response
    protocol
  • HTTP 1.1 support strongly recommended by spec
  • May support HTTPS (HTTP over SSL)
  • Can be installed directly in a web server or as
    an add-on using web server extension mechanisms
  • May impose security constraints on servlet

36
Servlet Container (Cont)
  • Web Application (servlet/jsp/html deployment) can
    be marked as distributable in the servlet 2.2
    specification
  • Servlet can be deployed in multiple JVMs running
    on one or more hosts
  • Deployed servlets must obey restrictions

37
Architecture
Get/Post Request
Request
Web Browser
Web Server
Servlet Container
HTML Page
Reply
Servlet
38
Key Servlet Classes
39
Servlet Lifecycle
  • init() called when servlet is instantiated
  • service() called to handle requests throughout
    the servlets lifetime
  • destroy() called when servlet engine unloads the
    servlet instance
  • period of inactivity
  • resource issues

40
Servlet Implementation
  • Extend HttpServlet. Override doGet/doPost
  • package ejava.servlets.webbasics
  • import javax.servlet.ServletConfig
  • import javax.servlet.ServletException
  • import javax.servlet.http.HttpServlet
  • import javax.servlet.http.HttpServletRequest
  • import javax.servlet.http.HttpServletResponse
  • public class PurchaseServlet extends HttpServlet
  • public void init(ServletConfig config) throws
    ServletException
  • super.init(config)
  • log("BonusServletinit(config)")

41
Servlet (Cont)
  • public void doGet(HttpServletRequest request,
  • HttpServletResponse
    response)
  • throws ServletException,
    java.io.IOException
  • response.setContentType("text/html")
  • java.io.PrintWriter out
    response.getWriter()
  • out.println("lthtmlgtltheadgtlttitlegt")
  • out.println("Purchase Servlet")
  • out.println("lt/titlegtlt/headgtltbodygt")
  • if (request.getParameter("BUYCMD") ! null)
  • String product request.getParameter("Pr
    oduct")
  • out.println("ltpgtltbgtpurchased
    productlt/bgt"product)
  • out.println("lt/bodygtlt/htmlgt")
  • out.close()

42
Request and Reply
  • Request URL
  • http//localhost7001/webbasics/PurchaseAlias?Prod
    uctID_1BUYCMDBUY
  • Reply Document
  • lthtmlgtltheadgtlttitlegt
  • Purchase Servlet
  • lt/titlegtlt/headgtltbodygt
  • ltpgtltbgtpurchased productlt/bgtID_1
  • lt/bodygtlt/htmlgt

43
Understanding the Request
  • Form parameters
  • String choicerequest.getParameter(Product)
  • Cookies
  • Cookie request.getCookies()
  • getName(), getValue()
  • Binary Data
  • InputStream is request.getInputStream()
  • Character Data
  • Reader r request.getReader()

44
Requests and Responses
45
Obtaining Selected Product
  • Form snippet
  • ltSELECT NAME"Product" SIZE2gt
  • ltOPTION VALUE"ID_1"gtOffer 1 Desclt/OPTIONgt
  • ltOPTION VALUE"ID_8"gtOffer 8 Desclt/OPTIONgt
  • lt/SELECTgt
  • doGet(), doPost()
  • String choice req.getParameter(Product)
  • // choice is ID_1 if Offer 1 Desc is
  • // selected

46
Generating a Response
  • ServletResponse permits servlet to generate
    output
  • setContentType( mimeType )
  • setContentLength( int len)
  • getOutputStream() ServletOutputStream
  • binary output to web browser
  • getWriter() Writer
  • character output for web browser

47
HttpServletResponse
  • Extends ServletResponse to allow HTTP-specific
    information to be communicated
  • setHeader(String header, String value)
  • addCookie(Cookie cookie)
  • sendError(int sc, String msg)
  • setStatus(int sc)

48
Simple HTML Output
  • public void doGet( HttpServletRequest req,
  • HttpServletResponse resp )
  • throws ServletException, java.io.IOException
  • resp.setContentType(text/html)
  • PrintWriter out resp.getWriter()
  • out.println("ltHTMLgtltHEADgtltTITLEgt")
  • out.println(Example Title)
  • out.println("lt/TITLEgtlt/HEADgtlt/HTMLgt")
  • out.close()

49
HTTP Headers Examples
  • HttpServletResponse methods
  • setHeader,setDataHeader,setIntHeader
  • HTTP response headers
  • Allow
  • Content-Encoding
  • Expires
  • Last-Modified

50
Example Response Headers(Disable Client Caching)
  • response.setDateHeader(Expires, 0)
  • response.setHeader(Pragma, no-cache)
  • if(request.getProtocol().equals(HTTP/1.1))
  • response.setHeader(Cache-Control,
    no-cache)

51
HttpSession
  • Session is a complete set of interactions with a
    user, but .
  • HTTP is a stateless protocol
  • every web page GET/POST typically results in a
    new socket connection
  • How do we track a user ?
  • URL re-writing
  • Cookies

52
HttpSession (Cont)
  • URL re-writing can be complex
  • session id has to be encoded into every URL
  • encodeUrl() on HttpServletResponse
  • Users may disable cookies
  • Session Tracking support added in 2.0
  • HttpServletRequest request
  • HttpSession sessionrequest.getSession(true)
  • session.putValue(Cart, new java.util.Vector() )

53
HttpSession Example
  • Integer salarynull
  • HttpSession session request.getSession(true)
  • if (session.isNew())
  • out.println("ltpgtsession is new")
  • session.setMaxInactiveInterval(5)
  • salary new Integer(1)
  • session.setAttribute("salary",salary)

54
HttpSession Example (cont.)
  • else
  • out.println("ltpgtsession is not new, id"
    session.getId())
  • out.println("ltpgtsession created at "
  • new java.util.Date(session.getCreationTime()
    ))
  • out.println("ltpgtsession last accessed at "
  • new java.util.Date(session.getLastAccessedTi
    me()))
  • out.println("ltpgtsession will time out after
    "
  • session.getMaxInactiveInterval() "
    secs")
  • salary (Integer)session.getAttribute("s
    alary")
  • out.println("ltpgtold salary" salary)
  • salary new Integer(salary.intValue()
    multiplierValue)
  • out.println("ltpgtnew salary" salary)
  • session.setAttribute("salary",salary)

55
HttpSession Example Output (1st Reload)
56
HttpSession (Cont)
  • HttpSession is a convenient place to store
    information
  • Shopping Cart
  • Preferences valid for this session only
  • Objects bound to session can implement
    HttpSessionBindingListener
  • valueBound(HttpSessionBindingEvent e)
  • valueUnbound(HttpSessionBindingEvent e)

57
Sessions (Cont)
  • Modern web application servers can store session
    data in persistent storage
  • Supports failover
  • Supports clustering
  • However . Session is not the place for large
    amounts of data
  • Session persistence is not covered in the j2ee
    spec

58
Http Session
59
Cookies
  • Cookies can be used to store information that
    should persist beyond the current session
  • Stored on client, limited size
  • Strings
  • Users may disable storing of cookies

60
Cookies
61
Cookie Example
  • HttpServletRequest req
  • Cookie cookie req.getCookies()
  • for( int i0iltcookie.lengthi)
  • System.out.println(cookiei.getName()
    cookiei.getValue() )
  • .
  • HttpServletResponse resp
  • resp.addCookie( new Cookie(user_id_for_site,
    862348762346324))

62
Additional Cookie Methods
  • setComment(String)
  • Description of cookies purpose
  • setDomain(String)
  • Set of computers that cookie will be sent to
  • setSecure(boolean)
  • Only send cookie on secure connection (https)
  • setMaxAge( int seconds )
  • -1this session only,0delete

63
Servlet Context
  • Servlet may wish to interact with the host server
  • GenericServletgetServletContext()
  • getMimeType( String file )
  • getServlet(String name) Servlet
  • log(Exception, String)
  • log(String)

64
(No Transcript)
65
Redirection
  • Web Browser redirection
  • resp.sendRedirect(String url)
  • resp.sendError(int code, String message)
  • Server-Side
  • RequestDispatcher rd
  • getServletContext().getRequestDispatcher(urlString
    )
  • rd.forward()

66
Request Dispatcher
67
Thread Safety
  • Servlets are inherently threaded
  • Only one servlet instance exists for each URL
  • Write thread-safe code
  • Synchronize access to shared resources
  • Use local variables
  • Implementing SingleThreadModel
  • Code that is not thread-safe
  • Operations that should not be threaded e.g. file
    deletion

68
Servlet Summary
  • Allows simple generation of dynamic web pages
  • All Java features can be used
  • JDBC, EJB, RMI, CORBA, etc.
  • Continuous out.println(someHtml) can still be
    tedious

69
Web Applications
70
WAR
  • Web Archive
  • Introduced with servlet 2.2 specification
  • Portable deployment mechanism for web
    applications
  • Defines directory structure
  • Jard into a .war file for deployment
  • Uses XML deployment descriptor

71
Directory Structure
  • find ./webbasics -print
  • ./webbasics
  • ./webbasics/WEB-INF
  • ./webbasics/WEB-INF/classes
  • ./webbasics/WEB-INF/classes/ejava
  • ./webbasics/WEB-INF/classes/ejava/servlets
  • ./webbasics/WEB-INF/classes/ejava/servlets/webbasi
    cs
  • ./webbasics/WEB-INF/classes/ejava/servlets/webbasi
    cs/BonusServlet.class
  • ./webbasics/WEB-INF/classes/ejava/servlets/webbasi
    cs/PurchaseServlet.class
  • ./webbasics/WEB-INF/web.xml
  • ./webbasics/WEB-INF/weblogic.xml
  • ./webbasics/FormExample.html
  • ./webbasics/MenuExample.html

72
Directory Structure (Cont)
  • WEB-INF
  • Contains web.xml deployment descriptor
  • Contains class files for web app (classes)
  • Contains .jar files for web app (lib)
  • Contains Tag Library Descriptors (tlds)
  • Can not be served to client
  • Other directories store web content i.e. jsp/html
    files, images, sound, etc.

73
Deployment Descriptor (web.xml)
lt!DOCTYPE web-app PUBLIC "-//Sun Microsystems,
Inc.//DTD Web Application 1.2//EN"
"http//java.sun.com/j2ee/dtds/web-app_2_2.dtd"gt lt
web-appgt ltdisplay-namegtHTML Basicslt/display-nam
egt ltcontext-paramgt ltparam-namegtweblogic.h
ttpd.servlet.reloadCheckSecslt/param-namegt
ltparam-valuegt1lt/param-valuegt lt/context-paramgt
ltservletgt ltservlet-namegtPurchaseServletlt/s
ervlet-namegt ltservlet-classgtejava.servlets.w
ebbasics.PurchaseServletlt/servlet-classgt
ltinit-paramgt ltparam-namegtparam1lt/param-na
megt ltparam-valuegtvalue1lt/param-valuegt
lt/init-paramgt lt/servletgt ltservletgt
ltservlet-namegtBonusServletlt/servlet-namegt
ltservlet-classgtejava.servlets.webbasics.BonusServl
etlt/servlet-classgt lt/servletgt ...
74
Mapping Servlets to URLs (web.xml)
ltservlet-mappinggt ltservlet-namegtPurcha
seServletlt/servlet-namegt lturl-patterngtPurcha
seAliaslt/url-patterngt lt/servlet-mappinggt
ltservlet-mappinggt ltservlet-namegtBonusServlet
lt/servlet-namegt lturl-patterngtBonusAliaslt/url
-patterngt lt/servlet-mappinggt ...
75
Declaring Default Pages (web.xml)
ltwelcome-file-listgt
ltwelcome-filegtwelcome.htmllt/welcome-filegt
lt/welcome-file-listgt ...
76
Setting up Security (web.xml)
ltsecurity-constraintgt
ltweb-resource-collectiongt
ltweb-resource-namegtprotectedlt/web-resource-namegt
lturl-patterngt/BonusAlias/lt/url-patterngt
lt/web-resource-collectiongt
ltauth-constraintgt ltrole-namegtinstructorlt/
role-namegt lt/auth-constraintgt
lt/security-constraintgt ltlogin-configgt
ltauth-methodgtBASIClt/auth-methodgt
lt/login-configgt ltsecurity-rolegt
ltrole-namegtinstructorlt/role-namegt
lt/security-rolegt ...
77
Setting up Security (weblogic.xml)
lt!DOCTYPE weblogic-web-app PUBLIC "-//BEA
Systems, Inc.//DTD Web Application 6.0 //EN"
"http//www.bea.com/servers/wls600/dtd/weblogic-we
b-jar.dtd"gt ltweblogic-web-appgt
ltsecurity-role-assignmentgt
ltrole-namegtinstructorlt/role-namegt
ltprincipal-namegtejava-instructorlt/principal-namegt
lt/security-role-assignmentgt ... lt/weblogic-web-
appgt
78
Setting up Security (WebLogic Console)
79
Setting up Database Access (web.xml
weblogic.xml)
ltresource-refgt ltres-ref-namegtjdbc/my
dblt/res-ref-namegt ltres-typegtjavax.sql.DataSo
urcelt/res-typegt ltres-authgtContainerlt/res-aut
hgt lt/resource-refgt lt!DOCTYPE
weblogic-web-app PUBLIC "-//BEA Systems,
Inc.//DTD Web Application 2.2//EN"
"http//www.beasys.com/j2ee/dtds/weblogic.web-jar.
dtd"gt ltweblogic-web-appgt ltreference-descriptor
gt ltresource-descriptiongt
ltres-ref-namegtjdbc/mydblt/res-ref-namegt
ltjndi-namegt weblogic.jdbc.dataSource.MyJDBC Data
Sourcelt/jndi-namegt lt/resource-descriptiongt
lt/reference-descriptorgt lt/weblogic-web-appgt
80
Viewing the Data Source in the JNDI Tree
(WebLogic Console)
81
Setting up Database Access (config/ltdomaingt/confi
g.xml)
ltJDBCConnectionPool DriverName"COM.cloudscape.cor
e.RmiJdbcDriver" Name"MyJDBC Connection
Pool" Properties"usernonepasswordnone"
Targets"myserver" TestConnectionsOnRelea
se"true" TestConnectionsOnReserve"true"
TestTableName"SYS.SYSTABLES"
URL"jdbccloudscapermi//localhost1099/ejava"/gt
ltJDBCDataSource JNDIName"weblogic.jdbc.
dataSource.MyJDBC Data Source"
Name"MyJDBC Data Source" PoolName"MyJDBC
Connection Pool"/gt
82
Setting up Database Access(HttpServlet.init)
  • public void init(ServletConfig config) throws
    ServletException
  • super.init(config)
  • ServletContext context getServletContext()
  • dataSource_ (DataSource)context.getAttribu
    te("dataSource")
  • if (dataSource_ null)
  • try
  • InitialContext jndi new
    javax.naming.InitialContext()
  • dataSource_ (DataSource)jndi.lookup(
    "javacomp/env/jdbc/mydb")
  • context.setAttribute("dataSource",
    dataSource_)
  • catch (NamingException ex)
  • throw new ServletException("error
    locating data source"ex)

83
Accessing Database(HttpServlet.doPost/doGet)
  • public void doGet(HttpServletRequest request,
  • HttpServletResponse
    response)
  • throws ServletException,
    java.io.IOException
  • Connection connectionnull
  • try
  • connection dataSource_.getConnection()
  • //do something with the connection...
  • catch (Exception ex)
  • finally
  • closeConnection(connection)

84
Creating the .war file
  • cd c\\weblogic/myserver/public_html/webbasics
    \
  • //c/jdk1.3/bin/jar cvf /webbasics.war
  • added manifest
  • adding FormExample.html(in 467) (out
    257)(deflated 44)
  • adding MenuExample.html(in 486) (out
    274)(deflated 43)
  • adding WEB-INF/(in 0) (out 0)(stored 0)
  • adding WEB-INF/classes/(in 0) (out 0)(stored
    0)
  • adding WEB-INF/classes/ejava/(in 0) (out
    0)(stored 0)
  • adding WEB-INF/classes/ejava/servlets/(in 0)
    (out 0)(stored 0)
  • adding WEB-INF/classes/ejava/servlets/webbasics/(
    in 0) (out 0)(stored 0)
  • adding WEB-INF/classes/ejava/servlets/webbasics/B
    onusServlet.class(in 2403) (
  • out 1260)(deflated 47)
  • adding WEB-INF/classes/ejava/servlets/webbasics/P
    urchaseServlet.class(in 2585
  • ) (out 1449)(deflated 43)
  • adding WEB-INF/web.xml(in 1843) (out
    587)(deflated 68)
  • adding WEB-INF/weblogic.xml(in 412) (out
    227)(deflated 44)
  • adding WEB-INF/web.xml(in 1071) (out
    366)(deflated 65)
  • adding welcome.html(in 183) (out
    103)(deflated 43)

85
Deploying WAR file/dir(WebLogic Console)
86
Summary
  • Standardized mechanism for web tier deployments

87
(Optional)Debugging Sevlets
88
Setup Application Server(startWebLogic)
  • "JAVA_HOME\bin\java" -hotspot -ms64m -mx64m
    -classpath"CLASSPATH" -Dweblogic.Domainmydomai
    n -Dweblogic.Namemyserver "-Dbea.homeC\bea"
    -Dweblogic.management.passwordWLS_PW
    -Dweblogic.ProductionModeEnabledSTARTMODE
    -Djava.security.policyC\bea\wlserver6.1/lib/w
    eblogic.policy" -Xdebug -Xnoagent
    -Djava.compilerNONE -Xrunjdwptransportdt_socke
    t,address8787,servery weblogic.Server

89
Attach to Remote Process(TogetherJ)
90
Set a Break Point(TogetherJ)
91
Invoke Servlet(Browser)
92
Step Debugger(TogetherJ)
93
Resources
  • Main Servlets Page
  • http//java.sun.com/products/servlet/
  • Java Servlet Specification v2.2
  • http//java.sun.com/products/servlet/2.2/index.htm
    l
  • Marty Halls servlet tutorial
  • http//www.apl.jhu.edu/hall/java/Servlet-Tutorial
    /

94
References
  • Developing Java Enterprise Applications. Asbury,
    Weiner. Wiley. 1999
  • Java Enterprise in a Nutshell. Flanagan et al.
    OReilly 1999
  • Sun Servlets Tutorial
  • Java Pro, January 2000 A Study of Servlets and
    Server Pages
  • Java Developers Journal Volume 5 Issue 2.
    Creating a JSP JavaBeans Framework and Servlet
    Session Display
  • Java Report, August 1999 Using Java Server Pages
    - Servlets Made Simple
  • Java 2 Platform, Enterprise Edition Platform and
    Component Specifications
  • Core Servlets and Java Server Pages
  • Web Development with Java Server Pages
  • Designing Enterprise Applications with the Java 2
    Platform, Enterprise Edition
Write a Comment
User Comments (0)
About PowerShow.com