You are on page 1of 117

Servlet Programming course

So far we have seen the different computing models and discussed about distributed component t based b d applications. li ti L Let t us now di discuss th the component tt technologies h l i i in th the context of the Java world. Suns Java 2 Platform, Enterprise Edition or J2EE specification helps us to develop such distributed component based applications using the Java language. J2EE provides an architecture for developing, deploying, and managing distributed components. J2EE uses a multitiered application model in which the application logic is divided into components based on its function. Each component is installed on different machines depending on the tier to which the component belongs. Theoretically, J2EE applications can have any number of tiers but most of the applications have three or four tiers. The four tiers, client, web, business or enterprise, and database, are installed on client, J2EE server, and database server machines. The J2EE components that can be used in different tiers are client, web, and business components.

J2ee follows the distributed multitier application approach which means the entire application d not do t reside id at t a single i l location l ti b but t di distributed. t ib t d A And d th the applications li ti i is di divided id d i into t various i tiers. J2ee application is composed of various plug and play components which can be created by the different developers and then assembled together. The application logic is divided into functions and then based upon functions the components are created. The components can be installed on different machines across various tiers. And the distribution of application components across the different tiers depends upon the functionality it performs. J2ee application tiers are Client Tier Web tier Business Tier Enterprise Information tier

Components are self contained piece of software that are reusable across applications and are configurable external to the source code code. J2EE components are of three types : client component, web component and business component. The client components interact with the user, the web components interact with the web browsers using the HTTP protocol, and the business components interact with the application server and execute the business logic. Client components is of two types : web client and application client. A web client, generally a browser, sends a request to the server and renders the webpage sent back by the server. However, it may not perform any complex tasks such as querying a database or performing any complicated business tasks and hence is also referred to as thin client. The complex tasks are performed on the server. For displaying web pages with applets, the web clients may require Java plug-ins and security policy files for executing the applets. An application client is a standalone application that doesnt run in browsers. It can access components in the business tier directly. Note that web clients that require access to a servlet running in the Web tier can open an HTTP connection with the servlet. Web components for java are Servlets and JavaServer Pages (JSP). A servlet receives HTTP requests from the client, processes them, and returns the output. It can also generate dynamic responses. Similar to servlets, JSP also create dynamic web pages. JSP pages are converted into servlets and executed within a servlet container. They are used to display the results processed by a servlet. Business components implement the business logic or the functional process logic that defines the business rules and constraints. For example business process such as withdrawing amount from the bank. Business components are of three types : session beans, entity beans, and message-driven beans. Session beans represent a session with a client. Being a transient object, they lose their data on completion of the session. On the other hand, entity beans are persistent objects and so retain data even after the session. They represent a row of data in a database table. Message-driven beans are for receiving the receiving Java Message Service (JMS) messages asynchronously.

Following are different type of Containers : M Manages th the execution ti of f application li ti client li t components. t A Application li ti clients li t and d th their i container run on the client. Application client container is the one which is responsible for managing the application client components. Both application client and its container resides at the client machine and are executed on the client end. Example of application container is JVM. Applet container is the container to manage the execution of applets. Examples of an applet container include Web browser and applet viewer. Enterprise JavaBeans (EJB) container: It is to manage the execution of EJB component of the J2EE application. Both the EJBs and its container run on the J2EE server. J2EE server provides the EJB container, and an example of J2EE server is WebLogic. Web container: It is to manage the execution of the Servlets and the JSP. Both the Web components and its container run on the J2EE server. An example of a web container is Tomcat.

Servlets Architecture

