10 Servlet
10 Servlet
10 Servlet
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
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;
4
Java Servlet
Http Servlet
5
Java Servlet
HttpServletRequest / HttpServletResponse
6
Java Servlet
HttpServletRequest
Enumeration getParameterNames()
returns names of all the parameters sent to servlet
Cookie[] getCookies()
7
Java Servlet
HttpServletResponse
PrintWriter getWriter()
obtains a character-based output stream.
ServletOutputStream getOutputStream()
obtains a byte-based output stream.
8
Java Servlet
DoGet
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
9
Java Servlet
<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" );
output.println( "</PRE></html>");
output.close(); }
}
11
Java Servlet
12
Java Servlet
HTTP
server
13
Java Servlet
14
Java Servlet
Applet HTTP
server
15
Java Servlet
16
Java Servlet
17
Java Servlet
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);}
}
18
Java Servlet
Servlet Cookies
19
Java Servlet
Methods on Cookies
Construct a Cookie:
Cookie cookie = new Cookie( name, value);
Access cookies:
cookies[i].getname();
cookies[i].getValue();
20
Java Servlet
response.setContentType( "text/html" );
PrintWriter output = response.getWriter();
21
Java Servlet
22