Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
SE2840 Lab 5: Dynamic web application with Java Servlets + Command Pattern Outcomes Addressed • • • • understand and apply object-oriented design patterns understand the use of UML in the design documentation process be able to design and implement small software components and systems be able to use computer-aided software engineering (CASE) tools in the design process Overview The purpose of this lab is to implement a Web based CommandPattern for processing diverse Web requests (commands) using the Tomcat Web Application Server and Java Servlets. Part 1 – Up and Running 1) Download and install Eclipse IDE for Java EE Developers http://www.eclipse.org/downloads/. Make sure you download an EE version of Eclipse. If you already have a compatible version of Eclipse or if you prefer IntelliJ or other IDE that supports Java Servlets and JSP, you can skip this step. Note: WebStorm to the best of my knowledge does not support Java EE (Servlets, JSP, etc.). You will need the JetBrains IntelliJ IDEA Ultimate version. There is a 30-day free trial, and then you will have to pay (a lot ;-). 2) Download and install Apache Tomcat (on your PC) http://tomcat.apache.org/index.html For Windows, I would recommend the Service Installer: 32-bit/64-bit Windows Service Installer (pgp, md5) For Mac or Linux, just download the zip file. Unzip tomcat into a convenient directory. Notes: • • I recommend sticking with Tomcat 7. It is very stable and widely deployed. The lab was tested on Tomcat 7. It should also work fine with Tomcat 8. I would avoid installing the Tomcat 9 alpha release. There should be a prompt where you can select the port. By default, Tomcat uses port 8080. If are not running any other servers, you can change the port to 80 (default HTTP port), otherwise you will have to specify your port in your URL. In my instructions, I am sticking with port 8080. 1 3) Define Eclipse Installed Server Runtime Note: Instructions for IntelliJ Ultimate version: https://www.jetbrains.com/help/idea/2016.2/tutorial-developing-a-java-ee-application.html In Eclipse, select Window->Preferences. In the left-hand pane select Server->Runtime Environment. Select Search… “Tomcat” and then Add the Apache Tomcat runtime environment to Eclipse. Select Finish. Note: You could also install Tomcat when you create your first Web app. Select Finish, select OK: 2 4) Create a “Dynamic Web Project.” File -> New -> Dynamic Web Project. Name your project. Under Target Runtime verify that your Apache Tomcat runtime is selected. 3 If Apache Tomcat was not selected under Target Runtime, select New Runtime and define a target runtime as follows. Otherwise, skip this step. 4 Accept source and output folders, select Next: Select Generate web.xml deployment descriptor, and select Finish: Tada! 5 5) Create a Servlet Expand your newly created Web project. Right-mouse click on Java-Resources: src to bring up the Wizard, select New and create a package called controller. Right-mouse-click the controller package, select New and select Servlet. Note: the Servlet selection may be under Web. Enter your servlet name: CmdServlet.(I have a way with names ;-) 6 Select Next, you can enter a description if you would like. Skip initialization parameters for now. Select Next again. Verify the doPost and doGet method stubs have are selected as follows. Alternatively, you could select doService. Select Finish. Your Web project hierarchy should look as follows: 7 7) Update your Web Descriptor web.xml You need to define your Servlet to your application. Define your servlet and servlet URL mapping as shown below. <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>CmdWeb</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <description></description> <display-name>CmdServlet</display-name> <servlet-name>CmdServlet</servlet-name> <servlet-class>controller.CmdServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>CmdServlet</servlet-name> <url-pattern>/CmdServlet</url-pattern> </servlet-mapping> </web-app> 8 8) Update your project properties build path Information purposes only: From your project, select Properties -> Java Build Path -> Libraries, Web App Libraries to select libraries to be packaged with your Web App. Not needed for this lab, but this is something you will frequently do. 9 8) Coding a test CmdServlet Add the following method to your CmdServlet, or place the code within the doGet() method. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String cmd = request.getParameter("cmd"); String String String String String String accept = request.getHeader("accept"); user_agent = request.getHeader("user-agent"); accept_charset = request.getHeader("accept-charset"); accept_language = request.getHeader("accept-language"); x_wap_profile = request.getHeader("x-wap-profile"); profile = request.getHeader("profile"); response.setContentType("text/html"); java.io.PrintWriter output = response.getWriter(); output.println("<html>"); output.println("<head><title>User Agent</title></title>"); output.println("<body>"); output.write("accept " + accept + "<br>"); output.write("user_agent " + user_agent + "<br>"); output.write("accept_charset " + accept_charset + "<br>"); output.write("accept_language " + accept_language + "<br>"); output.write("x_wap_profile " + x_wap_profile + "<br>"); output.write("profile " + profile + "<br>"); output.println("</body></html>"); output.close(); } Note 1: Its good practice to properly enclose your output in properly formatted HTML. Example: <HTML><HEADER><TITLE>title</TITLE></HEADER><HTML><BODY>output</BODY></HTML> Note 2: The service() method is the entry point to your servlet. When the Tomcat web application server receives a request for your servlet, it packages the HTML request within the HttpServletRequest class, and provides access to a PrintWriter allowing you to write a response to the requesting Web client. By default, the service() method calls doGet() for HTML get requests and doPost() for post requests. The getParameter method in HttpServletRequest class provides access to URL parameters. For example, for the url: http://localhost/CmdWeb/CmdServlet?cmd=time, the following getParameter method would return “time”. Experiment with different cmd parameters and refresh your Web App in the browser to verify reading by your servlet. String value = request.getParameter("cmd"); This mechanism allows you to return any cmd you choose from a URL. 10 8) Launch your Web application and test your Servlet. Right-mouse-click on your Web project and select Run On Server or Debug On Server. If you select Debug, you can set breakpoints and inspect variables. 11 Select Next. Verify your Web App is configured for the server. Select Finish. Otherwise select your Web project from the Available projects left-hand-column, and select Add to move your project to the Configured projects column on the right. Select Finish. An internal Web browser should launch. If not select the Globe Icon. Type in the following URL: http://localhost/CommandWeb/CmdServlet. You should receive output showing information about your browser: accept: */* user_agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; InfoPath.2; .NET CLR 3.0.04506.648; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729) accept_charset: null accept_language: en-us x_wap_profile: null profile: nullNote: You may have to restart your server. In the server window, right-mouse click on your server and select Restart either in debug or run mode. 12 Part 2 – Command Interface 1) Create a package to define your command interface and command objects package command; import javax.servlet.http.*; public interface Command { public String execute(HttpServletRequest request, HttpServletResponse response) throws CommandException; } 2) Refactor your CmdServlet as the Invoker in the Command Pattern. Your Servlet should accept cmd URL parameters and invoke concrete Command objects through the Command interface. public class CmdServlet extends HttpServlet { private static final long serialVersionUID = 1L; private HashMap<String, Command> commands; private String error = "error.jsp"; private String jspdir = "/"; public void init(ServletConfig config) throws ServletException { super.init(config); initCommands(); } public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String next; try { Command cmd = lookupCommand(request.getParameter("cmd")); cmd.execute(request, response); System.out.println("CmdServlet: cmd = " + cmd + ", next = " + next); } catch (CommandException e) { e.printStackTrace(); } //ignore for now //RequestDispatcher rd; //rd = getServletContext().getRequestDispatcher(jspdir + next); //rd.forward(req, res); } 13 3) Refactor the previous servlet code into a Command object. • • Define a Java interface with an execute(HttpServletRequest request) method. Implement a concrete instance of your Command interface for each command that you would like to process. 4) Add an initCommands() method to instantiate command objects, and a lookupCommand(req.getParameter("cmd")) method to look up Command’s to execute to CmdServlet. I would recommend using a HashMap to store your command objects. 5) Create at least one additional Command class of your choosing to provide useful information for your Web clients! For example, the URL: http://localhost/CmdWeb/CmdServlet?cmd=weather&loc=Milwaukee would return the weather for Milwaukee. In this case, the CmdServlet only processes the cmd parameter to look up the appropriate Command object. The CmdServlet forwards the context of the Web request to the appropriate concrete command using the HttpServletRequest object. The concrete Command can use HttpServletRequest to obtain additional URL parameters such as loc. Deliverables: 1. Lab report including the following: • • • • • • UML class diagram of your Command design pattern. UML Sequence diagram depicting the sequence of actives for processing a web request through your Command pattern (diagram can be hand drawn). Output from each of your Commands. Your feedback on the lab. Source code. Demo! Note: diagrams can be hand drawn (with good quality!). 2. Submit your lab assignment to Blackboard. Name your report as follows: “se2840-lab5dykstra.pdf”, zip your source and report as: “se2840- lab5-dykstra.zip.” In the subject of our email include: “SE2840 Lab 5” Your submission should include all deliverables listed above. Thanks, Jay Urbain 14