Building Web Applications In Java

Document Sample
Building Web Applications In Java Powered By Docstoc
					  Building Web Applications In Java




Nick Meshes
Agenda


   Choices in   Web Server Technology
   Review of    Basic Web Architecture
   Tiered Architecture Models

   Overview of    Java 2 Enterprise Edition (J2EE)
   J2EE   and the N-Tiered Architecture
  (continued)
Agenda


   Setting   up to create some examples
   Tomcat    structure
   Web    Containers and Web Applications
   Java   Servlet : HelloWorld.java
   JavaServer Page:      HelloWorld.jsp
  (continued)
Choices in Web Server Technology

   CGI   in PERL or C
   Proprietary APIs

   Active   Server Pages
   Java Servlets and   JSP
   Other    Boxed and Custom Web Server Solutions
Choices in Web Server Technology

  CGI in PERL or C
   First on   the block for dynamic content
   No   good session support
   Each request    invokes creating a process to handle it
   Code    may be tied to the server
   Can’t   communicate back with web server
Choices in Web Server Technology

  Proprietary APIs
   Handler runs    in same process as web server
   Code    written must be thread-safe to handle multiple
    users
   Error in   code could bring down webserver
Choices in Web Server Technology

  Active Server Pages (ASP)
   Provides a   clean, simple connection to data sources
   Manages sessions rather   than page instances
   Limited to   scripting and COM (.NET) capabilities
   Tightly coupled with   IIS/PWS/Windows
   Due   to .NET, comparable technology with J2EE
Choices in Web Server Technology

  Java Servlets and JavaServer Pages (JSP)
   Threads more    efficient than CGI processes
   Use   full functionality and utilities of JDK/J2EE
   Inherits Java’s portability to   other platforms
   Safety features of   Java, No shell escapes or buffer overflow
   Apache/Tomcat is     free, Jakarta offers free libraries
Review of Web Architecture


                          Web Server
              request     Server-side
                          Services
               response

Client
                                        Data
                                        Source
 Tiered Architecture Models
  Two -Tiered Model (Fat Client)
       Client                           Server
    Processing



                                         Data
                                         Source

 Too much load on PC
 Small changes require   big rollout
Tiered Architecture Models
Three -Tiered Model
    Client                         Server
                                Processing            Data
     GUI                           and                Source
                               Control Flow

   Client only   receives data and formats it
   Flexible server   can handle most processing
   Implementation     details are hidden from view
   Main issueis “a new service means a new server”
    independent of others
  Tiered Architecture Models
  N -Tiered Model
Presentation Logic   Presentation Logic        Resources and
                      Application                Business Data
  HTML Form           Object                       Remote or
                      Interface                      Legacy
  (Browser)                                          System
                        Application
   Java Applet                            Database
                        Object            Middleware
                                                       Database
   Any Data
    View
                                                       XML
                       Interface
                       Application
                       Object
Overview of Java 2 Enterprise Edition (J2EE)

    Many technologies for   many tasks (Java Servlets, JSP,
     EJBs, JNDI, Jini)
    Designed to   work with all other Java technologies
     seamlessly
    Component     development promotes reuse and
     modularity
J2EE and the N-Tiered Architecture

    Encapsulate dataand business logic from the client and
     other components
    Bridge between server      components and systems
    Link to   legacy systems
    Move  your components across computers or across the
     internet
Set up for Examples

                       Download seminar.zip from
                        http://www.meshes.com
                       Expand seminar.zip to
                        c:\Documents and
                        Settings\labuser
                       Open 2   command prompts
                       In   one, run “seminar1”
                       In   other, run “seminar2”
Set up for Examples

   At   this point, you should have 3 command prompts
     C:\Tomcat4.1.12\webapps\seminar\WEB-INF\classes

     C:\Tomcat4.1.12\bin

     One    running Tomcat


  These are your friends, do not get rid of them.
