Java Training Introduction to Servlets - PowerPoint PPT Presentation

1 / 41
About This Presentation
Title:

Java Training Introduction to Servlets

Description:

Tomcat is a popular (and free) servlet and JSP container and can be downloaded ... It returns a response (usually HTML) back to the client. ... – PowerPoint PPT presentation

Number of Views:594
Avg rating:3.0/5.0
Slides: 42
Provided by: cexpem
Category:

less

Transcript and Presenter's Notes

Title: Java Training Introduction to Servlets


1
Java TrainingIntroduction to Servlets
  • Written by Jeff Smith

2
What is a Servlet? -1
  • Servlets are server side Java classes that add
    functionality to a web server in a manner similar
    to the way applets add functionality to a
    browser.
  • Servlets can be used as a replacement for CGI
    scripts (or ASP scripts) and they support the
    standard request/response protocol supported by
    web servers.
  • In this request/response protocol, a client sends
    a request message to a server and the server
    responds by sending back a reply message
  • Reply is usually as HTML
  • Could be image, audio stream, video stream, etc.

3
What is a Servlet? -2
  • Servlets generally implement either the Servlet
    interface or extend the HttpServlet abstract
    class
  • Most programmers extend HttpServlet class
  • More on this class later
  • Servlets run in a servlet container (Tomcat is a
    popular one)
  • Servlets are platform independent
  • Your servlets will work on an Apache web server
    running on Linux or a IIS web server running on
    Windows XP
  • Servlets are generally invoked from a hyperlink
    or from the action attribute of an HTML form

4
What is a Servlet? -3
5
What is a Servlet? -4
6
Web/Servlet Architecture
7
Servlets -1
  • Servlets can run on the web server platform as
    part of the same process as the web server
    itself.
  • Alternatively, the servlet container can also run
    on a different machine
  • Tomcat is a popular (and free) servlet and JSP
    container and can be downloaded from the JavaZone
    web page
  • Apache Tomcat can also run web services
  • You can use Apache Axis (SOAP implementation for
    web services) with Tomcat

8
Servlets -2
  • The web server communicates with servlets via a
    simple interface javax.servlet.Servlet. This
    interface defines three important methods
  •   init() -- invoked on servlet startup, put
    init code hereservice() -- each client request
    invokes this methoddestroy() -- put cleanup code
    here
  • The servlet container controls the lifecycle of
    the servlet objects
  • initializes, invokes, and destroys each servlet
    instance.
  • You can write a servlet by extending the Servlet
    class and implement these three methods

9
Servlets -3
  • Servlet Lifecycle
  • init() -- This method is called when a servlet
    is first invoked by the servlet container. It
    could be used to write code that initializes
    files or connections to databases
  • service() -- This method process requests from
    the client (for example, a hyperlink or form
    action). It returns a response (usually HTML)
    back to the client.
  • The service() method provides two parameters
    ServletRequest and ServletResponse to provide
    access to the request object and response object
  • destroy() -- Called just before servlet is
    destroyed by container to enable programmer to
    clean up any resources (e.g. close a db
    connection)

10
Servlet Example -1
import java.io. import javax.servlet. public
class MyServlet implements Servlet private
ServletConfig config public void init
(ServletConfig config) throws
ServletException this.config config
public void destroy() // do nothing
11
Servlet Example -2
public ServletConfig getServletConfig()
//optional
//method return(config) public
void service(ServletRequest req,
ServletResponse res)
throws ServletException, IOException
res.setContentType( "text/html" )
PrintWriter out res.getWriter()
out.println( "lthtmlgtMy Servlet!!!lt/htmlgt" )
out.close()
12
Useful Servlet Methods -1
  • getRealPath() -- method translates a relative or
    virtual path to a new path relative to the
    server's HTML documentation root location. This
    is useful if your servlet needs to access a file,
    for example.
  • getServlet() -- Returns a Servlet object of a
    given name. Useful when you want to access the
    services of other servlets.
  • log() -- Writes information to a servlet log
    file. The log file name and format are server
    specific.
  • Note When extending the HttpServlet class, you
    access these methods via the ServletContext. For
    example
  • realPath getServletContext().getRealPath(virtual
    Path)

