Java Servlet
What Is a Servlet?
A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed via a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by Web servers. For such applications, Java Servlet technology defines HTTP-specific servlet classes.
What is life cycle of a servlet?
Three methods are central to the life cycle of a servlet. These are init(), service(), and destroy(). The init() and destroy() methods are called only once in the lifecycle of a servlet.
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.
Servlet
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.
Servlet
Note: Most Servlets, however, extend one of the standard implementations of that interface, namely javax.servlet.GenericServlet and javax.servlet.http.HttpServlet.
What is the difference between doGet() and doPost()?
#
| doGet() | doPost() |
---|---|---|
1
| In doGet() the parameters are appended to the URL and sent along with header information. | In doPost(), on the other hand will (typically) send the information through a socket back to the webserver and it won’t show up in the URL bar. |
2
| The amount of information you can send back using a GET is restricted as URLs can only be 1024 characters. | 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! |
3
| doGet() is a request for information; it does not (or should not) change anything on the server. (doGet() should be idempotent) | doPost() provides information (such as placing an order for merchandise) that the server is expected to remember |
4
| Parameters are not encrypted | Parameters are encrypted |
5
| doGet() is faster if we set the response content length since the same connection is used. Thus increasing the performance | 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 |
6
| doGet() should be idempotent. i.e. doget should be able to be repeated safely many times | This method does not need to be idempotent. Operations requested through POST can have side effects for which the user can be held accountable. |
7
| doGet() should be safe without any side effects for which user is held responsible | This method does not need to be either safe |
8
| It allows bookmarks. | It disallows bookmarks. |
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.
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.
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:
The easy way is, just support POST, then have your doGet method call your doPost method:
1
2
3
4
5
6
| public void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { this .doGet(servletRequest,servletResponse); } //end of doPost() method |
What is the load-on-startup element?
The element of a deployment descriptor is used to load a servlet file when the server starts instead of waiting for the first request. It is also used to specify the order in which the files are to be loaded. The element is written in the deployment descriptor as follows:
The element of a deployment descriptor is used to load a servlet file when the server starts instead of waiting for the first request. It is also used to specify the order in which the files are to be loaded. The element is written in the deployment descriptor as follows:
1
2
3
| ServletName ClassName 1 |
Note: The container loads the servlets in the order specified in the element.
How can an existing session be invalidated?
An existing session can be invalidated in the following two ways:
1. Setting timeout in the deployment descriptor: This can be done by specifying timeout between the tags as follows:
An existing session can be invalidated in the following two ways:
1. Setting timeout in the deployment descriptor: This can be done by specifying timeout between the tags as follows:
1
|
This will set the time for session timeout to be 10 minutes.
2. Setting timeout programmatically: This will set the timeout for a specific session. The syntax for setting the timeout programmatically is as follows:
2. Setting timeout programmatically: This will set the timeout for a specific session. The syntax for setting the timeout programmatically is as follows:
1
| public void setMaxInactiveInterval( int interval) |
The setMaxInactiveInterval() method sets the maximum time in seconds before a session becomes invalid.Setting the inactive period as negative(-1), makes the container stop tracking session, i.e, session never expires.
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:
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.
What is difference between Servlets and JSP?
The difference between Servlets and JSP is that Servlets typically Java code embed HTML inside that, while JSPs are HTML embed Java code in it.
The difference between Servlets and JSP is that Servlets typically Java code embed HTML inside that, while JSPs are HTML embed Java code in it.
What mechanisms are used by a Servlet Container to maintain session information?Cookies, URL rewriting, and HTTPS protocol information are used to maintain session information.
What is session?
The session is an object used by a servlet to track a user’s interaction with a Web application across multiple HTTP requests.
The session is an object used by a servlet to track a user’s interaction with a Web application across multiple HTTP requests.
Should I override the service() method?
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 are the types of Session Tracking ?
Sessions need to work with all web browsers and take into account the users security preferences. Therefore there are a variety of ways to send and receive the identifier:
- URL rewriting : URL rewriting is a method of session tracking in which some extra data (session ID) 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. This method is used with browsers that do not support cookies or where the user has disabled the cookies.
- Hidden Form Fields : Similar to URL rewriting. The server embeds new hidden fields in every dynamically generated form page for the client. When the client submits the form to the server the hidden fields identify the client.
- Cookies : Cookie is a small amount of information sent by a servlet to a Web browser. Saved by the browser, and later sent back to the server in subsequent requests. A cookie has a name, a single value, and optional attributes. A cookie’s value can uniquely identify a client.
- 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.
In web.xml file, <load-on-startup>1</load-on-startup> is defined between<servlet></servlet> tag. what does it means?
Ans: whenever we request for any servlet the servlet container will initialize the servlet and load it which is defined in our config file called web.xml by default it will not initialize when our context is loaded .defining like this 1is also known as pre initialization of servlet means now the servlet for which we have define this tag has been initialized in starting when context is loaded before getting any request.When this servlet question was asked to me in an interview few years back , I was not even aware of this element but this questions pointed me to look DTD of web.xml and understand other elements as well..
Ans: whenever we request for any servlet the servlet container will initialize the servlet and load it which is defined in our config file called web.xml by default it will not initialize when our context is loaded .defining like this 1is also known as pre initialization of servlet means now the servlet for which we have define this tag has been initialized in starting when context is loaded before getting any request.When this servlet question was asked to me in an interview few years back , I was not even aware of this element but this questions pointed me to look DTD of web.xml and understand other elements as well..
what is servlet collaboration?
Ans: communication between two servlet is called servlet collaboration which is achieved by 3 ways.
1. RequestDispatchers include () and forward() method.
2. Using sendRedirect()method of Response object.
3. Using servlet Context methods
Ans: communication between two servlet is called servlet collaboration which is achieved by 3 ways.
1. RequestDispatchers include () and forward() method.
2. Using sendRedirect()method of Response object.
3. Using servlet Context methods
How many instances will be created for a servlet in servlet container?
Ans: Only one instance will be created for every servlet. Generally servlet instantiation is done by the container. But based on the number of requests coming to the servlet that many no.of threads are created. Each thread will serve one request.
Ans: Only one instance will be created for every servlet. Generally servlet instantiation is done by the container. But based on the number of requests coming to the servlet that many no.of threads are created. Each thread will serve one request.
Servlet Filters:
The Servlet filters are basically used for intercepting and modifying requests and response from server. Consider a scenario where you want to check session from the every users request and if it is valid then only you want to let the user access the page. You can achieve this by checking sessions on all the servlet pages (or JSP pages) which users queries or you can do this by using Filter.
Filters have a wide array of uses; the Servlet 2.3 specification suggests the following uses:
authentication filters
logging and auditing filters
image conversion filters
data compression filters
encryption filters
tokenizing filters
filters that trigger resource access events
XSL/T filters that transform XML content
MIME-type chain filters
authentication filters
logging and auditing filters
image conversion filters
data compression filters
encryption filters
tokenizing filters
filters that trigger resource access events
XSL/T filters that transform XML content
MIME-type chain filters
A filter implements the interface javax.servlet.Filter, and configured in the web application web.xml file. For each request, the servlet container decides which filters to apply, and adds those filters to a chain in the same order they appear in web.xml. Each filter has its Filter.doFilter() method called, and triggers the invocation of the next filter in the chain or the loading of the final resource (HTML page, servlet, or whatever).
Writing a simple filter
To write a filter, we create a class implementing the Filter interface, which requires three methods: init(), doFilter(), and destroy(). init() and destroy() are called when the filter is first initialized and when it is destroyed, respectively, to allow configuration and cleanup. For the moment we’ll ignore these and focus on doFilter(), which is important.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
| import java.io.IOException; import java.util.Date; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; public class SimpleFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; //Get the IP address of client machine. String ipAddress = request.getRemoteAddr(); //Log the IP address and current timestamp. System.out.println( "IP " +ipAddress + ", Time " + new Date().toString()); chain.doFilter(req, res); } public void init(FilterConfig config) throws ServletException { //add code to initialize any thing which is used by Filter. } public void destroy() { //add code to release any resource } } |
In this filter example, we have implemented an interface javax.servlet.Filter and override its methods init, doFilter and destroy.
The init() method is used to initialize any code that is used by Filter. Also note that, init() method will get an object of FilterConfig which contains different Filter level information as well as init parameters which is passed from Web.xml (Deployment descriptor).
The doFilter() method will do the actual logging of information. You can modify this method and add your code which can modify request/session/response, add any attribute in request etc.
The destroy() method is called by the container when it wants to garbage collect the filter. This is usually done when filter is not used for long time and server wants to allocate memory for other applications.
Create Servlet Filter Mapping in Web.xml
Open web.xml file from WEB-INF directory of your Project and add following entry for filter tag.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| < filter > < filter-name >SimpleFilter </ filter-name > < filter-class > net.viralpatel.servlet.filters.SimpleFilter </ filter-class > < init-param > < param-name >test-param</ param-name > < param-value >This parameter is for testing.</ param-value > </ init-param > </ filter > < filter-mapping > < filter-name >SimpleFilter</ filter-name > < url-pattern >/*</ url-pattern > </ filter-mapping > |
In this entry, we have added SimpleFilter class in Web xml and mapped it with URL /*. Hence any request from client will generated a call to this filter. Also we have passed a parameter test-param. This is just to show how to pass and retrieve a parameter in servlet filter.
No comments:
Post a Comment