Introduction To Servlets

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 93

Hindustan College of Science and Technology

Gopalji Varshneya
Course B.Tech 2nd Year
Branch IT
 The Web page is based on data submitted by
the user
 E.g., results page from search engines and order-
confirmation pages at on-line stores
 The Web page is derived from data that
changes frequently
 E.g., a weather report or news headlines page
 The Web page uses information from databases
or other server-side sources
 E.g., an e-commerce site could use a servlet to build
a Web page that lists the current price and
availability of each item that is for sale.
 What you know:
 Java
 JDBC
 What we’ll tell you:
 How to use Java inside a webserver!
 Why you might care:
 Building non-trivial web interfaces and applications
 In particular: database-backed web applications
 Static webpages
 Plain files stored in the filesystem
 Webserver accepts pathnames
 Returns contents of corresponding file
 Boring!
 Can’t generate customized content—always serve
the same static pages…
Web Server

GET /path/index.html

STATUS …
<file contents> read

<file contents> /path/index.html

Filesystem
 CGI: Easy “fix”
 Common Gateway Interface
 Oldest standard
 But at least a standard!
 Inefficient
 No persistent state
 Forward requests to external programs
 Spawn one process for each new request (ouch!)
 Communicate viaStandard input/output
 Environment variables
 Process terminates after request is handled
Web Server CGI Program
GET /cgi-bin/query? KEY=foo
KEY=foo
<response
STATUS … text foo>
<response text foo>

stdin
Database, etc
stdout Filesystem
 Little Java programs…
 Contain application-specific code
 Web server does generic part of request handling
 Servlets run “in” the web server and do some of the
handling
 Highlights
 Standard!
 Efficiency (much better than CGI)
 Security (Java!)
 Persistence (handle multiple requests)
Web Server
JVM
GET /srv/pkg.Servlet?
doGe
KEY=foo res < t(req, res
STATUS … respo ) Servlet
<response foo> s e fo
o>

Filesystem Database, etc


Web Server
JVM

Servlet
t( r eq, r es)
GET /srv/pkg.Servlet? doGe
KEY=foo
<r es po nse bar>
res
STATUS …
<response bar>

Filesystem Database, etc


 Big applets require long download time
 Applets do not have access to all the system
resources
 Server-side Java solves problems that
applets face
 Code executed on the server side and only the
results sent to client
 Servlets can access legacy applications and data
sources
 Servlets are generic extensions to Java-enabled
servers
 Servlets are secure, portable, and easy to use
replacement for CGI
 Servlet is a dynamically loaded module that
services requests from a Web server
 Servlets are executed within the Java Virtual
Machine
 Because the servlet is running on the server
side, it does not depend on browser
compatibility
 Read explicit data sent by client (form data)
 Read implicit data sent by client
(request headers)
 Generate the results
 Send the explicit data back to client (HTML)
 Send the implicit data to client
(status codes and response headers)
Request
Web Web
Servlet
Browser Server
Response

 Applications of Java Servlets


 Building e-commerce store fronts
 Servlet builds an online catalog based on the
contents of a database
 Customer places an order, which is processed by
another servlet
 Servlets as wrappers for legacy systems
 Servlets interacting with EJB applications
 CGI – Common Gateway Interface
 New process for every cgi request
 Slow response time
 If cgi program terminates before responding to web server,
the browser just waits for a response until it times out
 Proprietary APIs
 NSAPI – Netscape Server API
 ISAPI – IIS Server API
 Dynamic link libraries
 Server-Side JavaScript
 Embedding javascript into precompiled HTML
pages – only few servers support it
 Efficiency
 More efficient – uses lightweight java threads as opposed
to individual processes
 Persistency
 Servlets remain in memory
 Servlets can maintain state between requests
 Portability
 Since servlets are written in Java, they are platform
independent
 Robustness
 Error handling, Garbage collector to prevent problems with
memory leaks
 Large class library – network, file, database, distributed
object components, security, etc.
 Extensibility
 Creating new subclasses that suite your needs
 Inheritance, polymorphism, etc.
 Security
 Security provided by the server as well as the Java Security
Manager
 Eliminates problems associated with executing cgi scripts using
