COSC 2206 Internet Tools Java Servlets BGA Java
COSC 2206 Internet Tools Java Servlets BGA
Java Servlets Tomcat Web Application Hello World Servlet Simple Servlets BGA
What is a servlet? n n n A servlet is a special Java class that can be loaded by a servlet enabled web server to respond to an HTTP request with an HTTP response. Servlets usually execute in a multi-threaded environment inside a servlet container that is part of the web server. We will use the Jakarta-Tomcat web server 11/26/2020 BGA 3
Comparison with CGI n n n Servlets are much more efficient than CGI scripts. Once a servlet is loaded it can efficiently respond to many requests. Each is a separate thread (lightweight process) In CGI each request causes a separate external process to be started in the operating system. 11/26/2020 BGA 4
Comparison with CGI n n Servlets have built-in object-oriented functionality for dealing with the HTTP request and the associated list of namevalue pairs resulting from a form or url submission They have support for cookies They have support for session management They are essentially part of the Web server rather than separate processes. 11/26/2020 BGA 5
Comparison with CGI n Servlets are portable and use a standard object-oriented API with several packages n n n javax. servlet. http For JSP there are the additional packages n n javax. servlet. jsp. tagext 11/26/2020 BGA 6
Some Interfaces and Classes Servlet. Context interface class Servlet. Config Http. Session implements extends Servlet. Request Http. Servlet. Request Servlet. Response Http. Servlet. Response Generic. Servlet Http. Servlet 11/26/2020 Servlet. Input. Stream Cookie Servlet. Output. Stream Servlet. Exception BGA 7
Servlet Life-cycle 1. Server loads servlet: creates an instance Servlet 2. init method is called Servlet 3. Servlet instance accepts 0 or more client requests Servlet Container 4. Server calls destroy method and unloads servlet A servlet is a class that extends the Http. Servlet class 11/26/2020 BGA 8
Servlet/Client interaction (1) client request Servlet client request Servlet Container Several client requests can be made to the same servlet instance using a thread for each request 11/26/2020 BGA 9
Servlet/Client Interaction (2) client making a GET request do. Get client making a GET request Servlet do. Post client making a POST request Server sends an Http. Request object to the servlet's do. Get or do. Post method. An Http. Response object is also sent so the servlet can use it for the response 11/26/2020 BGA 10
Simple Servlet Template (1) import javax. servlet. *; import javax. servlet. http. *; // other imports public class Template. Servlet extends Http. Servlet { public void init() { // called once when servlet created } public void destroy() { // called once when servlet is unloaded } // continued on next slide 11/26/2020 BGA 11
Simple Servlet Template (2) public void do. Get(Http. Servlet. Request request, Http. Servlet. Response response) throws IOException, Servlet. Exception { // Handle a GET request here } public void do. Post(Http. Servlet. Request request, Http. Servlet. Response response) throws IOException, Servlet. Exception { // Handle a POST request here } // other methods } 11/26/2020 BGA 12
HTTPServlet methods (1) n public void init() n n n called only once by servlet container just after the servlet is loaded into the servlet container public void destroy() n n called only once by servlet container just before the servlet is unloaded (removed) from the servlet container Note: Http. Servlet extends the Generic. Servlet class 11/26/2020 BGA 13
HTTPServlet methods (2) n protected void do. Get(Http. Servlet. Request request, Http. Servlet. Response response) throws IOException, Servlet. Exception n n the server (servlet container) calls this method when a client makes a GET request the request object contains information on the request such as parameters and their values this method responds using the response object this method should be thread-safe 11/26/2020 BGA 14
HTTPServlet methods (3) n protected void do. Post(Http. Servlet. Request request, Http. Servlet. Response response) throws IOException, Servlet. Exception n n the server (servlet container) calls this method when a client makes a POST request in a form. the request object contains information on the request such as form parameters and their values this method responds using the response object this method should be thread-safe 11/26/2020 BGA 15
HTTPServlet methods (4) n public String get. Init. Parameter(String name) n n Return a string for the value of an initialization parameter name If no value exists null is returned This method is used to get servlet initialization name-value pairs from the application's web. xml file More on this later 11/26/2020 BGA 16
HTTPServlet methods (5) n public Enumeration get. Init. Parameter. Names() n n n Return all the names of the initialization parameters as an enumeration This is useful if you don't know the names. Each name can then be used in the get. Init. Parameter method to get the value. 11/26/2020 BGA 17
Http. Servlet methods (6) n public Servlet. Config get. Servlet. Config() n n Each servlet in a web application has its own Servlet. Config object that is used by the servlet container to pass initialization information to the servlet. This initialization information is obtained from the web application's deployment descriptor (Tomcat) : the web. xml file we will see an example later that uses the <servlet> tag in the web. xml file 11/26/2020 BGA 18
Http. Servlet methods (7) n public Servlet. Context get. Servlet. Context() n n There is one Servlet. Context object per web application. It is used for communication between the application's servlets and the servlet container we will see an example later that uses the <context-param> tag in the web. xml file to provide context information. 11/26/2020 BGA 19
Http. Servlet. Request methods n String get. Parameter(String name) n n Enumeration get. Parameter. Names() n n get all parameter names as a list String[] get. Parameter. Values(name) n n get value of the specified parameter A parameter may have several values so this method returns all values as a string array There are many other methods 11/26/2020 BGA 20
Http. Servlet. Response methods n Servlet receives a response object of this type that it uses to send reply back to the client. Some important methods are n n n void set. Content. Type(String type) void set. Content. Length(int len) Print. Writer get. Writer() Servlet. Output. Stream get. Output. Stream() add. Cookie(Cookie cookie) send. Redirect(String location) 11/26/2020 BGA 21
Course web applications n n The web application called test is used only for the examples in the tomcat install instructions The remaining examples use a web application called c 2206 Both of these applications are available as the war files test. war and c 2206. war Put these files in webapps directory and tomcat will unpack them after a restart 11/26/2020 BGA 22
The Hello. World servlet (1) import java. io. *; import javax. servlet. http. *; public class Hello. World extends Http. Servlet { public void do. Get(Http. Servlet. Request request, Http. Servlet. Response response) throws IOException, Servlet. Exception { response. set. Content. Type("text/html"); Print. Writer out = response. get. Writer(); 11/26/2020 BGA 23
The Hello. World servlet (2) Send the HTML document out. println( "<html>n" + "<head>n" + "<title>Hello World</title>n" + "</head>n" + "<body>n" + "<h 1>Hello World</h 1>n" + "This html document was " + "produced by a servlet. n" + "</body>n" + "</html>n" ); out. close(); 11/26/2020 BGA 24
Compiling the servlet (1) n Put servlet in the test application directory c: tomcatwebappstestWEB-INFclasses n To compile it use the path and classpath SET PATH=c: j 2 sdk 1. 4. 2bin; %PATH% SET CLASSPATH=. ; c: tomcatwebappstestWEB-INFclasses SET CLASSPATH=%CLASSPATH%; c: tomcatcommonlibservlet-api. jar n Note: we have not put this servlet in a package (it's in default package). In practice most servlets are in named packages. 11/26/2020 BGA 25
Compiling the servlet (2) n Now use the compiler command from the classes directory: n n n javac Hello. World. java It is better to make a custom prompt to set the appropriate classpath. Tomcat installation notes show to do this. 11/26/2020 BGA 26
Testing the servlet (2) n Since we put the Hello. World servlet in the default package and didn't define a logical name for it in web. xml we can test it using n n http: //localhost: 8080/test/servlet/Hello. World there is also a version in the mypackage. It can be tested using n http: //localhost: 8080/test/servlet/mypackage. Hel lo. World Note this 11/26/2020 BGA 27
Testing the servlet (3) n n We can use the web. xml file to define servlet mappings which allow us to use logical names for our servlet: First define a servlet name in web. xml <servlet> <servlet-name>Example 1</servlet-name> <servlet-class>Hello. World</servlet-class> </servlet> mypackage. Hello. World for the package version 11/26/2020 BGA 28
Testing the servlet (4) n (1) Define a servlet mapping in web. xml <servlet-mapping> <servlet-name>Example 1</servlet-name> <url-pattern>helloa</url-pattern> </servlet-mapping> n Now the following url can be used n n http: //localhost: 8080/test/helloa See Tomcat installation notes 11/26/2020 BGA 29
Testing the servlet (5) n n The order of the tags in web. xml is important: all <servlet> tags must precede all <servlet-mapping> tags Also, when you modify web. xml it is usually necesssary to stop and restart the tomcat server so that it reads the new file. 11/26/2020 BGA 30
c 2206 web application n n Now we use the c 2206 web application Place a copy of c 2206. war in the webapps directory and restart tomcat The c 2206. war file will be automatically unpacked into a web app directory called c 2206 Now delete the war file in webapps. Why? 11/26/2020 BGA 31
Getting Init Parameters (1 a) n Initialization parameters are specified in the web. xml file using the XML tags <servlet> <servlet-name>Init. Parameter. Servlet</servlet-name> <servlet-class>simple. Init. Parameter. Servlet</servletclass> <init-param> <param-name>message</param-name> <param-value>This is the message in web. xml</paramname> </init-param> </servlet>. . . <servlet-mapping> <servlet-name>Init. Parameter. Servlet</servlet-name> <url-pattern>init</url-pattern> </servlet-mapping> 11/26/2020 BGA 32
Getting Init Parameters (1 b) n web. xml file is located in directory n n c: tomcatwebappsc 2206WEB-INF Run the servlet n n n http: //localhost: 8080/c 2206/init Servlet source code is located in directory c: tomcatwebappsc 2206WEBINFclassessimpleInit. Parameter. Servlet. java 11/26/2020 BGA 33
Getting Init Parameters (2) package simple; import java. io. *; import javax. servlet. http. *; public class Init. Parameter. Servlet extends Http. Servlet { private String message; private String default. Message = "This is the default message"; 11/26/2020 BGA 34
Getting Init Parameters (3) public void init() { Servlet. Config config = get. Servlet. Config(); message = config. get. Init. Parameter("message"); if (message == null) message = default. Message; } public void do. Post(Http. Servlet. Request request, Http. Servlet. Response response) throws IOException, Servlet. Exception { A trick for handling do. Get(request, response); GET and POST } requests in same way 11/26/2020 BGA 35
Getting Init Parameters (4) public void do. Get(Http. Servlet. Request request, Http. Servlet. Response response) throws IOException, Servlet. Exception { response. set. Content. Type("text/html"); Print. Writer out = new response. get. Writer(); out. println( "<html><head><title>" + message + "</title>" + "</head><body>" + "<h 1>" + message + "</h 1>" + "This HTML document was produced by a servlet" + "</body></html>"); out. close(); } } 11/26/2020 BGA 36
Dynamic Images (1) n n With Java 2 D it is easy to write a servlet that generates a dynamic image and returns it to the browser. Java 1. 4 has new imageio packages n n n import javax. imageio. *; import javax. imageio. stream. *; The supported types are JPG and PNG (portable network graphics) 11/26/2020 BGA 37
Dynamic Images (2) n Put HTML file images. html in test directory <html> <head><title>Generating Images with Servlets</title> </head> <body> <h 1>Generating Images with Servlets</h 1> <h 2>Generate a JPEG image dynamically</h 2> <img src="servlet/images. Image. Servlet 1" /> <h 2>Generate a PNG image dynamically</h 2> <img src="servlet/images. Image. Servlet 2" /> </body> note how servlets </html> are referenced 11/26/2020 BGA 38
Dynamic Images (3) n Try it n http: //localhost: 8080/c 2206/images. html 11/26/2020 BGA 39
Source code n Image. Servlet 1 and Image. Servlet 2 are located in directory n n c: tomcatwebappsc 2206WEBINFclassesimages Source code n n Image. Servlet 1. java Image. Servlet 2. java 11/26/2020 BGA 40
Image. Servlet 1. java (1) package images; import javax. servlet. *; import javax. servlet. http. *; import java. io. *; import java. awt. geom. *; import java. awt. image. *; import javax. imageio. stream. *; 11/26/2020 BGA 41
Image. Servlet 1. java (2) public class Image. Servlet 1 extends Http. Servlet { public void do. Get(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { // Make a simple image object Buffered. Image image = new Buffered. Image(100, Buffered. Image. TYPE_INT_RGB); Graphics 2 D g 2 D = (Graphics 2 D) image. get. Graphics(); 11/26/2020 BGA 42
Image. Servlet 1. java (3) g 2 D. set. Color(Color. yellow); Rectangle 2 D rect = new Rectangle 2 D. Double(25, 50, 50); g 2 D. fill(rect); g 2 D. dispose(); // Send image in JPEG format to browser Image. IO. set. Use. Cache(false); // important Output. Stream out = response. get. Output. Stream(); response. set. Content. Type("image/jpeg"); Image. IO. write(image, "jpg", out); out. close(); } } 11/26/2020 BGA 43
Image. Servlet 2. java n Replace response. Set. Content. Type("image/jpeg"); Image. IO. write(image, "jpg", out); n by response. Set. Content. Type("image/png"); Image. IO. write(image, "png", out); n in Image. Servlet 1 to get PNG output 11/26/2020 BGA 44
Getting client parameters (1) n n n Client information is sent to the server as a sequence of name-value pairs This is done either using a get request with a query string of name value pairs or by submitting an HTML form of name-value pairs. The servlet receives these pairs as part of an Http. Servlet. Request object. 11/26/2020 BGA 45
Getting client parameters (2) n n get. Parameter can be used if name is known and there's only one value for the parameter Example: suppose that request is an Http. Servlet. Request object and that "name" and "age" are parameters: String name = request. get. Parameter("name"); String age = request. get. Parameter("age"); n Note: values are always returned as strings 11/26/2020 BGA 46
Getting client parameters (3) n If a parameter has no value or there is no parameter with the specified name then null is returned so we can check using String name = request. get. Parameter("name"); if (name == null) { // didn't get parameter or name } else { // parameter exists and has a value } 11/26/2020 BGA 47
Getting client parameters (4) n Getting list of single-valued parameters Enumeration names = request. get. Parameter. Names(); if (names. has. More. Elements()) {. . . while (names. has. More. Elements()) { String name = (String) names. next. Element(); String value = request. get. Parameter(name); // do something with name and value here } else { // there were no parameters in request } 11/26/2020 BGA 48
Getting client parameters (5) n Getting list of multiple-valued parameters. Use the following while loop while (names. has. More. Elements()) { String name = (String) names. next. Element(); String[] values = request. get. Parameter. Values(name); for (int i = 0; i < values. length; i++) { // do something with the ith parameter with // this name } } 11/26/2020 BGA 49
Examples (1) n test/servlet/simple. Get. Request. Parameters 0 n n getting two specific parameters http: //localhost: 8080/c 2206/servlet/simple. Get. Request. Parameters 0? name=Fred&age =34 Source code: Get. Request. Parameters 0. java test/servlet/simple. Get. Request. Parameters 1 n n using get. Parameter. Names and get. Parameter in single valued case http: //localhost: 8080/c 2206/servlet/simple. Get. Request. Parameters 1? name=Fred+Flint stone&age=34 http: //localhost: 8080/c 2206/servlet/simple. Get. Request. Parameters 1? choice=Java&cho ice=Perl Source code: Get. Request. Parameters 1. java 11/26/2020 BGA 50
Examples (2) n test/servlet/simple. Get. Request. Parameters 2 n n n multiple valued case using get. Parameter. Values http: //localhost: 8080/c 2206/servlet/simple. Get. Request. Parameters 2? choice= Java&choice=Perl Source code: Get. Request. Parameters 2. java 11/26/2020 BGA 51
Get. Request. Parameters 0 package simple; import javax. servlet. *; import javax. servlet. http. *; import java. util. *; public class Get. Request. Parameters 0 extends Http. Servlet { public void do. Get(Http. Servlet. Request request, Http. Servlet. Response response) throws IOException, Servlet. Exception { response. set. Content. Type("text/html"); Print. Writer out = response. get. Writer(); // Display HTML header 11/26/2020 BGA 52
Get. Request. Parameters 0 // Display HTML header out. println("<html>" + "<head>n" + "<title>Get Request Parameters</title>n" + "</head>n" + "<bodyn" + "<h 1>Get Request Parameters</h 1>n" ); // Get the parameters explicitly String name = request. get. Parameter("name"); String age = request. get. Parameter("age"); 11/26/2020 BGA 53
Get. Request. Parameters 0 if (name == null) out. println("name was not specified n"); else if (name. equals("")) out. println("value for name not specified "); else out. println("value of name is " + name + " "); if (age == null) out. println("age was not specified n"); else if (age. equals("")) out. println("value of age not specified "); else out. println("value of age is " + age + "n"); out. println("</body>n</html>n"); out. close(); } } 11/26/2020 BGA 54
Get. Request. Parameters 1 package simple; import javax. servlet. *; import javax. servlet. http. *; import java. util. *; public class Get. Request. Parameters 1 extends Http. Servlet { public void do. Get(Http. Servlet. Request request, Http. Servlet. Response response) throws IOException, Servlet. Exception { response. set. Content. Type("text/html"); Print. Writer out = response. get. Writer(); // Display HTML header 11/26/2020 BGA 55
Get. Request. Parameters 1 // Display HTML header out. println("<html>" + "<head>n" + "<title>Get Request Parameters (single values</title>n" + "</head>n" + "<bodyn" + "<h 1>Get Request Parameters (single values</h 1>n" ); 11/26/2020 BGA 56
Get. Request. Parameters 1 // Get an enumeration of all the request // parameter names Enumeration parameter. Names = request. get. Parameter. Names(); // Display table header if (parameter. Names. has. More. Elements()) { out. println( "<table border="1">n" + "<tr>n" + "<th>Parameter Name</th>n" + "<th>Parameter Value</th>n" + "</tr>n" ); 11/26/2020 BGA 57
Get. Request. Parameters 1 // Iterate through the list and display the // parameter names and values while (parameter. Names. has. More. Elements()) { String parameter. Name = (String) parameter. Name. next. Element(); out. println( "<tr>n" + "<td>" + parameter. Name + "</td>n" + "<td>" + request. get. Parameter(parameter. Name) + "</td>n</tr>" ); } 11/26/2020 BGA 58
Get. Request. Parameters 1 else { out. println("No parameters were specified"); } out. println("</body></html>n"); out. close(); } 11/26/2020 BGA 59
Get. Request. Parameters 2 package simple; import javax. servlet. *; import javax. servlet. http. *; import java. util. *; public class Get. Request. Parameters 2 extends Http. Servlet { public void do. Get(Http. Servlet. Request request, Http. Servlet. Response response) throws IOException, Servlet. Exception { response. set. Content. Type("text/html"); Print. Writer out = response. get. Writer(); // Display HTML header 11/26/2020 BGA 60
Get. Request. Parameters 2 // Display HTML header out. println("<html>" + "<head>n" + "<title>Get Request Parameters (multiple values</title>n" + "</head>n" + "<bodyn" + "<h 1>Get Request Parameters (multiple values</h 1>n" ); 11/26/2020 BGA 61
Get. Request. Parameters 2 // Get an enumeration of all the request // parameter names Enumeration parameter. Names = request. get. Parameter. Names(); // Display table header if (parameter. Names. has. More. Elements()) { out. println( "<table border="1">n" + "<tr>n" + "<th>Parameter Name</th>n" + "<th>Parameter Value</th>n" + "</tr>n" ); 11/26/2020 BGA 62
Get. Request. Parameters 2 // Iterate through the list and display the // parameter names and values while (parameter. Names. has. More. Elements()) { String parameter. Name = (String) parameter. Name. next. Element(); // Get multiple values if any and put them // together in colon separated string String[] values = request. get. Parameter. Values(parameter. Name); String list = ""; for (int i=0; i < values. length; i++) { if (i == 0) list = values[0]; else list = list + ": " + values[i]; } 11/26/2020 BGA 63
Get. Request. Parameters 2 out. println( "<tr>n" + "<td>" + parameter. Name + "</td>n" + "<td>" + list + "</td>n" + "</tr>" ); } out. println("</table>n"); } else { out. println("No parameters were specified"); } out. println("</body>n</html>n"); out. close(); } 11/26/2020 BGA 64
Accessing the request headers n n n Use get. Header. Names() to return the header names as an Enumeration Use get. Header(name) to return the value of the header with the given name There also get methods that retrieve the CGI type parameters http: //localhost: 8080/c 2206/headers? name= fred Source code: Show. Request. Headers. java 11/26/2020 BGA 65
Show. Request. Headers package simple; import javax. servlet. *; import javax. servlet. http. *; import java. util. *; public class Show. Request. Headers extends Http. Servlet { public void do. Post(Http. Servlet. Request request, Http. Servlet. Response response) throws IOException, Servlet. Exception { do. Get(request, response); } 11/26/2020 BGA 66
Show. Request. Headers public void do. Get(Http. Servlet. Request request, Http. Servlet. Response response) throws IOException, Servlet. Exception { response. set. Content. Type("text/html"); Print. Writer out = response. get. Writer(); out. println( "<html><head>n" + "<title>Servlet Request Headers</title>n" + "<style type="text/css">n" + ". color {background-color: #CCCCCC; }n" + "</style>n" + "</head>n" + "<h 1>Servlet Request Headers</h 1>n" 11/26/2020 BGA 67
Show. Request. Headers + + + + "<b>Request Method: </b>" + request. get. Method() " n" "<b>Request PRotocol: </b>" + request. get. Protocol() " n" "<b>Auth Type: </b>" + request. get. Auth. Type() " n" "<b>Request URI: </b>" + request. Get. Request. URI() " n" "<b>Request URL: </b>" + request. get. Request. URL() " n" "Servlet Path: </b>" + request. get. Servlet. Path() " n" "Context Path: </b>" + request. get. Context. Path() " n" "Path Info: </b>" + request. get. Path. Info() 11/26/2020 BGA 68
Show. Request. Headers + + + " n" "<b>Path Translated: </b>" request. get. Path. Translated() " n" "Query String: </b>" + request. get. Query. String() " n" "<b>Remote User: </b>" + request. get. Remote. User() " n" "<table border="1">n" "<tr class="color">Header Name</th>n" "<th class="color">Header Values</th>n" "</tr>n" ); 11/26/2020 BGA 69
Show. Request. Headers Enumeration header. Names = request. get. Header. Names(); while (header. Names. has. More. Elements()) { String header. Name = (String) header. Names. next. Element(); out. println( "<tr>n" + "<td>" + header. Name + "</td>n" + "<td>" + request. get. Header(header. Name) + "</td>n<tr>" ); } out. println("</table>n</body>n</html>"); out. close(); }} 11/26/2020 BGA 70
COSC 2206 Internet Tools Java Servlets Simple Form Processing BGA
Form Processing with GET <html> <head><title>Processing form with GET</title></head> <body> <h 1>Processing form with GET</h 1> <form action="servlet/forms. Do. Form. Servlet 1" method="GET"> First name: <input type="text" name="firstname"> Last name: <input type="text" name="lastname"> <p><input type="submit" name="button" value="Submit Name"></p> </form></body></html> LOGICAL NAME form 1 CAN ALSO BE USED (see web. xml) 11/26/2020 BGA 72
Form Processing with POST <html> <head><title>Processing form with POST</title></head> <body> <h 1>Processing form with GET</h 1> <form action="servlet/forms. Do. Form. Servlet 1" method="POST"> First name: <input type="text" name="firstname"> Last name: <input type="text" name="lastname"> <p><input type="submit" name="button" value="Submit Name"></p> </form></body></html> LOGICAL NAME form 1 CAN ALSO BE USED (see web. xml) 11/26/2020 BGA 73
Do. Form. Servlet 1 public void do. Post(. . . ) { do. Get(request, response); } public void do. Get(. . . ) {. . . String first. Name = request. get. Parameter("firstname"); String last. Name = request. get. Parameter("lastname"); if (firstname == null) first. Name = ""; if (lastname == null) last. Name = ""; // Display page here showing parameter values } Do. Form. Servlet 1. java http: //localhost: 8080/c 2206/form 1_get. html http: //localhost: 8080/c 2206/form 1_post. html 11/26/2020 BGA 74
Generate form with servlet n The servlet can both generate the form and process it. The logic is IF button value is defined THEN process form and display output page ELSE display the page containing the form ENDIF http: //localhost: 8080/c 2206/servlet/forms. Do. Form. Servlet 2 http: //localhost: 8080/c 2206/form 2 11/26/2020 BGA 75
Do. Form. Servlet 2 public void do. Post(Http. Servlet. Request request, Http. Servlet. Response response) throws IOException { do. Get(request, response); } public void do. Get(Http. Servlet. Request request, Http. Servlet. Response response) throws IOException { String button = request. get. Parameter("button"); if (button != null) display. Output. Page(request, response); else display. Form. Page(request, response); } 11/26/2020 BGA 76
Do. Form. Servlet 2 public void display. Output. Page(Http. Servlet. Request request, Http. Servlet. Response response) throws IOException { String first. Name = request. get. Parameter("firstname"); String last. Name = request. get. Parameter("lastname"); if (first. Name == null) || firstname. equals("")) first. Name = "null"; if (last. Name == null) || last. Name. equals("")) last. Name = "null"; String self = request. get. Request. URI(); response. set. Content. Type("text/html"); Print. Writer out = response. get. Writer(); 11/26/2020 BGA 77
Do. Form. Servlet 2 out. println( "<html>n" + "<head><title>Form. Results</title></head>n" + "<body>n" + "<h 1>Form Results</h 1>n" + "Hello " + first. Name + " " + last. Name + " n" + "The request URI is " + self + "n" + "</body>n" + "</html>n" ); } 11/26/2020 BGA 78
Do. Form. Servlet 2 public void display. Form. Page(Http. Servlet. Request request, Http. Servlet. Response response) throws IOException { String self = request. get. Request. URI(); response. set. Content. Type("text/html"); Print. Writer out = response. get. Writer(); 11/26/2020 BGA 79
Do. Form. Servlet 2 out. println("<html>n" + "<head><title>Forms, Version 2</title></head>n" + "<body>n<h 1>Forms, Version 1</h 1>n" + "<form action="" + self + "" method="POST"n" + "First name: <input type="text"" + "name="firstname" /> n" + "Last name: <input type="text"" + "name="lastname" />n" + "<p><input type="submit" name="button"" + "value="Submit Name"/></p>n" + "</form>n</body>n</html>n" ); } } http: //localhost: 8080/c 2206/servlet/forms. Do. Form. Servlet 2 http: //localhost: 8080/c 2206/form 2 11/26/2020 BGA 80
Using two buttons n Alternate choices can be made by having more than one submit button IF button 1 was clicked THEN display page 1 ELSIF button 2 was clicked THEN display page 2 ELSE display form page ENDIF http: //localhost: 8080/c 2206/servlet/forms. Do. Form. Servlet 3 http: //localhost: 8080/c 2206/form 3 11/26/2020 BGA 81
Do. Form. Servlet 3 public void do. Post(Http. Servlet. Request request, Http. Servlet. Response response) throws IOException { do. Get(request, response); } public void do. Get(Http. Servlet. Request request, Http. Servlet. Response response) throws IOException { String button 1 = request. get. Parameter("button 1"); String button 2 = request. get. Parameter("button 2"); if (button 1 != null) display. Page 1(request, response); else if (button 2 != null) display. Page 2(request, response); else display. Form. Page(request, response); } 11/26/2020 BGA 82
Do. Form. Servlet 3 public void display. Page 1(Http. Servlet. Request request, Http. Servlet. Response response) throws IOException { String first. Name = request. get. Parameter("firstname"); String last. Name = request. get. Parameter("lastname"); response. set. Content. Type("text/html"); Print. Writer out = response. get. Writer(); out. println("<html>n" + "<head><title>Form Results</title></head>n" + "<body>n" + "<h 1>Form Results</h 1>n" + "Hello " + first. Name + " " + last. Name + " n"); out. println("You clicked the first button n"); out. println("</body>n"); out. println("</html>n"); } 11/26/2020 BGA 83
Do. Form. Servlet 3 public void display. Page 2(Http. Servlet. Request request, Http. Servlet. Response response) throws IOException { String first. Name = request. get. Parameter("firstname"); String last. Name = request. get. Parameter("lastname"); response. set. Content. Type("text/html"); Print. Writer out = response. get. Writer(); out. println("<html>n" + "<head><title>Form Results</title></head>n" + "<body>n" + "<h 1>Form Results</h 1>n" + "Hello " + first. Name + " " + last. Name + " n"); out. println("You clicked the second button n"); out. println("</body>n"); out. println("</html>n"); } 11/26/2020 BGA 84
Do. Form. Servlet 3 public void display. Form. Page(Http. Servlet. Request request, Http. Servlet. Response response) throws IOException { String self = request. get. Request. URI(); response. set. Content. Type("text/html"); Print. Writer out = response. get. Writer(); out. println( "<html>n" + "<head><title>Forms, Version 3</title></head>n" + "<body>n" + "<h 1>Forms, Version 3</h 1>n" + "In this version the form is generated by the " + "Servlet and there are two buttons and we need" + " to determine which one was clicked. n" 11/26/2020 BGA 85
Do. Form. Servlet 3 + + + + + "<form action="" + self + "" method="POST">" "First name: <input type="text" "name="firstname" />n" "Last name: <input type="text" "name="lastname" />n" "<p><input type="submit" name="button 1" "value="Submit Name 1" />n" "<input type="submit" name="button 2" " "value="Submit Name 2" />n" "</form>n<body>n<htmln" ); } Do. Form. Servlet 3. java } 11/26/2020 BGA 86
Error checking on forms n n n Can use regular expressions to check form data IF there are errors display an error message and redisplay the form showing the data that has been entered Forms like this are called sticky forms: they remember the previous values entered and display them in the form. http: //localhost: 8080/c 2206/servlet/forms. Do. Form. Servlet 4 http: //localhost: 8080/c 2206/form 4 11/26/2020 BGA 87
Do. Form. Servlet 4 public void do. Post(Http. Servlet. Request request, Http. Servlet. Response response) throws IOException { do. Get(request, response); } public void do. Get(Http. Servlet. Request request, Http. Servlet. Response response) throws IOException { String button = request. get. Parameter("button"); if (button != null) process. Form(request, response); else display. Form. Page(request, response, ""); } 11/26/2020 BGA 88
Do. Form. Servlet 4 public void process. Form(Http. Servlet. Request request, Http. Servlet. Response response) throws IOException { String error = validate. Form(request); if (! error. equals("")) { display. Form. Page(request, response, error); } else { display. Output. Page(request, response); } } 11/26/2020 BGA 89
Do. Form. Servlet 4 public String validate. Form(Http. Servlet. Request request) { String first. Name = request. get. Parameter("firstname"); String last. Name = request. get. Parameter("lastname"); first. Name = (first. Name == null) ? "" : firstname; last. Name = (last. Name == null) ? "" : lastname; String error = ""; Pattern p = Pattern. compile("^[a-z. A-Z-']+$"); Matcher m 1 = p. matcher(first. Name); Matcher m 2 = p. matcher(last. Name); if (! m 1. matches()) error += "First name invalid. . . "; if (! m 2. matches()) error += "Last name invalid. . . "; return error; } 11/26/2020 BGA 90
Do. Form. Servlet 4 public void display. Form. Page(Http. Servlet. Request request, Http. Servlet. Response response) throws IOException { String self = request. get. Request. URI(); String first. Name = request. get. Parameter("firstname"); String last. Name = request. get. Parameter("lastname"); first. Name = (first. Name == null) ? "" : first. Name; last. Name = (last. Name == null) ? "" : last. Name; response. set. Content. Type("text/html"); Print. Writer out = response. get. Writer(); out. println("<html>n" + "<head><title>Forms, Version 4</title></head>n" + "<body>n" + "<h 1>Forms, Version 4</h 1>n" 11/26/2020 BGA 91
Do. Form. Servlet 4 + "In this version the form is generated by the " + "Servlet using error checking and sticky forms. n" + "<p>" + error + "</p>n" + "<form action="" + self + "" method="post">n" + "First name: <input type="text"" + "name="firstname" " + "value="" + first. Name + "" /> n" + "Last name: <input type="text"" + "name="lastname" " + "value="" + last. Name + "" /> n" + "<p><input type="submit" name="button" " + "value="Submit Name" /></p>n" + "</form>n</body>n<html>" ); } 11/26/2020 BGA 92
Do. Form. Servlet 4 public void display. Output. Page(Http. Servlet. Request request, Http. Servlet. Response response) throws IOException { String first. Name = request. get. Parameter("firstname"); String last. Name = request. get. Parameter("lastname"); response. set. Content. Type("text/html"); Print. Writer out = response. get. Writer(); out. println("<html>n<head><title>Form Results " + "</title>n</head>n<body>n" + "<h 1>Form Results</h 1>n" + "Hello " + first. Name + " " + last. Name + " n" + "</body>n</html>n" ); } Do. Form. Servlet 4. java 11/26/2020 BGA 93
Reg Expressions in Java (1) n n Java has regular expressions An import statement is needed n n import java. util. regex. *; To use them create a string regexp representing the regular expression then define a target string and use n Pattern p = Pattern. compile(regexp); Matcher m = p. matcher(target); 11/26/2020 BGA 94
Reg Expressions in Java (2) n n The Matcher object m has 3 methods matches() n n looking. At() n n check for a match of the entire regex in target, return true if there is a match. try to find match by searching from beginning of the target string find() n iterator to find all matches of regex in target 11/26/2020 BGA 95
Reg Expressions in Java (3) n If a pattern is used more than once use Pattern p = Pattern. compile(regexp); Matcher m = p. matcher(target); if (m. matches()) {. . . } m. looking. At() else m. find() {. . . } 11/26/2020 BGA 96
Reg Expressions in Java (4) n If a pattern is used just once use if (Pattern. matches(regexp, target)) {. . . } else { looking. At(regexp, target). . . find(regexp, target) } 11/26/2020 BGA 97
Reg. Exp test application http: //localhost: 8080/c 2206/servlet/forms. Reg. Exp http: //localhost: 8080/c 2206/regexp 11/26/2020 BGA 98
Reg. Exp public void do. Get(Http. Servlet. Request request, Http. Servlet. Response response) throws IOExeception, Servlet. Exception { String self = request. get. Request. URI(); String regexp = request. get. Parameter("regexp"); String target = request. get. Parameter("target"); if (regexp == null) regexp = ""; if (target == null) target = ""; out. println( // html goes here // the three buttons have names matches, // looling. At, and find ); 11/26/2020 BGA 99
Reg. Exp Pattern p = Pattern. compile(regexp); Matcher m = p. matcher(target); if (request. get. Parameter("matches") != null) { if (m. matches()) out. println(. . . ); else out. println(. . . ); } if (request. get. Parameter("looking. At") != null) { if (m. looking. At()) out. println(. . . ); else out. println(. . . ); } 11/26/2020 BGA 100
Reg. Exp if (request. get. Parameter("find") != null) { out. println("<p>"); while (m. find()) { out. println("<b>find: Found a match</b> "); } out. println("</body>n</html>n"); out. close(); } Reg. Exp. java } 11/26/2020 BGA 101
Detecting form submission (1) n n Form submission can be detected using the GET request method. To do this specify POST as the method in the form. If the servlet receives a GET request then the form should be displayed If the servlet receives a POST request then the form has just been submitted. http: //localhost: 8080/c 2206/servlet/forms. Temperature 1 http: //localhost: 8080/c 2206/temperature 1 11/26/2020 BGA 102
Temperature 1 Conversion public class Temperature 1 extends Http. Servlet { public void do. Get(Http. Servlet. Request request, Http. Servlet. Response response) throws IOException, Servlet. Exception { // URL was submitted so display form String self = request. get. Request. URI(); response. set. Content. Type("text/html"); Print. Writer out = response. get. Writer(); out. println( // display page with form with fahrenheit // input field ands submit button called convert // form method is set to POST ); } 11/26/2020 BGA 103
Temperature 1 Conversion public void do. Post(Http. Servlet. Request request, Http. Servlet. Response response) throws IOException, Servlet. Exception { // form was submitted so get temperature double fahr = 0. 0; try { fahr = Double. parse. Double( request. get. Parameter("fahrenheit")); } catch (Number. Format. Exception e) { // use default temp in case of error } 11/26/2020 BGA 104
Temperature 1 Conversion double celsius = (fahr - 32. 0) * (5. 0/9. 0); Decimal. Format two = new Decimal. Format("0. 00"); String self = request. get. Request. URI(); response. set. Content. Type("text/html"); Print. Writer out = response. get. Writer(); out. println( // display output page with converted temp // and link to do another calculation using "<a href="" + self + "a>Another conversion</a>" ); Temperature 1. java } 11/26/2020 BGA 105
Detecting form submission (2) n n Form submission can be detected using a button Determine if button named "button" is clicked: String button. Value = request. get. Parameter("button"); if (button. Value == null) { // button was not clicked { else { // button was clicked } http: //localhost: 8080/c 2206/servlet/forms. Temperature 2 http: //localhost: 8080/c 2206/temperature 2 11/26/2020 BGA 106
Temperature 2 Conversion public class Temperature 2 extends Http. Servlet { public void do. Get(Http. Servlet. Request request, Http. Servlet. Response response) throws IOException, Servlet. Exception { // URL was submitted so display form String self = request. get. Request. URI(); response. set. Content. Type("text/html"); Print. Writer out = response. get. Writer(); 11/26/2020 BGA 107
Temperature 2 Conversion if (request. get. Parameter("calculate") == null) { // display the form } else { // display output and new calculation link } } } public void do. Post(Http. Servlet. Request request, Http. Servlet. Response response) throws IOException, Servlet. Exception { do. Get(request, response); } Temperature 2. java 11/26/2020 BGA 108
- Slides: 108