13
HTTP GET vs. POST -1
  • HTTP GET sends the contents of the form fields as
    extra data appended to the URL specified in the
    form's ACTION attribute.
  • For example, if you had a form with an action
    MyServlet and a single text element called search
    and you typed in "football" and clicked the
    submit button, the resulting URL might look
    likehttp//www.noaa.gov/MyServlet?searchfootba
    ll
  • Note that you could bookmark this URL to quickly
    reload it in a browser.
  • HTML forms that use do HTTP GETs should not
    contain too much data (1000 chars?) or they might
    overflow the web server

14
HTTP GET vs. POST -2
  • HTTP POST sends the contents of the form fields
    as a separate data stream to the web server
  • HTTP POSTs cannot be bookmarked by the browser
  • HTML forms that use do HTTP POSTs can send large
    amounts of data to the web server without any
    problems
  • The data that is sent is not visible in the URL
    that appears in the browser
  • For example, if you have a password field, you
    would want to do a HTTP POST so the password
    doesn't appear in the URL

15
HttpServlet -1
  • Instead of implementing the Servlet interface,
    most servlets extend the HttpServlet class
    because it has http support built in, making it
    easier to access the request and response
    objects.
  • When you extend HttpServlet, you generally write
    code for one or both of the following methods
  • doGet() -- corresponds to HTTP GET
  • doPost() -- corresponds to HTTP POST

16
HttpServlet -2
  • The doGet() and doPost() methods take two
    parameters
  • HttpServletRequest -- contains all the
    information about the request made by a web page,
    including any form data
  • HttpServletResponse -- object you can use to send
    data (usually html) back to the calling web page

17
HttpServlet -3
  • doGet() and doPost() methods generally do the
    following
  • Read the request data (html form data)
  • Process the request (perhaps invoking the code in
    other user-written classes within the servlet's
    package)
  • Set response object headers (what type of
    response will be sent--for example, will it be
    HTML or a JPEG image?)
  • Write the response data (for example, send HTML
    back to the calling web page)

18
HttpServlet Style Suggestions
  • It is a good idea to keep your servlet classes as
    lean as possible
  • In general, good OOP design would suggest that
    you put your "business" or "application" logic in
    a separate class and have your servlet's doPost()
    or doGet() methods invoke that code
  • For example, you don't want to have a doPost()
    method with 300 lines of code in it
  • Your servlet can directly return HTML, but in
    most real world (and complex) web apps, your
    servlets would not return HTML via out.println()
    statements.
  • Instead, your servlets would return JSP pages
    with all the HTML formatting already in it. These
    JSP pages could be created by a tool like
    Dreamweaver

19
HttpServlet Example -1
  • This web page prompts the user for the background
    color, title, and message that will be passed to
    a servlet. The servlet will read this data and
    create a new web page using the supplied
    information.

20
HttpServlet Example -2
  • In this example, the servlet will read the
    information typed into the web form and generate
    a new html document based on the user supplied
    information
  • To keep things simple, it will build the html
    string in the Java code and return it (it will
    not use JSP)
  • The form action for this web page might look
    like
  • ltform action"http//www.noaa.gov/DesignPageServle
    t"
  • method"post"gt

