+ All Categories
Home > Documents > 10 servlet

10 servlet

Date post: 10-Apr-2018
Category:
Upload: imseaman1112
View: 229 times
Download: 0 times
Share this document with a friend
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
Transcript

8/8/2019 10 servlet

http://slidepdf.com/reader/full/10-servlet 1/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

8/8/2019 10 servlet

http://slidepdf.com/reader/full/10-servlet 2/22

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 runsinside 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 APIdefines the support of these protocols).

• The most common protocol that Servlet supports isHTTP.

2

8/8/2019 10 servlet

http://slidepdf.com/reader/full/10-servlet 3/22

Java Servlet

Servlet Life Cycle

Servlets run on the web server platform as part of the

web-server process. The web server initializes, invokesand destroys servlet instances. It invokes servlets via Servlet interface, consisting of three methods:

• init(). It is called only once, when the servlet is firstloaded. It is guaranteed to finish before any other calls are made to the servlet.

• service(). Each request from a client results in asingle call to this method. It receives (from the webserver) a ServletRequest object & a ServletResponseobject to get request / send reply to clients.

• destroy(). It is called to allow your servlet to cleanup any resources. Most of the time, it can be an

empty method.

3

8/8/2019 10 servlet

http://slidepdf.com/reader/full/10-servlet 4/22

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 nothingpublic 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

8/8/2019 10 servlet

http://slidepdf.com/reader/full/10-servlet 5/22

Java Servlet

Http Servlet

The servlet packages define two abstract classes thatimplement interface Servlet :

GenericServlet from package javax.servlet HttpServlet from package javax.servlet.http

 HttpServlet overrides the key method service() byadding the code to distinguish HTTP requests and

invokes corresponding methods:doPost()doGet()doHead()doDelete()doOption()doTrace()

Most of programs extend class HttpServlet , andimplement methods doPost () and doGet ().

5

8/8/2019 10 servlet

http://slidepdf.com/reader/full/10-servlet 6/22

Java Servlet

HttpServletRequest / HttpServletResponse

• Interfaces HttpServletRequest and

 HttpServletResponse extend interfaces ServletRequest and ServletResponse.

• The methods of  HttpServlet receives two parameters: a HttpServletRequest object, whichcontains the request from the client, and a

 HttpServletResponse object, which contains theresponse to the client.

• When a client makes a HttpServlet call, the webserver creates a HttpServletRequest object and a HttpServletResponse object, and passes them to theservlet’s service() method, which passes them further 

to doGet () or doPost () methods. 

6

8/8/2019 10 servlet

http://slidepdf.com/reader/full/10-servlet 7/22

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

8/8/2019 10 servlet

http://slidepdf.com/reader/full/10-servlet 8/22

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

8/8/2019 10 servlet

http://slidepdf.com/reader/full/10-servlet 9/22

8/8/2019 10 servlet

http://slidepdf.com/reader/full/10-servlet 10/22

Java Servlet

HTML file for doGet ServletN.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

8/8/2019 10 servlet

http://slidepdf.com/reader/full/10-servlet 11/22

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 clientresponse.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

8/8/2019 10 servlet

http://slidepdf.com/reader/full/10-servlet 12/22

8/8/2019 10 servlet

http://slidepdf.com/reader/full/10-servlet 13/22

Java Servlet

Servlet Database Connection

• A servlet can connect to a database server by usingJDBC (both making sql request and receiving ResultSet ), in the same way as any Java program.

• A servlet can be started directly from browser’scommand line, e.g.,http://jserv.cs.cityu.edu.hk:8080/jia/servlet/Coffee

 because this servlet implements GET method whichis the method the browser asks HTTP server toexecute (download) the servlet.

• The servlet generates output in HTML format and passes them back to the browser for display.

HTTPserver 

Servlet DBMS

system

JDBC

13

8/8/2019 10 servlet

http://slidepdf.com/reader/full/10-servlet 14/22

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

8/8/2019 10 servlet

http://slidepdf.com/reader/full/10-servlet 15/22

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 sameformat as HTML form, e.g., “name=X+Jia&addr=CityU

&ID=5012344”, so servlet can use getParameter to getthe parameter value.

• The Applet processes the results from the servlet inthe 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

AppletHTTPserver 

Servlet DBMSsystem

JDBC

15

8/8/2019 10 servlet

http://slidepdf.com/reader/full/10-servlet 16/22

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

8/8/2019 10 servlet

http://slidepdf.com/reader/full/10-servlet 17/22

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 theCGI program in the 3-tier structure of JDBC.

•The servlet gets request from applet via“getParameter” method on param “request” (see thesample program for details). Note that the string

 posted from applet must have the parameter in theright format!

• The servlet sends reply back to applet via “println”method on param “response”, which will be read bythe applet. Note that since applet cannot processHTML 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 almostthe same as the applet in the 3-tier structure of JDBC.

17

8/8/2019 10 servlet

http://slidepdf.com/reader/full/10-servlet 18/22

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

8/8/2019 10 servlet

http://slidepdf.com/reader/full/10-servlet 19/22

Java Servlet

Servlet Cookies

HTTP server is stateless, i.e., it does not keep any infoabout the clients. Some applications require that theresponse to a client’s request depends on the data sentfrom the client earlier. Cookie is for this purpose.

• Cookies are extracted from the client’s data sent tothe servlet. They are sent back to the client to store at

the client side.

• A cookie is associated with an age. When the ageexpires, it will be removed.

• The cookies are included in a header of the requestand sent to the servlet together with a request. The

servlet can analyse the cookies and reponse to therequest accordingly.

• HTTPSession is a similar technology as the Cookiefor the same purpose.

Browser  Servlet

1. generate cookiesfrom client-requst

2. send cookies to browser 

for storage

3. include cookies inthe next client-request

19

8/8/2019 10 servlet

http://slidepdf.com/reader/full/10-servlet 20/22

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

8/8/2019 10 servlet

http://slidepdf.com/reader/full/10-servlet 21/22

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 removedresponse.addCookie( c ); // must precede getWriter 

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

// send HTML page to clientoutput.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

8/8/2019 10 servlet

http://slidepdf.com/reader/full/10-servlet 22/22

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];}


Recommended