Sunteți pe pagina 1din 20

Datenbank-Praktikum

Universität zu Lübeck
Sommersemester 2006
Lecture: Servlet/JSP

Ho Ngoc Duc 1
Learning objectives

n Overview of Servlet technology


n Servlet life cycle
n Handling the client request

n Reference
q Sun Microsystems, J2EE Tutorial
q Marty Hall, Core Servlets and JSP

Ho Ngoc Duc 2
Overview of Servlet technology

n A servlet is a Java class that is designed to respond


with dynamic content to client requests over a
network
n Servlets extend request/response-oriented servers
q Most widely used within HTTP servers
q Java technology that can replace CGI programs
n Efficient: threads instead of OS processes,
n Convenient: lots of high-level utilities
n Portable: virtually all operating systems and servers
n Secure: no shell escapes, no buffer overflows

Ho Ngoc Duc 3
Architecture

n Servlets are installed in web containers


(servlet container) as part of web applications
q A web container can be an add-on component to
an HTTP server, or a standalone server
n When server recognizes that the service of a
servlet is requested: pass request to it
n What a servlet does:
q Read data sent by client
q Generate the results
q Send data back to client

Ho Ngoc Duc 4
Writing Servlets

n All servlets implement the


javax.servlet.Servlet interface
n Typically: write servlets that extend
javax.servlet.http.HttpServlet
q Abstract implementation of Servlet interface,
specially designed to handle HTTP requests
n Override doGet() or doPost() method to
handle GET or POST requests

Ho Ngoc Duc 5
The Servlet Life Cycle

n init()
q Executed once when the servlet is first loaded
n service()
q Called in a new thread by server for each request
q Dispatches to doGet, doPost, etc.
n doGet(), doPost(), doXxx()
q Handles GET, POST, etc. requests
q Override these methods to provide desired behavior
q Same servlet instance in different threads!
n destroy()
q Called when server deletes servlet instance

Ho Ngoc Duc 6
HelloWorld Servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloPlain extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello World");
}
}

• Not really dynamic page, but easy to add dynamic content


• When doGet() or doPost() called, the servlet container creates
HttpServletRequest and HttpServletResponse objects and passes them in as
parameters to these request handler methods
• The response object has getOutputStream() and getWriter()

Ho Ngoc Duc 7
Compiling the HelloWorld servlet

n Make sure you have the Servlet API classes


(javax.servlet, javax.servlet.http) in your
CLASSPATH
q $TOMCAT5_HOME/common/lib/servlet-api.jar
q $TOMCAT4_HOME/common/lib/servlet.jar
n Either set the CLASSPATH environment
variable, or run javac with –classpath
q javac -classpath .../servlet.jar HelloWorld.java
n Using Eclipse: add servlet.jar to project build
path
Ho Ngoc Duc 8
Deploying HelloWorld servlet

n In Jakarta Tomcat: web applications located under


$TOMCAT_HOME/webapps/
q Each web application usually a subdirectory
n Each web applications consist of static HTML files,
multimedia resources, servlets...
q Code for the servlets: WEB-INF/classes (class files) or
WEB-INF/lib (jar archives)
q To deploy in sample web app: copy HelloWorld.class to
$TOMCAT4_HOME/webapps/examples/WEB-INF/classes/
q Then access it via
http://localhost:8080/examples/servlet/HelloWorld

Ho Ngoc Duc 9
Servlet that generates HTML

• Tell the server we are sending HTML: response.setContentType("text/html");


• Generates valid HTML code to be printed

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloHTML extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML><HEAD><TITLE>Hello</TITLE></HEAD><BODY>");
out.println("<H1>Hello World</H1>");
out.println("</BODY></HTML>");
}
}

Ho Ngoc Duc 10
Deploying Servlets

n Copy servlet class file (and any necessary


classes) to WEB-INF/classes
n Alternatively: package the servlet class file in
a JAR file, copy it to WEB-INF/lib
n If use package: create subdirectories that
match package structure
q Access to servlet using fully qualified class name:
http://localhost:8080/examples/servlet/myPackage.MyServlet

Ho Ngoc Duc 11
Deploying Servlets

