1、1,Introduction to Java Server-Side Technologies: Servlets and JSP,Sun tutorial to servlets,Sun JSP Tutorial,2,Introduction to Servlets,3,What is a Servlet?,Servlets are Java programs that can be run dynamically from a Web Server Servlets are a server-side technology A Servlet is an intermediating la
2、yer between an HTTP request of a client and the data stored on the Web server,4,A Java Servlet,Web browser,Web server,Servlet,5,An Example,In the following example, the local server calls the Servlet TimeServlet with an argument supplied by the user,This example, as well as all the examples in this
3、lecture can be found at http:/inferno:5000/ (accessible only from CS!),6,Reload / Refresh Servlet Result,Trying to refresh the content created by a servlet will lead to fetching a new content from the server This is not the case with static resources Response headers of a static (as opposed to a ser
4、vlet generated) resource contain Etag, Last-Modified While trying to refresh a resource Cache-Contol: max-age=0 is sent and that means the server/proxies will try to revalidate the resource Only in the static case the resource could be revalidated against some values the client holds So in the stati
5、c case the client sends the Etag value attached to the If-None-Match header, and the Last-Modified value is sent in If-Modified-Since,Clear the cache, open and then reload /dbi/Time.html Open and reload /dbi/init Compare the headers sent and received.,7,What can Servlets do?,Read data sent by the us
6、er (e.g., form data) Look up other information about the request in the HTTP request (e.g. authentication data, cookies, etc.) Generate the result (may do this by talking to a database, file system, etc.) Format the result as a document (e.g., convert it into HTML format) Set the appropriate HTTP re
7、sponse parameters (e.g. cookies, content-type, etc.) Send the resulting document to the user,8,Supporting Servlets,To run Servlets, the Web server must support them Apache Tomcat Also functions as a module for other Apache servers Sun Java System Web Server and Java System Application Server IBMs We
8、bSphere Application Server BEAs Weblogic Application Server Macromedias Jrun an engine that can be added to Microsofts IIS, Apaches Web servers and more. Oracle Application Server ,9,Creating a Simple Servlet,Read more about the Servlet Interface,10,The Servlet Interface,Java provides the interface
9、Servlet Specific Servlets implement this interface Whenever the Web server is asked to invoke a specific Servlet, it activates the method service() of an instance of this Servlet,11,HTTP Request Methods,POST - application data sent in the request body GET - application data sent in the URL HEAD - cl
10、ient sees only header of response PUT - place documents directly on server DELETE - opposite of PUT TRACE - debugging aid OPTIONS - list communication options,12,Servlet Hierarchy,YourOwnServlet,HttpServlet,Generic Servlet,Servlet,service(ServletRequest, ServletResponse),doGet(HttpServletRequest , H
11、ttpServletResponse) doPost(HttpServletRequest HttpServletResponse) doPut doTrace ,Called by the servlet container to allow the servlet to respond to any request method,Called by the servlet container to allow the servlet to respond to a specific request method,A generic, protocol-independent class,
12、implementing Servlet,13,Class HttpServlet,Class HttpServlet handles requests and responses of HTTP protocol The service() method of HttpServlet checks the request method and calls the appropriate HttpServlet method: doGet, doPost, doPut, doDelete, doTrace, doOptions or doHead This class is abstract,
13、Read more about the HttpServlet Class,That is, a class that can be sub-classed but not instantiated. This class methods however are not abstract,14,Creating a Servlet,Extend the class HTTPServlet Implement doGet or doPost (or both; also maybe others) Both methods get: HttpServletRequest: methods for
14、 getting form (query) data, HTTP request headers, etc. HttpServletResponse: methods for setting HTTP status codes, HTTP response headers, and get an output stream used for sending data to the client Many times, we implement doPost by calling doGet, or vice-versa,You could also run: CheckRequestServl
15、et /dbi/empty ,Check the result of an empty implementation http:/localhost/dbi/empty,15,import java.io.*; import javax.servlet.*; import javax.servlet.http.*;public class TextHelloWorld extends HttpServlet public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IO
16、Exception PrintWriter out = res.getWriter();out.println(“Hello World“);public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException doGet(req, res); ,HelloWorld.java,16,Returning HTML,By default, no content type is given with a response In order to generat
17、e HTML: Tell the browser you are sending HTML, by setting the Content-Type header (response.setContentType() Modify the printed text to create a legal HTML page You should set all headers before writing the document content. Can you guess why?,Download LiveHttpHeaders Extension,As you can check usin
18、g LiveHttpHeaders plug-in,17,public class HelloWorld extends HttpServlet public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException PrintWriter out = response.getWriter();out.println(“Hello Worldn“);out.println(“);out.println(“ + new java.util.Date
19、() + “n“);out.println(“Hello Worldn“); ,HelloWorld.java,Content type wasnt set, but the browser will understand )dont rely on this in a real product / the project),18,Configuring the Server,helloHelloWorldhello/hello,myApp/WEB-INF/web.xml,http:/inferno:5000/dbi/hello,More on this in when we Tomcat i
20、n depth,19,Getting Information From the Request,20,An HTTP Request Example,GET /default.asp HTTP/1.0 Accept: image/gif, image/x-xbitmap, image/jpeg, image/png, */* Accept-Language: en Connection: Keep-Alive Host: magni.grainger.uiuc.edu User-Agent: Mozilla/4.04 en (WinNT; I ;Nav) Cookie:SITESERVER=I
21、D=8dac8e0455f4890da220ada8b76f; ASPSESSIONIDGGQGGGAF=JLKHAEICGAHEPPMJKMLDEM Accept-Charset: iso-8859-1,*,utf-8,21,Getting HTTP Data,Values of the HTTP request can be accessed through the HttpServletRequest object Get the value of the header hdr using getHeader(“hdr“) of the request argument Get all
22、header names: getHeaderNames() Methods for specific request information: getCookies, getContentLength, getContentType, getMethod, getProtocol, etc.,Read more about the HttpRequest Interface,22,public class ShowRequestHeaders extends HttpServlet public void doGet(HttpServletRequest request,HttpServle
23、tResponseresponse) throws ServletException, IOException response.setContentType(“text/html“);PrintWriter out = response.getWriter();String title = “Servlet Example: Showing Request Headers“;out.println(“ + title + “n“ + “ + title+ “n“+ “Request Method: “+request.getMethod()+“+ “Request URI: “+reques
24、t.getRequestURI()+“+ “ServletPath: “+request.getServletPath()+“+ “Request Protocol: “+request.getProtocol()+“+ “n“+ “Header NameHeader Value“);,23,Enumeration headerNames = request.getHeaderNames();while (headerNames.hasMoreElements() String headerName = (String) headerNames.nextElement();out.printl
25、n(“ + headerName + “ +“+request.getHeader(headerName)+“);out.println(“n“); public void doPost(HttpServletRequest request,HttpServletResponseresponse) throws ServletException, IOException doGet(request, response); ,Compare the results of the different browsers,24,User Input in HTML,Using HTML forms,
26、we can pass parameters to Web applications comprises a single form action: the address of the application to which the form data is sent method: the HTTP method to use when passing parameters to the application (e.g. get or post),25,The Tag,Inside a form, INPUT tags define fields for data entry Stan
27、dard input types include: buttons, checkboxes, password fields, radio buttons, text fields, image-buttons, text areas, hidden fields, etc. Each one associates a single (string) value with a named parameter,26,GET Example,http:/ Example,POST /search HTTP/1.1 Host: Content-type: application/x-www-for
28、m-urlencoded Content-length: 10q=servlets,Google doesnt support POST! (try to guess why),28,Getting the Parameter Values,To get the (first) value of a parameter named x: req.getParameter(“x“) where req is the service request argument If there can be multiple values for the parameter: req.getParamete
29、rValues(“x“) To get parameter names: req.getParameterNames(),29,Sending Parameterspdisplay:table-row spandisplay:table-cell; padding:0.2em Please enter the parametersBackground color:Font color: Font size:,parameters.html,30,public class SetColors extends HttpServlet public void doGet(HttpServletReq
30、uestrequest,HttpServletResponse response)throws ServletException, IOException response.setContentType(“text/html“);PrintWriter out = response.getWriter();String bg = request.getParameter(“bgcolor“);String fg = request.getParameter(“fgcolor“);String size = request.getParameter(“size“);,An Example (co
31、nt),SetColors.java,31,out.println(“Set Colors Example“+“);out.println(“);out.println(“Set Colors Example“);out.println(“You requested a background color “ + bg + “);out.println(“You requested a font color “ + fg + “);out.println(“You requested a font size “ + size + “);out.println(“); ,An Example (c
32、ont),SetColors.java,32,public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException doGet(request, response); ,You dont have to do anything different to read POST data instead of GET data. (Cool!), ,Handling Post,33,Creating the Response of the Serv
33、let,34,HTTP Response,The response includes: Status line: version, status code, status message Response headers Empty line Content,HTTP/1.1 200 OK Content-Type: text/html Content-Length: 89 Server: Apache-Coyote/1.1HELLO WORLD Hello World ,Read more about the HttpResponse Interface,35,Setting the Res
34、ponse Status,Use the following HttpServletResponse methods to set the response status: setStatus(int sc) Use when there is no error, like 201 (created) No need to send 200 OK explicitly sendError(sc), sendError(sc, message) Use in erroneous situations, like 400 (bad request) The server may return a
35、formatted message sendRedirect(String location) As opposed to forwarding which is done within the server side completely, on redirect the client gets the “Location” header and a special code (302) and sends another request to the new location,http:/localhost/dbi/redirect,36,Setting the Response Stat
36、us,Class HTTPServletResponse has static integer variables for popular status codes for example: SC_OK(200), SC_NOT_MODIFIED(304), SC_UNAUTHORIZED(401), SC_BAD_REQUEST(400) Status code 200 (OK) is the default,37,Setting Response Headers,Use the following HTTPServletResponse methods to set the respons
37、e headers: setHeader(String hdr, String value), setIntHeader(String hdr, int value) If a header with the same name exists, it is overridden. addHeader(String hdr, String value), addIntHeader(String hdr, int value) The header is added even if another header with the same name exists.,38,Specific Resp
38、onse Headers,Class HTTPServletResponse provides setters for some specific headers: setContentType setContentLength automatically set if the entire response fits inside the response buffer setDateHeader setCharacterEncoding,39,More Header Methods,containsHeader(String header) Check existence of a hea
39、der in the response addCookie(Cookie) sendRedirect(String url) automatically sets the Location header Do not write into the response after sendError or sendRedirect,Check the result of writing a response after sendError/sendRedirect http:/localhost/dbi/bad.html,40,The Response Content Buffer,The res
40、ponse body is buffered Data is sent to the client when the buffer is full or the buffer is explicitly flushed Once the first data chunk is sent to the client, the response is committed You cannot set the response line nor change the headers. Such operations are either ignored or cause an exception t
41、o be thrown,Check the result of sendError/setContentType getting “commited” http:/localhost/dbi/bad.html,41,Buffer Related Methods,setBufferSize, getBufferSize What are the advantages of using big buffers? what are the disadvantages? flushBuffer resetBuffer Clears the unsent body content reset Clear
42、s any data that exists in the buffer as well as the status code and headers (if not yet sent) isCommitted,42,Supporting HTTP Methods,43,The HEAD Method,The simple implementation of doHead is executing doGet and excluding the response body In addition, the size of the body is calculated and added to
43、the headers You do not have to override this method Why would one want to override this method? The content size is not calculated in servlets as opposed to static html resources,Check the default implementation of doHead: Run CheckRequestServlet /dbi/init GET Run CheckRequestServlet /dbi/init HEAD
44、Run CheckRequestServlet /dbi/Time.html HEAD (shorter output yet its length is calculated) In class HOST=localhost, PORT=80,44,The HEAD Method (cont),The right way to implement doHead is : Dont implement doHead explicitly Instead, check within the doGet call, what is the requested method (httpServlet
45、Request.getMethod() If its HEAD do the same without returning the content This way the results of HEAD / GET requests are similar as they should be,45,OPTIONS and TRACE,doOptions returns the supported methods: For example, if you override doGet then the following header will be returned: Allow: GET,
46、 HEAD, TRACE, OPTIONS doTrace returns the request itself in the body of the message, for debugging purposes You usually do not override these methods Override doOptions if you offer some new methods,46,Unsupported Methods,By default, the methods doPost, doGet, doPut and doDelete return an error stat
47、us code 405 with the message: HTTP method XXX is not supported by this URL doHead calls doGet and therefore leads to the same result but with unsupported method GET In particular, you have to override doGet and doPost if you want to return an appropriate response for these methods Many applications
48、support only one of GET/POST,47,Servlet Life Cycle,48,Servlet Life Cycle,When the servlet mapped URL is requested, the server loads the Servlet class and initializes one instance of it Each client request is handled by the Serlvet instance in a separate threadThe server can remove the Servlet The Se
49、rvlet can remain loaded to handle additional requests,49,Servlet Life Cycle,When the Servlet in instantiated, its method init() is invoked (in our case, by Tomcat) External parameters are supplied Upon a request, its method service() is invoked Before the Servlet removal, its method destroy() is invoked,50,Servlet Life Cycle,Servlet Class,Calling the init method,ServletInstance,Deal with requests: call the service method,