operating system “shells”
 Powerful
 Servlets can directly talk to web server
 Facilitates database connection pooling, session tracking etc.
 Convenient
 Parsing and decoding HTML form data, reading and setting
HTTP headers, handling cookies, etc.
 Two packages make up the servlet architecture
 javax.servlet
 Contains generic interfaces and classes that are
implemented and extended by all servlets
 javax.servlet.http
 Contains classes that are extended when creating HTTP-
specific servlets
 The heart of servlet architecture is the interface
class javax.servlet.Servlet
 It provides the framework for all servlets
 Defines five basic methods – init, service,
destroy, getServletConfig and getServletInfo
<<Interface>> <<Interface>> <<Interface>>
javax.servlet.Servlet javax.io.Serializable javax.servlet.ServletConfig
init( ) getInitParameter( )
getServletConfig( ) getServletContext( )
service( )
getServletInfo( ) getInitParameterNames( )
destroy( ) javax.servlet.GenericServlet getServletName( )
init( )
getServletConfig( )
service( )
getServletInfo( )
destroy( )
getInitParameter( )
getServletContext( )
getInitParameterNames( )
getServletName( )
log( )

javax.servlet.http.HttpServlet
doDelete( )
doGet( )
doOptions( )
doPost( )
doPut( )
doTrace( )
getLastModified( )
service( )

Basic Servlet
 HttpServlet class is extended from GenericServlet
class
 GenericServlet.service() method has been defined
as an abstract method
 The two objects that the service() method
receives are ServletRequest and ServletResponse
 ServletRequest Object
 Holds information that is being sent to the servlet
 ServletResponse Object
 Holds data that is being sent back to the client
 Unlike the GenericServlet, when extending
HttpServlet, don’t have to implement the
service() method. It is already implemented for
you
 When HttpServlet.service( ) is invoked, it calls
doGet( ) or doPost( ), depending upon how data
is sent from the client
 HttpServletRequest and HttpServletResponse
classes are just extensions of ServletRequest and
ServletResponse with HTTP-specific information
stored in them
 Applet life cycle methods: init( ), start( ),
paint( ), stop( ), and destroy( ) – appropriate
methods called based on user action
 Similarly, servlets operate in the context of a
request and response model managed by a
servlet engine
 The engine does the following
 Loads the servlet when it is first requested
 Calls the servlet’s init( ) method
 Handles any number of requests by calling the
servlet’s service( ) method
 When shutting down, calls each servlet’s destroy( )
method
 Request for a servlet received by the servlet engine
 Checks to see if the servlet is already loaded
 If not, uses a class loader to get the required servlet class
and instantiates it by calling the constructor method
 After the servlet is loaded, but before it services any
requests, the init ( ) method is called
 Inside init( ), the resources used by the servlet are
initialized. E.g: establishing database connection
 This method is called only once just before the servlet is
placed into service
 The init( ) method takes a ServletConfig object as a
parameter
 Most common way of doing this is to have it call the
super.init( ) passing it the ServletConfig object
 The service( ) method handles all requests sent by a client
 It cannot start servicing requests until the init( ) method has
been executed
 Only a single instance of the servlet is created and the servlet
engine dispatches each request in a single thread
 The service( ) method is used only when extending
GenericServlet class
 Since servlets are designed to operate in the HTTP environment,
the HttpServlet class is extended
 The service(HttpServletRequest, HttpServletResponse) method
examines the request and calls the appropriate doGet() or
doPost() method.
 A typical Http servlet includes overrides to one or more of these
subsidiary methods rather than an override to service()
 This method signifies the end of a servlet’s life
 The resources allocated during init( ) are
released
 Save persistent information that will be used
the next time the servlet is loaded
 The servlet engine unloads the servlet
 Calling destroy( ) yourself will not acutally
unload the servlet. Only the servlet engine can
do this

