10 Servlet

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 22

Java Servlet

Lab Envrion Setting of Java Servlet

Servlet Engine searches file from dir “/usr/jt/webapps”.


To facilitate access to local files, make the link:
ln -s /home/lec/jia/www/java/js /usr/jt/webapps/jia
“/usr/jt/webapps/jia/” point to “~jia/www/java/js/”

Following the configuration of servlet engine:


1. The servlet engine looks servlet .class file in a dir:
/usr/jt/webapps/
e.g., http://jserv.cs.cityu.edu.hk:8080/jia/servlet/XXX is:
~jia/www/java/js/WEB-INF/classes/XXX
“servlet” ≡ “/WEB-INF/classes”

2. All servlet .class files MUST be in dir:


~jia/www/java/js/WEB-INF/classes/
The corresponding URL will be:
http://jserv.cs.cityu.edu.hk:8080/jia/servlet/GetServlet

3. All .html files MUST be in dir:


~jia/www/java/js/html/
The corresponding URL will be:
http://jserv.cs.cityu.edu.hk:8080/jia/html/test.html

1
Java Servlet

Java Servlet
 Servlet runs on the web site. To enable servlets, it
needs to install a servlet engine (e.g., Jserv, or
Tomcat), which is a module of a web-server and runs
inside the web-server process.
 Servlet generates HTML pages, sent to browser for
display, a similar technology as ASP.
 Servlet replaces CGI program to link browser-
clients to back-end servers.
 Servlet can support many protocols of request /
response type, such as HTTP, URL, FTP, SMTP.
That’s, any requests coming in the form of these
protocols can be processed by a servlet (Servlet API
defines the support of these protocols).
 The most common protocol that Servlet supports is
HTTP.

2
Java Servlet

Servlet Life Cycle


Servlets run on the web server platform as part of the
web-server process. The web server initializes, invokes
and destroys servlet instances. It invokes servlets via
Servlet interface, consisting of three methods:
 init(). It is called only once, when the servlet is first
loaded. It is guaranteed to finish before any other
calls are made to the servlet.
 service(). Each request from a client results in a
single call to this method. It receives (from the web
server) a ServletRequest object & a ServletResponse
object to get request / send reply to clients.
 destroy(). It is called to allow your servlet to clean
up any resources. Most of the time, it can be an
empty method.

3
Java Servlet

A Simple Servlet
N.B. run by http://jserv...hk:8080/jia/servlet/GenericServlet
import javax.servlet.*;
public class GenericServlet implements Servlet {
private ServletConfig config;

public void init (ServletConfig config)


throws ServletException {
this.config = config;
}
public void destroy() {} // do nothing
public ServletConfig getServletConfig() {
return config;
}
public String getServletInfo() {
return “A Simple Servlet”; }

public void service (ServletRequest req,


ServletResponse res
) throws ServletException, IOException {
res.setContentType( “text/html” );
PrintWriter out = res.getWriter();
out.println( “<html>” );
out.println( “<head>” );
out.println( “<title>A Simple Servlet</title>” );
out.println( “</head>” );
out.println( “<body>” );
out.println( “<h1>A Simple Servlet</h1>” );
…………
out.close(); }
}

4
Java Servlet

Http Servlet

The servlet packages define two abstract classes that


implement interface Servlet:
GenericServlet from package javax.servlet
HttpServlet from package javax.servlet.http

HttpServlet overrides the key method service() by


adding the code to distinguish HTTP requests and
invokes corresponding methods:
doPost()
doGet()
doHead()
doDelete()
doOption()
doTrace()

Most of programs extend class HttpServlet, and


implement methods doPost() and doGet().

5
Java Servlet

HttpServletRequest / HttpServletResponse

 Interfaces HttpServletRequest and


HttpServletResponse extend interfaces
ServletRequest and ServletResponse.

 The methods of HttpServlet receives two parameters:


a HttpServletRequest object, which contains the
request from the client, and a HttpServletResponse
object, which contains the response to the client.

 When a client makes a HttpServlet call, the web


server creates a HttpServletRequest object and a
HttpServletResponse object, and passes them to the
servlet’s service() method, which passes them further
to doGet() or doPost() methods.