n How does the container know a certain request is


intended for a servlet?
q /MyApp/servlet/MyServlet could be path to a file (or even
directory) MyServlet in directory servlet
n Some containers use a naming convention:
requests to /MyApp/servlet/* are served by servlets
n Other containers: no such standard names. You use
a deployment descriptor to configure your web
application
q File .../WEB-INF/web.xml

Ho Ngoc Duc 12
Use your own web application
• Create directory structure under $TOMCAT_HOME/webapps/
DBP06/
index.html
WEB-INF/
web.xml
classes/
lib/
(other files and directories if needed)

• Copy your classes into WEB-INF/classes/ (subdirectories for packages),


or package them in a jar file and copy to WEB-INF/lib/
• Tell the container when to invoke a servlet: add to WEB-INF/web.xml
<servlet-mapping>
<servlet-name>invoker</servlet-name>
<url-pattern>/servlet/*</url-pattern>
</servlet-mapping>

Ho Ngoc Duc 13
Initializing Servlets

n Common in real-life servlets


q E.g., initializing database connection(s)
n Where to get paratemeters?
q Call getServletConfig() to obtain the ServletConfig object
q Then: getInitParameter() read initialization parameters
n Set init parameters in web.xml
n Even when no init parameters: use init() for data that
must be initialized once
q Information from disk, etc.

Ho Ngoc Duc 14
Servlet with init parameters
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloParameter extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
String message = getServletConfig().getInitParameter("message");
int repeats = Integer.parseInt(getServletConfig().getInitParameter("repeats"));
PrintWriter out = response.getWriter();
out.println("<HTML><HEAD><TITLE>Hello</TITLE></HEAD><BODY>");
for (int i = 0; i < repeats; i++) {
out.println("<H1>"+message+"</H1>");
}
out.println("</BODY></HTML>");
}
}

Ho Ngoc Duc 15
Setting init parameters
Modify .../WEB-INF/web.xml

<web-app>
<servlet>
<servlet-name>HelloParameter</servlet-name>
<servlet-class>duc.lect24.HelloParameter</servlet-class>
<init-param>
<param-name>message</param-name>
<param-value>Gruss aus Luebeck</param-value>
</init-param>
<init-param>
<param-name>repeats</param-name>
<param-value>5</param-value>
</init-param>
</servlet>
<!– other things ... -->
</web-app>

Ho Ngoc Duc 16
Servlet mapping
We can map a servlet to any URL (within web app):

<web-app>
<servlet>
<servlet-name>HelloParameter</servlet-name>
<servlet-class>duc.lect24.HelloParameter</servlet-class>
<!– parameters as before -->
</servlet>
<servlet-mapping>
<servlet-name>HelloParameter</servlet-name>
<url-pattern>/ParameterServlet</url-pattern>
</servlet-mapping>
</web-app>

Then applet can be accessed in different ways:


http://localhost:8080/DBP06/ParameterServlet
http://localhost:8080/DBP06/servlet/HelloParameter

Ho Ngoc Duc 17
Reading query data
String getParameter("name"): return (first) parameter value as user
entered it (URL-decoded) or null if no such parameter
String[] getParameterValues("name"): return array of all values of a
repeated parameter
Enumeration getParameterNames(): enumerate names of all parameters

double number = 0;
try {
number = Double.parseDouble(request.getParameter("number"));
} catch (Exception e) {}
double res = Math.sqrt(number);
out.println("Square root of "+number+" is "+res);
String uri = request.getRequestURI();
out.println("<p><form method=POST action="+uri+">");
out.println("<input name=number value=\""+number+"\"></form>");

Ho Ngoc Duc 18
In-class exercise

n Download DBP06.zip
n Extract it to $TOMCAT_HOME/webapps
n Visit http://host:port/DBP06/
n Write a servlet that display a month's
calendar. The month should be given as
request parameter. If no valid parameters
given, use current month
q As plain text
q As HTML table
Ho Ngoc Duc 19
Datenbank-Praktikum

Universität zu Lübeck
Sommersemester 2006
Lecture: Servlet/JSP

Ho Ngoc Duc 20

S-ar putea să vă placă și