Idea:
 Use regular HTML for most of page
 Mark dynamic content with special tags
 Details in second half of course
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD><TITLE>Welcome to Our Store</TITLE></HEAD>
<BODY>
<H1>Welcome to Our Store</H1>
<SMALL>Welcome,
<!-- User name is "New User" for first-time visitors -->
<%= Utils.getUserNameFromCookie(request) %>
To access your account settings, click
<A HREF="Account-Settings.html">here.</A></SMALL>
<P>
Regular HTML for rest of on-line store’s Web page
</BODY></HTML>
 Apache Tomcat
 http://jakarta.apache.org/tomcat/
 Allaire/Macromedia JRun
 http://www.macromedia.com/software/jrun/
 New Atlanta ServletExec
 http://www.servletexec.com/
 Gefion Software LiteWebServer
 http://www.gefionsoftware.com/LiteWebServer/
 Caucho's Resin
 http://www.caucho.com/
 Set your CLASSPATH
 Servlet JAR file (e.g.,
install_dir\lib\common\servlet.jar).
 Top of your package hierarchy
 Put your servlet classes in proper location
 Locations vary from server to server. E.g.,
 tomcat_install_dir\webapps\examples\WEB-INF\classes
 jrun_install_dir\servers\default\default-app\WEB-INF\classes
 Invoke your servlets
 http://host/servlet/ServletName
 Custom URL-to-servlet mapping (via web.xml)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletTemplate extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Use "request" to read incoming HTTP headers
// (e.g. cookies) and HTML form data (query data)
// Use "response" to specify the HTTP response status
// code and headers (e.g. the content type, cookies).
PrintWriter out = response.getWriter();
// Use "out" to send content to browser
}
}
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet {


public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello World");
}
}
 Set the Content-Type header
 Use response.setContentType
 Output HTML
 Be sure to include the DOCTYPE
 Use an HTML validation service
 http://validator.w3.org/
 http://www.htmlhelp.com/tools/validator/
 If your servlets are behind a firewall, you can run
them, save the HTML output, and use a file upload
form to validate.
public class HelloWWW extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n";
out.println(docType +
"<HTML>\n" +
"<HEAD><TITLE>Hello WWW</TITLE></HEAD>\n" +
"<BODY>\n" +
"<H1>Hello WWW</H1>\n" +
"</BODY></HTML>");
}
}
 Move the files to a subdirectory that matches
the intended package name
 For example, the author uses the coreservlets package
for most of the rest of the servlets. So, the class files
need to go in a subdirectory called coreservlets.
 Insert a package statement in the class file
 E.g., top of HelloWWW2.java:
package coreservlets;
 Set CLASSPATH to top-level directory
 E.g., C:\Servlets+JSP.
 Include package name in URL
 http://localhost/servlet/coreservlets.HelloWWW2
public class ServletUtilities {
public static final String DOCTYPE =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">";

public static String headWithTitle(String title) {


return(DOCTYPE + "\n" +
"<HTML>\n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n");
}
...
}
 Don’t go overboard
 Complete HTML generation packages
usually work poorly
 The JSP framework is a better solution
package coreservlets;

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

public class HelloWWW3 extends HttpServlet {


public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(ServletUtilities.headWithTitle("Hello WWW") +
"<BODY>\n" +
"<H1>Hello WWW</H1>\n" +
"</BODY></HTML>");
}
}
 init
 Executed once when the servlet is first loaded.
Not called for each request.
 service
 Called in a new thread by server for each request.
Dispatches to doGet, doPost, etc.
Do not override this method!
 doGet, doPost, doXxx
 Handles GET, POST, etc. requests.
 Override these to provide desired behavior.
 destroy
 Called when server deletes servlet instance.
Not called after each request.
 You can add support for other services later
by adding doPut, doTrace, etc.
 You can add support for modification dates
by adding a getLastModified method
 The service method gives you automatic
support for:
 HEAD requests
 OPTIONS requests
 TRACE requests
 Alternative: have doPost call doGet
 Common in real-life servlets
 E.g., initializing database connection pools.
 Use ServletConfig.getInitParameter to read
initialization parameters
 Set init parameters in web.xml (ver 2.2/2.3)
 …/WEB-INF/web.xml
 Many servers have custom interfaces to create
web.xml
 It is common to use init even when
you don’t read init parameters
 See modification date example in
