Servlets - PowerPoint PPT Presentation

1 / 27
About This Presentation
Title:

Servlets

Description:

page autoFlush='true' % Tells JSP to flush the page buffer when it fills ... page language='lang' % Sets the JSP script language to lang ... – PowerPoint PPT presentation

Number of Views:320
Avg rating:3.0/5.0
Slides: 28
Provided by: chme3
Category:
Tags: jsp | servlets

less

Transcript and Presenter's Notes

Title: Servlets


1
Servlets
  • Server Side Web Based Java Programming

2
What are Servlets
  • Extensions to Java enabled servers
  • Servlet containers e.g.
  • Tomcat
  • Jetty
  • Server side replacement for CGI
  • Dynamically loaded module
  • Runs inside java virtual machine

3
Why Use Servlets
  • Efficient
  • Servlet loaded and Init method called once
  • Service method called everytime servlet requested
  • Persistent
  • As servlet stays running between requests, can
    maintain client state
  • Portable
  • Java byte code not tied to a particular platform
  • Secure
  • Can run within a security manager

4
Servlet Interface
  • init method
  • Called once when the servlet instantiated
  • service method
  • Called every time a client request is received
  • destroy method
  • Called when service is shutdown
  • GenericServlet implements this interface

5
HttpServlet
  • Has init, service and destroy methods
  • doGet method
  • Override the doGet method to process get requests
  • doPost method
  • Override the doPost method to process get
    requests
  • A processRequest method
  • Can be called by post and get methods

6
Using Netbeans to Create Servlets
  • Create a New Web Project
  • Choose a Web Application
  • Choose location for Project and Files
  • Accept defaults
  • This creates the necessary structure for
    deploying jsps and servlets to the Netbeans built
    in tomcat servlet container
  • Right click sources directory
  • Create Servlet
  • Uncomment text and run file
  • Or a Web Application with sources (if servlet
    code already exists)
  • Right click servlet in sources directory
  • Run file
  • Right click sources directory
  • Create Servlet
  • Specify Servlet Name and URL pattern
  • Note URL pattern shows how the servlet will be
    called
  • Uncomment text and run file
  • Edit the servlet to actually print some relevant
    content

