servlets webapps by fB7N0g

VIEWS: 6 PAGES: 94

									                                                    Enterprise
                                                         Java




                 Servlets
                    and
          Web Applications (WARs)
             HTML, Servlets, and Web Applications




v020218               Servlets & Web Apps                  1
                                             Enterprise
                                                  Java

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




v020218                Servlets & Web Apps          2
                                            Enterprise
                                                 Java

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




v020218               Servlets & Web Apps          3
                                                        Enterprise
                                                             Java

                         HTML
• Regular text with ‘markup’ elements specifying the desired
  appearance and layout of the information
• Style sheets can also be specified
• Tag Format
     – <TAG ATTR=optional>Value</TAG>




v020218                 Servlets & Web Apps                    4
                                                    Enterprise
                                                         Java

                  HTML Example
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 3.2//EN”>
<HTML>
<HEAD>
<TITLE>Example Page</TITLE>
</HEAD>
<BODY BGCOLOR = "WHITE">
<BLOCKQUOTE>
<H3>Bonus Calculation</H3>
</BLOCKQUOTE>
</BODY>
</HTML>




v020218                 Servlets & Web Apps                5
                                                      Enterprise
                                                           Java

                       HTML Structure
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 3.2//EN”>
<HTML>
    <HEAD>
        <TITLE>This is the title</TITLE>
    </HEAD>
    <BODY>
        <H1>Heading</H1>
        Other elements
    </BODY>
</HTML>




v020218                         Servlets & Web Apps          6
                                                 Enterprise
                                                      Java

                      Example Tags
• <HTML><HEAD><BODY>
     – Main document sections
• Headings <H1><H2> …. <H6>
• Paragraph <P> (</P> is optional)
• Lists
     – Numbered List <OL><LI> ….. </OL>
     – Bulleted Lists <UL><LI> ….. </UL>




v020218                    Servlets & Web Apps          7
                                                   Enterprise
                                                        Java

                     Other Capabilities
• Character Display
     – Bold <B>, Italic <I>, Font <F>, etc.
•   Hyperlinks <A HREF=url>Click</A>
•   Tables
•   Forms
•   Frames
•   Scripting




v020218                      Servlets & Web Apps          8
                                                     Enterprise
                                                          Java

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




v020218                Servlets & Web Apps                  9
                                                        Enterprise
                                                             Java

                     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




v020218                           Servlets & Web Apps         10
                                                            Enterprise
                                                                 Java

                             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 ===> /test.html
     – HTTP Version




v020218                            Servlets & Web Apps            11
                                                                            Enterprise
                                                                                 Java

                       Request Methods
• GET (HTTP 1.0)
    – Used by browsers for normal document requests
    – Additional info can be sent after URI
       GET /test.html?field1=value 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
v020218                         Servlets & Web Apps                               12
                                                              Enterprise
                                                                   Java

               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




v020218                      Servlets & Web Apps                    13
                                                                    Enterprise
                                                                         Java

                         Request Headers
• Additional, optional information for server
• Examples
     – Accept - MIME types client will accept in preference order
           • Accept */* - client is willing to accept anything
     – Authorization:auth-scheme:credentials
           • provides no privacy alone - can be combined with SSL
     – Connection: Keep-Alive
           • do not close connection between server interactions
     –    Content-Length - data length (POST)
     –    Cookie:name=val;name2=val2
     –    Referrer - URL of referring page
     –    Host - host and port from original URL
v020218                           Servlets & Web Apps                     14
                                                     Enterprise
                                                          Java

                      Request Example
GET /test.html?name=Dan HTTP/1.1
Accept: image/gif, image/jpeg, */*
Accept-Language: en
Host: www.sun.com:80
Content-Length:20 [required if request was POST]
(Blank Line)
[if request was POST, additional data here]




v020218                        Servlets & Web Apps         15
                                                  Enterprise
                                                       Java

               HTTP Server Response
• Example
     HTTP/1.0 200 Document Follows
     Content-Type: text/html
     Content-Length: 2908

     </!DOCTYPE …….>
     <HTML>
     ……
     </HTML>




v020218                     Servlets & Web Apps         16
                                                                         Enterprise
                                                                              Java

                 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




v020218                        Servlets & Web Apps                              17
                                                            Enterprise
                                                                 Java

                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




v020218                         Servlets & Web Apps               18
                                                 Enterprise
                                                      Java

           Response Header Example