Core Servlets and JavaServer Pages Chapter 2
public class ShowMessage extends HttpServlet {
private String message;
private String defaultMessage = "No message.";
private int repeats = 1;
public void init() throws ServletException {
ServletConfig config = getServletConfig();
message = config.getInitParameter("message");
if (message == null) {
message = defaultMessage;
}
try {
String repeatString =
config.getInitParameter("repeats");
repeats = Integer.parseInt(repeatString);
} catch(NumberFormatException nfe) {}
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "The ShowMessage Servlet";
out.println(ServletUtilities.headWithTitle(title)+
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=CENTER>" + title + "</H1>");
for(int i=0; i<repeats; i++) {
out.println(message + "<BR>");
}
out.println("</BODY></HTML>");
}
}
 ...\WEB-INF\web.xml
 tomcat_install_dir\webapps\examples\WEB-INF\web.xml
 See More Servlets & JSP (www.moreservlets.com) for details on
web.xml
<web-app>
<servlet>
<servlet-name>ShowMsg</servlet-name>
<servlet-class>coreservlets.ShowMessage</servlet-class>
<init-param>
<param-name>message</param-name>
<param-value>Shibboleth</param-value>
</init-param>
<init-param>
<param-name>repeats</param-name>
<param-value>5</param-value>
</init-param>
</servlet>
</web-app>
 Use print statements; run server on desktop
 Integrated debugger in IDE
 Look at the HTML source
 Return error pages to the client
 Plan ahead for missing or malformed data
 Use the log file
 log("message") or log("message", Throwable)
 Look at the request data separately.
 See EchoServer at www.coreservlets.com
 Look at the response data separately
 See WebClient at www.coreservlets.com
 Stop and restart the server
 Servlets are efficient, portable, powerful, and
widely accepted in industry
 Regardless of deployment server, run a free
server on your desktop for development
 Getting started:
 Set your CLASSPATH
 Servlet JAR file
 Top of your package hierarchy
 Put class files in proper location
 .../WEB-INF/classes
 Use proper URL, usually
http://host/servlet/ServletName
 Download existing servlet first time
 Start with HelloWWW from www.coreservlets.com
 Main servlet code goes in doGet or doPost:
 The HttpServletRequest contains the incoming
information
 The HttpServletResponse lets you set outgoing
information
 Call setContentType to specify MIME type
 Call getWriter to obtain a Writer pointing to client
 One-time setup code goes in init
 Servlet gets initialized and loaded once
 Servlet gets invoked multiple times
 Initialization parameters set in web.xml
 Cookies are good
 Remember who you are and your preferences
 Session tracking
 Cookies are bad
 When developer is not careful
(store password, credit card info, etc…)
 When people abuse them

(track information about you)


