1 / 34

Java Web Development with NetBeans IDE

Java Web Development with NetBeans IDE. -- Kai Qian. Chapter 2 Java Servlets. Objectives. Java Servlet Web Components Support Environments for Java Servlets Servlets with CGI Compared to Java Applets Functionality of Java Servlets Java Servlet API Java Servlet Debugging.

mercer
Télécharger la présentation

Java Web Development with NetBeans IDE

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java Web Development with NetBeans IDE --Kai Qian Chapter 2 Java Servlets

  2. Objectives • Java Servlet Web Components • Support Environments for Java Servlets • Servlets with CGI Compared to Java Applets • Functionality of Java Servlets • Java Servlet API • Java Servlet Debugging

  3. IntroductiontoJavaServlets • Java Servlets technology provides an HTTP-based request and response paradigm on web servers. • Java Servlets can handle generic service requests and respond to the client’s requests. • Java Servlets are used in embedded systems, wireless communication, and any other generic request/response application. • The Common Gateway Interface (CGI) was a popular technology used to generate dynamic HTTP web contents in the mid-1990s.

  4. CGIand Java Servlets Technology

  5. Java Servlets Advantages • Efficiency: Reduction of the time need for creating new processes and initialization and reduction of memory requirements as well. • Convenience: All needed functionality is provided by the Servlets API. • Portability: Cross-platform, Write Once Run Anywhere (WORA) code. • Security: Built-in security layers. • Open source: Free Servlet development kits available for download. • Functionality: Session tracking, data sharing, JDBC database connections, etc.

  6. JavaAppletandJavaServlet

  7. JavaAppletandJavaServlet, contd.

  8. IntroductiontoJavaServlets, contd. • A Servlet component can delegate the requests to its back-end tier such as a database management system, RMI, EAI, or other Enterprise Information System (EIS). • A Servlet is deployed as a middle tier just like other web components such as JSP components. • The Servlet components are building block components, which always work together with other components such as JSP components, JavaBean components, Enterprise Java Bean (EJB) components, and web service components. • A Servlet component is also a distributed component, which can provide services to remote clients and also access remote resources.

  9. Support Environments for Java Servlets • A Java Servlet application is supported by its Servlet container. • The Apache Tomcat web server is the official reference implementation of Servlet containers, supporting Servlets and JSP.

  10. WebServerConfiguration • An XML format file called server.xml is used to control and configure the behavior and setting of the Tomcat web server. • This file is located in the confsubdirectory of the Tomcat installation directory.

  11. WebServerConfiguration, contd. • 1. Reset the server port number where the Servlet class or other web component will listen for requests. • 2. Turn on Servlet reloading so that you don’t need to reload the recompiled Servlet.

  12. JavaServletsBasics • The Java Servlet is a server-side web component that takes a HTTP request from a client, handles it, talks to a database, talks to a JavaBean component, and responds with a HTTP response or dispatches the request to other Servlets or JSP components. • Servlets can dynamically produce text-based HTML markup contents and binary contents as well contents based on the client’s request.

  13. JavaServletArchitecture • A Java Servlet is a typical Java class that extends the abstract class HttpServlet. • The HttpServlet class extends another abstract class called GenericServlet. • The GenericServlet class implements three interfaces: javax.servlet.Servlet, javax.servlet.ServletConfig, and java.io.Serializable.

  14. JavaServletClassHierarchy

  15. ServletLifecycle • A Servlet has a lifecycle just like a Java applet. The lifecycle is managed by the Servlet container. • There are three methods in the Servlet interface, which each Servlet class must implement. They are init(), service(), and destroy().

  16. The Lifecycle of a Servlet

  17. Processing of HTTP Requests and Responses The prototypes of doGet() and doPost() • void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException; • void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException;

  18. Processing of HTTP Requests and Responses, contd. • HttpServletRequest and HttpServletResponse are the two interfaces that provide the Servlet with full access to all information from the request and the response sent back to the client. • When the doGet() or doPost() is called, the Servlet container passes in the HttpServletRequest and HttpServletResponse objects.

  19. import java.io.*; import java.net.*; import javax.servlet.*; import javax.servlet.http.*; import java.text.DecimalFormat; public class TestServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws javax.servlet.ServletException, java.io.IOException { String temperature = req.getParameter("temperature"); DecimalFormat twoDigits = new DecimalFormat("0.00"); try { double tempF = Double.parseDouble(temperature); String tempC = twoDigits.format((tempF -32)*5.0/9.0); PrintWriter out = res.getWriter(); out.println("<html>"); out.println("<head>"); out.println("</head>"); out.println("<body>"); out.println("<h3>" + temperature + " Fahrenheit is converted to " + tempC + " Celsius</h3><p>"); out.println("</body>"); out.println("</html>"); } catch(Exception e) { res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "There was an input error"); } } }

  20. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> • <html> • <head> • </head> • <body> • <h3>Please enter Fahrenheit temperature:</h3><p> • <form action="/conv/test"> • Temperature(F) : <input type="text" name="temperature"><br> • <input type="submit" value="Submit"> • </form> • </body> • </html>

  21. CommunicationfromClientstoHTTPServlets • For GET type HTTP requests you can also directly type http://<host>/<servletName> in the URL location field of the browser if you don’t want to pass in any parameter values. • If you do need to pass in some parameter values with the request you can type http://<host>/<servletName>?<paramterName>=<value> such as http://localhost:8080/conv/conversion?feet=100.

  22. Ways Servlets Communicate with Other Web Components • There are four web component scopes: page, request, session, and application. • The page scope only covers the current page. • Web components can share and delegate the data within a request, session, or application scope.

  23. AttributeScopesinServlet

  24. WebClientSessionTracking • HTTP is a stateless protocol that takes requests from web clients and responds with a file. It does not memorize what has happened in the past. • FTP and Telnet protocols know the client states, such as users, connections, and disconnections but HTTP does not. • A client session consists of a series of conversations between the client and web applications on the web server.

  25. WebClientSessionTracking, contd. • There are two mechanisms to handle client session tracking. • One is to save the client identification and session information on the server side once the Servlet gets a request from the client. • The other is to save the client information on the client browser at the client side for subsequent request use.

  26. WebClientSessionTracking, contd. • The hidden form field is a form field that does not appear on the GUI interface, but it can carry user input data just like any other input field. We can pass data via a hidden form field in a static or dynamic HTML page in an HTML form as follows: • <input type =”HIDDEN” name=”myId” value=”1234” />

  27. WebClientSessionTracking, contd. • URL Rewriting http://<host>/servlet/Servlet1;jsessionid=ABC123, where ABC123 is produced by the encodeURL() method of HttpServletResponse.

  28. WebClientSessionTracking, contd. • Servlet Cookies • Cookies are text files that store sets of param/value pairs. The Servlet at the server side generates the cookie based on the client’s HTTP request. • The cookie is created on the server side and sent back to the client along with the HttpServletResponse object. • The cookie is stored in the client’s browser.

  29. ServletCookie

  30. HttpSession Object in Session Tracking • Using the HttpSession API in session management is quite straightforward, and it may be the best option for session tracking in most cases. • The HttpSession object can hold a session id that can be used to identify whether the requests are within the same session so that they can share the same data. • Each HttpSession object represents a single user HTTP session.

  31. DebuggingServlets • The best solution to fix a runtime logic error is to plug in the Tomcat Servlet container to JBuilder, Eclipse, or VisualAge, or just use an integrated debugger in your IDE such as Sun One Studio, BEA WebLogic, or IBM WebSphere.

  32. DebuggingServlets, contd. • Check the generated HTML source code by using View Source from the web browser menu. Some simple HTML errors can be easily found this way, which can help to locate the Servlet error. • Use the sendError(int sc) method of HttpServletResponse to send an error response to the client with the specified status code and a default message. • Use the out.println() method to print debugging messages on the client page. • Use the jdb Java debug utility to debug the Servlet.

  33. DebuggingServlets, contd. • Use the void log(String message) method of HttpServlet to write debug information into the log file in the Tomcat installation directory. • Use System.out.println() or System.err.println() to write error messages. The error messages will be displayed on the server console if Tomcatis started in developer mode. • Check the request data and response data separately. Determine whether clients have sent the right data or the Servlets responded the right data. You can have separate classes to detect these problems.

  34. Chapter 2 • The End

More Related