Chapter 3 Web Component - Servlet PDF

Summary

This document is a presentation on servlets, a technology used to create dynamic web pages using Java. It provides an overview of servlets, including their life cycle, anatomy, and use cases. Detailed examples and diagrams complement the core concepts. The material focuses on technical aspects of servlet development.

Full Transcript

Chapter 3 Web Component – Servlet CSC584 ENTERPRISE PROGRAMMING What is a web application? A web application is an application accessible from the web. A web application is composed of web components like Servlet, JSP, etc. and other elements such as HTML, CSS, and JavaScript. The w...

Chapter 3 Web Component – Servlet CSC584 ENTERPRISE PROGRAMMING What is a web application? A web application is an application accessible from the web. A web application is composed of web components like Servlet, JSP, etc. and other elements such as HTML, CSS, and JavaScript. The web components typically execute in Web Server and respond to the HTTP request. Servlets Understand the concept of Servlets Servlet technology is primarily designed for use with the HTTP protocol of the Web. Servlets are Java programs that run on a Web server. Java servlets can be used to process client requests or produce dynamic Web pages. What are Servlets? What are Servlets? Units of Java code that run on server-side. Run in containers Helps with client-server communications Not necessarily over HTTP But usually over HTTP What are Servlets? A servlet is any class that implements the javax.servlet.Servlet interface In practice, most servlets extend the javax.servlet.http.HttpServlet class Some servlets extend javax.servlet.GenericServlet instead Servlets usually lack a main method, but must implement or override certain other methods What is the life-cycle of a servlet? 1. Servlet class is loaded. 2. Servlet instance is created. 3. init method is invoked. 4. service method is invoked. 5. destroy method is invoked. Servlets A servlet is like an applet, but on the server side Client sends a request to server Server starts a servlet client server Servlet computes a result for server and does not quit client Server returns response to client servlet Another client sends a request Server calls the servlet again Why Servlets? Web pages with dynamic content Easy coordination between Servlets to make Web applications Where are Servlets? Static File system HTTP Web Server Servlet Dynamic Server Tomcat = Web Server + Servlet Server Methods for the request-response Two common methods for the request-response between a server and client are: GET- It requests the data from a specified resource POST- It submits the processed data to a specified resource Anatomy of Get Request The query string (name/value pairs) is sent inside the URL of a GET request: Data is sent in request header in case of get request. It is the default request type. Let's see what information is sent to the server: Anatomy of Post Request The query string (name/value pairs) is sent in HTTP message body for a POST request: In case of post request original data is sent in message body. Let's see how information is passed to the server in case of post request. Differences between the Get and Post request GET POST In case of Get request, only limited amount of In case of post request, large amount of data can be data can be sent because data is sent in header. sent because data is sent in body. Get request is not secured because data is exposed in Post request is secured because data is not exposed in URL bar. URL bar. Get request can be bookmarked. Post request cannot be bookmarked. Get request is idempotent. It means second request Post request is non-idempotent. will be ignored until response of first request is delivered Get request is more efficient and used more than Post request is less efficient and used less than get. Post. The Servlet API The servlet API provides the interfaces and classes that support servlets. These interfaces and classes are grouped into two packages: javax.servlet, and javax.servlet.http. The Servlet Interface Method Description public void init(ServletConfig config) initializes the servlet. It is the life cycle method of servlet and invoked by the web container only once. public void service(ServletRequest provides response for the incoming request. It is request,ServletResponse response) invoked at each request by the web container. public void destroy() is invoked only once and indicates that servlet is being destroyed. public ServletConfig getServletConfig() returns the object of ServletConfig. public String getServletInfo() returns information about servlet such as writer, copyright, version etc. Servlet Example Servlet Lifecycle Server loads Servlets No Concurrency Issue - run init method Server runs init only once, not per request Servlets Accept Request from service must be thread-safe Clients and return Data back - multiple service method at a time - run service method if that is impossible, servlet must implement SingleThreadModel interface Server removes Servlets destroy must be thread-safe - run destroy method - when server runs destroy, other threads might be accessing shared resources Server reloads Servlets - run init method When are Servlets? Receive Request for Servlet S Loaded when first used, or after modified Is S loaded? no yes no Is S current? (re)Load S yes Servlets die when Servlet Forward Request Server dies to S Servlet Architecture Overview - HTTP servlets parameters, protocol, remote host, ServerInputStream(binary data etc..) Servlet interface ServletRequest doGet(ServletRequest req, ServletResponse res); Servlet GET ServletResponnse Client ServletRequest POST doPost(ServletRequest req, ServletResponse res); Servlet IS-A ServletResponse mime type to reply,reply data, ServletOutputStream The HTTPServlet Class 1. The HttpServlet class defines a servlet for the HTTP protocol. It extends GenericServlet and implements the service method. 2. The service method is implemented as a dispatcher of HTTP requests. The HTTP requests are processed in the following methods: doGet, doPost, doDelete, doPut, doOptions, and doTrace. All these methods have the same signature as follows: protected void doXxx(HttpServletRequest req, HttpServletResponse resp) throws ServletException, java.io.IOException The HttpServletRequest Interface 1. Every doXxx method in the HttpServlet class has an argument of the HttpServletRequest type, which is an object that contains HTTP request information including parameter name and values, attributes, and an input stream. 2. HttpServletRequest is a sub interface of ServletRequest. ServletRequest defines a more general interface to provide information for all kinds of clients. The HttpServletResponse Interface 1. Every doXxx method in the HttpServlet class has an argument of the HttpServletResponse type, which is an object that assists a servlet in sending a response to the client. 2. HttpServletResponse is a sub interface of ServletResponse. ServletResponse defines a more general interface for sending output to the client. Request Parameters Each access to a servlet can have any number of request parameters associated with it. These parameters are typically name/value pairs that tell the servlet any extra information it needs to handle the request. An HTTP servlet gets its request parameters as part of its query string (for GET requests) or as encoded post data (for POST requests). getParameter() − Call this method to get the value of a form parameter. getParameterValues() − Call this method if the parameter appears more than once and returns multiple values, for example checkbox. Request Parameters - getParameter() java.lang.String getParameter​( java.lang.String name) Returns the value of a request parameter as a String, or null if the parameter does not exist. Request parameters are extra information sent with the request. For HTTP servlets, parameters are contained in the query string or posted form data. This method is used when you are sure the parameter has only one value. If the parameter might have more than one value, use getParameterValues(java.lang.String). Parameters: name - a String specifying the name of the parameter Returns: a String representing the single value of the parameter E.g: String name = request.getParameter("name"); int age = Integer.parseInt(request.getParameter("age")); Request Parameters - getParameterValues() java.lang.String[] getParameterValues​( java.lang.String name) Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist. If the parameter has a single value, the array has a length of 1. Parameters: name - a String containing the name of the parameter whose value is requested Returns: an array of String objects containing the parameter's values E.g: String[] interests= request.getParameterValues("interests"); Servlet Annotation Servlet uses the deployment descriptor (web.xml file) for deploying application into a web server. Servlet API 3.0 introduced a new package called javax.servlet.annotation which provides annotation types. It can be used for annotating a servlet class. Deployment descriptor (web.xml) is not required if annotation is used (Tomcat 7 or later version) Annotations can replace equivalent XML configuration in the web deployment descriptor file (web.xml) such as servlet declaration and servlet mapping. Servlet containers will process the annotated classes at deployment time. @WebServlet - declare a servlet. Steps to create a servlet 1. Create a project 2. Create a Servlet 3. Check the deployment descriptor 4. Start the server and deploy the project 5. Access the servlet 1. Create a project The directory structure in the project defines that where to put the different types of files so that web container may get the information and respond to the client. 2. Create a Servlet Create a servlet that extends the HttpServlet class. In this example, we are inheriting the HttpServlet class and providing the implementation of the doGet() method. 2. Create a Servlet 3. Configure the deployment descriptor (if needed) The deployment descriptor is an xml file, from which Web Container gets the information about the servlet to be invoked. You can find the file under WebContent/WEB-INF. Element Description represents the whole application. is sub element of and represents the servlet. is sub element of represents the name of the servlet. is sub element of represents the class of the servlet. is sub element of. It is used to map the servlet. is sub element of. This pattern is used at client side to invoke the servlet. 3. Configure the deployment descriptor (if needed) is used to associate URL mappings () you can give any name not necessarily same as is the servlet class name is the URL that you want to display instead of displaying the servlet class name (e.g. instead of localhost:8081/First/Hellox it will display localhost:8081/First/welcome 4. Run the project 5. Access the Servlet Session Tracking 1. Web servers use Hyper-Text Transport Protocol (HTTP). HTTP is a stateless protocol (connection between the browser and the server is lost once the transaction ends). The HTTP Web server cannot associate requests from a client together. 2. Each request is treated independently by the Web server. This protocol works fine for simple Web browsing, where each request typically results in an HTML file or a text file being sent back to the client. 3. Such simple requests are isolated. However, the requests in interactive Web applications are often related. What is a Session ? A session can be defined as a series of related interactions between a single client and the Web server over a period of time. To track data among requests in a session is known as session tracking. Session Tracking Techniques 1. Using hidden values 2. Using cookies, 3. URL Rewriting 4. Using the session tracking tools from servlet API. Session Tracking Using Hidden Values 1. You can track session by passing data from the servlet to the client as hidden value in a dynamically generated HTML form by including a field like this: 2. So the next request will submit the data back to the servlet. 3. The servlet retrieves this hidden value just like any other parameter value using the getParameter method. Example: Using Hidden Values in the Registration form This example creates a servlet that processes a registration form. 1. The client first submits the form using the GET method. 2. The server collects the data in the form, displays the data to the client, and asks the client for confirmation. 3. The client confirms it by submitting the request with the hidden values using the POST method. 4. Finally, the servlet writes the data to a database. Example: Using Hidden Values in the Registration form Example: Using Hidden Values in the Registration form Example: Using Hidden Values in the Registration form Example: Using Hidden Values in the Registration form Example: Session Tracking Using Cookies 1. You can track sessions using cookies. Cookies are small text files that store sets of name=value pairs on the disk in the client’s computer. 2. Cookies are sent from the server through the instructions in the header of the HTTP response. 3. The instructions tell the browser to create a cookie with a given name and its associated value. If the browser already has the cookie with the key name, the value will be updated. 4. The browser will then send the cookie with any request submitted to the same server. Cookies can have expiration dates set, after which the cookies will not be sent to the server. Example: Session Tracking Using Cookies Example: Session Tracking Using Cookies Example: Session Tracking Using Cookies Example: Session Tracking Using Cookies Example: Session Tracking Using Cookies Session Tracking Using URL Rewriting A token(parameter) is added at the end of the URL. The token consist of name/value pair separated by an equal(=) sign When the User clicks on the URL having parameters, the request goes to the Web Container with extra bit of information at the end of URL. The Web Container will fetch the extra part of the requested URL and use it for session management. The getParameter() method is used to get the parameter value at the server side. Session Tracking Using the Servlet API 1. The problems of session tracking with hidden data and cookies are that data are not secured and difficult to deal with large set of data. 2. Java servlet API provides a session tracking tool, which enables tracking of a large set of data. Data can be stored as objects. Data are kept on the server side so they are secure. Session Tracking Using the Servlet API The HttpSession Class 1. To use the Java servlet API for session tracking, first create a session object using the getSession method in the HttpServletRequest interface like this: HttpSession session = request.getSession(true); 2. This obtains the session or creates a new session if the client does not have a session on the server. 3. The HttpSession class provides the methods for reading and storing data to the session, and for manipulating the session. The HttpSession Class The HttpServletRequest interface provides two methods to get the object of HttpSession: public HttpSession getSession():Returns the current session associated with this request, or if the request does not have a session, creates one. public HttpSession getSession(boolean create):Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session. How HttpSession works? On client's first request, the Web Container generates a unique session ID and gives it back to the client with response. This is a temporary session created by web container. The client sends back the session ID with each request. Making it easier for the web container to identify where the request is coming from. The Web Container uses this ID, finds the matching session with the ID and associates the session with the request. Session Tracking Using the Servlet API Some Important Methods of HttpSession Example: Session Tracking Using HttpSession Example: Session Tracking Using HttpSession Example: Session Tracking Using HttpSession

Use Quizgecko on...
Browser
Browser