HTTP/1.0 200 OK
Date: Fri, 29 Feb 2000 17:31:20 GMT
Set-Cookie: user-id=123; secure
Content-Length: 124
Content-Encoding: x-compress
Content-Type: text/html
<Blank Line>
HTML document




v020218                    Servlets & Web Apps         19
                                                                   Enterprise
                                                                        Java

              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




v020218                       Servlets & Web Apps                        20
                                                        Enterprise
                                                             Java

                        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




v020218                       Servlets & Web Apps             21
                                                                 Enterprise
                                                                      Java

                      Form Example
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
<head>
    <title>Form Example</title>
</head>
<body>
<form method="GET" action="BonusAlias">
<p>Enter social security number:
<p><input type="TEXT" name="SOCSEC"></input>
<p>Enter multiplier:
<p><input type="TEXT" name="MULTIPLIER"></input>
<p>
<input type="SUBMIT" name="Multiply" value="Multiply"></input>
<input type="RESET" name="Reset" value="Reset">
</form>
</body>
</html>

v020218                     Servlets & Web Apps                        22
                                  Enterprise
                                       Java

          Form Display




v020218     Servlets & Web Apps         23
                                                    Enterprise
                                                         Java

                       Form Structure
• Form Header
     – <FORM Method=GET ACTION=url>
     – Attributes
          • Action - URL of processing script
          • Method - HTTP method (GET or POST)
• Input Field(s)
     – <INPUT TYPE=type NAME=name></INPUT>
• Action Button(s)
     – <INPUT TYPE=type NAME=name VALUE=value></INPUT>




v020218                      Servlets & Web Apps          24
                                                       Enterprise
                                                            Java

                         Input Fields
• GUI controls for entering information
• Types
     –    Text Box       <INPUT TYPE=“TEXT”>
     –    Password Box   <INPUT TYPE=“PASSWORD”>
     –    Checkbox       <INPUT TYPE=“CHECKBOX”>
     –    Radio Button   <INPUT TYPE=“RADIO”>
     –    Hidden Field   <INPUT TYPE=“HIDDEN”>
     –    Images         <INPUT TYPE=“IMAGE”>
     –    File           <INPUT TYPE=“FILE”>
     –    Text Window    <TEXTAREA>…</TEXTAREA>
     –    Menu           <SELECT>…<OPTION>…</SELECT>




v020218                    Servlets & Web Apps               25
                                                                   Enterprise
                                                                        Java

                      Menu Example
  <!doctype html public "-//w3c//dtd html 4.0 transitional//en">
  <html>
  <head>
    <title>Menu Example</title>
  </head>
  <body>
  <form method="GET" action="PurchaseAlias">
  <p>Chose Product to Purchase
  <select name="Product" size=2>
  <option value="ID_1">Offer 1 Desc</option>
  <option value="ID_8">Offer 8 Desc</option>
  </select>
  <p>
  <input type="SUBMIT" name="BUYCMD" value="BUY"></input>
  <input type="SUBMIT" name="CANCELCMD" value="CANCEL"></input>
  </form>
  </body>
  </html>
v020218                      Servlets & Web Apps                         26
                                  Enterprise
                                       Java

          Menu Display




v020218     Servlets & Web Apps         27
                                                      Enterprise
                                                           Java

                     Form Submission
• Parameters are encoded and sent to the Action URL using
  GET or POST
• application/x-www-form-urlencoded
     name1=val1&name2=val2&namex=valx
     space ===> ‘+’
     non-alphanumeric ===> %xx
          • ‘~’ becomes %7E
          • ‘/’ becomes %2F




v020218                       Servlets & Web Apps           28
                                        Enterprise
                                             Java

          Form Submission Examples




v020218           Servlets & Web Apps         29
                                                           Enterprise
                                                                Java

              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




v020218                     Servlets & Web Apps                  30
                                                      Enterprise
                                                           Java

                     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




v020218                     Servlets & Web Apps             31
                                Enterprise
                                     Java




          Servlets




v020218   Servlets & Web Apps         32
                                                                 Enterprise
                                                                      Java

                       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




v020218                    Servlets & Web Apps                         33
                                                                       Enterprise
                                                                            Java

                        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




v020218                        Servlets & Web Apps                           34
                                                                    Enterprise
                                                                         Java

                     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




v020218                      Servlets & Web Apps                          35
                                                                  Enterprise
                                                                       Java

              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




v020218                     Servlets & Web Apps                         36
                                                                         Enterprise
                                                                              Java

                             Architecture

          Get/Post Request                Request
 Web                          Web
Browser   HTML Page          Server




                                      Reply          Servlet Container


                                                          Servlet