Tomcat structure

   Folders     entitled “classes” are for storing loose class files
   Folders     entitled “lib” are for storing .jar files (libraries)
   Under c:\Tomcat4.1.12
        bin: the executables to stop and start tomcat, compile jsps, process XML
        common: resources used by tomcat and commonly used by web application developers,
         visible to both code is split into lib, classes, and endorsed (which holds the endorsed
         versions of xml parsing utilities)
        conf: configuration files used by tomcat, modified to change context-specific information
        logs: log files generated by tomcat and by web applications
        server: resources used by tomcat, but not visible to contexts (except if you modify conf
         files)
        shared: resources used by application developers, visible to all contexts
        temp: work area for tomcat, acts as temporary directory for its JVM
        webapps: contexts or "web applications" stored here
        work: work area to compile JSPs into servlets, used by tomcat
Tomcat structure

   Structure of    a J2EE web application (“webapps”)
      Tomcat\webapps\WebApplication
        index files
            (optional) customary to place an index file here
            you can define any file as "index" in web.xml
        jsp
            (optional) customary to place JSP pages in a jsp directory
        WEB-INF
            (required) place all configuration files, including web.xml here
            lib directory to store jar-file resources
            classes directory to store class files
            web.xml file to configure context
Web Containers and Web Applications

   Web   Application
     Collection of   servlets, JSP pages, helper classes, resources, and
      libraries
     We   are building a web application
   Web   Container
     Java runtime    that implements Servlet API
     Responsible for   initialization, invoking, and managing Servlet
      lifecycle
     Tomcat is   a web container
                                                 Save file in WEB-INF\classes
                                                 Call file “HelloServlet.java”
Creating HelloServlet.java
  import javax.servlet.*;
  import javax.servlet.http.*;
  import java.io.*;

  public class HelloServlet extends HttpServlet {
     public void doGet(HttpServletRequest req, HttpServletResponse res)
       throws ServletException, IOException {

          res.setContentType("text/html");

          PrintWriter out = res.getWriter();

          out.println("<html>");
          out.println("<head><title>Hello World</title></head>");
          out.println("<body>");
          out.println("<h2>Hello World!</h2>");
          out.println("</body>");
          out.println("</html>");

          out.close();
      }

  }
HelloWorld.java

   To   compile HelloWorld.java
   In   “WEB-INF\classes” command prompt, type
              javac HelloWorld.java

   Get   no compile errors


   Next:   Create web.xml file in “WEB-INF”
                                                     Save file in WEB-INF
                                                     Call file “web.xml”
Creating web.xml file

   In   “bin” command prompt, type shutdown
  <?xml version="1.0" encoding="ISO-8859-1"?>
  <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application
     2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
  <web-app>
    <display-name>Seminar</display-name>
    <description>
      Example servlets, Jsps, etc from DePaul Seminar
    </description>
    <servlet>
       <servlet-name>HelloServlet</servlet-name>
       <servlet-class>HelloServlet</servlet-class>
     <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
       <servlet-name>HelloServlet</servlet-name>
       <url-pattern>/HelloServlet</url-pattern>
    </servlet-mapping>
  </web-app>
Running “Hello World” servlet

     In “bin” command prompt, type startup
     Open Internet Explorer
       http://localhost:8080/seminar/HelloServlet
                                                Save file in seminar\jsp
                                                Call file “HelloWorld.jsp”
Creating HelloWorld.jsp
  <%@ page language="java" info="HelloWorld Page" %>
  <%@ page import="java.util.*"%>

  <html>
    <head>
      <title>Hello World</title>
    </head>
    <body>
      <h2>Hello World!</h2>
      You'll notice this looks an aweful lot like straight HTML.<br>

     </body>
  </html>




     http://localhost:8080/seminar/jsp/HelloWorld.jsp
Enhancing HelloWorld.jsp
  …You'll notice this looks an aweful lot like straight HTML.<br>
      Today's date and time is: <%= new Date().toString() %><br>
      <table border=1>
                  <tr><td colspan=6>Shades of gray</td></tr>
                  <tr>
  <%
    String[] colorComponents = new String[] {"00", "33", "66", "99", "CC", "FF"};
    for (int i=0; i < colorComponents.length; i++) {

  //notice we end the scriptlet block INSIDE a loop
  %>


  <td bgcolor="#<%= colorComponents[i] %><%= colorComponents[i] %><%=
     colorComponents[i] %>">&nbsp;&nbsp;&nbsp;</td>

  <%
  //and we continue into another scriptlet block
     }
  %>
     </tr></table>
     </body>…
                                              Save file in seminar\jsp
                                              Call file “SessionAttribute.jsp”
