Presentation is loading. Please wait.

Presentation is loading. Please wait.

Servlets Replace Common Gateway Interface Scripts Extend Server Functionality Modules (software components) Like applets to browsers No GUI.

Similar presentations


Presentation on theme: "Servlets Replace Common Gateway Interface Scripts Extend Server Functionality Modules (software components) Like applets to browsers No GUI."— Presentation transcript:

1 Servlets Replace Common Gateway Interface Scripts Extend Server Functionality Modules (software components) Like applets to browsers No GUI

2

3 Versus CGI Easier to Write Faster to Run Platform Independence Handle HTTP Client Requests HTML Forms

4 Setup javax.servlet 2.4 http://java.sun.com/products/servlet/ Servlet Capable Web Server

5 What is a Servlet? Servlet interface defines methods that manage servlet and its communication with clients Servlet implements Servlet interface Extends a conveniance class (GenericServlet or HTTPServlet) Client Interaction: When it accepts call, service method receives two objects –ServletRequest –ServletResponse

6 Architecture

7 Http The service method of HttpServlet dispatches a request to different Java methods for different HTTP request methods. The recognized methods are GET, HEAD, PUT, POST, DELETE, OPTIONS and TRACE. An HTTP method XXX is dispatched to a Java method doXxx, e.g. GET -> doGet. All these methods expect the parameters " (HttpServletRequest req, HttpServletResponse res) ".

8 import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloClientServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println(" Hello Client! "+ " Hello Client! "); out.close(); } public String getServletInfo() { return "HelloClientServlet 1.0 by Stefan Zeiger"; }

9 8: private Vector addresses; 9: private String filename; 10: 11: public void init(ServletConfig config) throws ServletException 12: { 13: super.init(config); 14: filename = config.getInitParameter("addressfile"); 15: if(filename == null) 16: throw new UnavailableException(this, 17: "The \"addressfile\" property "+ 18: "must be set to a file name"); 19: try 20: { 21: ObjectInputStream in = 22: new ObjectInputStream(new FileInputStream(filename)); 23: addresses = (Vector)in.readObject(); 24: in.close(); 25: } 26: catch(FileNotFoundException e) { addresses = new Vector(); } 27: catch(Exception e) 28: { 29: throw new UnavailableException(this, 30: "Error reading address file: "+e); 31: } 32: } 104: private synchronized boolean subscribe(String email) throws IOException 105: { 106: if(addresses.contains(email)) return false; 107: addresses.addElement(email); 108: save(); 109: return true; 110: } 111: 112: private synchronized boolean unsubscribe(String email) throws IOException 113: { 114: if(!addresses.removeElement(email)) return false; 115: save(); 116: return true; 117: } 118: 119: private void save() throws IOException 120: { 121: ObjectOutputStream out = 122: new ObjectOutputStream(new FileOutputStream(filename)); 123: out.writeObject(addresses); 124: out.close(); 125: }

10 protected void doGet(HttpServletRequest req, 35: HttpServletResponse res) 36: throws ServletException, IOException 37: { 38: res.setContentType("text/html"); 39: res.setHeader("pragma", "no-cache"); 40: PrintWriter out = res.getWriter(); 41: out.print(" List Manager "); 42: out.print(" Members: "); 43: for(int i=0; i<addresses.size(); i++) 44: out.print(" " + addresses.elementAt(i)); 45: out.print(" "); 46: out.print("Enter your email address: "); 47: out.print(" "); 48: out.print(" "); 49: out.print(" "); 50: out.close(); 51: }

11