v020218                        Servlets & Web Apps                             37
                                                                                          Enterprise
                                                                                               Java

                            Key Servlet Classes
                  <<Interface>>
                     Servlet                                      ServletConfig

void destroy()                                       getInitParameter(String name) : String
getServletConfig() : ServletConfig                   getInitParameterNames() : Enumeration
getServletInfo() : String                            getServletContext() : ServletContext
init(ServletConfig config)
service(ServletRequest req, ServletResponse resp)



                                                                HttpServlet

                                             doDelete(ServletRequest req, ServletResponse res)
           GenericServlet                    doGet(ServletRequest req, ServletResponse res)
                                             doOptions(ServletRequest req, ServletResponse res)
                                             doPost(ServletRequest req, ServletResponse res)
                                             doPut(ServletRequest req, ServletResponse res)
                                             doTrace(ServletRequest req, ServletResponse res)




v020218                                Servlets & Web Apps                                      38
                                                          Enterprise
                                                               Java

                      Servlet Lifecycle
• init() called when servlet is instantiated
• service() called to handle requests throughout the servlet’s
  lifetime
• destroy() called when servlet engine unloads the servlet
  instance
     – period of inactivity
     – resource issues




v020218                       Servlets & Web Apps               39
                                                                    Enterprise
                                                                         Java

                   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("BonusServlet:init(config)");
 }


v020218                             Servlets & Web Apps                   40
                                                                Enterprise
                                                                     Java

                              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("<html><head><title>");
   out.println("Purchase Servlet");
   out.println("</title></head><body>");
   if (request.getParameter("BUYCMD") != null) {
      String product = request.getParameter("Product");
     out.println("<p><b>purchased product:</b>"+product);
   }
   out.println("</body></html>");
   out.close();
 }

v020218                              Servlets & Web Apps              41
                                                                         Enterprise
                                                                              Java

                     Request and Reply
• Request URL
     http://localhost:7001/webbasics/PurchaseAlias?Product=ID_1&BUYCMD=BUY

• Reply Document
     <html><head><title>
     Purchase Servlet
     </title></head><body>
     <p><b>purchased product:</b>ID_1
     </body></html>




v020218                        Servlets & Web Apps                             42
                                                        Enterprise
                                                             Java

             Understanding the Request
• Form parameters
     – String choice=request.getParameter(“Product”);
• Cookies
     – Cookie[] = request.getCookies()
     – getName(), getValue()
• Binary Data
     – InputStream is = request.getInputStream()
• Character Data
     – Reader r = request.getReader()




v020218                        Servlets & Web Apps            43
                                                                                 Enterprise
                                                                                      Java

                 Requests and Responses
            ServletRequest                              ServletResponse

  getContentLength() : int                getOutputStream() : ServletOutputStream
  getContentType() : String               getWriter() : PrintWriter
  getInputStream() : ServletInputStream   setContentLength(int len)
  getParameter(String name) : String      setContentType(String type)
  getReader() : BufferedReader




          HttpServletRequest                      HttpServletResponse

    getAuthType() : String                addCookie(Cookie c)
    getCookies() : Cookie[]               setHeader(String name, String value)
    getHeader(String name) : String       setStatus(int sc)
    getSession() : HttpSession



v020218                           Servlets & Web Apps                                  44
                                                    Enterprise
                                                         Java

           Obtaining Selected Product
• Form snippet
     <SELECT NAME="Product" SIZE=2>
     <OPTION VALUE="ID_1">Offer 1 Desc</OPTION>
     <OPTION VALUE="ID_8">Offer 8 Desc</OPTION>
     </SELECT>
• doGet(), doPost()
     String choice = req.getParameter(“Product”);
     // choice is ID_1 if ‘Offer 1 Desc’ is
     // selected




v020218                   Servlets & Web Apps             45
                                                        Enterprise
                                                             Java

                  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




v020218                         Servlets & Web Apps           46
                                                      Enterprise
                                                           Java

                    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)




v020218                         Servlets & Web Apps         47
                                                         Enterprise
                                                              Java

                    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("<HTML><HEAD><TITLE>");
          out.println(“Example Title”);
          out.println("</TITLE></HEAD></HTML>");
          out.close();
     }




v020218                           Servlets & Web Apps          48
                                                   Enterprise
                                                        Java

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




v020218                      Servlets & Web Apps         49
                                                     Enterprise
              Example Response Headers                    Java



               (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”);
}