6
Java Servlet

HttpServletRequest

Some important methods of HttpServletRequest :

String getParameter (String name)


returns the value of the named parameter

Enumeration getParameterNames()
returns names of all the parameters sent to servlet

String[] getParameterValues( String name)


returns an array of values of the named parameter

Cookie[] getCookies()

HttpSession getSession( Boolean create)

7
Java Servlet

HttpServletResponse

Some important methods of HttpServletResponse :

void setContentType (String type)


specifies the MIME type of the response to the
browser, e.g., “text/html”.

PrintWriter getWriter()
obtains a character-based output stream.

ServletOutputStream getOutputStream()
obtains a byte-based output stream.

void addCookie ( Cookie cookie)

8
Java Servlet

DoGet

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class GetServlet extends HttpServlet {


public void doGet( HttpServletRequest request,
HttpServletResponse response )
throws ServletException, IOException
{
PrintWriter output;

response.setContentType( "text/html" ); // content type


output = response.getWriter(); // get writer

String name = request.getParameter( "customer" );


String addr = request.getParameter( "address" );

// create and send HTML page to client


output.println( "<HTML><HEAD><TITLE>" );
output.println( "A Simple Servlet Example" );
output.println( "</TITLE></HEAD><BODY>" );
output.println( "<H1>Welcome to Servlets</H1>" );
output.println( "Dear " + name + "<br>");
output.println( "How are you doing at " + addr + "?<br>" );
output.println( "</BODY></HTML>" );
output.close(); // close PrintWriter stream }
}

9
Java Servlet

HTML file for doGet Servlet


N.B. URL: http://jserv.cs.cityu.edu.hk:8080/jia/html/GetServlet.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<!-- Fig. 29.6: HTTPGetServlet.html -->

<HEAD>
<TITLE>Servlet HTTP GET Example</TITLE>
</HEAD>

<BODY>
<FORM ACTION="http://jserv.cs.cityu.edu.hk:8080/jia/servlet/GetServlet"
METHOD="GET">
Name <input name="customer" size=47> <p>
Working Address <input name="address" size=40> <p>
<P>Click the button to connect the servlet</P>
<INPUT TYPE="submit" VALUE="Get HTML Document">
</FORM>
</BODY>
</HTML>

10
Java Servlet

DoPost
public class PostServlet extends HttpServlet {
private String animalNames[] ={ "dog", "cat", "bird", …};
public void doPost( HttpServletRequest request,
HttpServletResponse response )
throws ServletException, IOException {
int animals[] = null, total = 0;
//read in initial data of animals[] from a file
// .......
String value = request.getParameter( "animal" );

// update survey data in animals[]


for ( int i = 0; i < animalNames.length; ++i )
if ( value.equals( animalNames[ i ] ) ) ++animals[ i ];

// write animals[] to the file & calculate percentages


// ...........
// send a message & survey results to client
response.setContentType( "text/html" ); // content type

PrintWriter output = response.getWriter();


output.println( "<html>" );
output.println( "<title>Thank you!</title>" );
output.println( "Thank you for participating." );
output.println( "<BR>Results:<PRE>" );
// ....... println results.

output.println( "</PRE></html>");
output.close(); }
}

11
Java Servlet

HTML file for doPost Servlet

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">


<HTML>
<!-- Fig. 29.8: HTTPPostServlet.html -->
<HEAD> <TITLE>Servlet HTTP Post Example</TITLE> </HEAD>
<BODY>
<FORM ACTION="http://jserv.cs.cityu.edu.hk:8080/jia/servlet/PostServlet"
METHOD="POST">
What is your favorite pet?<BR><BR>
<INPUT TYPE="radio" NAME="animal" VALUE="dog">Dog<BR>
<INPUT TYPE="radio" NAME="animal" VALUE="cat">Cat<BR>
<INPUT TYPE="radio" NAME="animal" VALUE="bird">Bird<BR>
<INPUT TYPE="radio" NAME="animal" VALUE="snake">Snake<BR>
<INPUT TYPE="radio" NAME="animal" VALUE="none" CHECKED>None
<BR><BR><INPUT TYPE="submit" VALUE="Submit">
<INPUT TYPE="reset">
</FORM>
</BODY></HTML>

12
Java Servlet

Servlet Database Connection

 A servlet can connect to a database server by using


JDBC (both making sql request and receiving
ResultSet), in the same way as any Java program.

 A servlet can be started directly from browser’s


command line, e.g.,
http://jserv.cs.cityu.edu.hk:8080/jia/servlet/Coffee
because this servlet implements GET method which
is the method the browser asks HTTP server to
execute (download) the servlet.

 The servlet generates output in HTML format and


passes them back to the browser for display.

HTTP
server

Servlet JDBC DBMS


system

13
Java Servlet

A Servlet JDBC Connection Paired with HTML


// code: java/js/WEB-INF/classes/Coffee.java
public class Coffee extends HttpServlet {
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String url = "jdbc:sybase:Tds:ntr10:4100";
String query = "select COF_NAME, PRICE from COFFEES";
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {Class.forName("com.sybase.jdbc.SybDriver");
Connection con =
DriverManager.getConnection(url, "jdemo", "apple1");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
out.println("<HTML><HEAD><TITLE>");
out.println("</TITLE></HEAD>");
………….. HTML format…
out.println("<table border=1>");
out.println("<tr><th>Name<th>Price");
while (rs.next()) {
String s = rs.getString("COF_NAME");
float f = rs.getFloat("PRICE");
String text = "<tr><td>" + s + "<td>" + f;
out.println(text); }
stmt.close(); con.close();
out.println("</table>");
} catch(SQLException ex) { }
out.println("</BODY></HTML>");
out.close(); }}