21
HttpServlet Example -3
import javax.servlet. import
javax.servlet.http. import java.io. import
java.util. public class DesignPageServlet
extends HttpServlet //Initialization public
void init(ServletConfig config)
throws ServletException
super.init(config)
22
HttpServlet Example -4
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
String sBKCOLOR request.getParameter("BKCOLOR")
String sTITLE request.getParameter("TITLE")
String sMESSAGE request.getParameter("MESS
AGE") response.setContentType("text/html")
PrintWriter out new PrintWriter
(response.getOutputStream())
out.println("lthtmlgtltheadgtlttitlegt")
out.println(sTITLE "lt/titlegtlt/headgt")
out.println("ltbody bgColor" sBKCOLOR "gt")
out.println("lth1gt" sTITLE "lt/h1gt")
out.println("ltbrgtltbrgt" sMESSAGE)
out.println("lt/bodygtlt/htmlgt") out.close()

23
Tomcat Setup -1
  • Tomcat is a free servlet container that you can
    download from the web
  • Download it from herehttp//tomcat.apache.org/
  • After installation, the Tomcat folder will
    contain "Start Tomcat" and "Stop Tomcat"
    shortcuts
  • Make sure you have the JAVA_HOME environment
    variable set so Tomcat can find your JDK. For
    example, if your JDK is installed in c\jdk1.5_07
    then
  • JAVA_HOMEc\jdk1.5_07
  • In Windows, you set an environment variable by
    going to control panel, System, Advanced, and
    click on the Environment Variables button

24
Tomcat Setup -2
  • By default, once Tomcat has loaded a servlet, it
    does NOT reload it even if you modify and
    recompile the servlet
  • You must stop Tomcat and then re-start it in
    order for Tomcat to load the new version of your
    servlet
  • This results in better runtime performance since
    Tomcat doesn't need to check for re-loads each
    time a web user submits a request to the servlet
  • You can override this behavior and have Tomcat
    reload the servlet each time by changing the
    "reloadable" option in the Admin Tool to "true"

25
Tomcat Setup -3
  • Once Tomcat is running, you can go to the Tomcat
    home page (on your PC)

26
Tomcat Setup -4
  • To set up a new web application (or servlet) with
    Tomcat, you need to add a directory under the
    webapps dir and create a subdirectory called
    WEB-INF.
  • WEB-INF needs to contain a web.xml file (a
    Tomcat/servlet configuration file)
  • Make sure you are consistent in the way you use
    upper case and lower case in your directory names
    (since UNIX web servers will be picky about that
    detail!)
  • The easiest thing to do is to make a copy of the
    webdav directory and give it a new name
  • After the WEB-INF directory is created, create a
    subdirectory under it called classes
  • Your Java package/classes will go under this
    directory
  • (See next slide)

27
Tomcat Setup -5
28
Tomcat Setup (Oracle Tip) -6
  • Tomcat looks for libraries that match .jar
  • In their wisdom, Oracle's JDBC driver is named
    classes12.zip.
  • In order for Tomcat to reliably load the Oracle
    driver, you need to rename it classes12.jar (and
    place it in the Tomcat/common/lib directory)

29
Tomcat Setup (mySQL Tip) -6
  • External libraries to be used by Tomcat can be
    placed in the Tomcat common/lib directory
  • For example, you might put mail.jar or mySQLs
    jar there

30
web.xml file -1
  • Tomcats web.xml contains servlet configuration
    info
  • You can find it here

31
web.xml file -2
  • web.xml contains servlet configuration info for
    Tomcat
  • You need to add a servlet entry and a servlet
    mapping entry for each servlet you want Tomcat to
    run.
  • Add your entries after the ltweb-appgt tag inside
    web.xml
  • Tipstart with existing web.xml and swap in text
    below
  • ltservletgt
  • ltservlet-namegtDesignPageServletlt/servlet-namegt
  • ltservlet-classgtgov.noaa.DesignPageServlet
  • lt/servlet-classgt
  • lt/servletgt
  • ltservlet-mappinggt
  • ltservlet-namegtDesignPageServletlt/servlet-namegt
  • lturl-patterngt/DesignPageServletlt/url-patterngt
  • lt/servlet-mappinggt

32
web.xml file -3
  • Servlet mappings are how Tomcat matches a URL to
    the correct servlet on disk
  • They arent required to have the same name
    (although it usually makes sense to keep things
    simple and give them the same name)
  • For example, the following URL in your browser
    might invoke the DesignPageServlet on Tomcat
  • http//noaa.gov8080/mywebapp/DesignPageServlet
  • is invoked with this url-pattern in web.xml
  • lturl-patterngt/DesignPageServletlt/url-patterngt

33
Tomcat Admin Tool -1
  • Tomcat comes with a web based admin tool that you
    can use to configure Tomcat
  • You don't have to use the tool--you can edit the
    config files (server.xml) manually if you know
    what you are doing
  • Or if you are satisfied with the Tomcat default
    values, you don't need to run the Admin Tool at
    all
  • Run the Admin Tool by going to the Windows Start
    Button, Apache Tomcat program group, Tomcat
    Administration
  • This will load the admin tool in a web browser
  • You will be prompted for the admin login (use the
    values you specified during the install process)

34
Tomcat Admin Tool -2
35
Tomcat Admin Tool -3
36
Servlets, Actions, and Tomcat -1
  • When Tomcat is running on your local machine, you
    specify localhost8080 in your URL (e.g. form
    action).
  • By default, Tomcat runs on port 8080
  • You can change this to port 80 (so you never have
    to specify a port number) by using the admin tool
    or by editing the tomcat-home/conf/server.xml
    file and changing the default port from 8080 to
    just 80
  • For example, the following form action would
    refer to a servlet named MyServlet that is
    running in the wms folder on Tomcat running on
    the local machine
  • ltform action'http//localhost8080/wms/MyServlet'
    methodGETgt
  • MyServlet would reside in /ltTomcatDirgt/webapps/wms
    /WEB-INF/classes

37
Servlets, Actions, and Tomcat -2
  • You could also invoke your servlet by calling it
    directly from a browser address bar

38
Servlet Development Summary
  • Step 1 Create your html web form
  • Step 2 Create your Java Servlet
  • Step 3 Create app directory under
    tomcat/webapps
  • Tip--copy webdav directory and give it new name
  • Step 4 Modify web.xml file with your Servlet
    mappings
  • Step 5 Start or re-start tomcat
  • Step 6 Test servlet from your web form,
    remembering to restart Tomcat anytime you change
    your Servlet or your web.xml file
  • Alternatively, you may be able to set
    reloadabletrue

39
Exercise 1
  • Create the "Design your own web page" web page
    (html)
  • Write your servlet class (name it
    DesignWebPageServlet)
  • Download and install Tomcat (if it has not
    already been installed on your machine)
  • Create a folder with your name (e.g. jeff) under
    the tomcat-dir/webapps directory (see earlier
    slide) and edit your web.xml file to configure
    the DesignWebPageServlet
  • Deploy your servlet to Tomcat (place your
    package/classes under the classes directory under
    the WEB-INF directory
  • Specify your form action to be a HTTP GET to your
    servlet
  • Test your web application!
  • Extra credit 1 rewrite your web page to do a
    HTTP POST
  • Extra credit 2 write an Ant script that builds
    and deploys your servlet

40
Exercise 2
  • Create a guest book web application that prompts
    the user for a name, an email address, and a
    message.
  • When the user submits this information to your
    servlet, the servlet should write the user's
    information to a text file on disk (or database
    table) and then return a web page containing the
    current entries in the guest book
  • Extra credit Add an admin feature that allows a
    user to delete a guest book entry if they know
    the admin password
  • Extra credit write an Ant script that builds and
    deploys your servlet

41
Exercise 2 (continued)
Tip start out with a simple servlet, that when
invoked from the browser simply reads a guest
book text file that you created yourself. It
should read this text file and return it to the
browser (preferably formatted nicely in an HTML
table) Tip the code that reads the guest book
file could be in a class called GuestBook.java
Write a Comment
User Comments (0)
About PowerShow.com