7
Using Netbeans to Compile and Run
  • Compile the servlet
  • Right click servlet and compile
  • Test the servlet by running it
  • Right click servlet and select Run File
  • In browser select appropriate URL (e.g.
    http//localhost8080/servlet/myServlet)
  • Note Look at the web.xml file in the WEB-INF
    directory to see the servlet mappings that have
    been defined

8
HelloWorld Servlet
  • protected void processRequest(HttpServletRequest
    request, HttpServletResponse response) throws
    ServletException, IOException
  • response.setContentType("text/html")
  • PrintWriter out response.getWriter()
  • out.println("lthtmlgtltheadgtlttitlegtServletlt/titlegtlt/
    headgt")
  • out.println("ltbodygt")
  • out.println("Hello World")
  • out.println("lt/bodygtlt/htmlgt")
  • out.close()

9
Servlet Objects
  • Request Object
  • Contains references to HTTP Request variables
  • E.g. methods
  • getParameter read paramater values from Request
    Object
  • Following not normally used
  • getReader Retrieve request body as a Character
    Input Stream
  • getInputStream Retrieve request body as a bit
    Input Stream
  • Response Object
  • Encapsulates HTTP Response
  • E.g. methods
  • setContentType
  • getWriter Retrieve response body as a Character
    Output Stream
  • getOutputStream Retrieve response body as a bit
    Output Stream

10
Processing Form Variables
  • Use request objects getParameter(parameter)
    method
  • Returns string value of parameter
  • if more than one value only the first is given
  • getParameterNames()
  • Returns enumeration of parameter names
  • getParameterValues(parameter)
  • Returns string array of parameter values
  • Useful for multiple values

11
Session Variables
  • Create a session
  • HttpSession theSession req.getSession(true)
  • Retrieve session ID
  • theSession.getId()
  • Retrieve given session variable value
  • getAttribute(Name)
  • Store a Session variable value
  • void setAttribute(Name, Chris)
  • Remove a session variable
  • void removeAttribute(Name)
  • Retrieve enumeration of session variable names
  • Enumeration getAttributeNames()

12
Accessing Databases
  • Load the database driver
  • Class.forName("org.gjt.mm.mysql.Driver").newInstan
    ce()
  • Connect to database
  • theConnection DriverManager.getConnection("jdbc
    mysql//127.0.0.13306/Test2")
  • Create a statement object
  • Statement theStatementtheConnection.createStateme
    nt()
  • Execute a query
  • ResultSet theResulttheStatement.executeQuery("sel
    ect from sRecord")
  • Loop through results
  • while(theResult.next()).
  • Accessing returned result elements
  • theResult.getString(1) ..
  • Close the resources
  • Catch errors and exceptions in a try ..
    catch() block

13
Database Pooling
  • Allows Servlets to share connections
  • Pooled Connections stay open, more efficient
  • Faster response from servlets that interact with
    databases
  • Available in jdk 1.4.2
  • Pooled Datasource is initialised in the init
    method
  • Lookup process can take time, so just done once
  • Access to Datasource is via a synchronised block,
    so multiple servlet calls do not access same
    datasource

14
Additional Servlet Examples
  • response.sendRedirect(Location)
  • Uses http headers to request browser to load
    another page
  • Location is a string with the absolute URL
  • rdrequest.getRequestDispatcher(Resource)
  • rd.forward(request,response)
  • Forwards the current request to a resource on the
    current server. Does not use http.

15
Java Server Pages (JSPs)
  • Similar concept to PHP, ASP etc
  • Java code is embedded in HTML documents
  • lt gt
  • Tags used to embed code
  • HelloWorld JSP example

16
JSP scriptlets
  • Can add multiple scriplets on the JSP page
  • All the scriplets share the same context
  • Can access variables declared in different
    scriplets on the same page
  • All variables are local to service method
  • JSP comments
  • lt-- This is a JSP Comment --gt
  • Declare class level variables
  • lt! String name "Chris" gt

17
JSP directives
  • Directives added to page using lt_at_ gt tags
  • Used to import classes for the page
  • lt_at_ page import"java.util." gt
  • Declare HTTP headers, such as content type etc.
  • lt_at_page contentType"text/html"gt
  • Include Files into Current Context
  • lt_at_ include file"Date.jsp" gt

18
Additional JSP directives
  • lt_at_ page autoFlush"true" gtTells JSP to flush
    the page buffer when it fills
  • lt_at_ page buffersizekb gtGives the size of the
    page buffer in kb or none for no buffer
  • lt_at_ page errorPage"path" gtDefines a page to
    display if an error occurs in the JSP page
  • lt_at_ page info"description" gtGives a brief
    description for the page
  • lt_at_ page isErrorPage"true" gtGives an error page
    access to the exception implicit variable
  • lt_at_ page isThreadSafe"true" gtTells the JSP that
    multiple pages can execute in parallel
  • lt_at_ page language"lang" gtSets the JSP script
    language to lang
  • lt_at_ page session"true" gtTells JSP that the page
    participates in a session

19
JSP Implicit Objects
  • request
  • response
  • out
  • session
  • etc

20
JSP tags
  • Rather than using scriplets and java code
  • Code action can be included as HTML tags (useful
    for Web development IDEs)
  • ltjspinclude page"Date.jsp"gt
  • ltjspparam name"ParamName1" value"ParamValue1"
    /gt
  • lt/jspincludegt
  • ltjspforward page"PrintDate.jsp"/gt
  • Forwarding redirects to current page clearing any
    content that already has been buffered
  • Exception generated when content already has been
    sent
  • Increase size of buffer if this might be a
    problem
  • lt_at_ page buffer"12kb" gt

21
Additional Tags
  • jspplugin
  • To include an applet using the java plugin
  • jspusebean
  • Discussed later for using a javabean class
  • ltjspparamgt
  • Used inside include, forward and plugin tags

22
JavaBeans
  • Reusable software component
  • Seperate business logic from displayed HTML
  • Features of JavaBeans
  • a public class,
  • a public constructor with no arguments
  • public get and set methods to read and write to
    properties.
  • Make JavaBean part of a package
  • most servlet/JSP containers require it

23
JavaBean tags
  • ltjspuseBean id "myBean" scope"session" class
    myPkg.myBean" /gt
  • Specify which class the myBean referes to
  • ltjspsetProperty name "myBean" property
    "firstName value "Chris" /gt
  • Set a particular property value
  • ltjspgetProperty name "myBean" property
    "fullName" /gt
  • Get a particular property value
  • ltjspsetProperty name"BeanName" property"" /gt
  • Used to set all properties available from form
    variables

24
Tag Libraries
  • It is possible to create your own JSP tags
  • This is done by creating a Tag Handler class
  • A Tag Library descriptor file is also required so
    that the interface to the tag library is well
    defined
  • Custom tags
  • allow tag based content creation tools to easily
    add program elements to your code

25
JSP Standard Template Library (JSTL)
  • Part of JSP 1.2 and 2.0 specification
  • Available on version of tomcat in netbeans 6,
    otherwise add JSTL files to the applications lib
    directories
  • All scripting uses tag based syntax
  • Suitable for tools that automatically generate
    tags
  • E.g.
  • lt_at_ taglib uri"http//java.sun.com/jstl/core"
    prefix"c" gt
  • ltcforEach var"i" begin"1" end"10" step"1"gt
  • ltcout value"i" /gt ltbr /gt
  • lt/cforEachgt
  • Web.xml file must be modified with the location
    of the tdl files
  • lttaglibgt
  • lttaglib-urigthttp//java.sun.com/jstl/corelt/tag
    lib-urigt
  • lttaglib-locationgt/META-INF/c.tldlt/taglib-locat
    iongt
  • lt/taglibgt

26
More JSTL
  • ltcset var"foo" scope"session" value"..."/gt
  • ltcif test"!empty param.Add"gt . lt/cifgt
  • ltcchoosegt   
  • ltcwhen test"input '1'"gt...lt/cwhengt
  • ltcotherwisegt     ...   lt/cotherwisegt
  • lt/cchoosegt
  • ltcforEach var"item" items"sessionScope.item"
    gt   ... lt/cforEachgt

27
Summary
Main points to remember Servlet
Concepts Request and response objects Session
variables Database access JSPs JavaBeans Tag
Libraries JSTL
Write a Comment
User Comments (0)
About PowerShow.com