Servlets are the programs written in Java code which is executed in the server application on the th middle iddl tier. ti Thats Th t why h named d as servlet l t( (similar i il to t applet l t which hi h is i executed t d at t th the client end). They are for generating the dynamic pages. Servlets are not meant for any specific client server protocol . But as it is mostly used by the HTTP protocol, word Servlet refers to HTTPServlet. It was introduced by the Sun Microsystems as an alternative to CGI. We will see the comparison between the two in the coming slides. The output of a servlet can be a HTML/XML/Text or any other format as well.

10

What is a Servlet Container A standalone Java program is directly invoked by the end user and starts its execution from the main method. But in case of a servlet the client makes a http request to the Web-Server in order to execute the servlet. For the servlet to execute it has to be loaded into the memory, receive the client request and respond back to the client. These responsibilities are carried out by a service known as the Servlet container. Network Service :The Servlet Container along with a web server or application server, provides the necessary network services so that the request and response can be communicated over the network between the client and the server. Coding/decoding : The container decodes MIME (Multipurpose Internet Mailing Extensions) based requests and then passes on the request object to the servlet. Similarly formats the response generated by the servlet into MIME based responses so that the client browser understands the output generated by the servlet. LifeCycle Management :It manages the lifecycle of the servlet. It can either be a part of the host web server or installed as an add-on component to a Web Server. It can also be built into Application Servers. HTTP protocol is supported by all the vendors for requests and response. But along with HTTP they may support other request/response based protocols such as HTTPS (HTTP over SSL).

11

We are using tomcat as the default container for Servlet.However, since Tomcat can handle HTML Servlets and JSP HTML, JSP, Tomcat can be installed and used even without installing Apache web server. Steps to configure the Tomcat Server 1. Extract the file from the zipped tomcat folder (say jakarta-tomcat.zip) to a folder (say c:\tomcat) 2. Set the java_home environmental variable. 3. Open command prompt 3. Move to the bin directory of the tomcat foder. 4. Type startup to start the server 5. Use shutdown to shutdown the server. 6. Type http://localhost:8080 to access the rootcontext of the server(assuming that port number is 8080 for tomcat server) 7. Create your own context by creating a directory under c:\tomcat\webApps directory 8. Create a subdirectory named WEB-INF under myApp and a directory named classes under WEB-INF. Place all your class files under the classes folder. Files like Html, xml, jsp pages can be directly placed under myApp directory. 8.Test your context by writing a simple index.html file and placing it under the myApp. 9. Start the Server and type the URL in the browser - > http://localhost:8080/myApp

12

The Servlet Containers mode of Servlet Execution: The Request-Process-Response Cycle The client makes a request to the web server by the GET or POST method of HTTP. Normally the client is assumed as a browser from which the request is made to the web component present( jsp or servlet) in the web server. The request to the web server is then forwarded to the container to take appropriate action. The container determines which servlet to invoke for the particular request depending upon the internal configuration and loads the servlet to memory. The servlet then accepts the request paramaters and generates appropriate response. The Servlet container can be a part of the host server, or can be in a separate process on the same host, or can be on a separate host from the Web Server for which it processes requests.

13

The Request-Process-Response Cycle (Contd.) The request object holds the information about the client and the request The servlet uses this object to find out the identity of the host client, HTML form parameters sent and other information. The servlet then process the request to generate the output and sends back the response object to the container. Which is then forwarded to the server and then to the client in the form of response object. The servlet container returns control back to the host Web server after ensuring that the response is flushed properly.

14

15

16

The Servlet Interface

Servlets S l t are created t d by b implementing i l ti th the servlet l t interface, i t f which hi h i is th the central t l abstraction b t ti of f Servlet API. Servlet interface can be implemented directly or indirectly by extending from the class which implemented it. Generally its preferred to extend from the class rather then implementing the interface. The two such classes present in the API are : GenericServlet
and HttpServlet. Mostly HttpServlet class is used. The main packages that constitutes the Servlet API are javax.servlet and javax.servlet.http Request Handling Methods Servlet interface defines three methods : init() , service( ) and the destroy(). Service method is for handling the client request. When a client request reaches to the container it creates a thread of the servlet object. Along with that Request and the response object are created and passed as parameters to the service method. After that container invokes the service method to process the client request. This method is called for each client request for this instance of servlet. Multiple request threads may be executing within the service method at any time. The doGet (...) or doPost (...) methods can be used if the developer has extended the class from HttpServlet. It is the service method of the HttpServlet that calls the doGet or doPost method

depending upon the HTTP method


Number of Instances In case of multithreaded model, only one instance of the servlet is created in a container. But in case of Single ThreadedModel multiple instances of a servlet is maintained so that multiple requests can be handled in parallel while still serializing requests to the single instance. In distributed application there is one instance per JVM, for a servlet. If the servlet implements SingleThreadModel and is a part of distributed web application then in each JVM, multiple instances of the servlet are created by the container.

17

Servlet Life Cycle Servlet'life cycle defines how it is loaded, instantiated, handles requests from clients and how it is taken out of service. Servlet goes through a well defined life cycle. Before processing any request, Servlet is loaded into the memory, instantiated and initialized by the container. Initialization is done by calling the init() method of the servlet. Client request are processed through the service() method of the servlet. Once the container decides that the servlet is no longer needed it removes it from the memory and destroy method is called before destroying the servlet.

18

The life cycle is expressed in the API by the init(), service() and destroy() methods in that order d of f execution ti of f th the j javax.servlet.Servlet l tS l ti interface t f th that t all ll servlets l t di directly tl or i indirectly di tl implement.

19

The code shown in the slide is the most common code we write in the init method More about init() The init method of the class GenericServlet contains similar statements and hence classes that are inherited from GenericServlet need not override this method just for storing the ServletConfig object in a class variable
class FirstServlet implements Servlet { private transient ServletConfig cf; public void init(ServletConfig serConfig) throws ServletException { cf = serConfig; //More statements } public ServletConfig getServletConfig() { return cf; } //Other methods } Now, other methods can also access the ServletConfig object using the getServletConfig method

20

A Servlet that extends GenericServlet may want to store the ServletConfig object in a class variable and do some more work In such cases, GenericServlet helps the programmer to do more during initialization as follows public void init(ServletConfig serConfig) throws ServletException { config = serConfig; //More statements init(); } public void init() throws ServletException { } The init(ServletConfig) method of GenericServlet calls another method called init() and a blank implementation of init() is provided in GenericServlet.The programmer can override the init() method to do more in the init(ServletConfig) method.The programmers who are extending GenericServlet need not bother about init(ServletConfig) and instead, they can override init(). The programmer can call a method on the ServletConfig object in two different ways One way is to get a reference to the ServletConfig object by calling the getServletConfig method and call the method using this reference The second method is easier and as followsThe GenericServlet class is implementing the ServletConfig object.All the methods in ServletConfig object are available in GenericServlet itself Instead of calling the methods on the ServletConfig object, we can just call it on the GenericServlet.The GenericServlet will in turn call the corresponding method of the ServletConfig object and give the result. For example, the GenericServlet class implements the public String getInitParameter(String parametername) of ServletConfig as follows public String getInitParameter(String name) { return getServletConfig().getInitParameter(name); }

21

Request Handling As discussed earlier, the servlet can handle the request only after proper initialization. The request handling phase is carried out by the service method of the servlet life cycle. The service method of the Servlet takes ServletRequest and ServletRespose as the parameters. HTTPRequest object holds information about the request, client and the form data. Servlet then create a response to the request by using the provided object of type ServletResponse. For a HTTP request, the request and response objects are of type HttpServletRequest and HttpServletResponse respectively More about service method Most of the containers will create only one instance of a Servlet. The same instance is used for servicing all the client request. For each client request, the container executes the service method in a thread. So for multiple client requests, only multiple threads are created and not multiple objects. This model requires lesser memory and lesser cpu time compared to the multiple object model.

22

End of Service The Servlet need not to be alive throughout. It can be active in a container for milliseconds or as long as the container is up (which could be measured in days, months, years) or any amount of time in between. Before unloading the servlet from the memory it may be required to release the resource or save the persistence state. To do this the servlet container provides the destroy method which is called by the server before removing the servlet from the memory. But before calling the servlet destroy() method servlet container waits for the threads that are running in the service to either complete, or exceed a server defined time limit. Once the destroy is called no further requests can be processed by that instance of the servlet. In order to process new requests servlet container needs to create a new instance of the servlet's class. Once the destroy method finishes, the servlet container releases the servlet. And is collected by the garbage collector.

23

24

The web module can be pack aged as WAR file either using the JAR utility.

25

26

27

28

29

30

Note that the output produced by this servlet is only observed in the tomcat server console. The init() method is executed only once. The service() method is executed against each request made by the client. The destroy ()method is executed only once when the tomcat server is shut down.

31

32

33

34

A Simple Servlet Generating Plain Text, HTML, XML ServletResponse object is created by the container and passed on as an argument to the servlet's service() method. PrintWriter(returned by getWriter()) object is used to return character data. ServletOutputStream (returned by getOutputStream()) object is used to send binary data in a MIME body response setContentType(java.lang.String) is used to specify the charset for the MIME body response. For ex "text/html; charset=Shift_JIS". It can also be set using setLocale(java.util.Locale). If not specified then ISO-8859-1 is used. The setContentType() or setLocale() method must be called before getWriter() for the charset to affect the construction of the writer.

35

The example shows how to send the content from the servlet to the client browser with a content t tt type of f text/text. t t/t t

36

Example which sends html content from a servlet

37

Send an XML file to the client browser

38

39

40

Request Parameters Request parameters are string data, which is a part of the request object, sent from the client to a server. In case of Post request of the HttpServletRequest, the Paremeters are populated from the posted form data and in case of Get from the URI query string. And are stored by the servlet container as a set of name-value pairs. Multiple parameter values can exist for any given parameter name. ServletRequest interface has the following methods available to access parameters: getParameter(ParameterName) getParameterNames() getParameterValues(ParameterName) In order to retrieve multiple values, associated with a single parameter name getParameterValues() method is used. It returns an array of String objects containing all the parameter values associated with a parameter name. If there is only one value associated with a given parameter name then getParameter() is used. In case, the parameter name is associated with multiple parameter values, the first value of the parameter will be returned. To retrieve all the parameter names in the request getParameterNames() method is used. It returns an Enumeration of the parameter names

41

Request Parameters (Contd.) Form data and the query string data is then aggregated to create the parameter set. Order of the parameter set is decided based on whether the parameter is from query string or the post . Query string data takes precedence over the post body parameter data. For example, if a request is made with a query string of str= Infosys and a post body of str =hello&str=world, the resulting parameter set would be ordered as str =(Infosys,hello, world) If the parameter has to be fetched through the getParameter family of methods then it has to follow the above conditions. If the contditions are not met then the data can be accessed only through the request stream.

42

Attributes are the object associated with the request/session/application/page. There can be at t most t one value l associated i t d with ith a given i attribute tt ib t name. Some S attribute tt ib t names beginning b i i with prefixes like sun., com.sun., java. and javax. are reserved. Java. and javax. are for definitions. And sun., and com.sun. are reserved for definition by Sun Microsystems. Attributes may be set by the container/ servlet. Container use it to express information that otherwise could not be expressed via the API. Servlet use it to communicate information to another servlet (via RequestDispatcher). Attributes are accessed with the following methods of the ServletRequest interface getAttribute(), getAttributeNames() , setAttribute()

43

A HTML form with the fields fName, fAge, and fProfession submits to a Servlet named S l t1 Servlet1. The Servlet has to read the form-submitted values into different String objects.

44

A html form based on the previous code calls the servlet and store it in the ourApps di t directory. The servlet Serv1 knows the names of the form-submitted fields and calls the attribute by getParameter() method.

45

46

47

48

49

50

51

52

To access the value of a header associated with a given name getHeader() is used. In case th there are multiple lti l values l associated i t d with ith a given i name getHeaders() tH d () is i used d such h as cacheh control header. getHeaders() returns an enumeration of the string object associate with a given header name. If getHeader() is used to access the header having multiple values then the first value will be returned.

53

54

55

56

The above program retrieves the client request specific information:

57

58

59

60

61

62

It is rightly so that the Internet does not keep a session between the client and the server, after the Web server has serviced the request of the client browser browser. Otherwise Otherwise, it would increase the overheads of keeping a lot of sessions alive between the client and the server that would pose a serious performance issue. While this model scores from a performance viewpoint, it becomes a severe constraint when designing applications for the Web. Consider a client browser downloads a page from a server, and then subsequently clicks on a hyperlink on the page to connect to another related page as part of the workflow of an application. In this case, the server has no way of knowing that it is the same client who now wants to access another related page as part of the work-flow of the same application. User-specific data on the first page is something that the server will not be able to relate to the subsequent page, because as far as the server is concerned, it is a fresh hit even though the same user or client has made a hit to another subsequent page as part of the workflow of the application. The server is therefore, not able to maintain state (user or client specific data between accesses by the same client to different pages of an application. This problem can be overcome if a session is kept alive between a client and a server. For example, consider a typical scenario of a client application connecting to a database server. Once the client connects to a database, a session is established between the client and the database server. The client can invoke a stored procedure as part of its application logic. The call to the stored procedure can return data to the client that can be conditionally evaluated and different branches of execution can be initiated as part of continuing with the same application. This is precisely what cannot be simulated on Web-based applications on the Internet. The Hypertext Transfer Protocol (HTTP) is by design a stateless protocol. To build effective Web applications, it is imperative that a series of different requests from a particular client can be associated with each other. Many strategies for session tracking have evolved over time, but all are difficult or troublesome for the programmer to use directly. State maintenance and session tracking became serious bottlenecks for designing effective Web-based applications. The cookie evolved as a solution to the problem of state maintenance and session tracking.

63

Session tracking through HTTP cookies is the most used session tracking mechanism and is required to be supported pp by y all servlet containers. The servlet container sends a cookie to the client. The client will then return the cookie on each subsequent request to the server unambiguously associating the request with a session. The name of the session tracking cookie must be JSESSIONID. A cookie is an object that a server creates and places on the client when the client connects to it. A cookie contains state information. Cookies are valuable for tracking user activities. For example, assume that a user visits an online bookstore. A cookie can save the users name, address, email-id and other information. The user does not need to enter this data each time he or she visits the online bookstore. The names and values of cookies are stored on the client machine. Some of the information that is saved includes the cookies: Name Value Expiration date path

64

Cookies(notepages contd.) Th expiration The i ti date d t determines d t i when h this thi cookie ki is i deleted d l t d from f th clients the li t machine. hi If an expiration date is not explicitly assigned to a cookie, it is deleted when the current browser session ends. Otherwise, the cookie is saved in a file on the users machine. There will be so many cookies residing on the client machine pertaining to the different servers the client would have connected to. The key question that arises is how the right cookie pertaining to a particular server is picked up and sent to the server when the client connects to it. The domain and path of the cookie determine when it is included in the header of an HTTP request. If the user enters a URL whose domain and path match these value in the cookies, that cookie is then supplied to the Web server. Otherwise, it is not. Cookies therefore, are a general mechanism which server side connections use to both store and retrieve information on the client side of the connection. The addition of a simple, persistent, client-side state significantly extends the capabilities of Web-based client/server applications. A server, when returning an HTTP object to a client, may also send a piece of state information that the client will store. Included in that state object is a description of the range of URLs for which that state is valid. Any future HTTP requests made by the client that fall in that range will include a transmittal of the current value of the state object from the client back to the server. The state object is called a cookie, for no compelling reason. This simple mechanism provides a powerful new tool, which enables a host of new types of applications to be written for web-based environments. Shopping applications can now store information about the currently selected items, for fee services can send back registration information and free the client from retyping a user-id on next connection, sites can store per-user preferences on the client, and have the client supply those preferences every time that site is connected to.

65

66

67

Constructor Summary Cookie(java.lang.String name, java.lang.String value) - Constructs a cookie with a specified name and value. Method Summary java.lang.Object clone(): Overrides the standard java.lang.Object.clone method to return a copy of this cookie. java.lang.String getComment(): Returns the comment describing the purpose of this cookie, or null if the cookie has no comment. java.lang.String getDomain(): Returns the domain name set for this cookie. Int getMaxAge() : Returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will persist until browser shutdown. java.lang.String getName() : Returns the name of the cookie.

68

69

70

A HTML that accepts cookie name and cookie value.

71

CookieServ.java is the servlet which handles cookies

72

73

74

A context could be located at http://www.searchonline.com/catal. All requests that start with / t l request /catal t path, th which hi h i is k known as th the context t t path, th will ill be b routed t d to t this thi servlet l t context. t t

75

76

77

Why Session Tracking The Hypertext Transfer Protocol (HTTP) is by design a stateless protocol. It opens a separate connection to the Web Server, and the server does not automatically maintain information about a client. These cause a number of difficulties. For example when clients at an online store add an item to their shopping carts, the server has to have a mechanism of knowing what is already in them. Similarly, when clients decide to proceed to checkout, the server must be able to determine which previously created shopping carts are theirs. To build effective web applications, it is imperative that a series of different requests from a particular client can be associated with each other. Using the session object solves this problem.

78

URL Rewriting : URL rewriting is the lowest common denominator of session tracking. In cases where a client will not accept a cookie, URL rewriting may be used by the server to establish session tracking. URL rewriting involves adding data to the URL path that can be interpreted by the container on the next request to associate the request with a session. The session id is encoded as a path parameter in the resulting URL string. The name of the parameter must be jsessionid. Here is an example of a URL containing encoded path information. For example, http://www.sitex.com/catalog/index.html;jsessionid=1234 Cookies Session tracking through HTTP cookies is the most used session tracking mechanism and is supported by all servlet containers. The container sends a cookie to the client, The client will return the cookie on each subsequent request to the server unambiguously associating the request with a session. The name of the session tracking cookie is JSESSIONID.

79

Methods of HttpSession java.lang.Object getAttribute(java.lang.String name) :Returns the object which is bound with the particular name in this session, or null if no object is bound under the name. java.util.Enumeration getAttributeNames() :Returns Enumeration of String objects containing the names of all the objects bound to this session. long getCreationTime() :Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT. java.lang.String getId() :Returns a string containing the unique identifier assigned to this session. long getLastAccessedTime() :Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT, and marked by the time the container received the request. int getMaxInactiveInterval() :Returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses. void setAttribute(java.lang.String name, java.lang.Object value) :Binds an object to this session, using the name specified. void setMaxInactiveInterval(int interval) :Specifies the time, in seconds, between client requests before the servlet container will invalidate this session. void invalidate() :Invalidates this session then unbinds any objects bound to it. void removeAttribute(java.lang.String name) :Removes the object bound with the specified name from this session.

80

Example An Application Displaying per client no. of visits to a page. This sample application consists of two pages. 1. Starting.html 2. VisitServ.java Starting.html <html> <body> Welcome to our Web site. <p> <a href="servlet/VisitServ">Click Here</a> <p><p><p> <a href="servlet/Logout">Logout</a> </body> </html>

81

82

83

84

Instead of creating Connection objects every time a set of Connection objects are reused. Thi is This i normally ll known k as Connection C ti P li Pooling. C Connection ti pooling li was pioneered i d by b database vendors to allow multiple clients to share a cached set of connection objects that provide access to a database resource. The connection objects are created by pool manager upfront, at startup. The pool manager is implemented by the application service provider in its memory space and optimize resource usage by dynamically altering the pool size, based on demand.

85

Pre allocate the connections P f Perform thi particular this ti l task t k in i the th constructor. t t Allocate All t more connections ti i advance in d speed d things up if there will be too many concurrent requests later but causes an initial delay. As a result of this, a servlet that pre allocates many connections should build the connection pool from its init method. Managing available connection If connection is required , an idle connection is available, put it in the list of busy connections and then return it. The busy list is used to check limits on the total number of connections as well as when the pool is instructed to explicitly close all connections. Before returning the Connection, confirm that it is still open. If not discard the connection and repeat the process. Discarding a connection opens up a slot that can be used by process that needed a connection when the connection limit had been reached, so use notifyAll to tell all waiting threads to wake up and see if they can proceed. Allocate new Connections If a connection is required, there is no idle connection available, and the connection limit has not been reached, then start a background thread to allocate a new connection. Then wait for the first available connection, whether or not it is the newly allocated one. Wait for a connection to become available This situation occurs when there is no idle connection and you have reached the limit on the number of connections. The natural approach is to use the wait method, which gives up the thread synchronization lock and suspends the thread until notify or notifyAll is called. Since notifyAll could stem from several sources, threads that wake up still need to test to see if they can proceed. In this case, the simplest way to accomplish this task is to recursively repeat the process of trying to obtain a connection. Close connections when required Connections are closed when they are garbage collected, you do not have to explicitly close them. But, you sometimes want more explicit control over the process.

86

Example to show how to place the ConnectionPool object as an attribute in the S ServletContext. l tC t t ServletContext context = getServletContext(); ConnectionPool cpp = (ConnectionPool)context.getAttribute(databaseConnectionPool); if(cpp == null) { cpp = new ConnectionPool (2, 5, true, database url , driver class, username, password); context.setAttribute(databaseConnectionPool, cpp); } java.sql.Connection conn = cpp.getConnection(); cpp.free(conn);

87

88

Filters who are java components can be used to intercept and process request and then pass it to servlet l t .They Th also l can modify dif the th responses before b f sending di to t the th client. li t Which Whi h filter filt will ill be b called ll d depends upon the deployment descriptor configuration ,just the way we declare it for servlet. The request parameter can be passed to the filter and the filter either encrypt it or modify it and forward it to the next filter or to servlet to generate the required response. Filters generally are not used for creating a response or respond to request as servlets do, rather they will modify or adapt request from a resource or modify or adapt response from a resource.The resources are dynamic or static contents on which filters act.

89

Examples of filtering components: a) Authentication filter b) Logging and auditing filter c) Encryption filter d) Caching filter etc.

90

91

92

93

Every filter Should implement the 3 methods present in Filter interface .These are init() , doFilter() and d destroy() d t () . The init() method is used to instantiate a filter and any set up can be made before the filter is called. doFilter() is just like the service() method of servlet where the actual filter function lies.It is called each time when the container feels that the filter is to be applied to the current request(). Whenever the container decides to remove the filter instance the destroy() method is called.

94

javax.servlet.FilterChain Th d The doFilter() Filt () method th d of f Filt FilterChain Ch i API h helps l us t to pass th the request t and d response object bj t t to another filter available in the filterchain or to a servlet if no other filter is available in the chain.This helps us to do necessary modification both in the request object and response object.One point to be noted is that the Filterchain accepts request and response objects as parameters which belong to ServletRequest and ServletResponse interface.If we need to use HttpServletRequest and HttpServletResponse object then we have to explicitely cast it within the doFilter(ServletRequest req1,ServletResponse res1,Filterchain chain1) as follows HttpServletRequest req1=(HttpServletRequest) request;

95

javax.servlet.FilterConfig We can pass the filter configuration parameter via FilterConfig object within the init method: public void init(FilterConfig config) throws ServletException{ } javax.servlet.HttpServletResponseWrapper Sometimes we dont implement all the methods present in the HttpServletResponse interface which extends from ServletResponse.This can be done by the help of wrapper classes.It can be used to create customized response object but for this the wrapper class is to be subclassed that is we have to create a subclass that extends the wrapper class to do the needful. Other wrapper classes available are ServletRequestWrapper HttpServletRequestWrapper ServletResponseWrapper

96

Here in this slide we describe how the deployment descriptor is to be configured as it is the d l deployment t descriptor d i t who h d decides id which hi h filt filter i is t to b be called ll d and di in which hi h order d as th the servlet l ti is not t aware of the filter. <filter> <filter-name>- contains name of filter <filter-class> - contains the class associated with filter <url-pattern>declares filter for particular url pattern. <filter-name> and <filter-class> is mandatory where as <init-param> is optional and can have many for a particular filter. <filter-class> identifies a particular java class which is called for a filter declared in <filter-name> and the <url-pattern> identifies which web application resource should use the filter.

97

Here is an example of DD which describes the configuration of no of filters in Bookshop application lik FilterOrder like Filt O d , C CounterFilter t Filt . A particular web application may contain multiple filters. In the below mentioned code <filter> <filter-name> FilterOrder </filter-name> <filter-class> filter1. FilterOrder</filter-class> </filter> <filter-mapping> <filter-name> FilterOrder </filter-name> <url-pattern> /receipt1</url-pattern> </filter-mapping> FilterOrder is any filter which is present in filters package and can be accessible using url pattern /receipt1

98

99

100

The Html page from which the filter is going to be called by the container may be as follows <html> <head> <title>illustrating example related to filter</title> </head> <body> <h1>Demo on filter which will display the count valuer</h1> Click<a href="/counter/servlet/display">here</a>to see the effect of the filter </body> </html>

101

102

DisplayCountDemo Servlet going to process the request object

103

104

<filter-name> indicates the name of filter </filter-name> <filter-class>specifies the class associated with the filter</filter-class> <url-pattern>Indicates to which type of file the filter should respond</url-pattern> <servlet-name>indicates the name of servlet who will accept the request from the filterchain</servletname> <servlet-class>specifies the class associated with the filter who is going to generate the output</servlet-class>

105

106

For listening ServletContext events S l tC t tLi t ServletContextListener i t f interface.

we

can

put

listener

classes

that

implements

HTTP session listeners are used to manage state or resources associated with a series of requests made into a Web application from the same client or user. Servlet request listeners are used to manage state across the lifecycle of servlet requests.There may be multiple listener classes listening to each event type, and the Developer may specify the order in which the container invokes the listener beans for each event type.

107

<web-app> <display-name>MyListeningApp</display-name> <listener> <listener-class>com.infy.MyConnManager</listener-class> </listener> <listener> <listener-class>com.infy.MyLogModule</listener-class> </listener> <servlet> <display-name>RegiseredServlet</display-name> ...etc </servlet> </web-app>

108

The use of different listener interfaces in different scenarios are given below ServletContextListener- used to know if a context has been created or destroyed ServletContextAttributeListener-used to know if an attribute in a web app is added or removed or replaced HttpSessionListener- used to track the active session,to know how many concurrent users are there HttpSessionAttributeListener-Used to know when a session attribute has been added,removed or destoryed HttpSessionActivationListener-used whenever we have an attribute class and we want objects of this type to be notified when the session to which they are bound is migrating to and from another JVM.

109

110

To listen the ServletContext event we can write a listener class that implements S l tC t tLi t ServletContextListener class l and d put t it in i the th classes l directory di t of f WEB-INF WEB INF and d th the container t i can get t the information from the Deployment Descriptor. Lets check a code snippet how this is implemented and how the descriptor is to be configured. Here the ContextListener class which implements ServletContextListener gets the context init parameter and sets the context

111

112

113

We can also set the context parameter as follows <context-param> <param-name></param-name> <param-value>.</param-value> </context-param> <listener> tag is used to register listener.One point to be noted is that it can be put within <servlet> as the context listener is for the ServletContext that is for the application wide event and the application is to be initialized before any servlet is initialized.

114

115

116

117

You might also like