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

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

Dec 21, 2015

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Servlets Replace Common Gateway Interface Scripts Extend Server Functionality Modules (software components) Like applets to browsers No GUI.

Servlets

• Replace Common Gateway Interface Scripts

• Extend Server Functionality

• Modules (software components)

• Like applets to browsers

• No GUI

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

Versus CGI

• Easier to Write

• Faster to Run

• Platform Independence

• Handle HTTP Client Requests

• HTML Forms

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

Setup

• javax.servlet 2.4• http://java.sun.com/products/servlet/

• Servlet Capable Web Server

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

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

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

Architecture

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

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)".

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

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("<HTML><HEAD><TITLE>Hello Client!</TITLE>"+

"</HEAD><BODY>Hello Client!</BODY></HTML>"); out.close(); }

public String getServletInfo() { return "HelloClientServlet 1.0 by Stefan Zeiger"; }}

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

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 IOException105: {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 IOException113: {114: if(!addresses.removeElement(email)) return false;115: save();116: return true;117: }118:119: private void save() throws IOException120: {121: ObjectOutputStream out =122: new ObjectOutputStream(new FileOutputStream(filename));123: out.writeObject(addresses);124: out.close();125: }

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

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("<HTML><HEAD><TITLE>List Manager</TITLE></HEAD>"); 42: out.print("<BODY><H3>Members:</H3><UL>"); 43: for(int i=0; i<addresses.size(); i++) 44: out.print("<LI>" + addresses.elementAt(i)); 45: out.print("</UL><HR><FORM METHOD=POST>"); 46: out.print("Enter your email address: <INPUT TYPE=TEXT NAME=email><BR>"); 47: out.print("<INPUT TYPE=SUBMIT NAME=action VALUE=subscribe>"); 48: out.print("<INPUT TYPE=SUBMIT NAME=action VALUE=unsubscribe>"); 49: out.print("</FORM></BODY></HTML>"); 50: out.close(); 51: }

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

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("<HTML><HEAD><TITLE>List Manager</TITLE></HEAD><BODY>"); 92: out.print(msg); 93: out.print("<HR><A HREF=\""); 94: out.print(req.getRequestURI()); 95: out.print("\">Show the list</A></BODY></HTML>"); 96: out.close(); 97: }

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

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

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

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

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

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

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

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("<HTML><HEAD><TITLE>"); out.println(title); out.println("</TITLE></HEAD><BODY>"); out.println("<H1>" + title + "</H1>"); out.println("<P>This is output from SimpleServlet."); out.println("</BODY></HTML>"); out.close(); }

}

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

• Subclass HttpServlet• Override doGet()• User Request encapsulated in

HttpServletRequest object• Response encapsulated in

HttpServletResponse object• Use output stream from

HttpServletResponse

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

Interacting with Clients

• Requests and Responses

• Header Data

• Get Requests

• Post Requests

• Threading

• Servlet Descriptions

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

• 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

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

• HttpServletResponse Object– getWriter returns a Writer for text– getOutputStream returns ServletOutputStream for binary

– Set header data before above IO set– setContentType in header

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

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) + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=CENTER>" + title + "</H1>\n" + "<TABLE BORDER=1 ALIGN=CENTER>\n" + "<TR BGCOLOR=\"#FFAD00\">\n" + "<TH>Parameter Name<TH>Parameter Value(s)"); Enumeration paramNames = request.getParameterNames(); while(paramNames.hasMoreElements()) { String paramName = (String)paramNames.nextElement(); out.println("<TR><TD>" + paramName + "\n<TD>"); String[] paramValues = request.getParameterValues(paramName); if (paramValues.length == 1) { String paramValue = paramValues[0]; if (paramValue.length() == 0) out.print("<I>No Value</I>"); else out.print(paramValue); } else { out.println("<UL>"); for(int i=0; i<paramValues.length; i++) { out.println("<LI>" + paramValues[i]); } out.println("</UL>"); } } out.println("</TABLE>\n</BODY></HTML>"); }

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}

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

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML><HEAD> <TITLE>A Sample FORM using POST</TITLE></HEAD>

<BODY BGCOLOR="#FDF5E6"><H1 ALIGN="CENTER">A Sample FORM using POST</H1>

<FORM ACTION="/servlet/hall.ShowParameters" METHOD="POST"> Item Number: <INPUT TYPE="TEXT" NAME="itemNum"><BR> Quantity: <INPUT TYPE="TEXT" NAME="quantity"><BR> Price Each: <INPUT TYPE="TEXT" NAME="price" VALUE="$"><BR> <HR> First Name: <INPUT TYPE="TEXT" NAME="firstName"><BR> Last Name: <INPUT TYPE="TEXT" NAME="lastName"><BR> Middle Initial: <INPUT TYPE="TEXT" NAME="initial"><BR> Shipping Address: <TEXTAREA NAME="address" ROWS=3 COLS=40></TEXTAREA><BR> Credit Card:<BR> <INPUT TYPE="RADIO" NAME="cardType" VALUE="Visa">Visa<BR> <INPUT TYPE="RADIO" NAME="cardType" VALUE="Master Card">Master Card<BR> <INPUT TYPE="RADIO" NAME="cardType" VALUE="Amex">American Express<BR> <INPUT TYPE="RADIO" NAME="cardType" VALUE="Discover">Discover<BR> <INPUT TYPE="RADIO" NAME="cardType" VALUE="Java SmartCard">Java SmartCard<BR> Credit Card Number: <INPUT TYPE="PASSWORD" NAME="cardNum"><BR> Repeat Credit Card Number: <INPUT TYPE="PASSWORD" NAME="cardNum"><BR><BR> <CENTER> <INPUT TYPE="SUBMIT" VALUE="Submit Order"> </CENTER></FORM>

</BODY></HTML>

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