JAVA Servlets - PowerPoint PPT Presentation

1 / 29
About This Presentation
Title:

JAVA Servlets

Description:

Server-side Java classes, called using conventions similar to CGI. ... Perl can use other API's, and also connect to databases such as mySql and Oracle via DBI. ... – PowerPoint PPT presentation

Number of Views:33
Avg rating:3.0/5.0
Slides: 30
Provided by: tcnj
Category:
Tags: java | servlets

less

Transcript and Presenter's Notes

Title: JAVA Servlets


1
Chapter 6, 7
  • JAVA Servlets

2
IDL Examples
  • import "oaidl.idl"
  • import "ocidl.idl"
  • interface Synchronization TransactionalObject
  • void before_completion()
  • void after_completion(in Status status)
  • interface Resource
  • void prepare()
  • raises(
  • HeuristicMixed,
  • HeuristicHazard
  • )
  • interface RecoveryCoordinator
  • Status replay_completion(in Resource r)
  • raises(NotPrepared)

3
Servlets
  • Server-side Java classes, called using
    conventions similar to CGI.
  • They are usually an extension of HttpServlet
    class.
  • A URL calls a servlet in the same way a Perl
    script is called.

4
Servlet Programming
  • CGI (Common Gateway Interface)
  • Scripts are called from a URL, instead of
    embedded in an HTML page (submit), executed on/in
    the web server, and usually cretae a dynamic HTML
    page to be returned back.
  • Ex Perl, C, Unix shell scripts can utilize CGI.

5
Servlet Programming
  • Plug-Ins
  • ISAPI, NSAPI used for interfacing directly with a
    web servers API for resources.
  • Not very portable
  • Server-Side Includes
  • HTML extensions used to process code on the
    server.
  • .ASP, .JSP, server-side classes called from
    .jsp/servlets
  • Can be used to invoke .exes on the server

6
Perl
  • PG 136/137
  • HTML page contains an interface to a
    server-side perl script.
  • Form controls (and the submit button) can be used
    to build the URL that invokes the perl script,
    and post data to the script.
  • Perl can use other APIs, and also connect to
    databases such as mySql and Oracle via DBI.
  • Perl scripts are closed after each call
    (including any DB connections opened).

7
Posts / Gets
  • POSTS allow for fields to be read from an HTML
    page (they send an HTML body over).
  • GETS require all fields to be part of the URL.
  • Examples
  • www.tcnj.edu/new_student.pl?namejimssn123456789
  • www.tcnj.edu/new_student.pl(body containing
    field names/vales sent over after )

8
Servlet Architecture
  • Servlets, unlike Perl scripts, do not get
    destroyed after each call.
  • The first time a servlet is called (from any
    client), it is instantiated by the server (using
    a method called init(), equiv. to a constructor
    being called).
  • The public procedure (post or get) is then
    called.
  • This public procedure can then call a number of
    private procs, jdbc, or other classes.

9
Servlet Architecture
  • Subsequent calls to the servlet (from any
    client), will only call the public procedure
    (post, get, etc..).
  • If a database connection is used, that should be
    established either outside the servlet, or in the
    init().
  • Servlets are scalable, and managed by the server
    (assumes youre in multithreaded mode).

10
import java.io.import javax.servlet.import
javax.servlet.http.public class
BookReviewServlet extends HttpServlet
// Write a response to the client.
public void doPost(HttpServletRequest req,
HttpServletResponse res) throws
ServletException, IOException
res.setContentType("text/html") //Get the
response's PrintWriter to return text to the
client. PrintWriter toClient
res.getWriter() String fName
req.getParameter("fname") String chp
req.getParameter("favchap") String
writeServlet req.getParameter("writeservlet")

