Week 6 Servlets I Brief review of Java
Week 6 – Servlets I Brief review of Java inheritance n Introduction to Java servlet programming n 1
But first: Some regular expression references n http: //www. jansfreeware. com/articles/regexpress. html (contains a validator) n http: //www. visibone. com/regular-expressions COMP/DCOM 461 – CWB 2
The Role of Servlets in Server-Side Response Handling and Page Generation Browser Server POST or GET Form Validation Request Validation Result Java. Script Code HTTP (Web) Server Response Page Perl URL HTTP Params Servlet Container HTTP HTML Perl Script COMP/DCOM 461 – CWB URL HTTP Params HTTP HTML Servlet This is a Java object 3
Java Inheritance Concepts n What does this mean? public class My. Abc extends Abc n What does this mean? public class My. Abc implements Xyz COMP/DCOM 461 – CWB 4
To Extend a Class public class My. Abc extends Abc • If f() exists in Abc, this { overrides it for My. Abc int f() { … } • If f() does not exist in Abc, this }; adds a new method to My. Abc n My. Abc can n n Override the definitions of methods in Abc Add new methods and members that are not in Abc Use extension when you like what a class does generally but want to tweak some of its functionality or add some additional functionality. Think of extending as creating a sub-type. COMP/DCOM 461 – CWB 5
Extending n To extend a class means n My class can do anything your class can do, (only better). And more! n Any place you can use the base class, you can use the extended (derived) class COMP/DCOM 461 – CWB 6
Interfaces n What’s an interface? COMP/DCOM 461 – CWB 7
Interfaces n An interface is a set of method declarations public interface Xyz { int f(); void g(int a); }; n A semicolon instead of a method body A class may declare that it meets an interface (or multiple interfaces) public Abc implements Xyz { int f(){. . . } void g(int a) {. . . } }; COMP/DCOM 461 – CWB Commits class Abc to providing an implementation for each of the methods of the interface Xyz 8
Interfaces are often used to specify the API for some set of related functionality with the expectation that there may be multiple actual classes that meet the specification. COMP/DCOM 461 – CWB 9
Implementing n Implementing an interface means n n I guarantee that all the methods mentioned in the interface are in my class You can use my class any time the interface is called for in an API COMP/DCOM 461 – CWB 10
Servlets 11
The Servlet Concept n Servlet: a Java object that is invoked to respond to the URL request n n Much like a Perl CGI script The web container maps a particular URL path to a particular servlet. n For example, http: //cs. franklin. edu: 8461/brownc/Orders n might be mapped to the Java class file Orders. class An instance of that class would be used to handle the request COMP/DCOM 461 – CWB 12
Servlet Classes n A servlet is a Java class that implements a standard interface: javax. servlet. Servlet n n Contains methods for initialization, termination, and handling requests. Usually, your servlet class would extend the abstract class javax. servlet. http. Http. Servlet, n n Implements the Servlet interface Provides some commonly needed functionality http: //java. sun. com/j 2 ee/1. 4/docs/api/javax/servlet/Servlet. html COMP/DCOM 461 – CWB http: //java. sun. com/j 2 ee/1. 4/docs/api/javax/servlet/http/Http. Servlet. html 13
A Simple Servlet package app; /* a bunch of import statements go here*/ public class My. Servlet extends Http. Servlet { protected void do. Get(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { response. set. Content. Type("text/html"); response. set. Status(Http. Servlet. Response. SC_OK); Print. Writer out = response. get. Writer(); out. println("<html><head><title>Simple</title></head >"); out. println("<body>Hello Class!</body></html>"); out. close(); } }; http: //cs. franklin. edu: 8461/brownc/My. Servlet COMP/DCOM 461 – CWB 14
How the Servlet Container Invokes a Servlet Maps the HTTP Request URL to the servlet class Web Server Servlet Container once Http. Servlet init() My. Servlet every request once service() do. Get() web. xml destroy() do. Post() COMP/DCOM 461 – CWB The dashed arrows mean that the subclass method is invoked if it’s present 15
Servlet Lifetimes n The container creates an instance of your servlet class n Typically it creates an instance when first accessed and reuses that instance for all subsequent requests n n n There may be multiple simultaneous requests on the same instance (on separate threads) n n n init() method invoked only when instance is created Will re-load the instance if you re-compile the servlet class service() method invoked multiple times, possibly simultaneously It calls do. Get() or do. Post() as appropriate The container may unload the servlet at any time n destroy() method invoked COMP/DCOM 461 – CWB cont … 16
Servlet Lifetimes, cont. n Load-on-Startup n n An option to create one or more instance of the servlet class when the server starts up Defined in WEB-INF/web. xml COMP/DCOM 461 – CWB 17
Implications What are the implications of the container invoking a servlet multiple times simultaneously? COMP/DCOM 461 – CWB 18
Warning n Since there may be several simultaneous requests outstanding on the same servlet instance … n n Do not keep user-specific information in servlet fields – use the session object (next week) Make sure your code is thread-safe in general COMP/DCOM 461 – CWB 19
Servlets and the Model. View-Controller Pattern Request Response Request Context Servlet Class JSP Get/Set Session Context Get Java Bean COMP/DCOM 461 – CWB 20
Java Beans n n Java classes designed to certain conventions so that their properties may be ascertained through inspection For our purposes: n n Has a zero-argument constructor Accessing property abc of type T public T get. Abc() … n Changing property of type T public void set. Abc(T new. Value) … COMP/DCOM 461 – CWB 21
Implementing a Model with Java Beans Define a class for each type of object in the model 1. n 2. 3. E. g. , Shopping. Cart, Order, Registration The classes should implement Serializable For each property in a model object, say last. Name, Write a set method: public void set. Last. Name(String s) n Write a get method: public String get. Last. Name() n Write a validation tester method: public boolean is. Last. Name. Valid() Write a method public boolean is. Valid() to indicate if n 4. the data as a whole is valid If the object needs to be persistent, 5. n n Write a save method Write a method to instantiate an object, either reloading a saved object or creating a new one COMP/DCOM 461 – CWB 22
Saving Objects n n n Ideally a database is used (not in 461) Write data to a file in a format you choose. (We use this for the Order Model since we use a Perl script to read it. ) Use java. io. Object. Output. Stream. n The object and all its contents must be Serializable. COMP/DCOM 461 – CWB 23
Serializing an Object. Output. Stream oos = new Object. Output. Stream( new File. Output. Stream(fname)); oos. write. Object(reg); n Put code in try-catch because IO exceptions can be thrown http: //java. sun. com/j 2 se/1. 4. 2/docs/api/java/io/Object. Output. Stream. html COMP/DCOM 461 – CWB 24
Retrieving a Serialized Object. Input. Stream ois = new Object. Input. Stream( new File. Input. Stream(fname)); Registration reg= (Registration)ois. read. Object(); n Put code in try-catch because IO exceptions can be thrown http: //java. sun. com/j 2 se/1. 4. 2/docs/api/java/io/Object. Input. Stream. html COMP/DCOM 461 – CWB 25
Implementing a Servlet First: a View-Generating Servlet 26
The Servlet Support Classes -- HTTPServlet http: //java. sun. com/j 2 ee/1. 4/docs/api/javax/servlet/http/Http. Servlet. html n HTTPServlet class helps you get started implementing a servlet n n n Provides default methods for init(), destroy(), and service() (and others) Provide a service() method that invokes do. Get() or do. Post() depending on the type of request You override do. Get() and/or do. Post() to generate a response COMP/DCOM 461 – CWB 27
do. Get and do. Post protected void do. Get( Http. Servlet. Request req, Http. Servlet. Response resp) throws Servlet. Exception, IOException protected void do. Post( Http. Servlet. Request req, Http. Servlet. Response resp) throws Servlet. Exception, IOException What should be in the request and response objects? COMP/DCOM 461 – CWB 28
The Servlet Support Classes -- HTTPServlet. Request class has methods for n Getting cookies n Getting HTTP Headers n Various parts of the URL n Query-string or POST-content parameters (form fields) n Session context http: //java. sun. com/j 2 ee/1. 4/docs/api/javax/s ervlet/http/Http. Servlet. Request. html n Authorization COMP/DCOM 461 – CWB 29
Sidebar – interpreting the path http: //java. sun. com/webservices/docs/1. 0/tut orial/doc/Servlets 7. html#64433 n Context Path – ‘/’ + context root of your web app n Servlet Path – the alias that referred to this servlet, starting with ‘/’ n Path info – any stuff beyond the servlet path, excluding the query string COMP/DCOM 461 – CWB 30
Response What should be in Http. Servlet. Response? COMP/DCOM 461 – CWB 31
The Servlet Support Classes -- HTTPServlet. Response class has methods for n Adding cookies n Setting HTTP headers (Content-Type, etc. ) n Setting the HTTP status code (200, 404, etc. ) n Sending redirects (causing browser to go somewhere else) n Obtaining a Print. Writer or Output. Stream for generating output n n Note: you only print/output the content of the document, not the headers as you do with Perl CGI Flushing the output COMP/DCOM 461 – CWB 32
The Servlet Support Classes -- Cookie class is used to define a cookie, which is then sent using the add. Cookie method of HTTPServlet. Response n public Cookie(String name, String value) n public String get. Name() n public String get. Value() n public void set. Domain(String pattern) n public void set. Max. Age(int expiry) n public void set. Path(String uri) n public void set. Comment(String purpose) COMP/DCOM 461 – CWB 33
The Servlet Support Classes -- Servlet. Output. Stream n Obtain from the Http. Servlet. Response: Servlet. Output. Stream out = response. get. Output. Stream(); n n n Note: this throws IOException Servlet. Output. Stream class has a variety of methods for printing ints, floats, Strings, etc. n out. println(…) outputs with a new-line n out. print(…) outputs without a new-line Each of these methods n n Throws IOException Has return-type void COMP/DCOM 461 – CWB 34
Implementing a Servlet Remember: must be the first line of the. java file n n Declare package servlet will be in; e. g. , package app; Include the required J 2 EE packages Define a class that extends HTTPServlet Write a do. Get() and/or do. Post() method n n n Make sure the code is thread-safe! Set headers (at least Content Type) Print HTML code with the Servlet. Output. String or the Print. Writer Manage database, file, mail, or other connections If you need special operations at the time the servlet is initialized and/or destroyed, override the init() and/or destroy() methods COMP/DCOM 461 – CWB 35
The Packages That Are Usually Required import import javax. servlet. Servlet. Exception; javax. servlet. Unavailable. Exception; javax. servlet. http. Http. Servlet. Request; javax. servlet. http. Http. Servlet. Response; java. io. IOException; java. io. Print. Writer; //if used COMP/DCOM 461 – CWB 36
Conventions for Our Project web. xml is set up assuming n The package for the servlets is “app”, so the following must appear at the beginning of the servlet. java file: package app; n The first servlet assignment The second servlet assignment n n The servlets are placed in the directory WEB-INF/classes/app The servlet class for the Confirm Order page is called “Confirm. Order” The servlet class for the Controller servlet is called “Controller” COMP/DCOM 461 – CWB 37
The Simple Servlet Revisited Package for this servlet Required packages package app; import javax. servlet. Servlet. Exception; import javax. servlet. Unavailable. Exception; import javax. servlet. http. Http. Servlet. Request; Http. Servlet provides a lot import javax. servlet. http. Http. Servlet. Response; of default behavior for a import java. io. IOException; servlet import java. io. Print. Writer; public class My. Servlet extends Http. Servlet { request gives protected void do. Get(Http. Servlet. Request request, Http. Servlet. Response response) access to the URL and throws Servlet. Exception, IOException parameters in the { request response. set. Content. Type("text/html"); response. set. Status(Http. Servlet. Response. SC_OK); Print. Writer out = response. get. Writer(); response out. println("<html><head><title>Simple</title></head>"); out. println("<body>Hello Class!</body></html>"); provides out. close(); methods for } generating }; http: //cs. franklin. edu: 8461/brownc/My. Servlet Setting HTTP headers COMP/DCOM 461 – CWB the response 38
WEB-INF/web. xml Entries for My. Servlet <servlet> <servlet-name>My. Servlet</servlet-name> <servlet-class>app. My. Servlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>My. Servlet</servlet-name> <url-pattern>/My. Servlet/*</url-pattern> </servlet-mapping> COMP/DCOM 461 – CWB 39
Generating the HTTP Headers response. set. Content. Type("text/html"); response. set. Int. Header("Content-Length", len); response. set. Header("Content-Language", "es"); response. set. Status(Http. Servlet. Response. SC_OK); There a lot of these status codes in the Http. Servlet. Response documentation: http: //java. sun. com/j 2 ee/1. 4/docs/api/javax/servlet /http/Http. Servlet. Request. html n Also see cookie information on next slide COMP/DCOM 461 – CWB If provided, allows the web server to implement keep-alive. But it’s hard to figure out! 40
Cookie Handling n Getting existing cookies: Cookie[] clist= request. get. Cookies(); for(c= 0; c < clist. length; c++) if(clist[c]. get. Name(). equals("user. Prefs")) user. ID= clist[c]. get. Value(); n Setting cookies: name and value String prefs= my. Get. Preferences(); Cookie cookie= new Cookie("user. Prefs", prefs); cookie. set. Path("/"); cookie. set. Domain("franklin. edu"); cookie. set. Max. Age(-1); //expire when browser closes response. add. Cookie(Cookie cookie); COMP/DCOM 461 – CWB 41
Two Objects for Generating HTML n Stream output: Servlet. Output. Stream out= response. get. Output. Stream(); n n Each print and println method throws IOException Unless you catch IOException, your do. Get() or do. Post() will throw the IOException to the container, which will automatically generate an error response Prefer: use try-catch around the entire do. Get method body to provide user-friendly error message Writer output: Print. Writer out= response. get. Writer(); n n No exceptions are thrown Must call out. check. Error() to determine if failure occurred Use one or the other, but do not mix COMP/DCOM 461 – CWB 42
Obtaining HTTP Parameters (form values) To obtain a form field value passed in the query string (GET) or request message content (POST): String item. Id = request. get. Parameter("Item. ID"); if (item. Id != null) ; //do something with item. Id COMP/DCOM 461 – CWB 43
Obtaining Integer HTTP Parameters (form values) n Getting an integer-valued header int item = request. get. Int. Parameter("Item. ID"); if (item != -1) ; //handle integer parameter here COMP/DCOM 461 – CWB 44
Obtaining Multiple-Valued Parameters n When the form field might be sent multiple times: int item = -1; String[] item. Ids = request. get. Parameter. Values("Item. ID"); if (item. Ids != null) for(i = 0; i < item. Ids. length; i++) ; //process item. Ids[i] here COMP/DCOM 461 – CWB 45
Handling Errors -Exceptions n If do. Get() or do. Post() throws an IOException, Servlet. Exception, n n The container generates a response printing an exception message – not pretty If your code throws other types of exceptions, you have to catch them and translate them into a Servlet. Exception – see next slide http: //cs. franklin. edu: 8461/brownc/Exc. Servlet. java. txt COMP/DCOM 461 – CWB 46
Servlet. Exception Handling exceptions in do. Get() or do. Post(): catch(Some. Exception ex) { //some clean up work goes here throw new Servlet. Exception( "The widget database lookup failed. ", ex); Provide a better message; } one that is meaningful in the context of your servlet COMP/DCOM 461 – CWB 47
Example of Catching Exceptions in a Servlet http: //cs. franklin. edu: 8461/brownc/Better. Exc. Servlet. java. txt http: //cs. franklin. edu: 8461/brownc/Better. Exc. Servlet n Still not an ideal error message, though! COMP/DCOM 461 – CWB 48
Handling Errors – Logs n To log error messages: log( "some message"); log( "some message", an. Exception); n Where do the messages end up? n n Your web app’s log file – the file in the logs directory with today’s date in its name Accessing from a browser: n n n Set up a browser shortcut or link to refer to the logs directory Click on the file with today’s date in its name If you go back, be sure to do a refresh! http: //cs. franklin. edu: 8461/brownc/logs/ COMP/DCOM 461 – CWB 49
Including HTML from Other Sources Servlet. Context ctx= get. Servlet. Context(); Request. Dispatcher dispatch= ctx. get. Request. Dispatcher("/another. Url"); if(dispatch != null) dispatch. include(request, response); n n The URL must begin with “/” The URL is interpreted relative to the web app root. The result of invoking the URL is output to the response socket After include() returns, more output may be printed COMP/DCOM 461 – CWB 50
Forwarding n Forwarding means to switch to another resource (servlet, JSP, etc. ) without continuing the current servlet //Assume String dispatch. Url contains the URL to forward to if(dispatch. Url != null) The URL must { start with / Servlet. Context ctx= get. Servlet. Context(); Request. Dispatcher disp= ctx. get. Request. Dispatcher(dispatch. Url); if(disp != null) disp. forward(request, response); else throw new Servlet. Exception("Unknown view: " + dispatch. Url); return; //May not add anything more to the response } COMP/DCOM 461 – CWB 51
Building Your Servlet n n Building with javac on Einstein should work At home n n You must have the J 2 EE classes in your classpath Obtain from http: //java. sun. com/j 2 ee/sdk_1. 3/ n Remember: n Your servlet must be in a package called app n n Thus it must have a package statement package app; Thus the class file must reside in WEB-INF/classes/app COMP/DCOM 461 – CWB 52
Tips n n Put your source in the same directory as the class files are installed Make sure the class file is readable by “other” chmod 604 n Make sure the directories are readable and “executable” n n n If a directory has group “student”: chmod 705 If a directory has group “faculty”: chmod 750 Put log statements in your code while debugging Remove non-error cases once it’s working! Use javap to check interfaces and classes n n n Code-a-little, test-a-little COMP/DCOM 461 – CWB 53
Servlet References n n Chapters 6 and 7 of text (Wrox) Sun Tutorial: http: //java. sun. com/webservices/docs/1. 0/tutorial/doc/Servlets. html n n n Servlet (and other J 2 EE) API: http: //java. sun. com/j 2 ee/1. 4/docs/api/index. html Standard Java API: http: //java. sun. com/j 2 se/1. 3/docs/api/ Common Problems: http: //java. sun. com/webservices/docs/1. 0/tutorial/doc/Getting. Started 10. html#64516 n Example servlets from Sun (follow instructions for downloading the tutorial to obtain the source): http: //java. sun. com/webservices/docs/1. 0/tutorial/doc/Preface. html#63746 n The COMP 345 Tip Sheet: http: //cs. franklin. edu/~hanes/servlet-tips. html n n Remember: COMP/DCOM 461 installation for Tomcat is different Class source code: as referenced in previous slides with URLs of the form http: //cs. franklin. edu: 8461/brownc/XXXXX. java. txt COMP/DCOM 461 – CWB 54
Maintaining Session State Keeping the Model in the Session Context 55
Session Context n n n The session context contains a set of named attributes that can be any Serializable object The attributes should be objects that need to be present for the duration of a user session Typical attributes n n Model objects Other Serializable objects such as String objects COMP/DCOM 461 – CWB 56
Servlet Session Objects Request Servlet Container Session For User C Session For User B For User A A named attribute cart: Model Obj In the servlet’s do. Get or do. Post method: Http. Session session = request. get. Session(true); COMP/DCOM 461 – CWB Retrieves the session for this user true means: Create session if necessary 57
Http. Session: Selected Methods Your servlet can insert n void set. Attribute( String name, Object value); Object get. Attribute( String name); n n Cast this to the type of the object you set in the request context: n Order ord= (Order)session. get. Attribute( “Order. Model”); any number of named objects into the session context Later, any servlet or JSP can retrieve those object by name The value objects should be Serializable since the Web Container may need to save them to disk temporarily The value objects are often Model objects COMP/DCOM 461 – CWB 58
A Shopping Cart Example Using Session Data http: //cs. franklin. edu: 8461/brownc/Cart. java. txt http: //cs. franklin. edu: 8461/brownc/Cart n Note: This is an example of using the session state. In the Controller assignment, the servlet will set up the session context and then forward to a separate resource to generate the shopping cart view COMP/DCOM 461 – CWB 59
How Does the Servlet Container Maintain Sessions? n Cookies n n The Servlet Container assigns a unique ID to each session The Container sets a cookie whose value is this ID When a new request comes in with this cookie set, the Container can look up the Http. Session object using the ID If the client refuses cookies … COMP/DCOM 461 – CWB 60
How Does Servlet Container Maintain Sessions If Cookies Are Refused? n n The servlet container uses URL parameters to pass the session ID All URLs referring to a servlet that uses the session must contain the appropriate parameter n Such URLs can be generated with the encode. Url(String) method n n n This is a method in Http. Servlet. Response It adds the session ID stuff to the supplied URL This includes URLs in action, href, or src attributes COMP/DCOM 461 – CWB 61
Generating a Link Using encode. Url() String url= "/some. Page. html"; out. println("<a href="" + response. encode. Url(url) + "">Example Link</a>"); Modifies the given URL to encode the session ID. http: //cs. franklin. edu: 8461/brownc/Cart. java. txt http: //cs. franklin. edu: 8461/brownc/Cart COMP/DCOM 461 – CWB 62
To Encode URL or Not? n Encoding URL n n Permits sessions to work if browser refuses cookies Requires all pages participating in the session to be generated so that their internal URL references may contain the proper encoding Difficult for pages generated by a non-J 2 EE mechanism Not encoding URL n n Easier Suitable only if it’s OK for sessions to fail if the user’s browser is configured to reject cookies URL encoding is not required for the assignments in this course. COMP/DCOM 461 – CWB 63
The Request Context n n Cast this to the type of the object you set in the request context. Recall: the request context is valid for the lifetime of the request, including any forwards or includes. To save or retrieve items in the Request Context, use the following methods of the Http. Servlet. Request object n n void set. Attribute(String name, Object value) Object get. Attribute(String name) COMP/DCOM 461 – CWB 64
The Servlet Homework Assignments n Due next week: write a servlet that generates the Confirm Order page n n n Replace all lines in your HTML file with println statements Temporarily hard-code any data required Keep it simple n n n Simplify the design of the page if you want Include any HTML that would not vary from order-toorder or user-to-user Due after the exam: write a controller servlet COMP/DCOM 461 – CWB 65
Next Week n n Servlet-based Controllers Java. Bean Data Models COMP/DCOM 461 – CWB 66
- Slides: 66