ervlet introduc
Download
Report
Transcript ervlet introduc
Servlets
Server-side java programming
Material in this ppt is partly gleaned from
chapters 1 and 2 of Jason Hunter’s text, but
also includes Tomcat installation information.
remarks
• Javax.servlet and javax.servlet.http packages
were the first java classes to be released as
open source and now reside at Apache Software
Foundation.
• Open-source developers like Hunter handle bug
fixes.
• Tomcat is the official servlet container
specification and is open-sourced.
• Hunter’s book covers Servlet 2.2 API
• Text examples may still be available at
http://www.oreilly.com/catalog/jservlet2
What are the (server-side) options?
•
•
•
•
•
•
•
•
•
•
CGI
fastGCI
PerlEx
modPerl – Apache web server only.
Server extensions: WAI and ISAPI
Server-side javascript
ASP
JSP
PHP
ColdFusion, …
CGI and fast CGI
• Expression-processing in Perl makes it a good language
to use for CGI.
• CGI has been around a long time.
• Client requests for CGI-bin cause the server to run the
programs.
• Each perl program runs in its own process and its own
perl interpreter.
• This creates substantial server overhead.
• Although fastCGI does not spawn a new process for
every request (just one for each unique program being
requested) there is still a lot of overhead.
Server extensions: WAI and ISAPI
• Using these you can extend the basic
functionality of the server.
• The extensions exist inside the main server
process.
• These use linked C or C++ and run very fast.
• But – they are difficult to develop and maintain,
and a problem with one can bring down the
server.
• Proprietary extensions are tied to the server API
and possibly OS for which they were developed.
ASP and Server-side javascript
• MS developed ASP which allows code snippets in
VBScript or Javascript or other languages to be inserted
into HTML creating dynamic web pages. The code is
read and executed by the server before being sent to the
client. COM components provide support for ASP. ASP
can be installed on non-windows platforms from 3rd party
vendors (like Chili!Soft) but such ASP installations will
not have the COM library support. ASP is essentially
MS-proprietary.
• iPlanet/Netscape has developed server-side scripting
called server-side javascript. SSJS allows snippets of
code to be inserted into html to create active content.
SSJS uses javascript as the script language. Support for
SSJS is provided only by iPlanet/Netscape.
JSP
• JSP are discussed elsewhere and we’ll
probably write some, even if just for hw.
• These are compiled into servlets, so the servlet
container is needed to support these.
• The compilation process does create some
overhead. This can be mitigated if the jsp are
(pre-)compiled at server start-up.
• JSP are a better was to present “mostly” html
content to the client than servlets. They provide
a mechanism for inserting java code as the
scripting element into html, much as ASP used
VBScript.
SERVLETS
• JSP specification is based on servlet specification (recall JSP are
compiled into servlets). And JSP are often combined with servlets in
a web app.
• Like CGI, NSAPI and ISAPI, servlets add new functionality to a
server. They are written in java and can run on any system with a
JRE, (but will need a servlet container!)
• Servlets can take advantage of other java technologies: JDBC,
JNDI, RMI and so on.
• Servlets execute as individual threads and reside in the server web
app until it is shut down. (Recall CGI generates a new thread for
each request).
• Servlet apps are scalable.
• Java is more robust than Perl or C++.
Servlet containers
• This is the connection between the web server
and the servlets. It provides a runtime
environment, loads and invokes servlets.
• Some containers are addons or plugins and
provide servlet support if the server doesn’t have
it (like Apache or IIS). Containers can be standalone servers or embedded.
• The servlet container maps the request to a
servlet handling this URI. The container must
also convert the servlet response into an http
response and return it to the client.
Servlet contexts and web apps
• A java web app may consist of JSP, servlets, applets, static html,
custom tag libraries and other java classes. Containers compliant
with Servlet 2.2 specifications provide a standard portable resource
packaging mechanism and a web app deployment descriptor
describing how the resources fit together.
• All these files are arranged in a pre-defined file hierarchy (and may
be packaged as a web-archive file. This is an archived file, built
using the jar utility but having a .war extension.)
• They may be arranged in the requisite hierarchical structure within
the Webapps directory and are automatically deployed on startup by
the server.
• Each web app is represented by a servlet context associated with a
unique URI path prefix called the context path.
• The various contexts are hermetic. A context can hold objects
shared by other components of the web app, like DB connections.
• These specifications are also applied to JSP
Servlet directory structures
• In the webapps directory of jakarta/tomcat
create a directory for your work, let’s say you call
it MyStuff
• Create 2 directories, servlets and web-inf
under MyStuff.
• In servlets, you will put all your servlet.html files.
• In web-inf you will place web.xml (your servlet
information file) and a directory called classes,
where you’ll place the servlet.class files.
Directory Structure
Jakarta/tomcat
Webapps
ROOT
Other directories
myexamples
Servlets- put html in here
Web-inf
web.xml
Classes- put the .class files in here
web-inf
• The files in web-inf are not served to the client,
they are classes and configuration information
for the web app. Web-inf/ classes contains class
files. Web-inf lib contains class files stored as jar
files (java-archive)
• Web.xml in web-inf is a deployment descriptor. It
contains configuration information about the web
app in which it resides.
• Hunter’s book contains the full DTD for web.xml
in appendix C.
HTTP and servlet basics
(Chapter 2 of Hunter)
• A web application is an application running
on a server accessible via a thin client, like
a browser. (Client might also be PDA, cell
phone, …)
• HTTP defines the way clients and servers
communicate.
The HTTP request/response model
•
•
1.
2.
3.
A client sends a request to a server, the server returns
a response corresponding to the requested resource
or an error message.
Three factors are implied in this model:
HTTP is stateless. The server doesn’t remember client
(requests) once they’ve been processed.
Web applications have trouble providing immediate
responses like desktop GUI-based software.
The server can’t tell how the request was made: Was a
button pressed or a window resized? The server can’t
look at the browser history or send the response to a
particular window. The server doesn’t know when the
user closes the browser.
Requests
• A browser requests a particular resource from a
particular server via an HTTP URL:
http://employees.oneonta.edu/higgindm/index.ht
ml
• The request has the syntax: protocol (http)server name (employees.oneonta.edu)resource (my home page).
• Servers typically listen on port 80. Your tomcat
server will listen (by default) on port 8080 as in
• http://csci345.oneonta.edu:8080/myexamp
les/servlets/ServletDirectory.html
URL…URI… URN
• A URL is a specialized form of a URI,
universal resource identifier. A URN is a
universal resource name. HTTP handles
only URL. URL refers, generally, to the
format above, protocol-server (optional
port#)-resource. URI might be used once
we are at the server and only the identifier
part of the resource is needed.
A request
A request to a server consists of
• A request line
• A header
• Possibly a request body
The request line specifies the method name (like get or post) followed
by the URI and protocol version # as in:
GET /index.html HTTP/1.1
A GET request retrieves a resource and it is the default. The header
provides additional information the server might use and a message
body is only included in certain requests.
The request also contains information about character sets, image
types, language, type of browser, etc. The requested URI might be
a static page, a database record, an executable program.
Response structure
• The response consists of a status line, response
headers and (optionally) a body.
• The status line starts with the protocol, a status
code.
• The headers indicate date of last modification of
the resource. Content-type and length are also
included.
• The body might be an html page:
<html><body>
Hello world
</body></html>
Request parameters
• Besides the URI and headers a request
message may contain parameters. A
parameter might be a zip code submitted
to weather.com. They can be tacked on to
the URI as a query string or included in the
body. A query string starts with ‘?’ and
consists of name/value pairs separated by
‘&’. Characters may need special encoding
so they are not confused with URI and
meta characters.
Request methods
• GET and POST are the most common methods.
POST requests some processing on the server
like updating a database or processing an order.
• A GET uses a query string for parameters and a
POST puts them in the request body.
• An html form tag allows GET or POST method to
be specified.
• A GET request can easily be saved and
reloaded, a POST cannot.
Get vs Post
• A get operation “gets” information. It is like
reading from a bulletin board. It is the
default.
• A post operation may “post” information to
the server.
• Get operations may have only limited
allowable length (for parameters).
• Post operations generally allow transfer of
a lot of data.
Get vs Post: Which method should
you use?
• In fact it doesn’t matter much and a call to
doPost() could even simply call doGet() in
its body or visa versa.
• But a get can be bookmarked and server
security prohibits saving of data from a
post, so you should not generally use a
get to do post operations (save to a
database, eg.)
Other methods
• OPTIONS- what options are available for this
URI?
• HEAD- send all headers generated by GET
• PUT- store message body on the server as a
resource accessible via the URI
• DELETE: delete this URI
• TRACE: return request as response body to test
communication between client and server.
Javax.servlet.Servlet and
HTTPServlet and GenericServlet
• Every servlet must implement
javax.servlet.Servlet
• Most do this by implementing either the
GenericServlet (javax.servlet.GenericServlet) or
HTTPServlet (javax.servlet.http.HttpServlet)
interface.
• Like Applets, servlets have no main() method.
The server invokes servlet methods to handle a
request just as a browser invokes applet
methods (start, init, etc).
• When a servlet is dispatched its service()
method is called.
More servlet basics
• A GenericServlet should override its
service() method. This method gets a
request and a response object as
parameters.
• An Http Servlet overrides either doGet() or
doPost() methods, or both. HTTP Servlet
service() method handles dispatching to a
doXXX() method and should not be
overridden.
Other methods
• HTTP servlet can override doPut() and
doDelete() but doTrace() and doOptions()
are handled by default (server)
implementations.
Hello world servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld 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("<BIG>Hello World</BIG>");
out.println("</BODY></HTML>");
}
}
API remark
• Java API:
http://java.sun.com/j2se/1.5.0/docs/api/
• PrintWriter extends Writer and can write
String, boolean, double, float, int, char[],
and even an object. It also has flush() and
close() methods. It can be formatted with
a format string.
About Hello World servlet
• Page generation: refers to servlets which
write an html page by sending
<html>…</html> to the response writer
(see above: response.getWriter() etc)
• In webapp design, this may not prove to
be a good separation of service delivery,
since any GUI upgrade or change will also
involve changes to your processing
(server-side) code.
deployment
• You’ll need to compile servlets, which you can
do anywhere, but you’ll need the javax.servlet
classes which come with Tomcat so you can do
your compilation there.
• Server_root/lib/servlet.jar contains the servlet
stuff.
• You’ll need to set classpaths properly to get
compiles to work.
• I just copied javax.servlet to my java/bin and do
compiling there.
To run the example(s)
• Place the class file as per above, in
tomcat/webapps/…web-inf/classes
directory
• You’ll have to edit the web.xml deployment
info that the server uses which is also in
the web-inf directory.
• If there is an html file that calls the servlet
you’ll need to place that in the servlet
directory under your webapp directory.
about xml in general and web.xml
• XML files may have a required format – some
have a document type description or dtd. Some
have a schema, which is itself an xml. XML files
can be validated against their format and some
processors may reject poorly formed XML.
• web.xml conforms to a DTD. You can find the
DTD (or schema) for this in Hunter’s book’s
appendices. Tomcat will not successfully deploy
your servlets if you foul up the web.xml format.
• Our Core Servlets covers this material starting
on page 60.
Sample web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
<servlet>
<servlet-name>
hi
</servlet-name>
<servlet-class>
HelloWorld
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>
hi
</servlet-name>
<url-pattern>
/hello.html
</url-pattern>
</servlet-mapping>
</web-app>
Development tools
• I have a zip file containing some useful
tools.
• It contains a class called Servlet Server.
Unfortunately it is compiled with 1.4 java,
so you’ll have to point it to a 1.4 jre in
order to get it to work.
• It is useful only for testing, not deployment.
Batch file for ServletServer
set path=c:\compilers\j2sdk1.4.1_01\bin\
set jdkhome=c:\compilers\j2sdk1.4.1_01\bin\
set
classpath=c:\compilers\j2sdk1.4.1_01\bin\;p:\;p:\classes;
c:\compilers\j2sdk1.4.1_01\lib
p:\classes
cd p:\classes
p:
:start
start /wait /Dp:\classes java ServletServer
goto start
DOS window for batch file
P:\classes>set path=c:\compilers\j2sdk1.4.1_01\bin\
P:\classes>set jdkhome=c:\compilers\j2sdk1.4.1_01\bin\
P:\classes>set
classpath=c:\compilers\j2sdk1.4.1_01\bin\;p:\;p:\classes;c:\compi
lers\j2sdk1.4.1_01\lib
P:\classes>p:\classes
'p:\classes' is not recognized as an internal or external command,
operable program or batch file.
P:\classes>cd p:\classes
P:\classes>p:
P:\classes>start /wait /Dp:\classes java ServletServer
DOS window for server
More about ServletServer
• This is a mini server for testing servlets. Like
Tomcat, it listens at port 8080 (so you can’t run
both at the same time without changing default
port number).
• It has no interface or configuration or
deployment settings.
• You can test a servlet by running it directly.
• It does not load html.
• (These files are on my p drive.)
ServletServer
• It is a pain in the neck to have two java versions
and to try to remember which one to use but
ServletServer does provide a nicer way to test
your servlets than having to complete
deployment using web.xml in Tomcat.
• You can use the default servlet context and this
sidesteps editing web.xml. This solution is for
development (or classroom) use only, not for
production.
Servlet1.java source (similar to HelloWorld)
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class Servlet1 extends HttpServlet {
//Initialize global variables
public void init(ServletConfig config) throws ServletException {
super.init(config); }
//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = new PrintWriter (response.getOutputStream());
out.println("<html>");
out.println("<head><title>Servlet1</title></head>");
out.println("<body>");
out.println("Hello World...Servlet1 is running!");
out.println("</body></html>");
out.close(); }
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request,response);
}
//Get Servlet information
public String getServletInfo() { return "untitled3.Servlet1 Information"; }
}
Running Servlet1
com.oreilly.servlet.*.class files
• You can download utility classes used in
the text in addition to the text examples,
and you’ll need them to run some of the
examples.
• These can be found at the book’s website.
• You’ll need to save them in their package
hierarchical structure. (as per the heading
above)
Here’s my p:\classes\com\oreilly\servlet
directory (copied after I unzipped download)
A form whose Get action runs a
servlet
<HTML>
<HEAD>
<TITLE>Introductions</TITLE>
</HEAD>
<BODY>
<FORM METHOD=GET
ACTION="http://csci345.oneonta.edu:8080/servlet/Hello">
If you don't mind me asking, what is your name?
<INPUT TYPE=TEXT NAME="name"><P>
<INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>
In IE
The servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Hello extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String name = req.getParameter("name");
out.println("<HTML>");
out.println("<HEAD><TITLE>Hello, " + name + "</TITLE></HEAD>");
out.println("<BODY>");
out.println("Hello, " + name);
out.println("</BODY></HTML>");
}
public String getServletInfo() {
return "A servlet that knows the name of the person to whom it's" +
"saying hello";
}
}
In IE
servlet which pastes in a name
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Hello extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String name = req.getParameter("name");
out.println("<HTML>");
out.println("<HEAD><TITLE>Hello, " + name + "</TITLE></HEAD>");
out.println("<BODY>");
out.println("Hello, " + name);
out.println("</BODY></HTML>"); }
public String getServletInfo() {
return "A servlet that knows the name of the person to whom it's" +
"saying hello";
}}
Handling post request via doGet()
method
• If a form had:
<FORM METHOD=POST ACTION=“servlets/Hello”>
• The servlet could provide a post method which simply
called get:
public void doPost(HttpServletRequest req, HttpServletResponse
res) throws ServletException,IOException{
doGet(req,res);}
Modifying form & Hello servlet to
handle Post request
<HTML>
<HEAD>
<TITLE>Introductions</TITLE>
</HEAD>
<BODY>
<FORM METHOD=POST
ACTION="http://localhost:8080/servlet/Hello">
If you don't mind me asking, what is your name?
<INPUT TYPE=TEXT NAME="name"><P>
<INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>
Modifying Hello to handle Post
Form & servlet with post action
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Hello extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String name = req.getParameter("name");
out.println("<HTML>");
out.println("<HEAD><TITLE>Hello, " + name + "</TITLE></HEAD>");
out.println("<BODY>");
out.println("Hello, " + name);
out.println("</BODY></HTML>");
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doGet(req,res); }
public String getServletInfo() {
return "A servlet that knows the name of the person to whom it's" +
"saying hello";
}
}
Handling head-only requests
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
if(req.getMethod().equals(“HEAD”))return;//leave after setting head info
PrintWriter out = res.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>Hello World</TITLE></HEAD>");
out.println("<BODY>");
out.println("<BIG>Hello World</BIG>");
out.println("</BODY></HTML>");
}
}
A few variations of welcome servlet
posted at:
• http://csci345.oneonta.edu:8080/myexamples/servlets/WelcomeServ
let.html
• http://csci345.oneonta.edu:8080/myexamples/servlets/WelcomeServ
let2.html
• http://csci345.oneonta.edu:8080/myexamples/servlets/WelcomeServ
let2B.html
• http://csci345.oneonta.edu:8080/myexamples/servlets/WelcomeServ
let3.html
• http://csci345.oneonta.edu:8080/myexamples/servlets/WelcomeServ
let4.html