Servlets Notes
Servlets Notes
WEB TECHNOLOIGIES
Servlets provide a component-based, platform-independent method for building Web-based applications, without the performance limitations of CGI programs.
Using Servlets, you can collect input from users through web page forms, present records from a database or another source, and create web pages dynamically
WEB TECHNOLOIGIES
utilities. Powerful. Java servlets let you easily do several things that are difficult or impossible with the regular CGI. For one thing, servlets can talk directly to Web server (regular CGI programs can't). This simplifies operations that need to look up images and other data stored in the standard places. Servlets can also share data among each other, making the useful things like database connection pools easy to implement. They can also maintain information from request to request, simplifying things like session tracking and caching of previous computation. Portable. Servlets are written in Java and followsss a well-standardized API. Consequently, servlets written for, say I-Planet Enterprise Server can alsp run virtually unchanged on Apache, Microsoft IIS, or WebStar. Servlets are supported directly or via a plugin on the almost every major Web server. Inexpensive. There are also a number of free or very inexpensive Web servers available that are good for "personal" use or low-volume Web sites. However, with major exception of Apache, which is free, most commercial-quality Web servers are relatively expensive. Nevertheless, once you have a Web server, no matter the cost of that server, adding servlets support to it (if it doesn't come preconfigured to support servlets) is generally free or cheap.
WEB TECHNOLOIGIES
WEB TECHNOLOIGIES
The service () method is called by the container and service method invokes doGe, doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service() method but you override either doGet() or doPost() depending on what type of request you receive from the client. The doGet() and doPost() are most frequently used methods with in each service request. Here are the signature of these two methods.
Architecture Digram:
The following figure depicts a typical servlet life-cycle scenario. First the HTTP requests coming to the server are delegated to the servlet container. M.Gangappa, Assoc Professor, CSE,VNRVJIET 4
WEB TECHNOLOIGIES
The servlet container loads the servlet before invoking the service() method. Then the servlet container handles multiple requests by spawning multiple threads, each thread executing the service() method of a single instance of the servlet.
Servlets - Examples
Servlets are Java classes which service HTTP requests and implement the javax.servlet.Servlet interface. Web application developers typically write servlets that extend javax.servlet.http.HttpServlet, an abstract class that implements the Servlet interface and is specially designed to handle HTTP requests.
WEB TECHNOLOIGIES
Compiling a Servlet:
Let us put above code if HelloWorld.java file and put this file in C:\ServletDevel (Windows) or /usr/ServletDevel (Unix) then you would need to add these directories as well in CLASSPATH. Assuming your environment is setup properly, go in ServletDevel directory and compile HelloWorld.java as follows:
$ javac HelloWorld.java
If the servlet depends on any other libraries, you have to include those JAR files on your CLASSPATH as well. I have included only servlet-api.jar JAR file because I'm not using any other library in Hello World program. This command line uses the built-in javac compiler that comes with the Sun Microsystems Java Software Development Kit (JDK). For this command to work properly, you have to include the location of the Java SDK that you are using in the PATH environment variable.
WEB TECHNOLOIGIES
If everything goes fine, above compilation would produce HelloWorld.class file in the same directory. Next section would explain how a compiled servlet would be deployed in production.
Servlet Deployment:
By default, a servlet application is located at the path <Tomcat-installationdirectory>/webapps/ROOT and the class file would reside in <Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes. If you have a fully qualified class name of com.myorg.MyServlet, then this servlet class must be located in WEB-INF/classes/com/myorg/MyServlet.class. For now, let us copy HelloWorld.class into <Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes and create following entries in web.xml file located in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/
<servlet> <servlet-name>HelloWorld</servlet-name> <servlet-class>HelloWorld</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloWorld</servlet-name> <url-pattern>/HelloWorld</url-pattern> </servlet-mapping>
Above entries to be created inside <web-app>...</web-app> tags available in web.xml file. There could be various entries in this table already available, but never mind. You are almost done, now let us start tomcat server using <Tomcat-installationdirectory>\bin\startup.bat (on windows) or <Tomcat-installation-directory>/bin/startup.sh (on Linux/Solaris etc.) and finally type http://localhost:8080/HelloWorld in browser's address box. If everything goes fine, you would get following result:
WEB TECHNOLOIGIES
WEB TECHNOLOIGIES
Integration Servlets are tightly integrated with the server. Servlet can use the server to translate the file paths, perform logging, check authorization, and MIME type mapping etc. Extensibility The servlet API is designed in such a way that it can be easily extensible. As it stands today, the servlet API support Http Servlets, but in later date it can be extended for another type of servlets. Inexpensive There are number of free web servers available for personal use or for commercial purpose. Web servers are relatively expensive. So by using the free available web servers you can add servlet support to it.
Read notes
4.What are the phases of the servlet life cycle?
Read notes
.What is Servlet interface? The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or , more commonly by extending a class that implements it.
WEB TECHNOLOIGIES
Note: Most Servlets, however, extend one of the standard implementations of that interface, namely javax.servlet.GenericServlet and javax.servlet.http.HttpServlet. 5.What is the GenericServlet class? GenericServlet is an abstract class that implements the Servlet interface and the ServletConfig interface. In addition to the methods declared in these two interfaces, this class also provides simple versions of the lifecycle methods init and destroy, and implements the log method declared in the ServletContext interface. Note: This class is known as generic servlet, since it is not specific to any protocol. ***6.What's the difference between GenericServlet and HttpServlet? GenericServlet HttpServlet An abstract class that simplifies writing HTTP The GenericServlet is an abstract class that is servlets. It extends the GenericServlet base extended by HttpServlet to provide HTTP class and provides an framework for handling protocol-specific methods. the HTTP protocol. The GenericServlet does not include protocol-specific methods for handling request parameters, cookies, sessions and setting response headers. GenericServlet is not specific to any protocol. The HttpServlet subclass passes generic service method requests to the relevant doGet() or doPost() method. HttpServlet only supports HTTP and HTTPS protocol.
7.Why is HttpServlet declared abstract? The HttpServlet class is declared abstract because the default implementations of the main service methods do nothing and must be overridden. This is a convenience implementation of the Servlet interface, which means that developers do not need to implement all service methods. If your servlet is required to handle doGet() requests for example, there is no need to write a doPost() method too.
10
Servlets Notes Sample Q & A on Servlets *** 8.What is the difference between doGet() and doPost()?
# doGet() doPost()
WEB TECHNOLOIGIES
In doPost(), on the other hand will (typically) In doGet() the parameters are appended to send the information through a socket back 1 the URL and sent along with header to the webserver and it won't show up in the information. URL bar. The amount of information you can send 2 back using a GET is restricted as URLs can only be 1024 characters. doGet() is a request for information; it does not (or should not) change anything 3 on the server. (doGet() should be idempotent) 4 Parameters are not encrypted doGet() is faster if we set the response 5 content length since the same connection is used. Thus increasing the performance doGet() should be idempotent. i.e. doget 6 should be able to be repeated safely many times 7 doGet() should be safe without any side effects for which user is held responsible You can send much more information to the server this way - and it's not restricted to textual data either. It is possible to send files and even binary data such as serialized Java objects! doPost() provides information (such as placing an order for merchandise) that the server is expected to remember Parameters are encrypted doPost() is generally used to update or post some information to the server.doPost is slower compared to doGet since doPost does not write the content length This method does not need to be idempotent. Operations requested through POST can have side effects for which the user can be held accountable. This method does not need to be either safe It disallows bookmarks.
8 It allows bookmarks.
9.When to use doGet() and when doPost()? Always prefer to use GET (As because GET is faster than POST), except mentioned in the following reason: If data is sensitive Data is greater than 1024 characters If your application don't need bookmarks.
*10. .How do I support both GET and POST from the same Servlet?
The easy way is, just support POST, then have your doGet method call your doPost method: public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); }
11
Servlets Notes Sample Q & A on Servlets 11. Should I override the service() method?
WEB TECHNOLOIGIES
We never override the service method, since the HTTP Servlets have already taken care of it. The default service function invokes the doXXX() method corresponding to the method of the HTTP request.For example, if the HTTP request method is GET, doGet() method is called by default. A servlet should override the doXXX() method for the HTTP methods that servlet supports. Because HTTP service method check the request method and calls the appropriate handler method, it is not necessary to override the service method itself. Only override the appropriate doXXX() method. What is a servlet context object? A servlet context object contains the information about the Web application of which the servlet is a part. It also provides access to the resources common to all the servlets in the application. Each Web application in a container has a single servlet context associated with it. 12.What are the differences between the ServletConfig interface and the ServletContext interface? ServletConfig The ServletConfig interface is implemented by the servlet container in order to pass configuration information to a servlet. The server passes an object that implements the ServletConfig interface to the servlet's init() method. There is one ServletConfig parameter per servlet. The param-value pairs for ServletConfig object are specified in the <init-param> within the <servlet> tags in the web.xml file ServletContext A ServletContext defines a set of methods that a servlet uses to communicate with its servlet container. There is one ServletContext for the entire webapp and all the servlets in a webapp share it. The param-value pairs for ServletContext object are specified in the <context-param> tags in the web.xml file.
13.What's the difference between forward() and sendRedirect() methods? forward() A forward is performed internally by the servlet. The browser is completely unaware that it has taken place, so its original URL remains intact. Any browser reload of the resulting page will simple repeat the original request, with the original URL sendRedirect() A redirect is a two step process, where the web application instructs the browser to fetch a second URL, which differs from the original. The browser, in this case, is doing the work and knows that it's making a new request. A browser reloads of the second URL ,will not repeat the original request, but will rather fetch the second URL.
Both resources must be part of the same This method can be used to redirect users to context (Some containers make provisions for resources that are not part of the current cross-context communication but this tends context, or even in the same domain. not to be very portable) Since both resources are part of same Because this involves a new request, the
12
WEB TECHNOLOIGIES
previous request scope objects, with all of its parameters and attributes are no longer available after a redirect. (Variables will need to be passed by via the session object). redirect is marginally slower than a forward, since it requires two browser requests, not one.
13
WEB TECHNOLOIGIES
*15. What is session? A session refers to all the requests that a single client might make to a server in the course of viewing any pages associated with a given application. Sessions are specific to both the individual user and the application. As a result, every user of an application has a separate session and has access to a separate set of session variables.
16. What is Session Tracking? Session tracking is a mechanism that servlets use to maintain state about a series of requests from the same user (that is, requests originating from the same browser) across some period of time. For more information read the class notes and Java2 complete reference 17. What is the need of Session Tracking in web application? HTTP is a stateless protocol i.e., every request is treated as new request. For web applications to be more realistic they have to retain information across multiple requests. Such information which is part of the application is reffered as "state". To keep track of this state we need session tracking. Typical example: Putting things one at a time into a shopping cart, then checking out--each page request must somehow be associated with previous requests.
14
WEB TECHNOLOIGIES
Secure Socket Layer (SSL) Sessions : Web browsers that support Secure Socket Layer communication can use SSL's support via HTTPS for generating a unique session key as part of the encrypted conversation. 19. How do I use cookies to store session state on the client? In a servlet, the HttpServletResponse and HttpServletRequest objects passed to method HttpServlet.service() can be used to create cookies on the client and use cookie information transmitted during client requests. JSPs can also use cookies, in scriptlet code or, preferably, from within custom tag code. To set a cookie on the client, use the addCookie() method in class HttpServletResponse. Multiple cookies may be set for the same request, and a single cookie name may have multiple values. To get all of the cookies associated with a single HTTP request, use the getCookies() method of class HttpServletRequest
20. What are some advantages of storing session state in cookies? Cookies are usually persistent, so for low-security sites, user data that needs to be stored long-term (such as a user ID, historical information, etc.) can be maintained easily with no server interaction. For small- and medium-sized session data, the entire session data (instead of just the session ID) can be kept in the cookie.
22. What is URL rewriting? URL rewriting is a method of session tracking in which some extra data is appended at the end of each URL. This extra data identifies the session. The server can associate this session identifier with the data it has stored about that session. Every URL on the page must be encoded using method HttpServletResponse.encodeURL(). Each time a URL is output, the servlet passes the URL to encodeURL(), which encodes session ID
15
WEB TECHNOLOIGIES
in the URL if the browser isn't accepting cookies, or if the session tracking is turned off. E.g., http://abc/path/index.jsp;jsessionid=123465hfhs Advantages URL rewriting works just about everywhere, especially when cookies are turned off. Multiple simultaneous sessions are possible for a single user. Session information is local to each browser instance, since it's stored in URLs in each page being displayed. This scheme isn't foolproof, though, since users can start a new browser instance using a URL for an active session, and confuse the server by interacting with the same session through two instances. Entirely static pages cannot be used with URL rewriting, since every link must be dynamically written with the session state. It is possible to combine static and dynamic content, using (for example) templating or server-side includes. This limitation is also a barrier to integrating legacy web pages with newer, servlet-based pages.
DisAdvantages Every URL on a page which needs the session information must be rewritten each time a page is served. Not only is this expensive computationally, but it can greatly increase communication overhead. URL rewriting limits the client's interaction with the server to HTTP GETs, which can result in awkward restrictions on the page. URL rewriting does not work well with JSP technology. If a client workstation crashes, all of the URLs (and therefore all of the data for that session) are lost.
23.How can an existing session be invalidated? An existing session can be invalidated in the following two ways: Setting timeout in the deployment descriptor: This can be done by specifying timeout between the <session-timeout>tags as follows:
<session-config> <session-timeout>10</session-timeout> </session-config>
This will set the time for session timeout to be ten minutes. Setting timeout programmatically: This will set the timeout for a specific session. The syntax for setting the timeout programmatically is as follows:
public void setMaxInactiveInterval(int interval)
The setMaxInactiveInterval() method sets the maximum time in seconds before a session becomes invalid. Note :Setting the inactive period as negative(-1), makes the container stop tracking
16
WEB TECHNOLOIGIES
24. A client sends requests to two different web components. Both of the components access the session. Will they end up using the same session object or different session ? Creates only one session i.e., they end up with using same session . Sessions is specific to the client but not the web components. And there is a 1-1 mapping between client and a session. 25. What is servlet lazy loading? A container doesnot initialize the servlets ass soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading. The servlet specification defines the <load-on-startup> element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.
26.What is Servlet Chaining? Servlet Chaining is a method where the output of one servlet is piped into a second servlet. The output of the second servlet could be piped into a third servlet, and so on. The last servlet in the chain returns the output to the Web browser. 27. How are filters? Filters are Java components that are used to intercept an incoming request to a Web resource and a response sent back from the resource. It is used to abstract any useful information contained in the request or response. Some of the important functions performed by filters are as follows: Security checks Modifying the request or response Data compression Logging and auditing Response compression Filters are configured in the deployment descriptor of a Web application. Hence, a user is not required to recompile anything to change the input or output of the Web application. 28. What are the functions of an intercepting filter? The functions of an intercepting filter are as follows: It intercepts the request from a client before it reaches the servlet and modifies the request if required. It intercepts the response from the servlet back to the client and modifies the request if required. There can be many filters forming a chain, in which case the output of one filter becomes an input to the next filter. Hence, various modifications can be performed on a single request and response.
17
WEB TECHNOLOIGIES
29. What are the functions of the Servlet container? The functions of the Servlet container are as follows: Lifecycle management : It manages the life and death of a servlet, such as class loading, instantiation, initialization, service, and making servlet instances eligible for garbage collection. Communication support : It handles the communication between the servlet and the Web server. Multithreading support : It automatically creates a new thread for every servlet request received. When the Servlet service() method completes, the thread dies. Declarative security : It manages the security inside the XML deployment descriptor file. JSP support : The container is responsible for converting JSPs to servlets and for maintaining them.
18