v020218                     Servlets & Web Apps            50
                                                                   Enterprise
                                                                        Java

                         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




v020218                     Servlets & Web Apps                          51
                                                               Enterprise
                                                                    Java

                       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 session=request.getSession(true);
          session.putValue(“Cart”, new java.util.Vector() );




v020218                           Servlets & Web Apps                52
                                                  Enterprise
                                                       Java

              HttpSession Example
Integer salary=null;
HttpSession session = request.getSession(true);
 if (session.isNew()) {
   out.println("<p>session is new");
   session.setMaxInactiveInterval(5);
   salary = new Integer(1);
   session.setAttribute("salary",salary);
}



v020218                 Servlets & Web Apps             53
                                                                    Enterprise
                                                                         Java

            HttpSession Example (cont.)
else {
     out.println("<p>session is not new, id=" + session.getId());
     out.println("<p>session created at: " +
          new java.util.Date(session.getCreationTime()));
     out.println("<p>session last accessed at: " +
          new java.util.Date(session.getLastAccessedTime()));
     out.println("<p>session will time out after: " +
          session.getMaxInactiveInterval() + " secs");
     salary = (Integer)session.getAttribute("salary");
   }
   out.println("<p>old salary=" + salary);
   salary = new Integer(salary.intValue() * multiplierValue);
   out.println("<p>new salary=" + salary);
   session.setAttribute("salary",salary);
v020218                          Servlets & Web Apps                      54
          HttpSession Example Output     Enterprise
                                              Java



                  (1st Reload)




v020218            Servlets & Web Apps         55
                                                            Enterprise
                                                                 Java

                    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)




v020218                       Servlets & Web Apps                 56
                                                        Enterprise
                                                             Java

                      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




v020218                      Servlets & Web Apps              57
                                                Enterprise
                                                     Java

                 Http Session


                     HttpSession

          getValue(String name) : Object
          putValue(String name, Object value)
          getId() : String
          getCreationTime() : long
          invalidate() : void




v020218              Servlets & Web Apps              58
                                                         Enterprise
                                                              Java

                             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




v020218                      Servlets & Web Apps               59
                                Enterprise
                                     Java

          Cookies




v020218   Servlets & Web Apps         60
                                                                              Enterprise
                                                                                   Java

                               Cookie Example
HttpServletRequest req;
Cookie[] cookie = req.getCookies();
for( int i=0;i<cookie.length;i++)
{
      System.out.println(cookie[i].getName() +”:” + cookie[i].getValue() );
}
…….

HttpServletResponse resp;
resp.addCookie( new Cookie(“user_id_for_site”, “862348762346324”));




v020218                                  Servlets & Web Apps                        61
                                                     Enterprise
                                                          Java

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




v020218                    Servlets & Web Apps             62
                                                      Enterprise
                                                           Java

                          Servlet Context
• Servlet may wish to interact with the host server
• GenericServlet::getServletContext()
     –    getMimeType( String file )
     –    getServlet(String name) : Servlet
     –    log(Exception, String)
     –    log(String)




v020218                         Servlets & Web Apps         63
                                Enterprise
                                     Java




v020218   Servlets & Web Apps         64
                                                                Enterprise
                                                                     Java

                            Redirection
• Web Browser redirection
     – resp.sendRedirect(String url)
     – resp.sendError(int code, String message)
• Server-Side
     – RequestDispatcher rd =
         getServletContext().getRequestDispatcher(urlString);
     – rd.forward();




v020218                        Servlets & Web Apps                    65
                                     Enterprise
                                          Java

          Request Dispatcher




v020218        Servlets & Web Apps         66
                                                                   Enterprise
                                                                        Java

                           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




v020218                          Servlets & Web Apps                     67
                                                          Enterprise
                                                               Java

                   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




v020218                  Servlets & Web Apps                    68
                                    Enterprise
                                         Java




          Web Applications




v020218       Servlets & Web Apps         69
                                                         Enterprise
                                                              Java

                                WAR
•   Web Archive
•   Introduced with servlet 2.2 specification
•   Portable deployment mechanism for web applications
•   Defines directory structure
     – Jar’d into a .war file for deployment
• Uses XML deployment descriptor




v020218                       Servlets & Web Apps              70
                                                                             Enterprise
                                                                                  Java

                       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/webbasics
./webbasics/WEB-INF/classes/ejava/servlets/webbasics/BonusServlet.class
./webbasics/WEB-INF/classes/ejava/servlets/webbasics/PurchaseServlet.class
./webbasics/WEB-INF/web.xml
./webbasics/WEB-INF/weblogic.xml
./webbasics/FormExample.html
./webbasics/MenuExample.html