11
// Respond to client with a thank
you toClient.println("ltHTMLgt") toClient.print
ln("ltTITLEgtBook Review Responselt/TITLEgt") toCli
ent.print(fName) toClient.println(", thank you
for your feedback.ltBRgt") toClient.print("Your
favorite chapter so far is chapter
") toClient.println(chp ".ltBRgt") toClient.
println("lt/HTMLgt") // Close the writer
the response is done. toClient.close()

12
Servlet Chaining
  • When a URL (HTML Interface) calls a servlet, and
    that servlet returns the output (HTML) from
    another servlet that it calls.
  • First servlet creates a URL object that is a call
    to another servlet.

13
Chapter 7Servlet Programming
  • Servlet API
  • init() called only when a servlet is
    instantiated.
  • service(ServletRequest, ServletResponse) called
    after init() (for first call), and during each
    servlet request.
  • destroy() called once when servlet is unloaded
    by the server.

14
Servlet Programming
  • Servlet API
  • ServletRequest input stream that contains
    session information, including all variables from
    the URL
  • ServletResponse output stream used to pass back
    HTML or other type of output (images, serialized
    java objects, etc)

15
ServletRequestHttpServletRequest
  • Common methods for these objects
  • getContentType() HTML, GIF, etc
  • getInputStream() binarystream
  • getParameter(name) returns value of specified
    parameter
  • getParameterNames() returns list of parameter
    names
  • getParameterValues(name) returns array of values
    if parameter returns more then one
  • getCookies() returns an array of all cookies
    from req.
  • getSession() returns HTTPSession object from
    req.

16
ServletResponseHttpServletResponse
  • Common methods for these objects
  • getOutputStream() binary stream (for non-text
    data)
  • getWriter() text stream
  • sendRedirect(url) redirects output to new URL
  • addCookie(cookie) adds a cookie to the HTTP
    header
  • setContentType() sets return type

17
HttpSessions
  • Used for tracking individual client/session
    information.
  • Because HTTP is stateless, this creates a state
    for a particular session between client calls to
    the servlet.
  • A session id is passed between client servlets.

18
HttpSessions
  • Sessions may be implemented as cookies, if
    theyre supported by the browser. Else, they use
    UTL directly (as encoded). This is all
    transparent to the developer, and controlled by
    the server.
  • Sessions are portable, and values can be java
    objects as well as just strings or ints.
    Sessions can also be saved by serializing the
    objects.

19
Cookies
  • Only store strings, and only on the client.
    Always permanent, up to expiration date.
  • Associated with a specific server and path, for a
    layer of protection against other servers reading
    them.

20
Servlets Applets
  • Extends the portability issue of servlets onto
    the client interfaces (Applets are just as
    portable of servlets).
  • Servlets can be designed to return text or binary
    data instead of HTML. This data can be sent back
    to Applets to populate datagrids, listboxes, and
    other controls, or to call business logic on the
    server.

21
Servlets Applets
  • Ideally, servlets should be designed
    independantly of the client calling them. Clients
    could then pass as a param, the return type.The
    same servlet from different clients (HTML or
    Applets) can then be used by switching the return
    type.
  • Pg 186 uses a servlet returning text, that the
    Applet displays.

22
Applet Code For Servlets
  • // create a new URL (same as typing in browser)
  • URL url new URL(HTTP,141.12.24.232,1521,s
    rvMsg?msgHi)
  • // use this to retrieve data from the servlet
  • InputStream in url.openStream()

23
Notes On Servlet Design
  • Validate ALL User Input (and ignore case).
  • Account for missing fields.
  • Assume the servlet will be hacked. Dont send
    back files based on user-entered paths.
  • Dont use servlets for static HTML pages. Only
    for true dynamic content and/or database
    connectivity.

24
Tomcat Servlet/JSP Enginehttp//jakarta.apache.or
g/tomcat/index.html
  • From Apaches JAKARTA project.
  • Can run standalone, without another web server
    (including Apache).
  • Installs on Win95-2000, or Unix.
  • You can install yourself on a PC, or use the
    installation on springfield.

25
Tomcat Servlet/JSP Engine
  • To Install Yourself
  • Download build 3.1(jakarta-tomcat.zip 2.4MG)
  • Unzip fromc\ to create a c\tomcat directory and
    subdirectories
  • Set these two env. Vars up
  • TOMCAT_HOMEc\tomcat
  • JAVA_HOMEc\jdk1.2.2 (or your path)
  • Execute it - youre done!
  • c\tomcat\bin\startup

26
Tomcat Servlet/JSP Engine
  • By default, this will run from port
    8080(httplocalhost8080/servletdir)
  • Notes
  • If you have problems running it, change the
    startup.bat to run the server from the same DOS
    prompt, so you can see the error.
  • If you get an out of environment error, add the
    Classpaths to each JAVA call instead of setting
    up front (make sure ALL of them are changed - not
    just the RUN).

27
Tomcat Servlet/JSP Engine
  • or
  • Use TCNJs tomcat installation.
  • Follow the guide handed out.

28
Chap. 8 Servlet Based - Search Enginer
  • Use this as an example of a live servlet using
    Tomcat Servlet engine.
  • Understand all the classes that make up the
    application, including the index package (import
    index.)

29
Homework
  • Install and run the servlet-based search engine
    in Chap. 8 (pg 215)
  • Queries a web server directory of your choice.
  • INCLUDE YOUR NAME on the query index.html page,
    above the Query textboxEX Jims Search
    Engine.
  • HAND-IN
  • Development Environment (NT, Unix, etc)
  • Example query screen and results page.
Write a Comment
User Comments (0)
About PowerShow.com