Chapter 8 lập trình mạng servlets

23 11 0
Chapter 8 lập trình mạng servlets

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

• Servlet là một chương trình được viết bằng Java chạy trên máy chủ Web. • Nó được thực thi theo yêu cầu HTTP của khách hàng (tức là của trình duyệt) và tạo một tài liệu (thường là tài liệu HTML) sẽ được trả lại cho khách hàng bởi người phục vụ.

1/2/2020 Chapter Servlets Contents • • • • • • • • • • Servlet basics Setting up the servlet API Creating a Web Application The Servlet URL and the Invoking web page Servlet structure Testing a servlet Passing data Sessions Cookies Accessing a database via a servlet 8.1 Servlet basics • A servlet is a program written in Java that runs on a Web server • It is executed in response to a client’s (i.e., a browser’s) HTTP request and creates a document (usually an HTML document) to be returned to the client by the server • It extends the functionality of the server, without the performance limitations associated with CGI (Common Gateway Interface) programs • A servlet is Java code that is executed on the server, while an applet is Java code that is executed on the client As such, a servlet may be considered to be the server- side equivalent of an applet • However, Java’s servlet API is not part of Java SE (Standard Edition), though it is included in Java EE (Enterprise Edition)  This means that non-Enterprise users must download an implementation of the Java servlet API 1/2/2020 8.2 Setting up the servlet API • Install Apache Tomcat web server 8.2 Setting up the servlet API • Eclipse IDE for Enterprise Java Developers • https://www.eclipse.org/downloads/packages/ 8.3 Creating a Web Application 1/2/2020 8.3 Creating a Web Application • Note: The web.xml must have and tags that identify the associated Java class file and the servlet’s URL location (relative to the web application) respectively • These and tags will have exactly the same structure for any other servlet 8.4 The Servlet URL and the Invoking web page • Recall that a servlet will be executed on a Web server only in response to a request from a user’s browser • As noted in the previous section, each servlet must be held in folder \webapps\\WEB-INF\classes • The URL for such a servlet has the following format: http://localhost:8080// • For example: http://localhost:8080/MyWebApp/FirstServlet 8.4 The Servlet URL and the Invoking web page • But it is much more common for a servlet to be called from a preceding HTML page • This is usually achieved by the use of an HTML form, with the form’s METHOD attribute specifying either ‘GET’ or ‘POST’ and its ACTION attribute specifying the address of the servlet • The servlet in last slide may then be invoked via the ACTION attribute of a FORM tag in a preceding HTML page as follows: • Note that the URL for the servlet is relative to the Web application that contains both the servlet and the HTML page 1/2/2020 8.4 The Servlet URL and the Invoking web page • To keep things as simple as possible for the time being, we shall start off with a Web page that calls up a servlet without actually sending it any data A First Servlet body{text-align:center;} 8.5 Servlet structure • Servlets must import the following two packages: javax.servlet javax.servlet.http • As of Tomcat 7, it is also necessary to import the following annotation type: javax.servlet.annotation.WebServlet • In addition, since servlet output uses a PrintWriter stream, package java.io is required • Servlets that use the HTTP protocol (which means all servlets, at the present time) must extend class HttpServlet from package java.servlet.http 8.5 Servlet structure • The two most common HTTP requests (as specified in the HTML pages that make use of servlets) are GET and POST • At the servlet end, method service will dispatch either method doGet or method doPost in response to these requests The programmer should override (at least) one of these two methods • All three methods ( doGet , doPost and service ) have a void return type and take the following two arguments: an HttpServletRequest object; an HttpServletResponse object 1/2/2020 8.5 Servlet structure • All three methods ( doGet , doPost and service ) have a void return type and take the following two arguments: an HttpServletRequest object; an HttpServletResponse object • The former (the first parameter) encapsulates the HTTP request from the browser and has several methods, but none will be required by our first servlet • The second argument holds the servlet’s response to the client’s request • There are just two methods of this HttpServletResponse object that are of interest to us at present : • void setContentType(String ): This specifies the data type of the response Normally, this will be “ text/HTML” • PrintWriter getWriter(): Returns the output stream object to which the servlet can write character data to the client (using method println ) 8.5 Servlet structure • There are four basic steps in a servlet: Execute the setContentType method with an argument of “ text/HTML ” Execute the getWriter method to generate a PrintWriter object Retrieve any parameter(s) from the initial Web page (Not required in our first servlet.) Use the println method of the above PrintWriter object to create elements of the Web page to be ‘served up’ by our Web server • The above steps are normally carried out by doGet or doPost • Note that these methods may generate IOException s and ServletException s, which are checked exceptions (and so must be either thrown or handled locally) • Note also that step involves a lot of tedious outputting of the required HTML tags 8.5 Servlet structure • Finally, as of Tomcat 7, a WebServlet annotation tag is required before the opening line of the servlet class This tag indicates the name of the servlet and the path to it (relative to the classes folder) and has the following format: • @WebServlet(“//”) 1/2/2020 8.5 Servlet structure • Phân tích lại code servlet cho rõ phần structure 8.6 Testing a servlet • Build lại app chạy demo, tốt nên demo từ cmd 8.7 Passing data • The previous example was very artificial, since no data was passed by the initial form and so there was no unpredictability about the contents of the page generated by the servlet • Let’s modify the initial form a little now, in order to make the example rather more realistic… Enter your first name: 1/2/2020 8.7 Passing data • It is now appropriate to consider the methods of HttpServletRequest that are responsible for handling values/parameters received by servlets • There are three such methods: • String getParameter(String ) Returns the value of a single parameter sent with GET or POST • Enumeration getParameterNames() Returns the names of all parameters sent with POST • String[] getParameterValues(String ) Returns the values for a parameter that may have more than one value 8.7 Passing data • Sửa lại ví dụ phần 8.4 • Code: page 235 (347 OF 389), file PersonalServlet.java 8.7 Passing data • One potential problem with this method is that, if the browser’s ‘Back’ button is clicked to return to the opening Web page, the initial name entered is still visible • This doesn’t really matter in this particular example, but, for other (repeated) data entry, it probably would • In order to overcome this problem, we need to force the browser to reload the original page, rather than retrieve it from its cache, when a return is made to this page 1/2/2020 8.7 Passing data • There is an HTML META tag that will this, but the tag varies from browser to browser However, the following set of tags will satisfy most of the major browsers: • These should be placed immediately after the tag on the initial Web page 8.7 Passing data • Force page reload when back button is used 8.7 Passing data • Explanation 1/2/2020 8.7 Passing data • Continuing now with the approach of gradually adding to the complexity of our servlets, the next step is to carry out some processing of the data entered and display the results of such processing • The next example accepts two numbers, adds them and then displays the result • Since there are multiple inputs, we shall use the POST method • In addition, an HTML table has been used for laying out the page elements neatly 8.7 Passing data • Code for html: page 237 (249 of 389) • Code for servlet: page 238 (250 of 389) • AdderServlet 8.7 Passing data • Explanation 1/2/2020 8.8 Sessions • One fundamental restriction of HTTP is that it is a stateless protocol That is to say, each request and each response is a self-contained and independent transaction • However, different parts of a Web site often need to know about data gathered in other parts • For example, the contents of a customer’s electronic cart on an ecommerce shopping site need to be updated as the customer visits various pages and selects purchases • To cater for this and a great number of other applications, servlets implement the concept of a session 8.8 Sessions • A session is a container where data about a client’s activities may be stored and accessed by any of the servlets that have access to the session object • The session expires automatically after a prescribed timeout period (30 for Tomcat) has elapsed or may be invalidated explicitly by the servlet (by execution of method invalidate ) 8.8 Sessions • A session object is created by means of the getSession method of class HttpServletRequest This method is overloaded: HttpSession getSession() HttpSession getSession(boolean create) • If the first version is used or the second version is used with an argument of true , then the server returns the current session if there is one; otherwise, it creates a new session object For example: HttpSession cart = request.getSession(); • If the second version is used with an argument of false , then the current session is returned if there is one, but null is returned otherwise 10 1/2/2020 8.8 Sessions • A session object contains a set of name-value pairs • Each name is of type String and each value is of type Object • Note that objects added to a session must implement the Serializable interface (This is true for the String class and for the type wrapper classes such as Integer ) • A servlet may add information to a session object via the following method: void setAttribute(String , Object ) 8.8 Sessions • Example String currentProduct = request.getParameter("Product"); HttpSession cart = request.getSession(); cart.setAttribute("currentProd",currentProduct); 8.8 Sessions • The method to remove an item is removeAttribute , which has the following signature: Object removeAttribute(String ) • For example: cart.removeAttribute(currentProduct); 11 1/2/2020 8.8 Sessions • To retrieve a value, use: Object getAttribute(String ) • Note that a typecast will usually be necessary after retrieval For example: String product = (String)cart.getAttribute("currentProd"); 8.8 Sessions • To get a list of all named values held, use: String[] getAttributeNames() • For example: String[] prodName = cart.getAttributeNames(); 8.8 Sessions • Full example application: This example involves a simplified shopping cart into which the user may place a specified weight of apples and/or a specified weight of pears • Three servlets are used, for the following purposes: • selection of apples/pears; • entry of required weight; • checking out • If one servlet needs to transfer execution to another, then method sendRedirect of class HttpServletResponse may be used 12 1/2/2020 8.8 Sessions • Html code: 242 (254 of 389) 8.8 Sessions • When a selection has been made and the user has clicked ‘Submit’, the Selection servlet is executed Before we look at the code for this servlet, there is an apparent minor problem (that turns out not to be a problem at all) that needs to be considered… • As you are aware by now, a servlet builds up a Web page by outputting the required HTML tags in string form via method println of class PrintWriter This means, of course, that any string literals must be enclosed by speech marks For example: println(""); 8.8 Sessions • However, the next servlet needs to output a FORM tag with an ACTION attribute specifying the address of another servlet • This address, if we follow the convention from our previous examples, will already be enclosed by speech marks • If we try to include both sets of speech marks, then an error will be generated, since what is intended to be opening of the inner speech marks will be taken as closure of the outer speech marks Here is an example of such invalid code: out.println("

Ngày đăng: 10/08/2021, 21:07

Tài liệu cùng người dùng

Tài liệu liên quan