v020218                            Servlets & Web Apps                             71
                                                                      Enterprise
                                                                           Java

                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.




v020218                            Servlets & Web Apps                      72
                                                                                      Enterprise
                                                                                           Java

            Deployment Descriptor (web.xml)
      <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 1.2//EN"
      "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
      <web-app>
         <display-name>HTML Basics</display-name>
         <context-param>
           <param-name>weblogic.httpd.servlet.reloadCheckSecs</param-name>
           <param-value>1</param-value>
         </context-param>
         <servlet>
           <servlet-name>PurchaseServlet</servlet-name>
           <servlet-class>ejava.servlets.webbasics.PurchaseServlet</servlet-class>
           <init-param>
             <param-name>param1</param-name>
             <param-value>value1</param-value>
           </init-param>
         </servlet>
         <servlet>
           <servlet-name>BonusServlet</servlet-name>
           <servlet-class>ejava.servlets.webbasics.BonusServlet</servlet-class>
         </servlet>
      ...
v020218                                   Servlets & Web Apps                               73
                                                         Enterprise
                                                              Java

          Mapping Servlets to URLs (web.xml)

      …
        <servlet-mapping>
          <servlet-name>PurchaseServlet</servlet-name>
          <url-pattern>PurchaseAlias</url-pattern>
        </servlet-mapping>
        <servlet-mapping>
          <servlet-name>BonusServlet</servlet-name>
          <url-pattern>BonusAlias</url-pattern>
        </servlet-mapping>
     ...


v020218                 Servlets & Web Apps                    74
                                                      Enterprise
                                                           Java

          Declaring Default Pages (web.xml)

      …
         <welcome-file-list>
          <welcome-file>welcome.html</welcome-file>
        </welcome-file-list>
     ...