12 protected void doPost(HttpServletRequest req, 54: HttpServletResponse res) 55: throws ServletException, IOException 56: { 57: String email = req.getParameter("email"); 58: String msg; 59: if(email == null) 60: { 61: res.sendError(res.SC_BAD_REQUEST, 62: "No email address specified."); 63: return; 64: } 65: if(req.getParameter("action").equals("subscribe")) 66: { 67: if(subscribe(email)) 68: msg = "Address " + email + " has been subscribed."; 69: else 70: { 71: res.sendError(res.SC_BAD_REQUEST, 72: "Address " + email + " was already subscribed."); 73: return; 74: } 75: } 76: else 77: { 78: if(unsubscribe(email)) 79: msg = "Address " + email + " has been removed."; 80: else 81: { 82: res.sendError(res.SC_BAD_REQUEST, 83: "Address " + email + " was not subscribed."); 84: return; 85: } 86: } 88: res.setContentType("text/html"); 89: res.setHeader("pragma", "no-cache"); 90: PrintWriter out = res.getWriter(); 91: out.print(" List Manager "); 92: out.print(msg); 93: out.print(" <A HREF=\""); 94: out.print(req.getRequestURI()); 95: out.print("\">Show the list "); 96: out.close(); 97: }

13 ServletRequest Interface Encapsulates communication from client to server Parameters passed by client, protocol used by client, names of remote host, and server ServletInputStream for data transfer from client to server using HTTP POST and PUT HttpServletRequest access HTTP header info

14 ServletResponse Interface Methods for replying to client Set content length and MIME type of reply ServletOutputStream and a Writer to send data HttpServletResponse protocol specific

15 Http Specifics MIME: Multipurpose Internet Mail Extension to identify file type GET/POST/PUT: Ways that browser sends form data to the server Persistent Sessions Cookies

16 public class SimpleServlet extends HttpServlet { /** * Handle the HTTP GET method by building a simple web page. */ public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out; String title = "Simple Servlet Output"; // set content type and other response header fields first response.setContentType("text/html"); // then write the data of the response out = response.getWriter(); out.println(" "); out.println(title); out.println(" "); out.println(" " + title + " "); out.println(" This is output from SimpleServlet."); out.println(" "); out.close(); } }

17 Subclass HttpServlet Override doGet() User Request encapsulated in HttpServletRequest object Response encapsulated in HttpServletResponse object Use output stream from HttpServletResponse

18 Interacting with Clients Requests and Responses Header Data Get Requests Post Requests Threading Servlet Descriptions

19 Handle requests through service method (calls doGet() ) HttpServletRequest Objects –getParameter returns value of named parameter –getParameterValues if more than one value –getParameterNames for names of parameters –getQueryString for HTTP GET returns string of raw data from client. Must parse. –HTTP POST, PUT, DELETE Requests Text: getReader returns BufferedReader Binary: getInputStream returns ServletInputStream

20 HttpServletResponse Object –getWriter returns a Writer for text –getOutputStream returns ServletOutputStream for binary –Set header data before above IO set –setContentType in header

21 public class ShowParameters extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Reading All Request Parameters"; out.println(ServletUtilities.headWithTitle(title) + " \n" + " " + title + " \n" + " \n" + " Parameter Name Parameter Value(s)"); Enumeration paramNames = request.getParameterNames(); while(paramNames.hasMoreElements()) { String paramName = (String)paramNames.nextElement(); out.println(" " + paramName + "\n "); String[] paramValues = request.getParameterValues(paramName); if (paramValues.length == 1) { String paramValue = paramValues[0]; if (paramValue.length() == 0) out.print(" No Value "); else out.print(paramValue); } else { out.println(" "); for(int i=0; i<paramValues.length; i++) { out.println(" " + paramValues[i]); } out.println(" "); } out.println(" \n "); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }

22

23 A Sample FORM using POST A Sample FORM using POST <FORM ACTION="/servlet/hall.ShowParameters" METHOD="POST"> Item Number: Quantity: Price Each: First Name: Last Name: Middle Initial: Shipping Address: Credit Card: <INPUT TYPE="RADIO" NAME="cardType" VALUE="Visa">Visa <INPUT TYPE="RADIO" NAME="cardType" VALUE="Master Card">Master Card <INPUT TYPE="RADIO" NAME="cardType" VALUE="Amex">American Express <INPUT TYPE="RADIO" NAME="cardType" VALUE="Discover">Discover <INPUT TYPE="RADIO" NAME="cardType" VALUE="Java SmartCard">Java SmartCard Credit Card Number: Repeat Credit Card Number:

24


Download ppt "Servlets Replace Common Gateway Interface Scripts Extend Server Functionality Modules (software components) Like applets to browsers No GUI."

Similar presentations


Ads by Google