 Making Web Applications Better
 For the Developer
 More features, better API, ...
 Time-To-Market (beat your competitors)
 For the End-User
 Better Continuity
 Better User Experience
 Client Side
 Store Variable=Value Bindings in HTML Page, or
Cookies
 Server Side
 Store Variable=Value Bindings in DB/Server
Memory
 Store Session ID on Client Side, to identify Client
 Cookies
 URL Rewriting
 Hidden Fields
 Lifetime
 Session – not written to file system
 Persistent – written to user preferences
 Only returns cookie to requesting domain
 Cookie must be specified by content
 No special characters in cookie
1239865610

String sID = makeUniqueString();


Hashtable sessionInfo = new Hashtable();
Hashtable globalTable = findTableStoringSessions();
globalTable.put(sID, sessionInfo);
Cookie sessionCookie = new Cookie("JSESSIONID", sID);
sessionCookie.setPath("/");
response.addCookie(sessionCookie);
1239865610

String sID = makeUniqueString();


Hashtable sessionInfo = new Hashtable();
Hashtable globalTable = findTableStoringSessions();
globalTable.put(sID, sessionInfo);
Cookie sessionCookie = new Cookie("JSESSIONID", sID);
sessionCookie.setPath("/");
response.addCookie(sessionCookie);
1239865610

String sID = makeUniqueString();


Hashtable sessionInfo = new Hashtable();
Hashtable globalTable = findTableStoringSessions();
globalTable.put(sID, sessionInfo);
Cookie sessionCookie = new Cookie("JSESSIONID", sID);
sessionCookie.setPath("/");
response.addCookie(sessionCookie);
1239865610

String sID = makeUniqueString();


Hashtable sessionInfo = new Hashtable();
Hashtable globalTable = findTableStoringSessions();
globalTable.put(sID, sessionInfo);
Cookie sessionCookie = new Cookie("JSESSIONID", sID);
sessionCookie.setPath("/");
response.addCookie(sessionCookie);
1239865610

JSESSIONID → 1239865610
String sID = makeUniqueString();
Hashtable sessionInfo = new Hashtable();
Hashtable globalTable = findTableStoringSessions();
globalTable.put(sID, sessionInfo);
Cookie sessionCookie = new Cookie("JSESSIONID", sID);
sessionCookie.setPath("/");
response.addCookie(sessionCookie);
1239865610

JSESSIONID → 1239865610
PATH → /
String sID = makeUniqueString();
Hashtable sessionInfo = new Hashtable();
Hashtable globalTable = findTableStoringSessions();
globalTable.put(sID, sessionInfo);
Cookie sessionCookie = new Cookie("JSESSIONID", sID);
sessionCookie.setPath("/");
response.addCookie(sessionCookie);
1239865610

Set-Cookie: JSESSIONID=1239865610; path=/;

String sID = makeUniqueString();


Hashtable sessionInfo = new Hashtable();
Hashtable globalTable = findTableStoringSessions();
globalTable.put(sID, sessionInfo);
Cookie sessionCookie = new Cookie("JSESSIONID", sID);
sessionCookie.setPath("/");
response.addCookie(sessionCookie);
Cookie: JSESSIONID=1239865610;

// On request
String sID = request.getCookie("JSESSIONID");
Hashtable globalTable = findTableStoringSessions();
Hashtable sInfo = (Hashtable) globalTable.get(sID);
Cookie: JSESSIONID=1239865610;

// On request
String sID = request.getCookie("JSESSIONID");
Hashtable globalTable = findTableStoringSessions();
Hashtable sInfo = (Hashtable) globalTable.get(sID);
1239865610

Cookie: JSESSIONID=1239865610;

// On request
String sID = request.getCookie("JSESSIONID");
Hashtable globalTable = findTableStoringSessions();
Hashtable sInfo = (Hashtable) globalTable.get(sID);
 Rewrite all URLs in response to contain SessionID
 http://foo.com/servlet/cart?id=123xyz
 Parse out session ID from request line
 encodeURL() in HttpResponse object will rewrite
session-id onto URL
 Limitations
 Always include ?sessionID=238423984
 e.g.
http://www.amazon.com/exec/obidos/subst/home/
home.html/103-0036360-1119059
 <input type=“hidden” name=“session” value=“...”>
 Session tracking API built on top of URL
rewriting or cookies
 Look up HttpSession object associated with current
request (or create new one)
 All cookie/URL rewriting mechanics hidden
 Look up information associated with a session
 Associate information with a session
HttpSession session = request.getSession(true);
ShoppingCart sc = (ShoppingCart)
session.getAttribute("shoppingCart");
if (cart == null) {
cart = new ShoppingCart();
session.setAttribute("shoppingCart", cart);
}
...
// do something with your shopping cart object
 public String getId()
 public boolean isNew()
 public long getCreationTime()
 public long getLastAccessedTime()
 public int getMaxInactiveInterval()
 public void setMaxInactiveInterval(int secs)
 public void invalidate()
HttpSession session = request.getSession(true);
session.setAttribute("referringPage",
request.getHeader("Referer"));

ShoppingCart cart =
(ShoppingCart)session.getAttribute("previousItems");

if (cart == null) {
cart = new ShoppingCart();
session.setAttribute("previousItems", cart);
}

String itemID = request.getParameter("itemID");


if (itemID != null) {
cart.addItem(Catalog.getItem(itemID));
}
 Automatic! After a long enough interval
(getMaxInactiveInterval)
Request
Session ID = 123XYZ
Amazon Shopping Cart sc
[item 1=324]

Servlet Container
Session ID = 123XYZ
Amazon Shopping Cart sc
[item 1=324]

Response:
Set-Cookie: sid=123XYZ
Servlet Container
Request:
Set-Cookie: sid=123XYZ
Session ID = 123XYZ
Amazon Shopping Cart sc
[item 1=324]

Servlet Container
Request:
Set-Cookie: sid=123XYZ
Session ID = 123XYZ

Amazon Shopping Cart sc


[item 1=324
item 2=115]

Servlet Container
 Printing to output not really a special case
when writing heaps of HTML!
 Well… why not make that the common case in
the syntax and program statements the “special
case?”
 And while we’re at it, why not hide the
compilation steps (let the server do it)?
 Now things look more like “plain old HTML”
(only they aren’t… they can produce dynamic
content and really are Java programs)
<%@ page import=“java.io.*” %>
<html>
<head><title>Sample JSP</title></head>
<% String s = “JSP”; %>
<body>
<h1>Hello <%= s %> World!</h1>
<p><% out.print(“Scriptlet Statement Hello!”); %></p>
<p>Key is <%= request.getParameter(“KEY”) %></p>
</body>
</html>

