B.M.S. COLLEGE OF ENGINEERING (Autonomous College under VTU, Approved by AICTE, Accredited by NAAC) MASTER OF COMPUTER APPLICATIONS (Accredited by NBA for 5 years 2019 - 2024) Advance Java Programming (22MCA3PCAJ) SUBMITTED BY Ananya A Rao (1BM22MC002) Submission Date : 13/01/2024 UNDER THE GUIDANCE OF R V Raghavendra Rao (Assistant Professor) Exercises: Servlet Basics 1. Modify HelloServlet so that it says “Hello Your-Name”. Compile and run it. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Hello Servlet Example</title> </head> <body> <h2>Enter Your Name</h2> <form action="HelloServlet" method="get"> <label for="name">Name:</label> <input type="text" id="name" name="name"> <input type="submit" value="Say Hello"> </form> </body> </html> import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class viewport extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Retrieve the parameter "name" from the request String name = request.getParameter("name"); // Set the response content type response.setContentType("text/html"); // Get the PrintWriter object to write the HTML page java.io.PrintWriter out = response.getWriter(); // Write the HTML page content out.println("<html>"); out.println("<head><title>HelloServlet</title></head>"); out.println("<body>"); // Check if the name parameter is provided if (name != null && !name.isEmpty()) { out.println("<h1>Hello " + name + "!</h1>"); } else { out.println("<h1>Hello Your-Name!</h1>"); } out.println("</body></html>"); } } 2. Create a servlet that makes a bulleted list of four random numbers. • Reminder 1: you use Math.random() to output a random number in Java. • Reminder 2: you make a bulleted list in HTML as follows <UL> <LI>List item 1 <LI>List item 2 ... </UL> import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class RandomNumberServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set the response content type response.setContentType("text/html"); // Get the PrintWriter object to write the HTML page PrintWriter out = response.getWriter(); // Write the HTML page content out.println("<html>"); out.println("<head><title>RandomNumberServlet</title></head>"); out.println("<body>"); out.println("<h2>Random Numbers List:</h2>"); out.println("<ul>"); for (int i = 0; i < 4; i++) { double randomNumber = Math.random(); out.println("<li>" + randomNumber + "</li>"); } out.println("</ul>"); out.println("</body></html>"); } } 3. Create a servlet that uses a loop to output an HTML table with 25 rows and 3 col umns. For instance, each row could contain “RowX, Col1”, “RowX Col2”, and “RowX Col3”, where X is the current row number. import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class TableServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set the response content type response.setContentType("text/html"); // Get the PrintWriter object to write the HTML page PrintWriter out = response.getWriter(); // Write the HTML page content out.println("<html>"); out.println("<head><title>TableServlet</title></head>"); out.println("<body>"); out.println("<h2>HTML Table with 25 rows and 3 columns:</h2>"); out.println("<table border='1'>"); // Loop to generate 25 rows for (int row = 1; row <= 25; row++) { out.println("<tr>"); // Loop to generate 3 columns for each row for (int col = 1; col <= 3; col++) { out.println("<td>Row" + row + " Col" + col + "</td>"); } out.println("</tr>"); } out.println("</table>"); out.println("</body></html>"); } } 5. If you have some previous servlet/JSP experience and want to try something we haven’t yet covered in detail in class, try making a custom Web application. See the short summary in the notes (but we will cover it in detail later). You don’t need to start from scratch; you can start by copying and renaming the ROOT directory. package com.customwebapp; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/greet") public class GreetingServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set content type response.setContentType("text/html"); // Write the response response.getWriter().println("<html><body>"); response.getWriter().println("<h2>Hello, Welcome to CustomWebApp!</h2>"); response.getWriter().println("</body></html>"); } } greeting.jsp <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Greeting Page</title> </head> <body> <h2>${message}</h2> </body> </html> Web.xml <servlet> <servlet-name>GreetingServlet</servlet-name> <servlet-class>com.customwebapp.GreetingServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>GreetingServlet</servlet-name> <url-pattern>/greet</url-pattern> </servlet-mapping> greetingServelt <servlet> <servlet-name>GreetingServlet</servlet-name> <servlet-class>com.customwebapp.GreetingServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>GreetingServlet</servlet-name> <url-pattern>/greet</url-pattern> </servlet-mapping> protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set content type response.setContentType("text/html"); // Set a message attribute request.setAttribute("message", "Hello, Welcome to CustomWebApp!"); // Forward the request to the JSP page request.getRequestDispatcher("/greeting.jsp").forward(request, response); } Exercises: Form Data Try the first exercise and whichever others best fit your interests, background, and available time. 1. Download ThreeParamsForm.html from the Core Servlets and JSP archive site and install it in tomcat_install_dir\webapps\ROOT. Load it by means of the URL http://localhost/ThreeParamsForm.html. Install the ThreeParams servlet and verify that you can send data to it from the form. package coreservlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; /** Simple servlet that reads three parameters from the * form data. * <P> * Taken from Core Servlets and JavaServer Pages * from Prentice Hall and Sun Microsystems Press, * http://www.coreservlets.com/. * &copy; 2000 Marty Hall; may be freely used or adapted. */ public class ThreeParams extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Reading Three Request Parameters"; out.println(ServletUtilities.headWithTitle(title) + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=CENTER>" + title + "</H1>\n" + "<UL>\n" + " <LI><B>param1</B>: " + request.getParameter("param1") + "\n" + " <LI><B>param2</B>: " + request.getParameter("param2") + "\n" + " <LI><B>param3</B>: " + request.getParameter("param3") + "\n" + "</UL>\n" + "</BODY></HTML>"); } } 2. Change the ThreeParams servlet to reside in your package/directory. Make appropriate changes to the form that sends data to it. Test it. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Parameter Input Form</title> </head> <body> <h1>Enter Parameters</h1> <form action="ThreeParams" method="GET"> <label for="param1">Parameter 1:</label> <input type="text" id="param1" name="param1" required> <br> <label for="param2">Parameter 2:</label> <input type="text" id="param2" name="param2" required> <br> <label for="param3">Parameter 3:</label> <input type="text" id="param3" name="param3" required> <br> <input type="submit" value="Submit"> </form> </body> </html> import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ThreeParams extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Reading Three Request Parameters"; out.println("<html><head><title>" + title + "</title></head>"); out.println("<body bgcolor=\"#FDF5E6\">"); out.println("<h1 align=\"center\">" + title + "</h1>"); out.println("<ul>"); out.println("<li><b>param1</b>: " + request.getParameter("param1") + "</li>"); out.println("<li><b>param2</b>: " + request.getParameter("param2") + "</li>"); out.println("<li><b>param3</b>: " + request.getParameter("param3") + "</li>"); out.println("</ul>"); out.println("</body></html>"); } } 3. Make a variation of the ThreeParams form and servlet that uses POST instead of GET. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Parameter Input Form (POST)</title> </head> <body> <h1>Enter Parameters</h1> <form action="/your-web-app-name/ThreeParams" method="POST"> <label for="param1">Parameter 1:</label> <input type="text" id="param1" name="param1" required> <br> <label for="param2">Parameter 2:</label> <input type="text" id="param2" name="param2" required> <br> <label for="param3">Parameter 3:</label> <input type="text" id="param3" name="param3" required> <br> <input type="submit" value="Submit"> </form> </body> </html> import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ThreeParams extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Reading Three Request Parameters (POST)"; out.println("<html><head><title>" + title + "</title></head>"); out.println("<body bgcolor=\"#FDF5E6\">"); out.println("<h1 align=\"center\">" + title + "</h1>"); out.println("<ul>"); out.println("<li><b>param1</b>: " + request.getParameter("param1") + "</li>"); out.println("<li><b>param2</b>: " + request.getParameter("param2") + "</li>"); out.println("<li><b>param3</b>: " + request.getParameter("param3") + "</li>"); out.println("</ul>"); out.println("</body></html>"); } } 4. Use the ThreeParams form to send data to the ThreeParams servlet that contains HTML-specific characters. Verify that this can cause malformed results. Make a variation of the servlet that filters the strings before displaying them. Html file <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Parameter Input Form</title> </head> <body> <h1>Enter Parameters</h1> <form action="ThreeParams" method="GET"> <label for="param1">Parameter 1:</label> <input type="text" id="param1" name="param1" required> <br> <label for="param2">Parameter 2:</label> <input type="text" id="param2" name="param2" required> <br> <label for="param3">Parameter 3:</label> <input type="text" id="param3" name="param3" required> <br> <input type="submit" value="Submit"> </form> </body> </html> import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import org.apache.commons.lang3.StringEscapeUtils; public class ThreeParams extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Reading Three Request Parameters (POST)"; out.println("<html><head><title>" + title + "</title></head>"); out.println("<body bgcolor=\"#FDF5E6\">"); out.println("<h1 align=\"center\">" + title + "</h1>"); out.println("<ul>"); // Get and escape parameters to prevent XSS String param1 = StringEscapeUtils.escapeHtml4(request.getParameter("param1")); String param2 = StringEscapeUtils.escapeHtml4(request.getParameter("param2")); String param3 = StringEscapeUtils.escapeHtml4(request.getParameter("param3")); out.println("<li><b>param1</b>: " + param1 + "</li>"); out.println("<li><b>param2</b>: " + param2 + "</li>"); out.println("<li><b>param3</b>: " + param3 + "</li>"); out.println("</ul>"); out.println("</body></html>"); } } 5. Make a “registration” form that collects a first name, last name, and email address. Send the data to a servlet that displays it. Feel free to modify the ThreeParams HTML form and servlet to accomplish this. Next, modify the servlet to use a default value (or give an error message) if the user omits any of the three required parameters. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="registeration" content="width=device-width, initial-scale=1.0"> <title>Registration Form</title> </head> <body> <h2>Registration Form</h2> <form action="registeration" method="post"> <label for="firstName">First Name:</label> <input type="text" id="firstName" name="firstName" required> <br> <label for="lastName">Last Name:</label> <input type="text" id="lastName" name="lastName" required> <br> <label for="email">Email Address:</label> <input type="email" id="email" name="email" required> <br> <input type="submit" value="Submit"> </form> </body> </html> import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class registeration extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set the response content type response.setContentType("text/html"); // Get the PrintWriter object to write the HTML page PrintWriter out = response.getWriter(); // Retrieve form parameters String firstName = request.getParameter("firstName"); String lastName = request.getParameter("lastName"); String email = request.getParameter("email"); // Check for missing parameters and handle accordingly if (firstName == null || lastName == null || email == null || firstName.isEmpty() || lastName.isEmpty() || email.isEmpty()) { // Handle missing parameters - show an error message out.println("<html><body><h2>Error: Please provide all required parameters</h2></body></html>"); } else { // Display the collected data out.println("<html><body>"); out.println("<h2>Registration Details:</h2>"); out.println("<p>First Name: " + firstName + "</p>"); out.println("<p>Last Name: " + lastName + "</p>"); out.println("<p>Email Address: " + email + "</p>"); out.println("</body></html>"); } } } 6. [Hard; for the truly inspired.] Make a variation of the previous servlet and accompanying form, but, in this case, if the user fails to supply a value for any of the fields in the form, you should redisplay the form but with an error message saying that the value is missing. Don’t make the user reenter values that they’ve entered already. Hint: you have two main choices given the tools available to us so far: have one big servlet that generates both the HTML form and the results page (the form submits the data to itself), or two separate servlets (one that generates the HTML form and the other that generates the results page). There is an example of the first approach in the book. If you want to try the second approach, you might want to know about response.sendRedirect, which lets you redirect the browser to a speci fied page. For example, here is a doGet method that sends the user to www.whitehouse.gov: public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.sendRedirect("http://www.whitehouse.gov/"); } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Registration Form</title> </head> <body> <h2>Registration Form</h2> <form action="reg" method="post"> <label for="firstName">First Name:</label> <input type="text" id="firstName" name="firstName" required> <br> <label for="lastName">Last Name:</label> <input type="text" id="lastName" name="lastName" required> <br> <label for="email">Email Address:</label> <input type="email" id="email" name="email" required> <br> <input type="submit" value="Submit"> </form> </body> </html> import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class reg extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set the response content type response.setContentType("text/html"); // Get the PrintWriter object to write the HTML page PrintWriter out = response.getWriter(); // Retrieve form parameters String firstName = request.getParameter("firstName"); String lastName = request.getParameter("lastName"); String email = request.getParameter("email"); // Check for missing parameters and handle accordingly if (firstName == null || lastName == null || email == null || firstName.isEmpty() || lastName.isEmpty() || email.isEmpty()) { // Handle missing parameters - show an error message and redisplay the form out.println("<html><body>"); out.println("<h2>Error: Please provide all required parameters</h2>"); out.println("<a href='reg.html'>Go back to the registration form</a>"); out.println("</body></html>"); } else { // Display the collected data out.println("<html><body>"); out.println("<h2>Registration Details:</h2>"); out.println("<p>First Name: " + firstName + "</p>"); out.println("<p>Last Name: " + lastName + "</p>"); out.println("<p>Email Address: " + email + "</p>"); out.println("</body></html>"); } } } Exercises: Request Headers Do whichever exercises fit your background and interests. They are ordered in approximate order of difficulty. As always, feel free to experiment on your own with other related exercises. 1. Install the servlet that shows all request headers (ShowRequestHeaders). Access it from both Firefox and Internet Explorer. Remember that, since the servlet is in the coreservlets package, you have to install it in the coreservlets directory and use the URL http://host name/servlet/coreservlets.ShowRequestHeaders. import java.io.IOException; import java.io.PrintWriter; import java.util.Collections; import java.util.Enumeration; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ShowRequestHeader extends HttpServlet { @SuppressWarnings("unchecked") protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.println("<html><head><title>Show Request Headers</title></head><body>"); out.println("<h2>All Request Headers:</h2>"); out.println("<ul>"); Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); out.println("<li><b>" + headerName + ":</b> " + Collections.list(request.getHeaders(headerName)) + "</li>"); } out.println("</ul></body></html>"); } } 2. Make a tiny Web page that contains a hypertext link to the servlet that shows all request headers. What new header shows up that wasn’t there previously? Remember that HTML documents (and images, JSP pages, etc.) go in tomcat-install-dir\webapps\ROOT. Html file :<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Servlet Link</title> </head> <body> <h2>Web application to display request headrers </h2> <p>This page contains a link to the servlet that shows all request headers:</p> <a href="ShowRequestHeader">Show Request Headers</a> </body> </html> 3. Write a servlet that just says “Hello.” Use a red background and a yellow foreground for Internet Explorer users; use a yellow background and a red foreground for Firefox and other non-IE users. If you are a bit rusty with HTML, you set colors as follows: <BODY BGCOLOR="colorName" TEXT="colorName"> or <BODY BGCOLOR="#RRGGBB" TEXT="#RRGGBB"> (where R, G, and B are hex values for the red, green and blue components. I.e., #FF00FF is magenta -- 255 for red, 0 for green, and 255 for blue). import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class HelloServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); // Determine the browser type based on User-Agent header String userAgent = request.getHeader("User-Agent"); boolean isInternetExplorer = (userAgent != null && userAgent.contains("MSIE")); // Set background and text color based on the browser type String backgroundColor, textColor; if (isInternetExplorer) { backgroundColor = "#FF0000"; // Red background for Internet Explorer textColor = "#FFFF00"; // Yellow text for Internet Explorer } else { backgroundColor = "#FFFF00"; // Yellow background for non-IE browsers textColor = "#FF0000"; // Red text for non-IE browsers } // Generate the HTML page with Hello message and styling out.println("<html><head><title>Hello Servlet</title></head><body " + "style='background-color:" + backgroundColor + "; color:" + textColor + ";'>"); out.println("<h2>Hello</h2>"); out.println("</body></html>"); } } 4. Some informational sites want users to access pages in a certain order. They want to pro hibit users from jumping directly to a bookmarked page later in the sequence because the data on the pages may have changed since the user bookmarked the page. Create two pages. The first page should have a link to the second page. If a user accesses the first page and then follows the link to the second page, it works normally. But, if the user directly types in the address of the second page (or follows a link from a page with a different name than the first page), they should get sent back to the first page automatically. Hints: - Use response.sendRedirect (as on previous exercise) to send users back to page1 - It is not necessary to make page1 be a servlet. Page1.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Page 1</title> </head> <body> <h2>Welcome to Page 1</h2> <p>Click the link to proceed to Page 2:</p> <a href="Page2.html">Go to Page 2</a> </body> </html> Page2.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Page 2</title> <script> // Check if the document was referred from Page1.html if (document.referrer.indexOf("first.html") === -1) { // Redirect the user back to Page1.html window.location.href = "first.html"; } </script> </head> <body> <h2>Welcome to Page 2</h2> <p>This is Page 2 content.</p> </body> </html> On execution of page2.html Exercises: HTTP Status Codes 1. Write a servlet that sends about half the users to http://www.mozilla.org and about half to http://www.microsoft.com. Choose at random (compare the output of Math.random() to 0.5). <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Random Redirect Page</title> </head> <body> <h2>Random Redirect Page</h2> <p>Click the button to get redirected randomly:</p> <form action="/contextPath/RandomRedirectServlet" method="get"> <button type="submit">Redirect Me</button> </form> </body> </html> import java.io.IOException; import java.util.Random; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/RandomRedirectServlet") public class RandomRedirectServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { // Approximately 50% chance to redirect to Mozilla and 50% chance to Microsoft String redirectUrl = (new Random().nextDouble() > 0.5) ? "http://www.mozilla.org" : "http://www.microsoft.com"; response.sendRedirect(redirectUrl); } } import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class RandomRedirectServlet extends HttpServlet { private static final long serialVersionUID = 1L protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { // Approximately 50% chance to redirect to Mozilla and 50% chance to Microsoft String redirectUrl = (new Random().nextDouble() > 0.5) ? "http://www.mozilla.org" : "http://www.microsoft.com"; // Perform the redirection response.sendRedirect(redirectUrl); } } 2. Write a servlet that returns a “page not found” error page (404) unless the user sup plies a favoriteLanguage request (form) parameter with a value of “Java.” 3. Write a servlet that sends the first 9 requests to washingtonpost.com (an organization that uses servlets and JSP extensively, by the way), the next request to nytimes.com, and then repeats. That is, every tenth request should get sent to nytimes.com and the rest should get sent to washingtonpost.com. Don’t just use probabilities (i.e., don’t compare Math.random to 0.9); actually count the overall requests. So, for example, if the server received between 1000 and 1009 overall requests since last being booted, exactly 100 of them should have sent users to nytimes.com, and the rest should have sent users to washingtonpost.com. Hint: use an instance variable (aka field, data member). import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class PageNotFoundServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Check if the favoriteLanguage parameter is present and has a value of "Java" String favoriteLanguage = request.getParameter("favoriteLanguage"); if (favoriteLanguage == null || !favoriteLanguage.equals("Java")) { // Return a "page not found" error (HTTP 404) response.sendError(HttpServletResponse.SC_NOT_FOUND, "Page Not Found"); } else { // Your normal processing for the valid case can go here // This is just a simple example response.getWriter().println("<html><body><h2>Your favourite language is java ,Welcome to java world !</h2></body></html>"); } } } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>User Input Form</title> </head> <body> <h2>User Input Form</h2> <p>Enter your favorite language here:</p> <form action="PageNotFoundServlet" method="get"> <label for="favoriteLanguage">Favorite Language:</label> <input type="text" id="favoriteLanguage" name="favoriteLanguage" required> <br> <input type="submit" value="Submit"> </form> </body> </html> .3. Write a servlet that sends the first 9 requests to washingtonpost.com (an organization that uses servlets and JSP extensively, by the way), the next request to nytimes.com, and then repeats. That is, every tenth request should get sent to nytimes.com and the rest should get sent to washingtonpost.com. Don’t just use probabilities (i.e., don’t compare Math.random to 0.9); actually count the overall requests. So, for example, if the server received between 1000 and 1009 overall requests since last being booted, exactly 100 of them should have sent users to nytimes.com, and the rest should have sent users to washingtonpost.com. Hint: use an instance variable (aka field, data member). import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/RequestDispatcherServlet") public class RequestDispatcherServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final String WASHINGTON_POST_URL = "https://www.washingtonpost.com"; private static final String NY_TIMES_URL = "https://www.nytimes.com"; private int requestCount = 0; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Increment the overall request count requestCount++; // Determine the destination URL based on the request count String destinationURL = (requestCount % 10 == 0) ? NY_TIMES_URL : WASHINGTON_POST_URL; // Redirect the user to the appropriate URL response.sendRedirect(destinationURL); } } 1. Redo the first problem from the previous set of exercises. Instead of using response.sendRedirect, set the appropriate status code and response header explicitly. Do you get the same result? import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/RedirectServlet") public class RedirectServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set the status code to 302 for temporary redirect response.setStatus(HttpServletResponse.SC_FOUND); // Set the location header for the redirect response.setHeader("Location", "http://www.example.com"); } } 2. Write a servlet that instructs the browser to reconnect every five seconds. Display the time (print new java.util.Date()) on each connection. import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/ReconnectServlet") public class ReconnectServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set content type response.setContentType("text/html;charset=UTF-8"); // Get PrintWriter object PrintWriter out = response.getWriter(); // Display the time on each connection out.println("<html><head><title>Reconnect Servlet</title></head><body>"); out.println("<h2>Current Time: " + new Date() + "</h2>"); out.println("<script>setTimeout(function(){ location.reload(); }, 5000);</script>"); out.println("</body></html>"); } } 3. Write a servlet that generates an Excel spreadsheet with 10 rows and 5 columns. Dis- play a random number in each cell. Try it from both Firefox and Internet Explorer. What happens when you hit the “Reload” button? import java.io.IOException; import java.io.PrintWriter; import java.util.Random; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/ExcelServlet") public class ExcelServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set content type to Excel response.setContentType("application/vnd.ms-excel"); // Set content disposition to trigger a download prompt response.setHeader("Content-Disposition", "attachment; filename=excel_example.xls"); // Get PrintWriter object PrintWriter out = response.getWriter(); // Generate Excel content with random numbers Random random = new Random(); out.println("sep=;\n"); // Set the separator for Excel for (int i = 0; i < 10; i++) { for (int j = 0; j < 5; j++) { out.print(random.nextInt(100)); // Random number if (j < 4) { out.print(";"); } } out.println(); // Move to the next row } } } 4. Write a servlet that returns a page to Internet Explorer users saying they will be sent to http://www.microsoft.com after 10 seconds. Send them there after that timeout. Send Firefox users to http://www.mozilla.org after the same delay. You’ll have to read about the Refresh header in the book (page 203) to see the option of supplying a specific URL to connect to. import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/DelayedRedirectServlet") public class DelayedRedirectServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set content type response.setContentType("text/html;charset=UTF-8"); // Get PrintWriter object PrintWriter out = response.getWriter(); // Check the user agent to determine the browser String userAgent = request.getHeader("User-Agent"); // Display a message based on the browser and set a delayed redirect if (userAgent != null && userAgent.contains("MSIE")) { out.println("<html><head><title>Delayed Redirect</title></head><body>"); out.println("<h2>You will be redirected to Microsoft after 10 seconds.</h2>"); out.println("<script>setTimeout(function(){ window.location.href = 'http://www.microsoft.com'; }, 10000);</script>"); out.println("</body></html>"); } else { // Assume other browsers are Firefox response.setHeader("Refresh", "10;url=http://www.mozilla.org"); } } } Exercises: Cookies 2. Write a servlet that displays the values of the firstName, lastName, and emailAddress request parameters. If a parameter is missing and the client is a first-time visitor, have the servlet list “Unknown” for the missing values. If a parameter is missing and the client is a repeat visitor, have the servlet use previously-entered values for the missing values. import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class UserInfoServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set content type to text/html response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { // Get session HttpSession session = request.getSession(); // Retrieve parameters String firstName = request.getParameter("firstName"); String lastName = request.getParameter("lastName"); String emailAddress = request.getParameter("emailAddress"); // Check if the client is a first-time visitor boolean firstTimeVisitor = isFirstTimeVisitor(session); // Display values or use defaults based on whether the parameter is missing out.println("<html><body>"); out.println("<h2>User Information</h2>"); out.println("<p><b>First Name:</b> " + (firstName != null ? firstName : (firstTimeVisitor ? "Unknown" : getSavedValue(session, "firstName"))) + "</p>"); out.println("<p><b>Last Name:</b> " + (lastName != null ? lastName : (firstTimeVisitor ? "Unknown" : getSavedValue(session, "lastName"))) + "</p>"); out.println("<p><b>Email Address:</b> " + (emailAddress != null ? emailAddress : (firstTimeVisitor ? "Unknown" : getSavedValue(session, "emailAddress"))) + "</p>"); // Save entered values to session for repeat visitors if (!firstTimeVisitor) { saveValueToSession(session, "firstName", firstName); saveValueToSession(session, "lastName", lastName); saveValueToSession(session, "emailAddress", emailAddress); } out.println("</body></html>"); } } private boolean isFirstTimeVisitor(HttpSession session) { Boolean firstTimeVisitor = (Boolean) session.getAttribute("firstTimeVisitor"); if (firstTimeVisitor == null) { session.setAttribute("firstTimeVisitor", true); return true; } return false; } private String getSavedValue(HttpSession session, String paramName) { String savedValue = (String) session.getAttribute(paramName); return (savedValue != null) ? savedValue : "Unknown"; } private void saveValueToSession(HttpSession session, String paramName, String paramValue) { if (paramValue != null) { session.setAttribute(paramName, paramValue); } } } 3. Make a small page that displays some simple information of your choosing. Make another page that lets users choose the foreground and background color that they want the first page to use. For example, if users never visit the the color choice page, the main informational page should use default colors of your choosing. But if a user visits the color choice page and chooses a yel low background and red foreground, all subsequent visits to the main page by that user should result in red on yellow. There is no need to vet the colors; you can accept whatever color values the user gives you. If you are a bit rusty with HTML, you set colors as follows: <BODY BGCOLOR="colorName" TEXT="colorName"> or <BODY BGCOLOR="#RRGGBB" TEXT="#RRGGBB"> (where R, G, and B are hex values for the red, green and blue components. I.e., #FF00FF is magenta -- 255 for red, 0 for green, and 255 for blue). import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class InformationalPageServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set content type to text/html response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { // Get session HttpSession session = request.getSession(); // Retrieve user-selected colors or use defaults String backgroundColor = getSavedValue(session, "backgroundColor", "#FFFFFF"); String foregroundColor = getSavedValue(session, "foregroundColor", "#000000"); // Display the informational page with user-selected colors out.println("<html><body style='background-color:" + backgroundColor + "; color:" + foregroundColor + "'>"); out.println("<h2>Welcome to the Informational Page!</h2>"); out.println("<p>This is some simple information of your choosing.</p>"); out.println("</body></html>"); } } private String getSavedValue(HttpSession session, String paramName, String defaultValue) { String savedValue = (String) session.getAttribute(paramName); return (savedValue != null) ? savedValue : defaultValue; } } import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class ColorChoicePageServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set content type to text/html response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { // Get session HttpSession session = request.getSession(); // Retrieve user-selected colors or use defaults String backgroundColor = getSavedValue(session, "backgroundColor", "#FFFFFF"); String foregroundColor = getSavedValue(session, "foregroundColor", "#000000"); // Display the color choice page out.println("<html><body>"); out.println("<h2>Color Choice Page</h2>"); out.println("<form action='/your-context/ColorChoicePageServlet' method='post'>"); out.println("Background Color: <input type='color' name='backgroundColor' value='" + backgroundColor + "'><br>"); out.println("Foreground Color: <input type='color' name='foregroundColor' value='" + foregroundColor + "'><br>"); out.println("<input type='submit' value='Save Colors'>"); out.println("</form>"); out.println("</body></html>"); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get session HttpSession session = request.getSession(); // Get user-selected colors from the form String backgroundColor = request.getParameter("backgroundColor"); String foregroundColor = request.getParameter("foregroundColor"); // Save user-selected colors to session saveValueToSession(session, "backgroundColor", backgroundColor); saveValueToSession(session, "foregroundColor", foregroundColor); // Redirect to the informational page response.sendRedirect(request.getContextPath() + "/InformationalPageServlet"); } private String getSavedValue(HttpSession session, String paramName, String defaultValue) { String savedValue = (String) session.getAttribute(paramName); return (savedValue != null) ? savedValue : defaultValue; } private void saveValueToSession(HttpSession session, String paramName, String paramValue) { if (paramValue != null) { session.setAttribute(paramName, paramValue); } } } Exercises: Session Tracking 1. Use session tracking to redo the servlet (from the Cookies lecture) that says “Wel come Aboard” to first-time visitors (within a browsing session) and “Welcome Back” to repeat visitors. Was this servlet harder or easier than the equivalent version using cookies explicitly? import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class gservlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); // Get the session object HttpSession session = request.getSession(); // Check if the user is a repeat visitor if (session.isNew()) { // This is the first visit out.println("<h2>Welcome Aboard!</h2>"); session.setAttribute("visitedBefore", true); // Set a session attribute to mark the user as a repeat visitor } else { // Repeat visitor out.println("<h2>Welcome Back!</h2>"); } out.close(); } } 2. Write a servlet that displays the values of the firstName, lastName, and emailAddress request parameters. Have the servlet list “Unknown” for missing values of first-time visitors and the previously entered values for repeat visitors. This should definitely be easier than the version that used cookies explicitly. import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class UserInfoServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set content type to text/html response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { // Get session HttpSession session = request.getSession(); // Retrieve parameters String firstName = request.getParameter("firstName"); String lastName = request.getParameter("lastName"); String emailAddress = request.getParameter("emailAddress"); // Check if the client is a first-time visitor boolean firstTimeVisitor = isFirstTimeVisitor(session); // Display values or use defaults based on whether the parameter is missing out.println("<html><body>"); out.println("<h2>User Information</h2>"); out.println("<p><b>First Name:</b> " + (firstName != null ? firstName : (firstTimeVisitor ? "Unknown" : getSavedValue(session, "firstName"))) + "</p>"); out.println("<p><b>Last Name:</b> " + (lastName != null ? lastName : (firstTimeVisitor ? "Unknown" : getSavedValue(session, "lastName"))) + "</p>"); out.println("<p><b>Email Address:</b> " + (emailAddress != null ? emailAddress : (firstTimeVisitor ? "Unknown" : getSavedValue(session, "emailAddress"))) + "</p>"); // Save entered values to session for repeat visitors if (!firstTimeVisitor) { saveValueToSession(session, "firstName", firstName); saveValueToSession(session, "lastName", lastName); saveValueToSession(session, "emailAddress", emailAddress); } out.println("</body></html>"); } } private boolean isFirstTimeVisitor(HttpSession session) { Boolean firstTimeVisitor = (Boolean) session.getAttribute("firstTimeVisitor"); if (firstTimeVisitor == null) { session.setAttribute("firstTimeVisitor", true); return true; } return false; } private String getSavedValue(HttpSession session, String paramName) { String savedValue = (String) session.getAttribute(paramName); return (savedValue != null) ? savedValue : "Unknown"; } private void saveValueToSession(HttpSession session, String paramName, String paramValue) { if (paramValue != null) { session.setAttribute(paramName, paramValue); } } } 3. Make a servlet that prints a list of the URLs of the pages that the current user has used to link to it (within the current browsing session). That is, if one user has fol lowed hypertext links from three different pages to the servlet, the servlet should show the user the URLs of those three pages. Test out your servlet by making a couple of different static Web pages that link to it. import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class LinkedPageServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set content type to text/html response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { // Get session HttpSession session = request.getSession(); // Get the list of linked pages from the session List<String> linkedPages = getLinkedPages(session); // Get the referrer URL from the request String referrer = request.getHeader("referer"); // Add the referrer URL to the list if it is not null if (referrer != null) { linkedPages.add(referrer); } // Save the updated list to the session session.setAttribute("linkedPages", linkedPages); // Display the list of linked pages out.println("<html><body>"); out.println("<h2>List of Linked Pages:</h2>"); if (linkedPages.isEmpty()) { out.println("<p>No linked pages yet.</p>"); } else { out.println("<ul>"); for (String page : linkedPages) { out.println("<li>" + page + "</li>"); } out.println("</ul>"); } out.println("</body></html>"); } } @SuppressWarnings("unchecked") private List<String> getLinkedPages(HttpSession session) { List<String> linkedPages = (List<String>) session.getAttribute("linkedPages"); // If the list is null, create a new one if (linkedPages == null) { linkedPages = new ArrayList<>(); } return linkedPages; } } Exercises: JSP Scripting Elements 1. Make a JSP page that randomly selects a background color for each request. Just choose at random among a small set of predefined colors. Be sure you do not use the JSP-Styles.css style sheet, since it overrides the colors given by <BODY BGCOLOR="...">. <%@ page import="java.util.Random" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Random Background Color</title> </head> <body> <% // Predefined set of colors String[] colors = {"#FF5733", "#33FF57", "#5733FF", "#FFFF33", "#33FFFF"}; // Randomly select a color Random random = new Random(); String randomColor = colors[random.nextInt(colors.length)]; %> <!-- Set the background color using the selected color --> <body style="background-color: <%= randomColor %>;"> <h2>This page has a random background color!</h2> </body> </body> </html> 2. Make a JSP page that lets the user supply a request parameter indicating the back ground color. If no parameter is supplied, a background color should be selected at random. <%@ page import="java.util.Random" %> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Dynamic Background Color</title> </head> <body> <% // Get the background color parameter from the request String backgroundColor = request.getParameter("bgcolor"); // If no parameter is supplied, generate a random background color if (backgroundColor == null || backgroundColor.isEmpty()) { Random rand = new Random(); int r = rand.nextInt(256); int g = rand.nextInt(256); int b = rand.nextInt(256); backgroundColor = String.format("#%02x%02x%02x", r, g, b); } %> <div style="background-color: <%= backgroundColor %>;"> <h1>Welcome to the Dynamic Background Color Page!</h1> <p>This page allows you to specify a background color using the form below.</p> <form action="fifth.jsp" method="get"> <label for="bgcolor">Enter Background Color:</label> <input type="text" id="bgcolor" name="bgcolor" placeholder="e.g., #00ff00"> <button type="submit">Apply Color</button> </form> <p>If no color is provided, a random background color will be generated.</p> </div> </body> </html> 3. Make a JSP page that lets the user supply a request parameter indicating the background color. If no parameter is supplied, the most recently used background color (from a previous request by any user) should be used. <%@ page import="java.util.HashMap" %> <%@ page import="java.util.Map" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ page import="java.io.*" %> <%@ page import="javax.servlet.*" %> <%@ page import="javax.servlet.http.*" %> <% // Retrieve the session object HttpSession session = request.getSession(true); // Retrieve or initialize the background color map in the session Map<String, String> backgroundColorMap = (Map<String, String>) session.getAttribute("backgroundColorMap"); if (backgroundColorMap == null) { backgroundColorMap = new HashMap<>(); session.setAttribute("backgroundColorMap", backgroundColorMap); } // Retrieve the background color parameter from the request String backgroundColorParam = request.getParameter("backgroundColor"); // If the parameter is not provided, use the most recently used background color if (backgroundColorParam == null && !backgroundColorMap.isEmpty()) { backgroundColorParam = backgroundColorMap.get("lastUsedColor"); } // If the parameter is provided, update the most recently used background color if (backgroundColorParam != null) { backgroundColorMap.put("lastUsedColor", backgroundColorParam); } %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Background Color Page</title> </head> <body style="background-color: <%= backgroundColorParam %>;"> <h2>Background Color Page</h2> <form action="" method="get"> <label for="backgroundColor">Enter Background Color:</label> <input type="text" id="backgroundColor" name="backgroundColor" /> <input type="submit" value="Apply" /> </form> </body> </html> Exercises: The page Directive 1. Use JSP to make an Excel spreadsheet where the first row says “Year,” “Apples,” and “Oranges.” It should then have two rows of data (2005 and 2006), where each entry is a random number between 0 and 10. I.e. the result should look something like this: Year Apples Oranges 2005 9.23456 3.98765 2006 4.45678 2.223344 Index.html <!DOCTYPE html> <html> <head> <title>Excel Spreadsheet Generator</title> </head> <body> <h1>Generate Excel Spreadsheet</h1> <p>Click the button below to download the Excel spreadsheet.</p> <form action="excel.jsp" method="post"> <button type="submit">Download Excel</button> </form> </body> </html> excel.jsp <%@ page import="java.io.*" %> <%@ page import="java.util.Random" %> <%@ page import="java.text.DecimalFormat" %> <% // Set response headers for Excel download response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment; filename=excel_data.xls"); // Generate random values for Apples and Oranges for two years (2019 and 2020) Random random = new Random(); DecimalFormat df = new DecimalFormat("#.#####"); // Generate the Excel content out.println("Year\tApples\tOranges"); out.println("2019\t" + df.format(random.nextDouble() * 10) + "\t" + df.format(random.nextDouble() * 10)); out.println("2020\t" + df.format(random.nextDouble() * 10) + "\t" + df.format(random.nextDouble() * 10)); %> 2. Make an Excel spreadsheet with a random number of rows. <%@ page import="org.apache.poi.ss.usermodel.*" %> <%@ page import="org.apache.poi.xssf.usermodel.XSSFWorkbook" %> <%@ page import="java.io.*" %> <%@ page contentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" %> <%@ page language="java" %> <% // Create a new workbook Workbook workbook = new XSSFWorkbook(); // Create a sheet in the workbook Sheet sheet = workbook.createSheet("RandomDataSheet"); // Generate a random number of rows (between 5 and 20, for example) int numberOfRows = (int) (Math.random() * 16) + 5; // Create rows and cells with random data for (int i = 0; i < numberOfRows; i++) { Row row = sheet.createRow(i); // Generate random data (you can modify this part based on your requirements) Cell cell = row.createCell(0); cell.setCellValue("Data " + (i + 1)); cell = row.createCell(1); cell.setCellValue(Math.random() * 100); } // Set response headers response.setHeader("Content-Disposition", "attachment; filename=RandomData.xlsx"); // Write the workbook content to the response output stream OutputStream out = response.getOutputStream(); workbook.write(out); // Close the workbook and the output stream out.close(); workbook.close(); %> 3. The java.math package has a class called BigInteger that lets you create whole num bers with an arbitrary number of digits. Create a JSP page that makes a large BigInte ger from a String you supply as a request parameter, squares it, and prints out the result. Use the online API at http://java.sun.com/j2se/1.5.0/docs/api/ to see the syntax for the BigInteger constructor and squaring operations. <%@ page import="java.math.BigInteger" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>BigInteger Squaring</title> </head> <body> <% // Get the input parameter from the request String inputString = request.getParameter("input"); // Check if the input parameter is provided if (inputString != null && !inputString.isEmpty()) { try { // Create a BigInteger from the input string BigInteger inputNumber = new BigInteger(inputString); // Square the BigInteger BigInteger squaredResult = inputNumber.multiply(inputNumber); %> <h2>Input Number: <%= inputNumber %></h2> <h2>Squared Result: <%= squaredResult %></h2> <% } catch (NumberFormatException e) { // Handle the case where the input is not a valid number %> <h2>Invalid Input. Please provide a valid number.</h2> <% } } else { // Handle the case where the input parameter is not provided %> <h2>Please provide a number as a request parameter (e.g., ?input=123).</h2> <% } %> </body> </html> 4. Make a JSP page that sleeps for 20 seconds before returning the page. (Call Thread.sleep from inside a try/catch block that catches InterruptedException). Access it “simultaneously” from Firefox and Internet Explorer. Repeat the experi ment with the JSP page not allowing concurrent access. Verify the slower result. <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Sleeping JSP</title> </head> <body> <% try { // Simulate a long process by sleeping for 20 seconds Thread.sleep(20000); // 20 seconds } catch (InterruptedException e) { // Handle the interruption exception (if needed) e.printStackTrace(); } %> <h2>Finished Sleeping for 20 seconds!</h2> </body> </html> Exercises: Including Files and Applets 1. Make an HTML “signature” block with your name and email address. Include it in two JSP pages. Signature.jsp <!-- signature.jsp --> <!DOCTYPE html> <html> <head> <style> .signature { font-family: Arial, sans-serif; font-size: 14px; color: #333; margin-top: 20px; } </style> </head> <body> <div class="signature"> <p>My Name:Ananya A Rao</p> <p>Email:ananya.mca22@bmsce.ac.in</p> </div> </body> </html> Page1.jsp <!-- page1.jsp --> <!DOCTYPE html> <html> <head> <title>Page 1</title> </head> <body> <h1>Welcome to Page 1</h1> <!-- Include the signature block --> <jsp:include page="signature.jsp" /> </body> </html> Page2.jsp <!-- page2.jsp --> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <title>Page 2</title> </head> <body> <h1>Welcome to Page 2</h1> <!-- Forward the request to the signature.jsp --> <jsp:forward page="signature.jsp" /> </body> </html> 2. The value of the page attribute of jsp:include is allowed to be a JSP expression. Use this idea to make a JSP page that includes a “good news” page or a “bad news” mes sage at random. <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Good News</title> </head> <body> <h1>Good News Page</h1> <p>Here is some good news for you!</p> </body> </html> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Bad News</title> </head> <body> <h1>Bad News Page</h1> <p>Unfortunately, there is some bad news to share.</p> </body> </html> <%@ page import="java.util.Random" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Random News Page</title> </head> <body> <% // Array of news pages String[] newsPages = {"GoodNews.jsp", "BadNews.jsp"}; // Randomly choose a news page Random random = new Random(); String chosenNewsPage = newsPages[random.nextInt(newsPages.length)]; %> <jsp:include page="<%= chosenNewsPage %>" /> </body> </html> <%@ page import="java.util.Random" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Random News Page</title> </head> <body> <% // Array of news pages (replace these with your actual JSP pages) String[] newsPages = {"GoodNews.jsp", "BadNews.jsp"}; // Randomly choose a news page Random random = new Random(); String chosenNewsPage = newsPages[random.nextInt(newsPages.length)]; %> <jsp:include page="<%= chosenNewsPage %>" /> </body> </html> 3. Suppose that you have two different JSP pages that do two different things. However, for both pages you want to let the user supply a bgColor attribute to set the back ground color of the page. Implement this, but use an include mechanism to avoid repeating code. For example: White background: http://host/path/page1.jsp White background: http://host/path/page2.jsp Red background: http://host/path/page1.jsp?bgColor=RED Yellow background: http://host/path/page2.jsp?bgColor=YELLOW For testing, I do not care if you write an HTML form to collect the bgColor parame ter or if you simply attach it onto the end of the URL “by hand.” <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ page import="java.awt.Color" %> <%@ page import="javax.servlet.http.HttpServletRequest" %> <% // Function to get the background color from the request parameter String getBackgroundColor(HttpServletRequest request) { String bgColorParam = Optional.ofNullable(request.getParameter("bgColor")).orElse("WHITE"); try { // Attempt to parse the color, default to WHITE if parsing fails Color bgColor = Color.decode(bgColorParam.toUpperCase()); return String.format("#%06X", bgColor.getRGB() & 0xFFFFFF); } catch (NumberFormatException e) { return "WHITE"; } } %> Page1 <%@ page contentType="text/html;charset=UTF-8" language="java" %> <jsp:include page="bgsetter.jsp" /> <html> <head> <title>Page 1</title> </head> <body style="background-color: <%= getBackgroundColor(request) %>;"> <h1>Content of Page 1</h1> </body> </html> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <jsp:include page="bgsetter.jsp" /> <html> <head> <title>Page 2</title> </head> <body style="background-color: <%= getBackgroundColor(request) %>;"> <h1>Content of Page 2</h1> </body> </html> 4. Make two separate JSP pages that have bulleted lists containing random integers in a certain range. Avoid repeating code unnecessarily by including a page that defines a randomInt method. <%@ page import="java.util.Random" %> <%! // Method to generate a random integer in a specified range int randomInt(int min, int max) { Random rand = new Random(); return rand.nextInt((max - min) + 1) + min; } %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <jsp:include page="RandomInt" /> <html> <head> <title>Page 1</title> </head> <body> <h1>Random Integers on Page 1</h1> <ul> <li><%= randomInt(1, 10) %></li> <li><%= randomInt(1, 10) %></li> <li><%= randomInt(1, 10) %></li> </ul> </body> </html> Exercises: Beans For these exercises, avoid any Java code in the JSP pages. 1. Define a class called ColorBean that stores strings representing a foreground color and a background color. Compile and test it separately (i.e., without using a servlet or JSP page). Note: if your tester class (i.e., the one that has “public static void main(String[] args) {...}” in it) is in a package, remember that you have to use the package name when you run it from the command line. That is, you have to do “javac BeanTester.java” and then “java yourPackage.BeanTester”. public class ColorBean { private String foregroundColor; private String backgroundColor; // Default constructor public ColorBean() { // Initialize with default colors this.foregroundColor = "Black"; this.backgroundColor = "White"; } // Getter and setter methods for foreground color public String getForegroundColor() { return foregroundColor; } public void setForegroundColor(String foregroundColor) { this.foregroundColor = foregroundColor; } // Getter and setter methods for background color public String getBackgroundColor() { return backgroundColor; } public void setBackgroundColor(String backgroundColor) { this.backgroundColor = backgroundColor; } } public class BeanTester { public static void main(String[] args) { // Create an instance of ColorBean ColorBean colorBean = new ColorBean(); // Display default colors System.out.println("Default Foreground Color: " + colorBean.getForegroundColor()); System.out.println("Default Background Color: " + colorBean.getBackgroundColor()); // Set new colors colorBean.setForegroundColor("Red"); colorBean.setBackgroundColor("Yellow"); // Display updated colors System.out.println("Updated Foreground Color: " + colorBean.getForegroundColor()); System.out.println("Updated Background Color: " + colorBean.getBackgroundColor()); } } 2. Make a “color preference” form that collects the user’s preferred foreground and background colors. Send the data to a JSP page that displays some message using those colors. This JSP page should use a default value for any form value that the user fails to supply (but don’t worry about empty strings). So, for example, if the user goes directly to the JSP page (bypassing the form), the JSP page should still work fine. For now, don’t worry about the user sending you whitespace; just handle totally missing values. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Color Preference Form</title> </head> <body> <h2>Color Preference Form</h2> <form action="colorDisplay.jsp" method="post"> <label for="foregroundColor">Foreground Color:</label> <input type="text" id="foregroundColor" name="foregroundColor"> <br> <label for="backgroundColor">Background Color:</label> <input type="text" id="backgroundColor" name="backgroundColor"> <br> <input type="submit" value="Submit"> </form> </body> </html> <%@ page import="java.awt.Color" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <% // Get foreground color from the request parameter or use default (Black) String foregroundColor = request.getParameter("foregroundColor"); if (foregroundColor == null) { foregroundColor = "Black"; } // Get background color from the request parameter or use default (White) String backgroundColor = request.getParameter("backgroundColor"); if (backgroundColor == null) { backgroundColor = "White"; } // Set content type and display the message with the specified colors response.setContentType("text/html;charset=UTF-8"); %> <html> <head> <title>Color Display Page</title> </head> <body style="background-color: <%= backgroundColor %>; color: <%= foregroundColor %>;"> <h2>Your Color Preferences</h2> <p>This is a message using your preferred colors!</p> <p>Foreground Color: <%= foregroundColor %></p> <p>Background Color: <%= backgroundColor %></p> </body> </html> 3. Redo the color preference example, but if the user fails to supply either of the colors, use whatever value they gave last time. If you have no previous value, use a default. (Hint: this problem is almost exactly the same difficulty as the previous one.) 4. Redo the color preference example, but if the user fails to supply any of the parame ters, use whatever color the most recent user gave last time. Why could this give bad results? <%@ page contentType="text/html;charset=UTF-8" language="java" %> <% // Get or set session attributes for foreground and background colors String foregroundColor = (String) session.getAttribute("foregroundColor"); String backgroundColor = (String) session.getAttribute("backgroundColor"); // Update colors based on form submission String submittedForegroundColor = request.getParameter("foregroundColor"); String submittedBackgroundColor = request.getParameter("backgroundColor"); // Use last submitted values if the user fails to supply any parameters if (submittedForegroundColor != null && !submittedForegroundColor.isEmpty()) { foregroundColor = submittedForegroundColor; session.setAttribute("foregroundColor", foregroundColor); } if (submittedBackgroundColor != null && !submittedBackgroundColor.isEmpty()) { backgroundColor = submittedBackgroundColor; session.setAttribute("backgroundColor", backgroundColor); } // Use default colors if no previous values exist if (foregroundColor == null || foregroundColor.isEmpty()) { foregroundColor = "Black"; session.setAttribute("foregroundColor", foregroundColor); } if (backgroundColor == null || backgroundColor.isEmpty()) { backgroundColor = "White"; session.setAttribute("backgroundColor", backgroundColor); } // Set content type and display the message with the specified colors response.setContentType("text/html;charset=UTF-8"); %> <html> <head> <title>Color Display Page</title> </head> <body style="background-color: <%= backgroundColor %>; color: <%= foregroundColor %>;"> <h2>Your Color Preferences</h2> <p>This is a message using your preferred colors!</p> <p>Foreground Color: <%= foregroundColor %></p> <p>Background Color: <%= backgroundColor %></p> </body> </html> 5. Fix problem #2 so that it also handles whitespace. Do so without adding any explicit Java code to the JSP page. <%@ page import="java.awt.Color" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <% // Get or set session attributes for foreground and background colors String foregroundColor = (String) session.getAttribute("foregroundColor"); String backgroundColor = (String) session.getAttribute("backgroundColor"); // Update colors based on form submission String submittedForegroundColor = request.getParameter("foregroundColor"); String submittedBackgroundColor = request.getParameter("backgroundColor"); // Use last submitted values if the user fails to supply any parameters if (submittedForegroundColor != null && !submittedForegroundColor.trim().isEmpty()) { foregroundColor = submittedForegroundColor.trim(); session.setAttribute("foregroundColor", foregroundColor); } if (submittedBackgroundColor != null && !submittedBackgroundColor.trim().isEmpty()) { backgroundColor = submittedBackgroundColor.trim(); session.setAttribute("backgroundColor", backgroundColor); } // Use default colors if no previous values exist if (foregroundColor == null || foregroundColor.trim().isEmpty()) { foregroundColor = "Black"; session.setAttribute("foregroundColor", foregroundColor); } if (backgroundColor == null || backgroundColor.trim().isEmpty()) { backgroundColor = "White"; session.setAttribute("backgroundColor", backgroundColor); } // Set content type and display the message with the specified colors response.setContentType("text/html;charset=UTF-8"); %> <html> <head> <title>Color Display Page</title> </head> <body style="background-color: <%= backgroundColor %>; color: <%= foregroundColor %>;"> <h2>Your Color Preferences</h2> <p>This is a message using your preferred colors!</p> <p>Foreground Color: <%= foregroundColor %></p> <p>Background Color: <%= backgroundColor %></p> </body> </html> http://www.coreservlets.com Exercises: the MVC Architecture 1. Redo problem #2 from the previous exercises, but use MVC this time. Also, don’t let the foreground color be the same as the background color. public class ColorPreferenceModel { private String foregroundColor; private String backgroundColor; public String getForegroundColor() { return foregroundColor; } public void setForegroundColor(String foregroundColor) { this.foregroundColor = foregroundColor; } Public string getBackgroundColor() { return backgroundColor; } public void setBackgroundColor(String backgroundColor) { this.backgroundColor = backgroundColor; } } public class ColorPreferenceController { private ColorPreferenceModel model; public ColorPreferenceController(ColorPreferenceModel model) { this.model = model; } public void processFormData(String submittedForegroundColor, String submittedBackgroundColor) { // Check if submitted colors are not the same, update model if valid if (!submittedForegroundColor.equals(submittedBackgroundColor)) { model.setForegroundColor(submittedForegroundColor.trim()); model.setBackgroundColor(submittedBackgroundColor.trim()); } // If colors are the same, do not update the model (handle this scenario as needed) } } <%@ page import="java.awt.Color" %> <%@ page import="java.util.Random" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <c:set var="textColor" value="${model.foregroundColor}" /> <c:set var="bgColor" value="${model.backgroundColor}" /> <html> <head> <title>Color Display Page</title> </head> <body style="background-color: ${bgColor}; color: ${textColor};"> <h2>Your Color Preferences</h2> <p>This is a message using your preferred colors!</p> <p>Foreground Color: ${textColor}</p> <p>Background Color: ${bgColor}</p> </body> </html> import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/ColorPreferenceServlet") public class ColorPreferenceServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Create or retrieve the model ColorPreferenceModel model = (ColorPreferenceModel) request.getSession().getAttribute("colorModel"); if (model == null) { model = new ColorPreferenceModel(); request.getSession().setAttribute("colorModel", model); } // Get submitted form data String submittedForegroundColor = request.getParameter("foregroundColor"); String submittedBackgroundColor = request.getParameter("backgroundColor"); // Create or retrieve the controller ColorPreferenceController controller = (ColorPreferenceController) request.getSession().getAttribute("colorController"); if (controller == null) { controller = new ColorPreferenceController(model); request.getSession().setAttribute("colorController", controller); } // Process form data controller.processFormData(submittedForegroundColor, submittedBackgroundColor); // Forward to the view (JSP) request.getRequestDispatcher("/ColorPreferenceView.jsp").forward(request, response); } }