14
Java Servlet

Applet and Servlet

 Servlet can be used with Applet as a replacement of


CGI programs. Applet starts a servlet by POST (or
GET), in the same way as starting a CGI program.
 Applet passes parameters to servlet in the same
format as HTML form, e.g., “name=X+Jia&addr=CityU
&ID=5012344”, so servlet can use getParameter to get
the parameter value.
 The Applet processes the results from the servlet in
the same way as from a CGI program.
 HTTP server must be in version 1.1 or above, i.e., it
uses protocol:
POST /jia/servlet/CoffeeServlet HTTP/1.1

See a sample in java/servlet/CoffeeApplet.java

Applet HTTP
server

Servlet JDBC DBMS


system

15
Java Servlet

An Applet connecting to a Servlet


// source code: java/js/WEB-INF/classes/CoffeeApplet.java
// move CoffeeApplet.class and test.html to /js/html
// URL: http://jserv.cs.cityu.edu.hk:8080/jia /html/test.html
public class CoffeeApplet extends Applet implements Runnable {
public synchronized void start() {
if (worker == null) {
Thread worker = new Thread(this);
worker.start(); }
}
public void run() {
Socket s; String sdata = “type=select_COFFEES”;
DataInputStream in; PrintStream out;
s = new Socket("jserv.cs.cityu.edu.hk",8080);
in = new DataInputStream(s.getInputStream());
out = new PrintStream(s.getOutputStream());

out.println("POST /jia/servlet/CoffeeServlet HTTP/1.1");


out.println("Host: jserv.cs.cityu.edu.hk");
out.println("Content-type: application/x-www-form-urlencoded");
out.println("Content-length: " + sdata.length());
out.println("");
out.println(sdata);
String line = in.readLine();
while (! line.equals("START_DATA"))
line = in.readLine();
while (! line.equals("END")) {
results.addElement(line);
line = in.readLine(); }
out.close(); in.close();
}

16
Java Servlet

The Servlet Paired with Applet in JDBC


// code: java/js/WEB-INF/classes/CoffeeServlet.java

 The servlet working with an applet is similar to the


CGI program in the 3-tier structure of JDBC.

 The servlet gets request from applet via


“getParameter” method on param “request” (see the
sample program for details). Note that the string
posted from applet must have the parameter in the
right format!

 The servlet sends reply back to applet via “println”


method on param “response”, which will be read by
the applet. Note that since applet cannot process
HTML statements easily, the servlet needs to prepare
replies to the applet in a sequence of string lines
(same as the CGI prog), one for each row of data.