 Core syntactic elements:


 Directives <%@ page … %>
 Declarations <%! … %> (outside service method)
 Scriptlets <% … %>
 Expressions <%= … %>
package jsp._jsp;
// line:/jsp/hello.jsp:1
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;

public class _hello_2ejsp


extends org.gjt.jsp.HttpJspPageImpl
implements org.gjt.jsp.GnuJspPage {
[…]
public void _jspService (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException {
response.setContentType ("text/html");
[…]
HttpSession session = pageContext.getSession ();
JspWriter out = pageContext.getOut ();
[…]
try {
// line:/jsp/hello.jsp:2
out.print("<html>\n[…]");
// line:/jsp/hello.jsp:4
String s = "GNUJSP";
// line:/jsp/hello.jsp:5
out.print("\n<body>[…]");
// line:/jsp/hello.jsp:6
out.print(s);
[…]
// line:/jsp/hello.jsp:7
out.print(“Scriptlet Statement Hello!”);
[…]
// line:/jsp/hello.jsp:8
out.print(request.getParameter(“KEY”));
// line:/jsp/hello.jsp:8
out.print(“</p>\n</body>[…]”);
} catch (Throwable e) { […] }
}
}
<%@ page import=“java.io.*” %>
<%@ page import=“java.util.*” %>
<%@ page import=“java.sql.*” %>
<%!
Static final String dbHost = “…”; %>
Static final String oracleDriver = “…”;
%>
<%
String courseId = request.getParameter(“courseid”);
Class.forName(oracleDriver);
Connection conn = DriverManager.getConnection(…);
Statement stmt = con.createStatement();
String qry = “SELECT STUDENT.SID, SNAME, COURSE.CID ” +
“FROM STUDENT, COURSE, TAKE ” +
“WHERE TAKE.CID = ‘” + courseId + “’ AND ” +
“STUDENT.SID = TAKE.SID AND ” +
“COURSE.CID = TAKE.CID;”
ResultSet res = conn.executeQuery(qry);
%>
<html>
<head><title>Student Information</title></head>

<body>
<h1>Student Information for <%= courseId %></h1>

<p><table border=“1”>
<tr><th>CourseID</th><th>Student</th><th>StudentID</th></tr>
<% while (rs.next()) { %>
<tr>
<td><%= rs.getString(“cid”) %></td>
<td><%= rs.getString(“sname”) %></td>
<td><%= rs.getString(“sid”) %></td>
</tr>
<% } // end while %>
</table></p>

</body>
</html>
 Dynamically loadable server modules
 Web server offers standard API for request handlers
 Request handlers are dynamic libraries
 Loaded into server address space (security?!)
 Very efficient!
 Better suited for generic server extensions than application-
specific logic
 CGI flavors
 Persistent CGI (PCGI) / FastCGI
 Too little, too late

 Modern web publishing systems


 Essentially databases that “speak HTTP”
 Servlets and JSPs:
 http://java.sun.com/products/servlet/
 http://java.sun.com/products/jsp/
 JDBC:
 http://java.sun.com/products/jdbc/
 The purpose of a servlet is to create a Web page in response to a
client request
 Servlets are written in Java, with a little HTML mixed in
 The HTML is enclosed in out.println( ) statements
 JSP (Java Server Pages) is an alternate way of creating servlets
 JSP is written as ordinary HTML, with a little Java mixed in
 The Java is enclosed in special tags, such as <% ... %>
 The HTML is known as the template text
 JSP files must have the extension .jsp
 JSP is translated into a Java servlet, which is then compiled
 Servlets are run in the usual way
 The browser or other client sees only the resultant HTML, as usual
 Tomcat knows how to handle servlets and JSP pages

83
 There is more than one type of JSP “tag,” depending on
what you want done with the Java
 <%= expression %>
 The expression is evaluated and the result is inserted into the
HTML page
 <% code %>
 The code is inserted into the servlet's service method
 This construction is called a scriptlet
 <%! declarations %>
 The declarations are inserted into the servlet class, not into a
method

84
 <HTML>
<BODY>
Hello!  The time is now <%= new java.util.Date() %>
</BODY>
</HTML>

 Notes:
 The <%= ... %> tag is used, because we are computing
a value and inserting it into the HTML
 The fully qualified name (java.util.Date) is used,
instead of the short name (Date), because we haven’t
yet talked about how to do import declarations
85
 You can declare your own variables, as usual
 JSP provides several predefined variables
 request : The HttpServletRequest parameter
 response : The HttpServletResponse parameter
 session : The HttpSession associated with the
request, or null if there is none
 out : A JspWriter (like a PrintWriter) used to send
output to the client
 Example:
 Your hostname: <%= request.getRemoteHost() %>

86
 Scriptlets are enclosed in <% ... %> tags
 Scriptlets do not produce a value that is inserted directly
into the HTML (as is done with <%= ... %>)
 Scriptlets are Java code that may write into the HTML
 Example:
<% String queryData = request.getQueryString();
out.println("Attached GET data: " + queryData); %>
 Scriptlets are inserted into the servlet exactly as
written, and are not compiled until the entire servlet
is compiled
 Example:
<% if (Math.random() < 0.5) { %>
Have a <B>nice</B> day!
<% } else { %>
Have a <B>lousy</B> day!
<% } %>
87
 Use <%! ... %> for declarations to be added to your
servlet class, not to any particular method
 Caution: Servlets are multithreaded, so nonlocal variables
must be handled with extreme care
 If declared with <% ... %>, variables are local and OK
 Data can also safely be put in the request or session objects
 Example:
<%! private int accessCount = 0; %>
Accesses to page since server reboot:
<%= ++accessCount %>
 You can use <%! ... %> to declare methods as easily as
to declare variables

88
 Directives affect the servlet class itself
 A directive has the form:
<%@ directive attribute="value" %>
or
<%@ directive attribute1="value1"
attribute2="value2"
...
attributeN="valueN" %>
 The most useful directive is page, which lets
you import packages
 Example: <%@ page import="java.util.*" %>

89
 The include directive inserts another file into the
file being parsed
 The included file is treated as just more JSP, hence it
can include static HTML, scripting elements, actions,
and directives
 Syntax: <%@ include file="URL " %>
 The URL is treated as relative to the JSP page
 If the URL begins with a slash, it is treated as relative
to the home directory of the Web server
 The include directive is especially useful for
inserting things like navigation bars
90
 Actions are XML-syntax tags used to control
the servlet engine
 <jsp:include page="URL " flush="true" />
 Inserts the indicated relative URL at execution time
(not at compile time, like the include directive does)
 This is great for rapidly changing data
 <jsp:forward page="URL" />
<jsp:forward page="<%= JavaExpression %>" />
 Jump to the (static) URL or the (dynamically
computed) JavaExpression resulting in a URL

91
 JSP can be embedded in XML as well as in HTML
 Due to XML’s syntax rules, the tags must be different
(but they do the same things)
 HTML: <%= expression %>
XML: <jsp:expression>expression</jsp:expression>
 HTML: <% code %>
XML: <jsp:scriptlet>code</jsp:scriptlet>
 HTML: <%! declarations %>
XML:
<jsp:declaration>declarations</jsp:declaration>
 HTML: <%@ include file=URL %>
XML: <jsp:directive.include file="URL"/>

92
93

You might also like