SessionAttribute.jsp
  <%@ page language="java" info=“Session Attributes Page" %>
  <%@ page import="java.util.*"%>

  <html>
    <head><title>Setting/Getting Session Attributes in a JSP</title></head>

     <body>
      <h2>Session Attributes</h2>

      <table border=1>
                <tr> <td>Attribute Name</td> <td>Attribute Value</td> </tr>

  <%
    String aName = request.getParameter("new_attribute");

    if (aName != null) {
       String aValue = request.getParameter("new_attribute_value");
       session.setAttribute(aName, aValue);
    }
  %>
  CONTINUED
                                                Save file in seminar\jsp
                                                Call file “SessionAttribute.jsp”
SessionAttribute.jsp
  <%
    String newInterval = request.getParameter("max_interval");

     if (newInterval != null && newInterval.length() > 0) {
        session.setMaxInactiveInterval(Integer.parseInt(newInterval.trim()));
     }

     Enumeration attribNames = session.getAttributeNames();

    while (attribNames.hasMoreElements()) {
     String attribute = (String)attribNames.nextElement();
  %>

      <tr>
                 <td><%= attribute %></td>
                 <td><%= session.getAttribute(attribute) %></td>
      </tr>

  <%
    }
  %>
  CONTINUED
                                          Save file in seminar\jsp
                                          Call file “SessionAttribute.jsp”
SessionAttribute.jsp
      </table>

      <hr/>
      <form name="attributesForm" method="GET" action="SessionAttribute.jsp">
               Wanna add an attribute to the session?<br>
               Name: <input type="text" name="new_attribute" length="20"/><br>
               Value: <input
                          type="text"
                          name="new_attribute_value"
                          length="20"/><br>
               <input type="submit" name="Submit Me" value="Submit"/><br>
               By the way, your session will timeout in
  <%= session.getMaxInactiveInterval() %> seconds<br>
               Set interval to: <input
                                    type="text"
                                    name="max_interval"
                                    length="20"/> seconds
      </form>
     </body>
  </html>
                                                Save file in WEB-INF\classes
                                                Call file “SessionServlet.java”
SessionServlet.java
  import javax.servlet.*;
  import javax.servlet.http.*;
  import java.io.*;

  public class SessionServlet extends HttpServlet {

     public void doGet(HttpServletRequest req, HttpServletResponse res) throws
     ServletException, IOException {

       HttpSession session = req.getSession(true);
       Integer numVisits = (Integer)session.getValue("NumberOfVisits");
       res.setContentType("text/html");
       PrintWriter out = res.getWriter();
       out.println("<html>");
       out.println("<body>");
       out.print("You have visited ");

  CONTINUED
                                                 Save file in WEB-INF\classes
                                                 Call file “SessionServlet.java”
SessionServlet.java
          if (numVisits == null) {
                    out.print("1");
                    numVisits = new Integer(1);
          }
          else {
                    out.print(numVisits.intValue());
                    numVisits = new Integer(numVisits.intValue() + 1);
          }

          out.println(" times this session.");
          out.println("</body>");
          out.println("</html>");

          out.close();

          session.putValue("NumberOfVisits", numVisits);
      }
  }
Modify web.xml for SessionServlet
  …</servlet>

  <servlet>
       <servlet-name>SessionServlet</servlet-name>
       <servlet-class>SessionServlet</servlet-class>
     <load-on-startup>3</load-on-startup>
  </servlet>

  <servlet-mapping>
      <servlet-name>SessionServlet</servlet-name>
      <url-pattern>/servlet/SessionServlet</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
      <servlet-name>HelloServlet</servlet-name>
      <url-pattern>/HelloServlet</url-pattern>
    </servlet-mapping>

  Compile SessionServlet.java from compiling command prompt
  http://localhost:8080/seminar/servet/SessionServlet
Many More Examples as time allows
    Creating and    Reading Cookies
    Managing Beans in     a page and on the HttpSession
    Tags   in a JSP Page and the Struts Tag Libraries
    Filtering   Requests with J2EE Filters
    Struts Actions and   the Struts ActionServlet