What Are Servlets?What Are Servlets?
Basically, a java program that runs Basically, a java program that runs on the serveron the server
Creates dynamic web pagesCreates dynamic web pages
What Do They Do?What Do They Do?
Handle data/requests sent by users Handle data/requests sent by users (clients)(clients)
Create and format resultsCreate and format results Send results back to userSend results back to user
Who Uses Servlets?Who Uses Servlets?
Servlets are useful in many business Servlets are useful in many business oriented websitesoriented websites
… … and MANY othersand MANY others
HistoryHistory
Dynamic websites were often Dynamic websites were often created with CGIcreated with CGI
CGI: Common Gateway InterfaceCGI: Common Gateway Interface Poor solution to today’s needsPoor solution to today’s needs A better solution was neededA better solution was needed
Servlets vs. CGIServlets vs. CGI Servlet AdvantagesServlet Advantages
EfficientEfficient Single lightweight java thread handles multiple requestsSingle lightweight java thread handles multiple requests Optimizations such as computation caching and keeping Optimizations such as computation caching and keeping
connections to databases openconnections to databases open ConvenientConvenient
Many programmers today already know javaMany programmers today already know java PowerfulPowerful
Can talk directly to the web serverCan talk directly to the web server Share data with other servletsShare data with other servlets Maintain data from request to requestMaintain data from request to request
PortablePortable Java is supported by every major web browser (through Java is supported by every major web browser (through
plugins)plugins) InexpensiveInexpensive
Adding servlet support to a server is cheap or freeAdding servlet support to a server is cheap or free
Servlets vs. CGIServlets vs. CGI
CGI AdvantagesCGI Advantages CGI scripts can be written in any CGI scripts can be written in any
languagelanguage Does not depend on servlet-enabled Does not depend on servlet-enabled
serverserver
What Servlets NeedWhat Servlets Need
JavaServer Web Development Kit JavaServer Web Development Kit (JSWDK)(JSWDK)
Servlet capable serverServlet capable server Java Server Pages (JSP)Java Server Pages (JSP) Servlet codeServlet code
Java Server Web Development Java Server Web Development KitKit
JSWDKJSWDK Small, stand-alone server for testing Small, stand-alone server for testing
servlets and JSP pagesservlets and JSP pages The J2EE SDKThe J2EE SDK
Includes Java Servlets 2.4Includes Java Servlets 2.4
Servlet capable serverServlet capable server
ApacheApache Popular, open-source serverPopular, open-source server
TomcatTomcat A “servlet container” used with ApacheA “servlet container” used with Apache
Other servers are availableOther servers are available
Java Server PagesJava Server Pages
Lets you mix regular, static HTML pages Lets you mix regular, static HTML pages with dynamically-generated HTMLwith dynamically-generated HTML
Does not extend functionality of ServletsDoes not extend functionality of Servlets Allows you to separate “look” of the site Allows you to separate “look” of the site
from the dynamic “content”from the dynamic “content” Webpage designers create the HTMLWebpage designers create the HTML Servlet programmers create the dynamic Servlet programmers create the dynamic
contentcontent Changes in HTML don’t effect servletsChanges in HTML don’t effect servlets
<head></head><body><%// jsp sample codeout.println(" JSP, ASP, CF, PHP - you name it, we support it!");%></body></html>
<html><head></head><body><b> JSP, ASP, CF, PHP - you name it, we support it!</b></body></html></font>
<head></head><body><%// jsp sample codeout.println(" JSP, ASP, CF, PHP - you name it, we support it!");%></body></html>
<html><head></head><body><b> JSP, ASP, CF, PHP - you name it, we support it!</b></body></html></font>
<head></head><body><%// jsp sample codeout.println(" JSP, ASP, CF, PHP - you name it, we support it!");%></body></html>
<html><head></head><body><b> JSP, ASP, CF, PHP - you name it, we support it!</b></body></html></font>
<head></head><body><%// jsp sample codeout.println(" JSP, ASP, CF, PHP - you name it, we support it!");%></body></html>
<html><head></head><body><b> JSP, ASP, CF, PHP - you name it, we support it!</b></body></html></font>
Servlet CodeServlet Code
Written in standard JavaWritten in standard Java Implement the javax.servlet.Servlet Implement the javax.servlet.Servlet
interface interface
package servlet_tutorials.PhoneBook;import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*; import java.sql.*; import java.net.*;
public class SearchPhoneBookServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String query = null; String where = null; String firstname = null; String lastname = null; ResultSet rs = null;
res.setContentType("text/html"); PrintWriter out = res.getWriter();
// check which if any fields in the submitted form are empty if (req.getParameter("FirstName").length() > 0) firstname = req.getParameter("FirstName"); else firstname = null;}
Main Concepts of Servlet Main Concepts of Servlet ProgrammingProgramming
Life CycleLife Cycle Client InteractionClient Interaction Saving StateSaving State Servlet CommunicationServlet Communication Calling ServletsCalling Servlets Request Attributes and ResourcesRequest Attributes and Resources MultithreadingMultithreading
Life Cycle: InitializeLife Cycle: Initialize
Servlet is created when servlet Servlet is created when servlet container receives a request from container receives a request from the clientthe client
Init() method is called only onceInit() method is called only once
Life Cycle: ServiceLife Cycle: Service
Any requests will be forwarded to the Any requests will be forwarded to the service() methodservice() method doGet()doGet() doPost()doPost() doDelete()doDelete() doOptions()doOptions() doPut()doPut() doTrace() doTrace()
Life Cycle: DestroyLife Cycle: Destroy
destroy() method is called only oncedestroy() method is called only once Occurs whenOccurs when
Application is stoppedApplication is stopped Servlet container shuts downServlet container shuts down
Allows resources to be freedAllows resources to be freed
Client InteractionClient Interaction
RequestRequest Client (browser) sends a request containingClient (browser) sends a request containing
Request line (method type, URL, protocol)Request line (method type, URL, protocol) Header variables (optional)Header variables (optional) Message body (optional)Message body (optional)
ResponseResponse Sent by server to clientSent by server to client
response line (server protocol and status code)response line (server protocol and status code) header variables (server and response information)header variables (server and response information) message body (response, such as HTML)message body (response, such as HTML)
Thin clients (minimize download)Thin clients (minimize download) Java all “server side”Java all “server side”
ClientServer
Servlets
Saving StateSaving State
Session TrackingSession Tracking A mechanism that servlets use to A mechanism that servlets use to
maintain state about a series of maintain state about a series of requests from the same user (browser) requests from the same user (browser) across some period of time. across some period of time.
CookiesCookies A mechanism that a servlet uses to have A mechanism that a servlet uses to have
clients hold a small amount of state-clients hold a small amount of state-information associated with the user. information associated with the user.
Servlet CommunicationServlet Communication
To satisfy client requests, servlets To satisfy client requests, servlets sometimes need to access network sometimes need to access network resources: other servlets, HTML resources: other servlets, HTML pages, objects shared among pages, objects shared among servlets at the same server, and so servlets at the same server, and so on. on.
Calling ServletsCalling Servlets
Typing a servlet URL into a browser Typing a servlet URL into a browser window window Servlets can be called directly by typing Servlets can be called directly by typing
their URL into a browser's location their URL into a browser's location window.window.
Calling a servlet from within an HTML Calling a servlet from within an HTML pagepage Servlet URLs can be used in HTML tags, Servlet URLs can be used in HTML tags,
where a URL for a CGI-bin script or file where a URL for a CGI-bin script or file URL might be found. URL might be found.
Request Attributes and Request Attributes and ResourcesResources
Request AttributesRequest Attributes getAttributegetAttribute getAttributeNames getAttributeNames setAttribute setAttribute
Request Resources - gives you Request Resources - gives you access to external resourcesaccess to external resources getResourcegetResource getResourceAsStreamgetResourceAsStream
MultithreadingMultithreading
Concurrent requests for a servlet are Concurrent requests for a servlet are handled by separate threads executing the handled by separate threads executing the corresponding request processing method corresponding request processing method (e.g. doGet or doPost). It's therefore (e.g. doGet or doPost). It's therefore important that these methods are thread important that these methods are thread safe. safe.
The easiest way to guarantee that the code The easiest way to guarantee that the code is thread safe is to avoid instance variables is thread safe is to avoid instance variables altogether and instead use synchronized altogether and instead use synchronized blocks. blocks.
import java.io.*; import java.io.*; import javax.servlet.*; import javax.servlet.*; import javax.servlet.http.*;import javax.servlet.http.*;
public class SimpleCounter extends HttpServlet { public class SimpleCounter extends HttpServlet { int count = 0; int count = 0; public void doGet(HttpServletRequest req, HttpServletResponse res) public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException { throws ServletException, IOException { res.setContentType("text/plain"); res.setContentType("text/plain"); PrintWriter out = res.getWriter(); PrintWriter out = res.getWriter(); count++; count++; out.println("This servlet has been accessed " + count + " times out.println("This servlet has been accessed " + count + " times
since loading");since loading"); }} } }
Simple Counter Example
MultiThread ProblemsMultiThread Problems
Problem - Synchronization between threadsProblem - Synchronization between threads
count++; // by thread1count++; // by thread2out.println.. // by thread1out.println.. // by thread2
Two Requests willget the samevalue of counter
Solution - Use Synchronized Block!Solution - Use Synchronized Block! Synchronized BlockSynchronized Block Lock(Monitor)Lock(Monitor)
Better ApproachBetter Approach
The approach would be to synchronize only the The approach would be to synchronize only the section of code that needs to be executed section of code that needs to be executed automically: automically: PrintWriter out = res.getWriter(); PrintWriter out = res.getWriter(); synchronized(this) synchronized(this) {{ count++; count++; out.println("This servlet has been accessed " + out.println("This servlet has been accessed " + count + "times since loading"); count + "times since loading");}}This reduces the amount of time the servlet This reduces the amount of time the servlet spends in its synchronized block, and still spends in its synchronized block, and still maintains a consistent count. maintains a consistent count.
Search FormSearch Form
<html><html><head> <head> <title>Search Phonebook</title> <title>Search Phonebook</title> </head> </head> <body bgcolor="#FFFFFF"> <p><b><body bgcolor="#FFFFFF"> <p><b>Search Company Phone Book</b></p> Search Company Phone Book</b></p> <form name="form1" method="get" <form name="form1" method="get" action="servlet/servlet_tutorials.PhoneBook.SearchPhoneBookSeraction="servlet/servlet_tutorials.PhoneBook.SearchPhoneBookServlet"> vlet"> <table border="0" cellspacing="0" cellpadding="6"> <tr> <td >Search <table border="0" cellspacing="0" cellpadding="6"> <tr> <td >Search by</td> <td>by</td> <td></td> </tr> <tr> <td><b></td> </tr> <tr> <td><b>First Name First Name </b></td> <td> </b></td> <td> <input type="text" name="FirstName"> AND/OR</td> </tr> <tr> <td <input type="text" name="FirstName"> AND/OR</td> </tr> <tr> <td ><b>><b>Last NameLast Name</b></td> <td ></b></td> <td ><input type="text" name="LastName"></td> </tr> <tr> <td ></td> <td <input type="text" name="LastName"></td> </tr> <tr> <td ></td> <td >><input type="submit" name="Submit" value="Submit"><input type="submit" name="Submit" value="Submit"></td> </tr> </table></td> </tr> </table></form></form></body></body></html> </html>
Java server PageSearch_phone_book.jsp
Display ResultsDisplay Results
<html><html><%@page import ="java.sql.*" %><%@page import ="java.sql.*" %><jsp:useBean id="phone" class="servlet_tutorials.PhoneBook.PhoneBookBean"/> <jsp:useBean id="phone" class="servlet_tutorials.PhoneBook.PhoneBookBean"/> <%@ page buffer=35 %><%@ page buffer=35 %><%@ page errorPage="error.jsp" %><%@ page errorPage="error.jsp" %><html><html><head><head><title>Phone Book Search Results</title><title>Phone Book Search Results</title><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head><body bgcolor="#FFFFFF"> <b>Search Results</b> <p> <body bgcolor="#FFFFFF"> <b>Search Results</b> <p> <% String q = request.getParameter("query"); <% String q = request.getParameter("query"); ResultSet rs = phone.getResultSet(q); ResultSet rs = phone.getResultSet(q); %>%><% if (rs.wasNull()) { <% if (rs.wasNull()) { %> %> "NO RESULTS FOUND" "NO RESULTS FOUND" <% <% } else } else %>%><table> <tr> <td> <div align="center">First Name</b></div> </td> <td> <div <table> <tr> <td> <div align="center">First Name</b></div> </td> <td> <div align="center">Last Name</font></b></div> </td> <td> <div align="center">Phone align="center">Last Name</font></b></div> </td> <td> <div align="center">Phone Number</font></b></div> </td> <td> <div align="center">Email</font></b></div> </td> Number</font></b></div> </td> <td> <div align="center">Email</font></b></div> </td> </tr></tr>
<% while(rs.next()) { %><% while(rs.next()) { %> <tr> <td> <tr> <td><%= rs.getString("first_name") %><%= rs.getString("first_name") %></td> <td></td> <td><%= rs.getString("last_name") %><%= rs.getString("last_name") %></td> </td> <td><td><%= rs.getString("phone_number") %><%= rs.getString("phone_number") %></td> <td></td> <td><%= rs.getString("e_mail") %<%= rs.getString("e_mail") %>></td> </tr> </td> </tr> <% } %><% } %> </table> </table>
Java Server PageDisplay_search_results.jsp
ServletServletListing 2 SearchPhoneBookServlet.java
package servlet_tutorials.PhoneBook; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import java.sql.*; import java.net.*; public class SearchPhoneBookServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String query = null; String where = null; String firstname = null; String lastname = null; ResultSet rs = null; res.setContentType("text/html"); PrintWriter out = res.getWriter(); // check which if any fields in the submitted form are empty if (req.getParameter("FirstName").length() > 0) firstname = req.getParameter("FirstName"); else firstname = null; if (req.getParameter("LastName").length() > 0) lastname = req.getParameter("LastName"); else lastname = null; // Build sql query string if ((firstname != null) && (lastname != null)){ where = "first_name ='"; where += firstname; where += "' AND "; where += "last_name ='"; where += lastname; where += "'"; } else if ((firstname == null) && (lastname != null)){ where = "last_name ='"; where += lastname; where += "'"; }
Java Bean & Database Java Bean & Database linkedlinked
Listing 4 PhoneBookBean.java
package servlet_tutorials.PhoneBook; import java.io.*; import java.net.*; import java.sql.*; import java.util.*; public class PhoneBookBean { private Connection con = null; private Statement stmt = null; private ResultSet rs = null; private String query = null; public PhoneBookBean() {} public ResultSet getResultSet(String query) { // grab a connection to the database con = ConnectDB.getConnection(); try{ stmt = con.createStatement(); // run the sql query to obtain a result set rs = stmt.executeQuery(query); } catch(SQLException sqlex){ sqlex.printStackTrace(); } catch (RuntimeException rex) { rex.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } return rs; } }
Listing 5 ConnectDB.java
package servlet_tutorials.PhoneBook; import java.io.*; import java.net.*; import java.sql.*; import java.util.*; /** * Re-usable database connection class */ public class ConnectDB { // setup connection values to the database static final String DB_DRIVER = "sun.jdbc.odbc.JdbcOdbcDriver"; static final String URL = "jdbc:odbc:PhoneBook"; static final String USERNAME = "anon_user"; static final String PASSWORD = ""; // Load the driver when this class is first loaded static { try { Class.forName(DB_DRIVER).newInstance(); } catch (ClassNotFoundException cnfx) { cnfx.printStackTrace(); } catch (IllegalAccessException iaex){ iaex.printStackTrace(); } catch(InstantiationException iex){ iex.printStackTrace (); } } /** * Returns a connection to the database */ public static Connection getConnection() { Connection con = null; try { con = DriverManager.getConnection(URL, USERNAME, PASSWORD); } catch (Exception e) { e.printStackTrace(); } finally { return con;
ReferencesReferences
http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Overviehttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Overview.htmlw.html
www.cis.upenn.edu/~matuszek/ cit597-2004/Lectures/21-servlets.pptwww.cis.upenn.edu/~matuszek/ cit597-2004/Lectures/21-servlets.ppt http://learning.unl.ac.uk/im269/lectures/week6servletsp1.ppthttp://learning.unl.ac.uk/im269/lectures/week6servletsp1.ppt http://java.sun.com/docs/books/tutorialNB/download/tut-servlets.ziphttp://java.sun.com/docs/books/tutorialNB/download/tut-servlets.zip http://www.webdevelopersjournal.com/articles/intro_to_servlets.htmlhttp://www.webdevelopersjournal.com/articles/intro_to_servlets.html
Top Related