v020218                Servlets & Web Apps                  75
                                                              Enterprise
                          Setting up Security                      Java



                               (web.xml)
      …
      <security-constraint>
         <web-resource-collection>
           <web-resource-name>protected</web-resource-name>
                 <url-pattern>/BonusAlias/*</url-pattern>
         </web-resource-collection>
         <auth-constraint>
           <role-name>instructor</role-name>
         </auth-constraint>
       </security-constraint>

       <login-config>
         <auth-method>BASIC</auth-method>
       </login-config>

         <security-role>
           <role-name>instructor</role-name>
         </security-role>
      ...
v020218                             Servlets & Web Apps             76
                                                                           Enterprise
                         Setting up Security                                    Java



                          (weblogic.xml)
     <!DOCTYPE weblogic-web-app PUBLIC "-//BEA Systems, Inc.//DTD Web
     Application 6.0
     //EN" "http://www.bea.com/servers/wls600/dtd/weblogic-web-jar.dtd">

     <weblogic-web-app>
        <security-role-assignment>
          <role-name>instructor</role-name>
          <principal-name>ejava-instructor</principal-name>
        </security-role-assignment>
     ...
     </weblogic-web-app>




v020218                           Servlets & Web Apps                            77
                                     Enterprise
           Setting up Security            Java



          (WebLogic Console)




v020218        Servlets & Web Apps         78
                                                                                    Enterprise
                 Setting up Database Access                                              Java



                 (web.xml & weblogic.xml)
      …
        <resource-ref>
         <res-ref-name>jdbc/mydb</res-ref-name>
         <res-type>javax.sql.DataSource</res-type>
         <res-auth>Container</res-auth>
       </resource-ref>
     …
     <!DOCTYPE weblogic-web-app PUBLIC "-//BEA Systems, Inc.//DTD Web
     Application 2.2//EN" "http://www.beasys.com/j2ee/dtds/weblogic.web-jar.dtd">

     <weblogic-web-app>
      <reference-descriptor>
        <resource-description>
          <res-ref-name>jdbc/mydb</res-ref-name>
          <jndi-name> weblogic.jdbc.dataSource.MyJDBC Data Source</jndi-name>
         </resource-description>
       </reference-descriptor>
     </weblogic-web-app>
v020218                            Servlets & Web Apps                                    79
                                         Enterprise
   Viewing the Data Source in the JNDI Tree   Java



             (WebLogic Console)




v020218           Servlets & Web Apps          80
                                                                          Enterprise
               Setting up Database Access                                      Java



             (config/<domain>/config.xml)
     <JDBCConnectionPool DriverName="COM.cloudscape.core.RmiJdbcDriver"
        Name="MyJDBC Connection Pool"
        Properties="user=none;password=none" Targets="myserver"
        TestConnectionsOnRelease="true" TestConnectionsOnReserve="true"
        TestTableName="SYS.SYSTABLES"
        URL="jdbc:cloudscape:rmi://localhost:1099/ejava"/>

     <JDBCDataSource
        JNDIName="weblogic.jdbc.dataSource.MyJDBC Data Source"
        Name="MyJDBC Data Source" PoolName="MyJDBC Connection Pool"/>




v020218                        Servlets & Web Apps                              81
            Setting up Database Access                                  Enterprise
                                                                             Java



                  (HttpServlet.init)
 public void init(ServletConfig config) throws ServletException {
    super.init(config);
    ServletContext context = getServletContext();
    dataSource_ = (DataSource)context.getAttribute("dataSource");
    if (dataSource_ == null) {
       try {
         InitialContext jndi = new javax.naming.InitialContext();
         dataSource_ = (DataSource)jndi.lookup("java:comp/env/jdbc/mydb");
         context.setAttribute("dataSource", dataSource_);
       }
       catch (NamingException ex) {
          throw new ServletException("error locating data source:"+ex);
       }
    }
v020218
  }                                Servlets & Web Apps                        82
                 Accessing Database                           Enterprise
                                                                   Java



             (HttpServlet.doPost/doGet)
public void doGet(HttpServletRequest request,
             HttpServletResponse response)
             throws ServletException, java.io.IOException {
   Connection connection=null;
   try {
     connection = dataSource_.getConnection();
     //do something with the connection...
   }
   catch (Exception ex) {
   }
   finally {
     closeConnection(connection);
   }

v020218                         Servlets & Web Apps                 83
                                                                                   Enterprise
                                                                                        Java

                        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/BonusServlet.class(in = 2403) (
out= 1260)(deflated 47%)
adding: WEB-INF/classes/ejava/servlets/webbasics/PurchaseServlet.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%)
v020218                                  Servlets & Web Apps                             84
          Deploying WAR file/dir       Enterprise
                                            Java



           (WebLogic Console)




v020218          Servlets & Web Apps         85
                                                    Enterprise
                                                         Java

                     Summary
• Standardized mechanism for web tier deployments




v020218               Servlets & Web Apps                 86
                                    Enterprise
                                         Java




             (Optional)
          Debugging Sevlets




v020218       Servlets & Web Apps         87
              Setup Application Server                             Enterprise
                                                                        Java



                  (startWebLogic)
"%JAVA_HOME%\bin\java" -hotspot -ms64m -mx64m -classpath
   "%CLASSPATH%" -Dweblogic.Domain=mydomain
   -Dweblogic.Name=myserver "-Dbea.home=C:\bea"
   -Dweblogic.management.password=%WLS_PW%
   -Dweblogic.ProductionModeEnabled=%STARTMODE% ”
   -Djava.security.policy==C:\bea\wlserver6.1/lib/weblogic.policy"
   -Xdebug -Xnoagent -Djava.compiler=NONE
   -Xrunjdwp:transport=dt_socket,address=8787,server=y weblogic.Server




v020218                     Servlets & Web Apps                          88
          Attach to Remote Process      Enterprise
                                             Java



                 (TogetherJ)




v020218           Servlets & Web Apps         89
          Set a Break Point         Enterprise
                                         Java



             (TogetherJ)




v020218       Servlets & Web Apps         90
          Invoke Servlet          Enterprise
                                       Java



            (Browser)




v020218     Servlets & Web Apps         91
          Step Debugger           Enterprise
                                       Java



           (TogetherJ)




v020218     Servlets & Web Apps         92
                                                             Enterprise
                                                                  Java

                             Resources
•   Main Servlets Page
     – http://java.sun.com/products/servlet/
•   Java Servlet Specification v2.2
     – http://java.sun.com/products/servlet/2.2/index.html
•   Marty Hall’s servlet tutorial
     – http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/




v020218                       Servlets & Web Apps                  93
                                                                                             Enterprise
                                                                                                  Java

                                    References
•   Developing Java Enterprise Applications. Asbury, Weiner. Wiley. 1999
•   Java Enterprise in a Nutshell. Flanagan et al. O’Reilly 1999
•   Sun Servlets Tutorial
•   Java Pro, January 2000 ‘A Study of Servlets and Server Pages’
•   Java Developer’s 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




v020218                                Servlets & Web Apps                                         94

								
To top