 The applet working with the servlet here is almost the


same as the applet in the 3-tier structure of JDBC.

17
Java Servlet

Servlet paired with the Applet

public class CoffeeServlet extends HttpServlet {

public void doPost( HttpServletRequest request,


HttpServletResponse response )
throws ServletException, IOException {
try {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

a_req = request.getParameter("type");
if (a_req.equals("select_COFFEES")) {
line = ReqSql();
out.println("START_DATA");
out.println(line);
out.println(“END”);
}
} catch (Exception e) { System.out.println("Error"+e);}
}

static String ReqSql() {


String url = "jdbc:sybase:Tds:ntr10:4100";
String query = "select COF_NAME, PRICE from COFFEES";

// make JDBC connection and executeQuery


// process ResultSet to a line of string "results"
return(results.toString());
}
}

18
Java Servlet

Servlet Cookies

HTTP server is stateless, i.e., it does not keep any info


about the clients. Some applications require that the
response to a client’s request depends on the data sent
from the client earlier. Cookie is for this purpose.

 Cookies are extracted from the client’s data sent to


the servlet. They are sent back to the client to store at
the client side.

 A cookie is associated with an age. When the age


expires, it will be removed.

 The cookies are included in a header of the request


and sent to the servlet together with a request. The
servlet can analyse the cookies and reponse to the
request accordingly.

 HTTPSession is a similar technology as the Cookie


for the same purpose.

2. send cookies to 1. generate cookies


browser for storage from client-requst
Browser 3. include cookies in Servlet
the next client-request

19
Java Servlet

Methods on Cookies

Cookies are strings, defined in


javax.servlet.http.Cookie.

Construct a Cookie:
Cookie cookie = new Cookie( name, value);

Set an age for a cookie:


cookie.setMaxAge (seconds);

Add a cookie to a response to the client:


response.addCookie (cookie);

Get cookies from a client’s request:


Cookie cookies[];
cookies = request.getCookies();

Access cookies:
cookies[i].getname();
cookies[i].getValue();

Analyse cookies one by one:


for (i = 0; i < cookies.length; i++) {
cookies[i].getname() …
cookies[i].getValue();
g

20
Java Servlet

An example of using Cookies

public class CookieServlet extends HttpServlet {


private final static String names[] =
{ "C", "C++", "Java", "Visual Basic 6" };
private final static String isbn[] = { "0-13-226119-7",
"0-13-5289-6", "0-13-0125-5", "0-13-45695-5"};

public void doPost( HttpServletRequest request,


HttpServletResponse response )
throws ServletException, IOException
{
String language = request.getParameter( "lang" );

Cookie c = new Cookie( language, getISBN( language ) );


c.setMaxAge( 120 ); // seconds until cookie removed
response.addCookie( c ); // must precede getWriter

response.setContentType( "text/html" );
PrintWriter output = response.getWriter();

// send HTML page to client


output.println( "<HTML><HEAD><TITLE>" );
output.println( "Cookies" );
output.println( "</TITLE></HEAD><BODY>" );
output.println( "<P>Welcome to Cookies!<BR>" );
output.println( "<P>"+lang+" is a great language." );
output.println( "</BODY></HTML>" );

output.close(); // close stream


}

21
Java Servlet

An example of using Cookies (cont’d)

public void doGet( HttpServletRequest request,


HttpServletResponse response )
throws ServletException, IOException{
Cookie cookies = request.getCookies();
response.setContentType( "text/html" );
PrintWriter output = response.getWriter();
output.println( "<HTML><HEAD><TITLE>" );
output.println( "Cookies II" );
output.println( "</TITLE></HEAD><BODY>" );
if ( cookies != null && cookies.length != 0 ) {
output.println( "<H1>Recommendations</H1>" );
for ( int i = 0; i < cookies.length; i++ )
output.println(cookies[ i ].getName() +" Program" +
" ISBN#: " + cookies[ i ].getValue() + "<BR>" );
}
else {
output.println( "<H1>No Recommendations</H1>" );
output.println( "The cookies have expired." );
}
output.println( "</BODY></HTML>" );
output.close(); // close stream
}
private String getISBN( String lang )
{
for ( int i = 0; i < names.length; ++i )
if (lang.equals(names[i])) return isbn[i];
}

22

You might also like