Servlet Allen Long Email: allen@huihoo.com http://www.huihoo.com 2004-04 Huihoo - Enterprise Open Source http://www.huihoo.com 1
Huihoo - Enterprise Open Source http://www.huihoo.com 2
GET POST Huihoo - Enterprise Open Source http://www.huihoo.com 3
CGI FastCGI API (NSAPI ISAPI) ASP Servlet JSP Huihoo - Enterprise Open Source http://www.huihoo.com 4
Servlet Huihoo - Enterprise Open Source http://www.huihoo.com 5
Servlet Servlet Servlet Engine network Service, MIME request, Servlet Container Servlet Engine Servlet Servlet Engine Servlet Huihoo - Enterprise Open Source http://www.huihoo.com 6
Servlet Access Access Model Huihoo - Enterprise Open Source http://www.huihoo.com 7
Huihoo - Enterprise Open Source http://www.huihoo.com 8
Huihoo - Enterprise Open Source http://www.huihoo.com 9
Huihoo - Enterprise Open Source http://www.huihoo.com 10
Service Huihoo - Enterprise Open Source http://www.huihoo.com 11
Destroy Huihoo - Enterprise Open Source http://www.huihoo.com 12
Huihoo - Enterprise Open Source http://www.huihoo.com 13
Package javax.servlet.http Huihoo - Enterprise Open Source http://www.huihoo.com 14
HTTP Servlet Sample Extend HttpServlet The Service method is call by the servlet container for each request Huihoo - Enterprise Open Source http://www.huihoo.com 15
Sample Huihoo - Enterprise Open Source http://www.huihoo.com 16
HttpServletRequest CGI getparmeternames() HTML, getparmetervalues(string name) multi-valued getparameter(string name) Huihoo - Enterprise Open Source http://www.huihoo.com 17
HttpServletResponse servlet /...) URL Huihoo - Enterprise Open Source http://www.huihoo.com 18
Handling Requests Handling Requests Huihoo - Enterprise Open Source http://www.huihoo.com 19
ServletConfig Huihoo - Enterprise Open Source http://www.huihoo.com 20
An Example Huihoo - Enterprise Open Source http://www.huihoo.com 21
URLs A URL pointing to a Servlet can be split into portions: protocol, server, port Web Application name extra path information(servlet jsp html) the query string (containing parameters) Huihoo - Enterprise Open Source http://www.huihoo.com 22
Query Strings Use a query string to pass parameters from the browser to the web server. Query String Rules: Huihoo - Enterprise Open Source http://www.huihoo.com 23
Sample Huihoo - Enterprise Open Source http://www.huihoo.com 24
HTML Forms You can use HTML forms (instead of query strings) to send parameters to a servlet One parameter is passed for each form field HTML Form Syntax: Huihoo - Enterprise Open Source http://www.huihoo.com 25
Sample Huihoo - Enterprise Open Source http://www.huihoo.com 26
Response Structure A servlet uses an instance of HttpServletResponse to send data to the client. Huihoo - Enterprise Open Source http://www.huihoo.com 27
HttpServletResponse Huihoo - Enterprise Open Source http://www.huihoo.com 28
An Example Huihoo - Enterprise Open Source http://www.huihoo.com 29
Status/Error Messages The HttpServletResponse interface has many constants declared for status/errors: A Sampling of HTTP Constants: public static final SC_OK; // status code 200 public static final SC_NOT_FOUND; // status code 404 public static final SC_BAD_REQUEST; // status code 400 public static final SC_FORBIDDEN; // status code 403 These Values Can Be Used With: public void senderror(int); public void senderror(int, String); public void sendstatus(int); public void sendstatus(int, Stirng); Huihoo - Enterprise Open Source http://www.huihoo.com 30
HTTP Application (ServletContext) Session (HttpSession) Request () Page (JSP) Huihoo - Enterprise Open Source http://www.huihoo.com 31
Servlet Servlet Huihoo - Enterprise Open Source http://www.huihoo.com 32
public class SpecialSetter extends HttpServlet { public void doget(httpservletrequest req, HttpServletResponse res) throws ServletException, IOException { res.setcontenttype("text/plain"); PrintWriter out = res.getwriter(); ServletContext context = getservletcontext(); context.setattribute("com.costena.special.burrito", "Pollo Adobado"); context.setattribute("com.costena.special.day", new Date()); out.println("the burrito special has been set."); } } Huihoo - Enterprise Open Source http://www.huihoo.com 33
public class SpecialGetter extends HttpServlet { public void doget(httpservletrequest req, HttpServletResponse res) throws ServletException, IOException { res.setcontenttype("text/html"); PrintWriter out = res.getwriter(); ServletContext context = getservletcontext(); String burrito = (String) context.getattribute("com.costena.special.burrito"); Date day = (Date) context.getattribute("com.costena.special.day"); DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM); String today = df.format(day); out.println("our burrito special today (" + today + ") is: " + burrito); } } Huihoo - Enterprise Open Source http://www.huihoo.com 34
Session A session for a client is shared among multiple servlets. Huihoo - Enterprise Open Source http://www.huihoo.com 35
Web URL Cookie HttpSession Huihoo - Enterprise Open Source http://www.huihoo.com 36
The HttpSession object is the servlet s view of the session Session: public HttpSession getsession(boolean createnew); createnew: true session session false - session null Session: HttpSession session = request.getsession(true); Huihoo - Enterprise Open Source http://www.huihoo.com 37
HttpSession Huihoo - Enterprise Open Source http://www.huihoo.com 38
HttpSession public class SessionSnoop extends HttpServlet { public void doget(httpservletrequest req, HttpServletResponse res) throws ServletException, IOException { res.setcontenttype("text/html"); PrintWriter out = res.getwriter(); // Get the current session object, create one if necessary HttpSession session = req.getsession(); Integer count = (Integer)session.getAttribute("snoop.count"); if (count == null) count = new Integer(1); else count = new Integer(count.intValue() + 1); session.setattribute("snoop.count", count); out.println("<html><head><title>sessionsnoop</title></head>"); out.println("<body><h1>session Snoop</H1>"); out.println("<h3>here is your saved session data:</h3>"); Enumeration enum = session.getattributenames(); while (enum.hasmoreelements()) { String name = (String) enum.nextelement(); out.println(name + ": " + session.getattribute(name) + "<BR>"); } out.println("</body></html>"); } } Huihoo - Enterprise Open Source http://www.huihoo.com 39
Session web.xml <session-config> <session-timeout>30</session-timeout> </session-config> public void setmaxinactiveinterval(int interval) public int getmaxinactiveinterval() Huihoo - Enterprise Open Source http://www.huihoo.com 40
Servlets and Threads Huihoo - Enterprise Open Source http://www.huihoo.com 41
A servlet must be able to handle multiple, concurrent requests. Huihoo - Enterprise Open Source http://www.huihoo.com 42
Servlet Synchronized singelthreadmodel Huihoo - Enterprise Open Source http://www.huihoo.com 43
Huihoo - Enterprise Open Source http://www.huihoo.com 44
public class SimpleCounter extends HttpServlet { int count = 0; public void doget(httpservletrequest req, HttpServletResponse res) throws ServletException, IOException { res.setcontenttype("text/plain"); PrintWriter out = res.getwriter(); count++; out.println("since loading, this servlet has been accessed " + count + " times."); } } Huihoo - Enterprise Open Source http://www.huihoo.com 45
(block) Synchronized Block synchronized (AnyObject) { } The thread that can obtain AnyObject s mutex flag gets to enter the block Huihoo - Enterprise Open Source http://www.huihoo.com 46
Import java.io.*; Import javax.servlet.*; Import javax.servlet.http.*; Public class MultipleInstanceServlet extends HttpServlet { Object lock = null; public void init(servletconfig cg) { lock = new Object(); } Public void service(httpservletrequest request, HttpServletResponse response) throws IOExceptions, ServletException { synchronized(lock) { } // reqular code } } Huihoo - Enterprise Open Source http://www.huihoo.com 47
JBuilder Servlet Creating the project Creating the WebApp Creating the Servlet with the Servlet wizard Adding code to the Servlet Compiling and running the Servlet Huihoo - Enterprise Open Source http://www.huihoo.com 48
Create WebApp Huihoo - Enterprise Open Source http://www.huihoo.com 49
Creating the servlet with the Servlet wizard-1 Huihoo - Enterprise Open Source http://www.huihoo.com 50
Creating the servlet with the Servlet wizard-2 Huihoo - Enterprise Open Source http://www.huihoo.com 51
Creating the servlet with the Servlet wizard-3 Huihoo - Enterprise Open Source http://www.huihoo.com 52
Web Application Huihoo - Enterprise Open Source http://www.huihoo.com 53
Web Server Setup Huihoo - Enterprise Open Source http://www.huihoo.com 54
Tomcat Tomcat jakarta JavaWorld 2001 java (Most Innovative Java Product) sun servlet jsp ( http://java.sun.com/products/jsp/tomcat/) servlet jsp tomcat Huihoo - Enterprise Open Source http://www.huihoo.com 55
Web Application Archive (WAR) HTML JSP Java class Java jar Web (web.xml) Huihoo - Enterprise Open Source http://www.huihoo.com 56
WAR Huihoo - Enterprise Open Source http://www.huihoo.com 57
ServletConfig web.xml servlet Huihoo - Enterprise Open Source http://www.huihoo.com 58
Servlet Mapping Huihoo - Enterprise Open Source http://www.huihoo.com 59
Servlet Mapping <servlet> <servlet-name>hi</servlet-name> <servlet-class>helloworld</servlet-class> </servlet> <servlet-mapping> <servlet-name> hi</servlet-name> <url-pattern> /hello.html</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name> hi</servlet-name> <url-pattern> *.hello</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name> hi</servlet-name> <url-pattern> /hello/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name> hi</servlet-name> <url-pattern> /hello.html</url-pattern> </servlet-mapping> Huihoo - Enterprise Open Source http://www.huihoo.com 60
Web Huihoo - Enterprise Open Source http://www.huihoo.com 61
Servlet Huihoo - Enterprise Open Source http://www.huihoo.com 62
Huihoo - Enterprise Open Source http://www.huihoo.com 63
weblogic.xml Huihoo - Enterprise Open Source http://www.huihoo.com 64
Application Event Listener Servlet Event listener are classes that respond to notifications about ServletContext HttpSession Huihoo - Enterprise Open Source http://www.huihoo.com 65
Listener ServletContextListener ServletContextAttributeListener, HttpSessionListener HttpSessionAttributeListener Huihoo - Enterprise Open Source http://www.huihoo.com 66
Event ServletContextEvent ServletContextAttributeEvent HttpSessionEvent HttpSessionBindingEvent Huihoo - Enterprise Open Source http://www.huihoo.com 67
Sample Huihoo - Enterprise Open Source http://www.huihoo.com 68
<listener> <listener-class>app.listener</listener-class> </listener> Huihoo - Enterprise Open Source http://www.huihoo.com 69
GOF Observer( ) Huihoo - Enterprise Open Source http://www.huihoo.com 70
Servlet Filter : Log Huihoo - Enterprise Open Source http://www.huihoo.com 71
Servlet Filter Change request Change response Huihoo - Enterprise Open Source http://www.huihoo.com 72
Develop Filter Huihoo - Enterprise Open Source http://www.huihoo.com 73
Sample Huihoo - Enterprise Open Source http://www.huihoo.com 74
<filter> <filter-name>servlet3</filter-name> <filter-class>untitled7.servlet3</filter-class> <init-param> <param-name>param</param-name> <param-value /> </init-param> </filter> <filter-mapping> <filter-name>servlet3</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> Huihoo - Enterprise Open Source http://www.huihoo.com 75
Filter Chain Order Filter execute in the order they are define in the web.xml file <filter> <filter-name>authfilter</filter-name> <filter-class>untitled7.authfilter</filter-class> </filter> <filter> <filter-name>logfilter</filter-name> <filter-class>untitled7.logfilter</filter-class> </filter> <filter> <filter-name>servlet3</filter-name> <filter-class>untitled7.servlet3</filter-class> <filter> Huihoo - Enterprise Open Source http://www.huihoo.com 76
SA Huihoo - Enterprise Open Source http://www.huihoo.com 77
SA Huihoo - Enterprise Open Source http://www.huihoo.com 78
Huihoo - Enterprise Open Source http://www.huihoo.com 79
Huihoo - Enterprise Open Source http://www.huihoo.com 80
Sample public class HelloWorldGraphics extends HttpServlet { public void doget(httpservletrequest req, HttpServletResponse res) throws ServletException, IOException { ServletOutputStream out = res.getoutputstream(); // binary output! Frame frame = null; Graphics g = null; try { // Create an unshown frame frame = new Frame(); frame.addnotify(); // Get a graphics region, using the Frame Image image = frame.createimage(400, 60); g = image.getgraphics(); Huihoo - Enterprise Open Source http://www.huihoo.com 81
Sample // Draw "Hello World!" to the off-screen graphics context g.setfont(new Font("Serif", Font.ITALIC, 48)); g.drawstring("hello World!", 10, 50); // Encode the off-screen image into a GIF and send it to the client res.setcontenttype("image/gif"); GifEncoder encoder = new GifEncoder(image, out); encoder.encode(); } finally { // Clean up resources if (g!= null) g.dispose(); if (frame!= null) frame.removenotify(); } } } Huihoo - Enterprise Open Source http://www.huihoo.com 82
Servlet SVG Servlet XML Huihoo - Enterprise Open Source http://www.huihoo.com 83
http://java.sun.com/products/servlet/ sun servlet http://www.huihoo.com Huihoo - Enterprise Open Source http://www.huihoo.com 84
allen@huihoo.com http://www.huihoo.com Huihoo - Enterprise Open Source http://www.huihoo.com 85