<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>JavaBeat &#187; Servlets</title>
	<atom:link href="http://www.javabeat.net/category/java-j2ee/servlets/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.javabeat.net</link>
	<description>Java Technology News</description>
	<lastBuildDate>Wed, 22 May 2013 01:42:58 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>What is load on startup element in web.xml file</title>
		<link>http://www.javabeat.net/2013/02/what-is-load-on-startup-element-in-web-xml-file/</link>
		<comments>http://www.javabeat.net/2013/02/what-is-load-on-startup-element-in-web-xml-file/#comments</comments>
		<pubDate>Thu, 21 Feb 2013 04:33:47 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[JSP]]></category>
		<category><![CDATA[Servlets]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=5941</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>specify the order in which we want to initialize various Servlets. Like first initialize Servlet1 then Servlet2 and so on. This is accomplished by specifying a numeric value for the  &#60;load-on-startup&#62; tag. &#60;load-on-startup&#62; tag specifies that the servlet should be loaded automatically when the web application is started. The value is a single positive integer, [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><a id="dd_start"></a><p>specify the order in which we want to initialize various Servlets. Like first initialize Servlet1 then Servlet2 and so on.<br />
This is accomplished by specifying a numeric value for the  &lt;load-on-startup&gt; tag. &lt;load-on-startup&gt; tag specifies that the servlet should be loaded<br />
automatically when the web application is started.</p>
<p>The value is a single positive integer, which specifies the loading order. Servlets with lower values are loaded before servlets with<br />
higher values (ie: a servlet with a load-on-startup value of 1 or 5 is loaded before a servlet with a value of 10 or 20). When loaded, the init() method of the servlet is called. Therefore this tag provides a good way to do the following:</p>
<p>start any daemon threads, such as a server listening on a TCP/IP port, or a background maintenance thread perform initialisation of the application, such as parsing a settings file which provides data to other servlets/JSPs If no &lt;load-on-startup&gt; value is specified, the servlet will be loaded when the container decides it needs to be loaded &#8211; typically on it&#8217;s first access. This is suitable for servlets that don&#8217;t need to perform special initialisation.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>I hope that clears all the doubts regarding &lt;load-on-startup&gt; in web.xml.</p>
<div class='dd_outer'><div class='dd_inner'><div id='dd_ajax_float'><div class='dd_button_v'><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="http%3A%2F%2Fwww.javabeat.net%2Fcategory%2Fjava-j2ee%2Fservlets%2Ffeed%2F" send="false" show_faces="false"  layout="box_count" width="50"  ></fb:like></div><div style='clear:left'></div><div class='dd_button_v'><script type='text/javascript' src='https://apis.google.com/js/plusone.js'></script><g:plusone size='tall' href='http://www.javabeat.net/category/java-j2ee/servlets/feed/'></g:plusone></div><div style='clear:left'></div><div class='dd_button_v'><a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.javabeat.net/category/java-j2ee/servlets/feed/" data-count="vertical" data-text="Servlets" data-via="javabeat" ></a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div style='clear:left'></div><div class='dd_button_extra_v'><script type="text/javascript">jQuery(document).load(function(){ stLight.options({publisher:'bab47279-62c9-46af-addc-79fd1fe8fee0'}); });</script><div class="st_email_custom"><span id='dd_email_text'>email</span></div></div><div style='clear:left'></div><div class='dd_button_extra_v'><div id='dd_print_button'><span id='dd_print_text'><a href='javascript:window:print()'>print</a></span></div></div><div style='clear:left'></div></div></div></div><script type="text/javascript">var dd_offset_from_content = 44; var dd_top_offset_from_content = 0;</script><script type="text/javascript" src="http://www.javabeat.net/wp-content/plugins/digg-digg//js/diggdigg-floating-bar.js?ver=5.3.0"></script><div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2013/02/what-is-load-on-startup-element-in-web-xml-file/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ServletContextListener Example</title>
		<link>http://www.javabeat.net/2009/02/servletcontextlistener-example/</link>
		<comments>http://www.javabeat.net/2009/02/servletcontextlistener-example/#comments</comments>
		<pubDate>Thu, 26 Feb 2009 04:50:15 +0000</pubDate>
		<dc:creator>JavaBeat</dc:creator>
				<category><![CDATA[Servlets]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=521</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>This tips explains the how to use ServletContextListener. There will be only one ServletContext for each web application. ServletContext will be created while deploying the application. Once the ServletContext is created, it will be used by all the servlets and jsp files in the same application. ServletContext is also called as the application scope variables [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>This tips explains the how to use <b>ServletContextListener</b>. There will be only one ServletContext for each web application. ServletContext will be created while deploying the application. Once the ServletContext is created, it will be used by all the servlets and jsp files in the same application. <b>ServletContext</b> is also called as the application scope variables in the web application scenario.</p>
<p><b>ServletContextListener</b> has the following two methods:</p>
<ul>
<li>
<li>public void contextInitialized(ServletContextEvent event)</i></li>
<li>
<li>public void contextDestroyed(ServletContextEvent event)</i></li>
</ul>
<p>Look into the following example for how to implement the ServletContextListener methods:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p><b>ServletContextExample.java</b></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">package example;
&nbsp;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
&nbsp;
public class ServletContextExample implements ServletContextListener{
	ServletContext context;
	public void contextInitialized(ServletContextEvent contextEvent) {
		System.out.println(&quot;Context Created&quot;);
		context = contextEvent.getServletContext();
		// set variable to servlet context
		context.setAttribute(&quot;TEST&quot;, &quot;TEST_VALUE&quot;);
	}
	public void contextDestroyed(ServletContextEvent contextEvent) {
		context = contextEvent.getServletContext();
		System.out.println(&quot;Context Destroyed&quot;);
	}
}</pre></td></tr></table></div>

<p><b>web.xml</b></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;web-app version=&quot;2.5&quot;
	xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot;
	xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/javaee
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot;&gt;
  &lt;listener&gt;
  	&lt;listener-class&gt;
  		example.ServletContextExample
  	&lt;/listener-class&gt;
  &lt;/listener&gt;
&lt;/web-app&gt;</pre></td></tr></table></div>

<p>In the above example <i>ServletContextExample</i> implements <i>ServletContextListener</i>. It has two methods <i>contextInitialized</i> which is called when the ServletContext is created. Another one is  <i>contextDestroyed</i> which is called while context is destroyed, this happens normally when web server is shut down or crash.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2009/02/servletcontextlistener-example/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>load-on-startup element in web.xml</title>
		<link>http://www.javabeat.net/2009/02/load-on-startup-element-in-web-xml/</link>
		<comments>http://www.javabeat.net/2009/02/load-on-startup-element-in-web-xml/#comments</comments>
		<pubDate>Tue, 17 Feb 2009 04:47:07 +0000</pubDate>
		<dc:creator>JavaBeat</dc:creator>
				<category><![CDATA[Servlets]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=511</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>This tips explains the few points on how to use the load-on-startup element on the web.xml file. When erver is starting, it is possible to tell the container to load a servlet on the startup. You can load any number of servlets on the startup. Normally this is done for any initialization purpose. Look into [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>
This tips explains the few points on how to use the load-on-startup element on the web.xml file. When erver is starting, it is possible to tell the container to load a servlet on the startup. You can load any number of servlets on the startup. Normally this is done for any initialization purpose. Look into the following example:
</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;servlet&gt;
&lt;servlet-name&gt;TestServlet&lt;/servlet-name&gt;
 &lt;servlet-class&gt;TestServlet&lt;/servlet-class&gt;
 &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
&lt;/servlet&gt;</pre></td></tr></table></div>

<p>
The above example tells the container that the servlet will be loaded at first.The &lt;load-on-startup&gt; sub-element indicates the order in which each servlet should be loaded. Lower positive values are loaded first. If the value is negative or unspecified, then the container can load the servlet at anytime during startup.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2009/02/load-on-startup-element-in-web-xml/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Servlets Interview Questions</title>
		<link>http://www.javabeat.net/2009/02/servlets-interview-questions/</link>
		<comments>http://www.javabeat.net/2009/02/servlets-interview-questions/#comments</comments>
		<pubDate>Fri, 13 Feb 2009 15:43:33 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Interview Questions]]></category>
		<category><![CDATA[Servlets]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=408</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>1) Is it the &#8220;servlets&#8221; directory or the &#8220;servlet&#8221; directory? For Java Web Server: on the file system, it&#8217;s &#8220;servlets&#8221; c:\JavaWebServer1.1\servlets\DateServlet.class in a URL path, it&#8217;s &#8220;servlet&#8221; http://www.stinky.com/servlet/DateServlet 2) How do I support both GET and POST protocol from the same Servlet? The easy way is, just support POST, then have your doGet method call [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>1) Is it the &#8220;servlets&#8221; directory or the &#8220;servlet&#8221; directory?</h2>
<p>For Java Web Server:</p>
<ul>
<ul>
<li>on the file system, it&#8217;s &#8220;servlets&#8221;</li>
</ul>
</ul>
<p>c:\JavaWebServer1.1\servlets\DateServlet.class</p>
<ul>
<ul>
<li>in a URL path, it&#8217;s &#8220;servlet&#8221;</li>
</ul>
</ul>
<p>http://www.stinky.com/servlet/DateServlet</p>
<h2>2) How do I support both GET and POST protocol from the same Servlet?</h2>
<p>The easy way is, just support POST, then have your doGet method call your doPost method:</p>
<pre><code> public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doPost(req, res); } </code></pre>
<h2>3) How do I ensure that my servlet is thread-safe?</h2>
<p>This is actually a very complex issue. A few guidelines:</p>
<ol>
<ol>
<li>The init() method is guaranteed to be called once per servlet instance, when the servlet is loaded. You don&#8217;t have to worry about thread safety inside this method, since it is only called by a single thread, and the web server will wait until that thread exits before sending any more threads into your service() method.</li>
<li>Every new client request generates (or allocates) a new thread; that thread calls the service() method of your servlet (which may in turn call doPost(), doGet() and so forth).</li>
<li>Under most circumstances, there is only one instance of your servlet, no matter how many client requests are in process. That means that at any given moment, there may be many threads running inside the service() method of your solo instance, all sharing the same instance data and potentially stepping on each other&#8217;s toes. This means that you should be careful to <strong>synchronize</strong> access to shared data (instance variables) using the synchronized keyword.</li>
</ol>
</ol>
<p>(Note that the server will also allocate a new instance if you register the servlet with a new name and, e.g., new init parameters.)</p>
<ol>
<ol>
<li>Note that you need not (and should not) synchronize on local data or parameters. And especially you shouldn&#8217;t synchronize the service() method! (Or doPost(), doGet() et al.)</li>
<li>A simple solution to synchronizing is to always synchronize on the servlet instance itself using &amp;quot;synchronized (this) { &#8230; }&amp;quot;. However, this can lead to performance bottlenecks; you&#8217;re usually better off synchronizing on the data objects themselves.</li>
<li>If you absolutely can&#8217;t deal with synchronizing, you can declare that your servlet &amp;quot;implements SingleThreadModel&amp;quot;. This empty interface tells the web server to only send one client request at a time into your servlet. From the JavaDoc: <em>&amp;quot;If the target servlet is flagged with this interface, the servlet programmer is guaranteed that no two threads will execute concurrently the service method of that servlet. This guarantee is ensured by maintaining a pool of servlet instances for each such servlet, and dispatching each service call to a free servlet. In essence, if the servlet implements this interface, the servlet will be thread safe.&amp;quot;</em> Note that this is not an ideal solution, since performance may suffer (depending on the size of the instance pool), plus it&#8217;s more difficult to share data across instances than within a single instance.</li>
</ol>
</ol>
<p>See also <a>What&#8217;s a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?</a></p>
<ol>
<li>To share data across successive or concurrent requests, you can use either instance variables or class-static variables, or use <a>Session Tracking</a>.</li>
<li>The destroy() method is not necessarily as clean as the init() method. The server calls destroy <strong>either</strong> after all service calls have been completed, <strong>or</strong> after a certain number of seconds have passed, whichever comes first. This means that other threads might be running service requests at the same time as your destroy() method is called! So be sure to synchronize, and/or wait for the other requests to quit. Sun&#8217;s Servlet Tutorial has an example of how to do this with reference counting.</li>
<li>destroy() can not throw an exception, so if something bad happens, call log() with a helpful message (like the exception). See the &amp;quot;closing a JDBC connection&amp;quot; example in Sun&#8217;s Tutorial.</li>
</ol>
<h2>4) What is the difference between URL encoding, URL rewriting, HTML escaping, and entity encoding?</h2>
<p><strong>URL Encoding</strong> is a process of transforming user input to a CGI form so it is fit for travel across the network &#8212; basically, stripping spaces and punctuation and replacing with escape characters. URL Decoding is the reverse process. To perform these operations, call java.net.URLEncoder.encode() and java.net.URLDecoder.decode() (the latter was (finally!) added to JDK 1.2, aka Java 2).</p>
<p><strong>Example:</strong> changing &#8220;We&#8217;re #1!&#8221; into &#8220;We%27re+%231%21&#8243;</p>
<p><strong>URL Rewriting</strong> is a technique for saving state information on the user&#8217;s browser between page hits. It&#8217;s sort of like cookies, only the information gets stored inside the URL, as an additional parameter. The HttpSession API, which is part of the Servlet API, sometimes uses URL Rewriting when cookies are unavailable.</p>
<p><strong>Example:</strong> changing &lt;A HREF=&#8221;nextpage.html&#8221;&gt; into</p>
<p>&lt;A HREF=&#8221;nextpage.html;$sessionid$=DSJFSDKFSLDFEEKOE&#8221;&gt; (or whatever the actual syntax is; I forget offhand)<br />
(Unfortunately, the method in the Servlet API for doing URL rewriting for session management is called encodeURL(). Sigh&#8230;)</p>
<p>There&#8217;s also a feature of the Apache web server called URL Rewriting; it is enabled by the mod_rewrite module. It rewrites URLs on their way <strong>in</strong> to the server, allowing you to do things like automatically add a trailing slash to a directory name, or to map old file names to new file names. This has nothing to do with servlets. For more information, see the Apache FAQ (<a>http://www.apache.org/docs/misc/FAQ.html#rewrite-more-config</a>) .</p>
<h2>5) How do I upload a file to my servlet or JSP?</h2>
<p>On the client side, the client&#8217;s browser must support form-based upload. Most modern browsers do, but there&#8217;s no guarantee. For example,</p>
<pre><code> &lt;FORM ENCTYPE='multipart/form-data' method='POST' action='/myservlet'&gt; &lt;INPUT TYPE='file' NAME='mptest'&gt; &lt;INPUT TYPE='submit' VALUE='upload'&gt; &lt;/FORM&gt; </code></pre>
<p>The input type &amp;quot;file&amp;quot; brings up a button for a file select box on the browser together with a text field that takes the file name once selected. The servlet can use the GET method parameters to decide what to do with the upload while the POST body of the request contains the file data to parse.</p>
<p>When the user clicks the &#8220;Upload&#8221; button, the client browser locates the local file and sends it using HTTP POST, encoded using the MIME-type multipart/form-data. When it reaches your servlet, your servlet must process the POST data in order to extract the encoded file. You can learn all about this format in <a>RFC 1867</a>.</p>
<p>Unfortunately, there is no method in the Servlet API to do this. Fortunately, there are a number of libraries available that do. Some of these assume that you will be writing the file to disk; others return the data as an InputStream.</p>
<ul>
<li>Jason Hunter&#8217;s <a>MultipartRequest</a> (available from <a>http://www.servlets.com/</a>)</li>
<li>Apache <a>Jakarta Commons Upload</a> (package org.apache.commons.upload) &#8220;makes it easy to add robust, high-performance, file upload capability to your servlets and web applications&#8221;</li>
<li>CParseRFC1867 (available from <a>http://www.servletcentral.com/</a>).</li>
<li><a>HttpMultiPartParser</a> by Anil Hemrajani, at the <a>isavvix Code Exchange</a></li>
<li>There is a multipart/form parser availailable from Anders Kristensen (<a>http://www-uk.hpl.hp.com/people/ak/java/</a>, <a>ak@hplb.hpl.hp.com</a>) at <a>http://www-uk.hpl.hp.com/people/ak/java/#utils</a>.</li>
<li>JavaMail also has MIME-parsing routines (see the <a>Purple Servlet References</a>).</li>
<li>Jun Inamori has written a class called org.apache.tomcat.request.ParseMime which is available in the <a>Tomcat</a> CVS tree.</li>
<li><a>JSPSmart</a> has a free set of JSP for doing file upload and download.</li>
<li><a>UploadBean</a> by JavaZoom claims to handle most of the hassle of uploading for you, including writing to disk or memory.</li>
<li>There&#8217;s an Upload Tag in <a>dotJ</a></li>
</ul>
<p>Once you process the form-data stream into the uploaded file, you can then either write it to disk, write it to a database, or process it as an InputStream, depending on your needs. See <a>How can I access or create a file or folder in the current directory from inside a servlet?</a> and other questions in the <a>Servlets:Files Topic</a> for information on writing files from a Servlet.</p>
<p><strong>Please note</strong> that you can&#8217;t access a file on the client system directly from a servlet; that would be a huge security hole. You have to ask the user for permission, and currently form-based upload is the only way to do that.</p>
<h2>6) How does a servlet communicate with a JSP page?</h2>
<p>The following code snippet shows how a servlet instantiates a bean and initializes it with FORM data posted by a browser. The bean is then placed into the request, and the call is then forwarded to the JSP page, Bean1.jsp, by means of a request dispatcher for downstream processing.</p>
<pre><code> public void doPost (HttpServletRequest request, HttpServletResponse response) { try { govi.FormBean f = new govi.FormBean(); String id = request.getParameter("id"); f.setName(request.getParameter("name")); f.setAddr(request.getParameter("addr")); f.setAge(request.getParameter("age")); //use the id to compute //additional bean properties like info //maybe perform a db query, etc. // . . . f.setPersonalizationInfo(info); request.setAttribute("fBean",f); getServletConfig().getServletContext().getRequestDispatcher ("/jsp/Bean1.jsp").forward(request, response); } catch (Exception ex) { . . . } } </code></pre>
<p>The JSP page Bean1.jsp can then process fBean, after first extracting it from the default request scope via the useBean action.</p>
<pre><code> &lt;jsp:useBean id="fBean" class="govi.FormBean" scope="request"/&gt; &lt;jsp:getProperty name="fBean" property="name" /&gt; &lt;jsp:getProperty name="fBean" property="addr" /&gt; &lt;jsp:getProperty name="fBean" property="age" /&gt; &lt;jsp:getProperty name="fBean" property="personalizationInfo" /&gt; </code></pre>
<h2>7) What&#8217;s a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?</h2>
<p>Although the SingleThreadModel technique is easy to use, and works well for low volume sites, it does not scale well. If you anticipate your users to increase in the future, you may be better off implementing explicit synchronization for your shared data. The key however, is to effectively minimize the amount of code that is synchronzied so that you take maximum advantage of multithreading.</p>
<p>Also, note that SingleThreadModel is pretty resource intensive from the server&#8217;s perspective. The most serious issue however is when the number of concurrent requests exhaust the servlet instance pool. In that case, all the unserviced requests are queued until something becomes free &#8211; which results in poor performance. Since the usage is non-deterministic, it may not help much even if you did add more memory and increased the size of the instance pool.</p>
<h2>8) Can a servlet maintain a JTA UserTransaction object across multiple servlet invocations?</h2>
<p>No. A JTA transaction must start and finish within a single invocation (of the service() method). Note that this question does not address servlets that maintain and manipulate JDBC connections, including a connection&#8217;s transaction handling.</p>
<h2>9) How does the performance of JSP pages compare with that of servlets? How does it compare with Perl scripts?</h2>
<p>The performance of JSP pages is very close to that of servlets. However, users may experience a perceptible delay when a JSP page is accessed for the very first time. This is because the JSP page undergoes a &#8220;translation phase&#8221; wherein it is converted into a servlet by the JSP engine. Once this servlet is dynamically compiled and loaded into memory, it follows the servlet life cycle for request processing. Here, the jspInit() method is automatically invoked by the JSP engine upon loading the servlet, followed by the _jspService() method, which is responsible for request processing and replying to the client. Do note that the lifetime of this servlet is non-deterministic &#8211; it may be removed from memory at any time by the JSP engine for resource-related reasons. When this happens, the JSP engine automatically invokes the jspDestroy() method allowing the servlet to free any previously allocated resources.</p>
<p>Subsequent client requests to the JSP page do not result in a repeat of the translation phase as long as the servlet is cached in memory, and are directly handled by the servlet&#8217;s service() method in a concurrent fashion (i.e. the service() method handles each client request within a seperate thread concurrently.)</p>
<p>There have been some recent studies contrasting the performance of servlets with Perl scripts running in a &#8220;real-life&#8221; environment. The results are favorable to servlets, especially when they are running in a clustered environment.</p>
<h2>10) How do I call one servlet from another servlet?</h2>
<p>[ Short answer: there are several ways to do this, including</p>
<ul>
<li>use a RequestDispatcher</li>
<li>use a URLConnection or HTTPClient</li>
<li>send a redirect</li>
<li>call getServletContext().getServlet(name) (deprecated, doesn't work in 2.1+)</li>
</ul>
<p>- Alex ]</p>
<p>It depends on what you mean by &#8220;call&#8221; and what it is you seek to do and why you seek to do it.</p>
<p>If the end result needed is to invoke the methods then the simplest mechanism would be to treat the servlet like any java object , create an instance and call the mehods.</p>
<p>If the idea is to call the service method from the service method of another servlet, AKA forwarding the request, you could use the RequestDispatcher object.</p>
<p>If, however, you want to gain access to the instance of the servlet that has been loaded into memory by the servlet engine, you have to know the alias of the servlet. (How it is defined depends on the engine.) For example, to invoke a servlet in JSDK a servlet can be named by the property</p>
<pre><code> myname.code=com.sameer.servlets.MyServlet </code></pre>
<p>The code below shows how this named servlet can be accessed in the service method of another servlet</p>
<pre><code> public void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... MyServlet ms=(MyServlet) getServletConfig().getServletContext().getServlet("myname"); ... } </code></pre>
<p>That said, This whole apporach of accessing servlets in another servlets has been deprecated in the 2.1 version of the servlet API due to the security issues. The cleaner and better apporach is to just avoid accessing other servlets directly and use the RequestDispatcher instead.</p>
<h2>11) What are all the different kinds of servers? (Such as Web Servers, Application Servers, etc)</h2>
<p>The servers involved in handling and processing a user&#8217;s request break down into a few basic types, each of which may have one or more tasks it solves. This flexibility gives developers a great deal of power over how applications will be created and deployed, but also leads to confusion over what server is able to, or should, perform a specific task.</p>
<p>Starting at the basic level, a user is typically submitting a request to a system through a web browser. (We are conveniently ignoring all other types of clients (RMI, CORBA, COM/DCOM, Custom, etc..) for the time being for purposes of clarity.) The web request must be received by a <strong>Web Server</strong> (otherwise known as an <strong>HTTP Server</strong>) of some sort. This web server must handle standard HTTP requests and responses, typically returning HTML to the calling user. Code that executes within the server environment may be CGI driven, Servlets, ASP, or some other server-side programming language, but the end result is that the web server will pass back HTML to the user.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>The web server may need to execute an application in response to the users request. It may be generating a list of news items, or handling a form submission to a guest book. If the server application is written as a Java Servlet, it will need a place to execute, and this place is typically called a <strong>Servlet Engine</strong>. Depending on the web server, this engine may be internal, external, or a completely different product. This engine is continually running, unlike a traditional CGI environment where a CGI script is started upon each request to the server. This persistance gives a servlet connection and thread pooling, as well as an easy way to maintain state between each HTTP request. JSP pages are usually tied in with the servlet engine, and would execute within the same space/application as the servlets.</p>
<p>There are many products that handle the web serving and the servlet engine in different manners. Netscape/iPlanet Enterprise Server builds the servlet engine directly into the web server and runs within the same process space. Apache requires that a servlet engine run in an external process, and will communicate to the engine via TCP/IP sockets. Other servers, such as MS IIS don&#8217;t officially support servlets, and require add-on products to add that capability.</p>
<p>When you move on to Enterprise JavaBeans (and other J2EE components like JMS and CORBA) you move into the application server space. An <strong>Application Server</strong> is any server that supplies additional functionality related to enterprise computing &#8212; for instance, load balancing, database access classes, transaction processing, messaging, and so on.</p>
<p><strong>EJB Application Servers</strong> provide an EJB container, which is the environment that beans will execute in, and this container will manage transactions, thread pools, and other issues as necessary. These application servers are usually stand-alone products, and developers would tie their servlets/JSP pages to the EJB components via remote object access APIs. Depending on the application server, programmers may use CORBA or RMI to talk to their beans, but the baseline standard is to use JNDI to locate and create EJB references as necessary.</p>
<p>Now, one thing that confuses the issue is that many application server providers include some or all of these components in their product. If you look at WebLogic (http://www.beasys.com/) you will find that WebLogic contains a web server, servlet engine, JSP processor, JMS facility, as well as an EJB container. Theoretically a product like this could be used to handle all aspects of site development. In practice, you would most likely use this type of product to manage/serve EJB instances, while dedicated web servers handle the specific HTTP requests.</p>
<h2>12) Should I override the service() method?</h2>
<p>No. It provides a fair bit of housekeeping that you&#8217;d just have to do yourself. If you need to do something regardless of whether the request is e.g., a POST or a GET, create a helper method and call that at the beginning of e.g., doPost() and doGet().</p>
<h2>13) How can my application get to know when a HttpSession is removed (when it time-outs)?</h2>
<p>Define a class, say SessionTimeoutNotifier, that implements javax.servlet.http.HttpSessionBindingListener. Create a SessionTimeoutNotifier object and add it to the user session. When the session is removed, SessionTimeoutNotifier.valueUnbound() will be called by the servlet engine. You can implement valueUnbound() to do whatever you want.</p>
<h2>14) Why use JSP when we can do the same thing with servlets?</h2>
<p>[Original question: Why should I use JSP when there is already servlet technology available for serving dynamic content?]</p>
<p>While JSP may be great for serving up dynamic Web content and separating content from presentation, some may still wonder why servlets should be cast aside for JSP. The utility of servlets is not in question. They are excellent for server-side processing, and, with their significant installed base, are here to stay. In fact, architecturally speaking, you can view JSP as a high-level abstraction of servlets that is implemented as an extension of the Servlet 2.1 API. Still, you shouldn&#8217;t use servlets indiscriminately; they may not be appropriate for everyone. For instance, while page designers can easily write a JSP page using conventional HTML or XML tools, servlets are more suited for back-end developers because they are often written using an IDE &#8212; a process that generally requires a higher level of programming expertise.</p>
<p>When deploying servlets, even developers have to be careful and ensure that there is no tight coupling between presentation and content. You can usually do this by adding a third-party HTML wrapper package like htmlKona to the mix. But even this approach, though providing some flexibility with simple screen changes, still does not shield you from a change in the presentation format itself. For example, if your presentation changed from HTML to DHTML, you would still need to ensure that wrapper packages were compliant with the new format. In a worst-case scenario, if a wrapper package is not available, you may end up hardcoding the presentation within the dynamic content. So, what is the solution? One approach would be to use both JSP and servlet technologies for building application systems.</p>
<h2>15) How do I send information and data back and forth between applet and servlet using the HTTP protocol?</h2>
<p>Use the standard java.net.URL class, or &#8220;roll your own&#8221; using java.net.Socket. See <a>the HTTP spec</a> at W3C for more detail.</p>
<p>Note: The servlet cannot initiate this connection! If the servlet needs to asynchronously send a message to the applet, then you must open up a persistent socket using java.net.Socket (on the applet side), and java.net.ServerSocket and Threads (on the server side).</p>
<h2>16) Can I get the path of the current servlet where it lives on the file system (not its URL)?</h2>
<p>Try using:</p>
<pre><code> request.getRealPath(request.getServletPath()) </code></pre>
<p>An example may be:</p>
<pre><code> out.println(request.getRealPath(request.getServletPath())); </code></pre>
<h2>17) How can I daisy chain servlets together such that the output of one servlet serves as the input to the next?</h2>
<p>There are two common methods for chaining the output of one servlet to another servlet :</p>
<ol type="i">
<li>the first method is the aliasing which describes a series of servlets to be executed</li>
<li>the second one is to define a new MIME-Type and associate a servlet as handlers As I don&#8217;t really use the second one, I&#8217;ll focus on the aliasing.</li>
</ol>
<p>To chain servlets together, you have to specify a sequential list of servlets and associate it to an alias. When a request is made to this alias, the first servlet in the list is invoked, processed its task and sent the ouptut to the next servlet in the list as the request object. The output can be sent again to another servlets.</p>
<p>To accomplish this method, you need to configure your servlet engine (JRun, JavaWeb server, JServ &#8230;).</p>
<p>For example to configure JRun for servlet chaining, you select the JSE service (JRun servlet engine) to access to the JSE Service Config panel. You have just to define a new mapping rule where you define your chaining servlet.</p>
<p>Let say /servlets/chainServlet for the virtual path and a comma separated list of servlets as srvA,srvB.</p>
<p>So when you invoke a request like http://localhost/servlets/chainServlet, internally the servlet srvA will be invoked first and its results will be piped into the servlet srvB.</p>
<p>The srvA servlet code should look like :</p>
<pre><code> public class srvA extends HttpServlet { ... public void doGet (...) { PrintWriter out =res.getWriter(); rest.setContentType("text/html"); ... out.println("Hello Chaining servlet"); } } </code></pre>
<p>All the servlet srvB has to do is to open an input stream to the request object and read the data into a BufferedReader object as for example :</p>
<pre><code> BufferedReader b = new BufferedReader( new InputStreamReader(req.getInputStream() ) ); String data = b.readLine(); b.close(); </code></pre>
<p>After that you can format your output with the data.</p>
<p>It should work straigthforward with Java Web Server or Jserv too. Just look at in their documentation to define an alias name. Hope that it&#8217;ll help.</p>
<h2>18) Why there are no constructors in servlets?</h2>
<p>A servlet is just like an applet in the respect that it has an init() method that acts as a constrcutor. Since the servlet environment takes care of instantiating the servlet, an explicit constructor is not needed. Any initialization code you need to run should be placed in the init() method since it gets called when the servlet is first loaded by the servlet container.</p>
<h2>19) How to handle multiple concurrent database requests/updates when using JDBC with servlets?</h2>
<p>All the dbms provide the facility of locks whenever the data is being modified. There can be two scenarios:</p>
<ol>
<li>Multiple database updates on different rows, if you are using servlets the servlets will open multiple connections for different users. In this case there is no need to do additional programming.</li>
<li>If database updates are on the same row then the rows are locked automatically by the dbms, hence we have to send requests to the dbms repeatatively until the lock is released by dbms.</li>
</ol>
<p>This issue is dealt with in the JDBC documentation; look up &#8220;Transactions&#8221; and &#8220;auto-commit&#8221;. It can get pretty confusing.</p>
<h2>20) What is the difference between GenericServlet and HttpServlet?</h2>
<p>GenericServlet is for servlets that might not use HTTP, like for instance FTP servlets. Of course, it turns out that there&#8217;s no such thing as FTP servlets, but they were trying to plan for future growth when they designed the spec. Maybe some day there will be another subclass, but for now, always use HttpServlet.</p>
<h2>21) How do you share session objects between servlets and JSP?</h2>
<p>Sharing sessions between a servlet and a JSP page is straight forward. JSP makes it a little easy by creating a session object and making it availabe already. In a servlet you would have to do it yourself. This is how:</p>
<pre><code> //create a session if one is not created already now HttpSession session = request.getSession(true); //assign the session variable to a value. session.putValue("variable","value"); </code></pre>
<p>in the jsp page this is how you get the session value:</p>
<pre><code> &lt;% session.getValue("varible"); %&gt; </code></pre>
<h2>22) What is a servlet?</h2>
<p>A servlet is a way of extending your web server with a Java program to perform tasks previously dealt with by CGI scripts or proprietary server extension frameworks.</p>
<h2>23) Is there any method to unload a servlet from Web Server memory without restarting the server?</h2>
<p>There is no standard method/mechanism to unload a servlet from memory. Some servers, like JWS, provide the means to load and unload servlets from their administration module. Others, like Tomcat, require you to just replace the WAR file.</p>
<h2>24) What distinguishes a JavaBean from a Servlet?</h2>
<p>JavaBeans are a set of rules to follow to create reusable software components, or beans. This contains properties and events. At the end you have a component which could be examined by a program (like an IDE) to allow the user of your JavaBean component to configure it and to run in its Java programs.</p>
<p>Servlets are Java classes running in a Servlet engine implementing a particular interface: Servlet, forcing you to implement some methods (service()). The servlet is an extension of your web server where this servlet is running on and only lets you know when a user requests a GET or POST calls from a web page to your servlet.</p>
<p>So, both have nothing in common except Java.</p>
<h2>25) How much data we can store in a session object?</h2>
<p>Any amount of data can be stored there because the session is kept on the server side.</p>
<p>The only limitation is sessionId length, which shouldn&#8217;t exceed ~4000 bytes &#8211; this limitation is implied by HTTP header length limitation to 4Kb since sessionId may be stored in the cookie or encoded in URL (using &#8220;<strong>URL rewriting</strong>&#8220;) and the cookie specification says the size of cookie as well as HTTP request (e.g. GET /document.html\n) cannot be longer then 4kb.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2009/02/servlets-interview-questions/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>New Features in Servlets 2.5</title>
		<link>http://www.javabeat.net/2009/01/new-features-in-servlets-2-5/</link>
		<comments>http://www.javabeat.net/2009/01/new-features-in-servlets-2-5/#comments</comments>
		<pubDate>Tue, 06 Jan 2009 13:19:37 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Servlets]]></category>
		<category><![CDATA[Servlets 2.5]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=223</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>1.Introduction This article presents new features introduced in the Servlet 2.5. Servlet 2.5 is bundled with Java EE 5.0 edition and it has lot of new features. This version has major changes since it has to support the Java 5.0 version for all the J2EE technologies. One of the notable changes will be supporting Generics [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>1.Introduction</h2>
<p>This article presents new features introduced in the <strong><em>Servlet 2.5</em></strong>. <strong><em>Servlet 2.5</em></strong> is bundled with <strong><em>Java EE 5.0</em></strong> edition and it has lot of new features. This version has major changes since it has to support the <strong><em>Java 5.0</em></strong> version for all the J2EE technologies. One of the notable changes will be supporting <strong><em>Generics</em></strong> and <strong><em>Annotations</em></strong>. Using annotations in Java EE environment has simplified the developement process by eliminzating the much need for XML deployment descriptors.</p>
<p>EJB 3.0 is example for how it is simple compare to its previous versions. In the same way other technologies also have significent updates. One particular technology is Servlet and it is evloving very quickly. This <strong><em>Servlet 2.5</em></strong> has few changes and the next version <strong><em><a href="http://www.javabeat.net/2008/12/new-features-in-servlets-3-0/">Servlet 3.0</a></em></strong> has very exciting features like Web Fragments. The minimum requirement for the Servlet 2.5 is JDK 5.0 or above. Lets look into the <strong><em>Servlet 2.5</em></strong> features in this article.</p>
<p><span style="text-decoration: underline;"><strong>also read:</strong></span></p>
<ul>
<li><a href="http://www.javabeat.net/j2ee-books/">J2EE Books</a></li>
<li><a href="http://www.javabeat.net/2009/02/servlets-interview-questions/">Servlets interview questions</a></li>
<li><a href="http://www.javabeat.net/2009/01/new-features-in-java-ee-6-0/">New Features in Java EE 6.0</a></li>
<li><a href="http://www.javabeat.net/2007/08/annotations-in-java-5-0/">Annotations in Java 5.0</a></li>
</ul>
<p>The following are the list of notable features in servlet 2.5:</p>
<ul>
<li>Support for Annotations</li>
<li>Deployment descriptor changes</li>
<li>Removed restriction on error handling</li>
</ul>
<h2>2.Annotations in Servlet 2.5</h2>
<p>Annotations are a new language feature provided as part of <strong><em>JSR 175</em></strong> (A Metadata Facility for the Java Programming Language). One of the major change in the <strong><em>Servlet 2.5</em></strong> is its full support for the <strong><em>Java 5.0</em></strong> version. The minimum requirement for <strong><em>Servlet 2.5</em></strong> is the <strong><em>JDK 5.0</em></strong> installed in your system. <strong><em>Servlet 2.5</em></strong> introduces annotations programming in the Servlets technology.</p>
<p>The annotations has to be loaded into the containers memory while server start up. This will take up more time since the container has to scan all the files in the classpath including jar files to find all the annotations. There is option to diable annotations by using the <strong><em>metadata-complete</em></strong> attribute in the <strong><em>web.xml</em></strong> file. If you set this value as &#8220;true&#8221;, then the container will ignore all the annotations in the Servlet files. If you specify as &#8220;false&#8221; or ignore that, by default it will search for the annotations declaration. Look into the folloing sample code:</p>
<pre class="brush: java; title: ; notranslate">

&lt;web-app xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot; version=&quot;2.5&quot; metadata-complete=&quot;true&quot;&gt;
&lt;/web-app&gt; </pre>
<p>By default container will look into folders WEB-INF/classes and WEB-INF/lib for loading the servlets. Optionally container can search on the other location also. We will look into the details of few annotation in the next sections. The following are the few annotations introduced in the Servlet 2.5:</p>
<ul>
<li><em>@DeclaresRoles</em></li>
<li><em>@EJB</em></li>
<li><em>@EJBs</em></li>
<li><em>@Resource</em></li>
<li><em>@Resources</em></li>
<li><em>@PostConstruct</em></li>
<li><em>@PreDestroy</em></li>
<li><em>@PersistanceContext</em></li>
<li><em>@PersistanceUnit</em></li>
</ul>
<h3>2.1.@EJB</h3>
<p><strong><em>EJB 3.0</em></strong> components can be injected to a Servlet class by using the <strong><em>@EJB</em></strong> annotation. In the deployment descriptors this can be declared using the ejb-ref and ejb-local-ref elements. <strong><em>@EJB</em></strong> annotation can be used infront of a field to inject any <strong><em>EJB 3.0</em></strong> reference to that field. Like the following example:</p>
<pre class="brush: java; title: ; notranslate"> @EJB private LoginSample loginSample;</pre>
<h3>2.2.@EJBs</h3>
<p><strong><em>@EJBs</em></strong> annotation can be used for declraing more than one EJB in single line of declaration. For example:</p>
<pre class="brush: java; title: ; notranslate"> @EJBs({@EJB(LoginSample),@EJB(ProcessSample)})</pre>
<h3>2.3.@Resource</h3>
<p><strong><em>@Resource</em></strong> annotation used for declaring any of the resources like datasource, messaging destination,etc. <strong><em>@Resource</em></strong> annotation can be used for class,method or a field. Look into the following example:</p>
<pre class="brush: java; title: ; notranslate"> @Resource private javax.sql.DataSource mysqlDs;</pre>
<h3>2.4.@Resources</h3>
<p><strong><em>@Resources</em></strong> annotation is used for declaring more than one <strong><em>@Resource</em></strong> in a single line. For example:</p>
<pre class="brush: java; title: ; notranslate"> @Resources({@Resource(name=&quot;mysqlDs&quot; type=javax.sql.DataSource),
 @Resource(name=&quot;factory&quot; type=javax.jms.ConnectionFactory) })</pre>
<h3>2.5.@PostConstruct</h3>
<p>The <strong><em>@PostConstruct</em></strong> annotation is declared on a method that does not take any arguments, and must not throw any checked expections. The return value must be void. The method MUST be called after the resources injections have been completed and before any lifecycle methods on the component are called.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate"> @PostConstruct public void postConstruct() { }</pre>
<h3>2.6.@PreDestroy</h3>
<p>The <strong><em>@PreDestroy</em></strong> annotation is declared on a method of a container managed component. The method is called prior to component being reomvoed by the container.</p>
<pre class="brush: java; title: ; notranslate"> @PreDestroy public void preDestroy() { }</pre>
<h2>3.Error Handling</h2>
<p><strong><em>Servlet 2.5</em></strong> removed a few restrictions around error handling and session tracking. Now it has removed the restriction that the <em>&lt;error-page&gt;</em> could not call the <em>setStatus()</em> method to alter the error code that triggered them. In session tracking, <strong><em>Servlet 2.5</em></strong> eased a rule that a servlet called by RequestDispatcher <em>include()</em> couldn&#8217;t set response headers.</p>
<h2>4.Servlets 2.5 web.xml changes</h2>
<p>Servlets 2.5 has added few changes on the <strong><em>web.xml</em></strong> file. It is not major changes, but even though gives more<br />
flexibility on mapping the filters and servlets. The two changes are in the <em>filter-mapping</em> and <em>servlet-mapping</em> elements.</p>
<h3>4.1.servlet-mapping</h3>
<p>In the previous version you are allowed to use only the single <strong><em>url-pattern</em></strong> inside the <strong><em>servlet-mapping</em></strong>. This has the restriction or drawback if you want to map more than one url for the single servlet. <strong><em>Servlet 2.5</em></strong> updated this element so that you can add more than one <strong><em>url-pattern</em></strong> for the single servlet mapping. Look into the following example code:</p>
<pre class="brush: java; title: ; notranslate">
&lt;servlet-mapping&gt;
	  &lt;servlet-name&gt;JavaBeatServlet&lt;/servlet-name&gt;
	  &lt;url-pattern&gt;/servlets/*&lt;/url-pattern&gt;
	  &lt;url-pattern&gt;/servlet/javabeat/*&lt;/url-pattern&gt;
	  &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
	&lt;/servlet-mapping&gt;
</pre>
<p>The above snippet adds three <strong><em>url-pattern</em></strong> inside the single <strong><em>servlet-mapping</em></strong> element. This is more useful when you have the requirement to add three different url&#8217;s to be mapped for a single <strong><em>servlet-name</em></strong> element.</p>
<h3>4.2.filter-mapping</h3>
<p>Like the above changes in the <strong><em>servlet-mapping</em></strong>, <strong><em>filter-mapping</em></strong> has two changes. First one is introducing the <strong><em>wildcard(*)</em></strong> for <strong><em>filter-mapping</em></strong>.</p>
<pre class="brush: java; title: ; notranslate">
&lt;filter-mapping&gt;
	  &lt;filter-name&gt;Java Filter&lt;/filter-name&gt;
	  &lt;servlet-name&gt;*&lt;/servlet-name&gt;
	&lt;/filter-mapping&gt;
</pre>
<p>In the above example, all the requests will be redirected to the particular filter name. Another change is multiple entry in the<br />
<strong><em>filter-mapping</em></strong>. It is same as the servlet mappintg, we can add multiple entries in the <strong><em>filter-mapping</em></strong>.</p>
<pre class="brush: java; title: ; notranslate">
&lt;filter-mapping&gt;
	  &lt;filter-name&gt;Game Filter&lt;/filter-name&gt;
	  &lt;url-pattern&gt;/games/*&lt;/url-pattern&gt;
	  &lt;servlet-name&gt;PlayGame&lt;/servlet-name&gt;
	  &lt;servlet-name&gt;StopGame&lt;/servlet-name&gt;
	&lt;/filter-mapping&gt;
</pre>
<p>The above code is example for multiple entries in the <strong><em>filter-mapping</em></strong>.</p>
<p><strong>also read:</strong></p>
<ul>
<li><a href="http://www.javabeat.net/j2ee-books/">J2EE Books</a></li>
<li><a href="http://www.javabeat.net/2009/02/servlets-interview-questions/">Servlets interview questions</a></li>
<li><a href="http://www.javabeat.net/2009/01/new-features-in-java-ee-6-0/">New Features in Java EE 6.0</a></li>
<li><a href="http://www.javabeat.net/2007/08/annotations-in-java-5-0/">Annotations in Java 5.0</a></li>
</ul>
<h2>5.Summary</h2>
<p>This article explains what are the new features in Servlet 2.5 version. The main goal of this release is to provide Java 5.0 support and to start using the features like annotations and generics. In the next versions we can see there will be more changes.</p>
<h2>Servlets 2.5 Reference</h2>
<ul>
<li><a href="http://jcp.org/en/jsr/detail?id=154" target="_blank">JSR 154</a></li>
<li><a href="http://jcp.org/en/jsr/detail?id=315" target="_blank">Servlet 3.0</a></li>
<li><a href="http://www.javabeat.net/articles/97-new-features-in-servlets-30-1.html" target="_blank">Servlets 3.0</a></li>
</ul>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2009/01/new-features-in-servlets-2-5/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>New Features in Servlets 3.0</title>
		<link>http://www.javabeat.net/2008/12/new-features-in-servlets-3-0/</link>
		<comments>http://www.javabeat.net/2008/12/new-features-in-servlets-3-0/#comments</comments>
		<pubDate>Tue, 23 Dec 2008 13:14:25 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Servlets]]></category>
		<category><![CDATA[Servlets 3.0]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=214</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Introduction This article covers most of the important features available as part of Servlet 3.0 specification. Note that the Servlet 3.0 specification constantly keeps changing frequently with the reviews coming in and the features and the API&#8217;s mentioned in this article is based on the specification that is available in JCP for public review as [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>Introduction</h2>
<p align="justify">This article covers most of the important features available as part of <strong><em>Servlet 3.0</em></strong> specification. Note that the <strong><em>Servlet 3.0</em></strong> specification constantly keeps changing frequently with the reviews coming in and the features and the API&#8217;s mentioned in this article is based on the specification that is available in JCP for public review as of December 2008. This article focuses on the <strong><em>new set of annotations</em></strong> introduced that can be used by developers rather than put the data in the configuration file, followed by the enhanced <strong><em>Pluggability and the extension support</em></strong> for adding third-party frameworks. The article is finally concluded by detailing about the <strong><em>asynchronous execution of processing</em></strong> and the usage for the same. <strong><em>JSR 315</em></strong> talks about the Servlet 3.0 features. For attitional information please read the reference section of this article.</p>
<h2>Ease of Development through Annotations</h2>
<p align="justify">The configuration information about a component in a typical web application is expressed in an external meta file. The information about web components such as Servlets, Servlet Filters are mentioned in the deployment descriptor, which is <code>web.xml</code>. Starting from <em>Servlet 3.0</em>, it is also possible to specify the meta information about a component in the definition of a component itself, through Annotations. It doesn&#8217;t mean the deployment descriptor is now gone, deployment descriptor in the form of web.xml is still there. In fact information specified in the deployment descriptor takes precedence over the information specified through Annotations.</p>
<p align="justify">The <em>Servlet 3.0 specification</em> also provides an option for instructing the Web Container, whether the container should process the annotations defined on the web components. The name of the element is <em>metadata-complete</em> and it is a child element of <em>web-app</em> element. The <em>metadata-complete</em> element indicates whether the meta-data information available in the deployment descriptor is complete. So, if the value for the metadata-complete element is set to a value of true, then it means that the meta information found in the deployment descriptor is complete and eventually the annotations defined on the web components will be ignored by the <em>Servlet Container</em>. If the value for <em>metadata-complete</em> is set to false, then it means that the information in the deployment descriptor is not complete and web components decorated with annotations, if any, should be scanned and processed by the Web Container.</p>
<p align="justify">The following annotations are applicable starting from Servlet 3.0 specification,</p>
<ul>
<li>@WebServlet</li>
<li>@WebServletContextListener</li>
<li>@ServletFilter</li>
<li>@InitParam</li>
</ul>
<h3>Web Servlet and InitParam Annotation</h3>
<p align="justify">In this section, we will see the usage of <em>@WebServlet</em> and <em>@InitParam</em> using an example. Look at the following code,</p>
<p><strong>SimpleServlet.java</strong></p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.servlet30.newfeatures;

import javax.servlet.annotation.InitParam;
import javax.servlet.annotation.WebServlet;

@WebServlet(
    name = &quot;SimpleServlet&quot;,
    urlPatterns = {&quot;/simple&quot;},
    initParams = {
        @InitParam(name = &quot;param1&quot;, value = &quot;value1&quot;),
        @InitParam(name = &quot;param2&quot;, value = &quot;value2&quot;)}
)
public class SimpleServlet {

}</pre>
<p align="justify">In the example, we have declared a class by name SimpleServlet and this class is not made to extend or implement any of the Servlet/HttpServlet types. Instead, to qualify this class as a Servlet class we have annotated using <em>@WebServlet</em> annotation. Note that the name of the servlet is SimpleServlet as specified through the <em>name</em> attribute. The attribute <em>urlPatterns</em> defines a set of url-patterns that can be used to invoke the Servlet. The Servlet Container after scanning this class will generate the deployment descriptor which may look like the following,</p>
<p><strong>web.xml</strong></p>
<pre class="brush: java; title: ; notranslate">
...

&lt;servlet&gt;
    &lt;servlet-name&gt;SimpleServlet&lt;/servlet-name&gt;
    &lt;servlet-class&gt;net.javabeat.servlet30.newfeatures.SimpleServlet&lt;/servlet-class&gt;

        &lt;init-param&gt;
            &lt;param-name&gt;param1&lt;/param-name&gt;
            &lt;param-value&gt;value1&lt;/param-value&gt;
        &lt;/init-param&gt;

        &lt;init-param&gt;
            &lt;param-name&gt;param2&lt;/param-name&gt;
            &lt;param-value&gt;value2&lt;/param-value&gt;
    &lt;/init-param&gt;

&lt;/servlet&gt;

&lt;servlet-mapping&gt;
    &lt;url-pattern&gt;/simple&lt;/url-pattern&gt;
    &lt;servlet-name&gt;SimpleServlet&lt;/servlet-name&gt;
&lt;/servlet-mapping&gt;

...
</pre>
<h3>Filter annotation</h3>
<p align="justify">The <em>@Filter</em> annotation defines a <strong><em>Servlet Filter component</em></strong> for a web application. A filter is typically used to intercept a web request for performing any of the pre-processing operations well before reaching the actual servlet component. Let us see the definition of a filter component using <strong><em>Servlet 3.0</em></strong> approach,</p>
<p><strong>SimpleFilter.java</strong></p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.servlet30.newfeatures;

import javax.servlet.annotation.InitParam;
import javax.servlet.annotation.ServletFilter;

@ServletFilter(
    filterName = &quot;SimpleFilter&quot;,
    urlPatterns = &quot;/simple&quot;,
    initParams =
        {@InitParam(name = &quot;param1&quot;, value = &quot;value1&quot;),
         @InitParam(name = &quot;param2&quot;, value = &quot;value2&quot;)}
)
public class SimpleFilter {

}
</pre>
<p align="justify">Again, to support backward compatibility, the annotation information in the above class will be transformed as information in the deployment descriptor by the Servlet Container and the deployment descriptor might look like this,</p>
<p><strong>web.xml</strong></p>
<pre class="brush: java; title: ; notranslate">
...

&lt;filter&gt;

    &lt;filter-name&gt;SimpleFilter&lt;/filter-name&gt;
    &lt;filter-class&gt;net.javabeat.servlet30.newfeatures.SimpleFilter&lt;/filter-class&gt;

    &lt;init-param&gt;
        &lt;param-name&gt;param1&lt;/param-name&gt;
        &lt;param-value&gt;value1&lt;/param-value&gt;
    &lt;/init-param&gt;

    &lt;init-param&gt;
        &lt;param-name&gt;param2&lt;/param-name&gt;
        &lt;param-value&gt;value2&lt;/param-value&gt;
    &lt;/init-param&gt;

&lt;/filter&gt;

&lt;filter-mapping&gt;
    &lt;filter-name&gt;SimpleFilter&lt;/filter-name&gt;
    &lt;url-pattern&gt;/simple&lt;/url-pattern&gt;
&lt;filter-mapping&gt;

...
</pre>
<h3>Servlet Context Listener annotation</h3>
<p align="justify">The <em>Servlet Context Listener</em> is used to receive events whenever the servlet context is created and destroyed by the Web Container. Let us see an usage of this annotation,</p>
<p><strong>SimpleServletContextListener.java</strong></p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.servlet30.newfeatures;

import javax.servlet.ServletContextEvent;
import javax.servlet.annotation.WebServletContextListener;

@WebServletContextListener()
public class SimpleServletContextListener {

    public void contextInitialized(ServletContextEvent event){
    }

    public void contextDestroyed(ServletContextEvent event){
    }
}
</pre>
<p align="justify">The deployment descriptor in this case would be,</p>
<p><strong>web.xml</strong></p>
<pre class="brush: java; title: ; notranslate">
&lt;web-app&gt;

    &lt;listener&gt;
        &lt;listener-class&gt;net.javabeat.servlet30.newfeatures.SimpleServletContextListener
    &lt;/listener-class&gt;
    &lt;/listener&gt;

&lt;/web-app&gt;
</pre>
<h2 id="Pluggability">Pluggability in Servlet 3.0</h2>
<h3>Web Fragments</h3>
<p align="justify">Today, most of the modern popular frameworks such as Struts and Spring can be integrated easily with the Web Container for building robust applications. However, most of the time, the integration happens in such a way that the web.xml deployment descriptor has to be edited manually to configure framework specific servlet and listener classes. Have a look into the following code snippet,</p>
<p><strong>web.xml</strong></p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;web-app version=&quot;2.5&quot;
    xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot;
    xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
    xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot;&gt;

    &lt;servlet&gt;
        &lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt;
        &lt;servlet-class&gt;javax.faces.webapp.FacesServlet&lt;/servlet-class&gt;
        &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
    &lt;/servlet&gt;

    &lt;servlet-mapping&gt;
        &lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt;
        &lt;url-pattern&gt;/faces/*&lt;/url-pattern&gt;
    &lt;/servlet-mapping&gt;

&lt;/web-app&gt;
</pre>
<p align="justify">The above web.xml will be familiar for someone who had used the <em>JSF framework</em>. We have used a framework-specific servlet called the <em>FacesServlet</em> in the above case for intercepting all the url requests with the pattern <em>/faces/*</em>. Same will be the case for another intergration frameworks such as Spring or Struts.</p>
<p align="justify">The problem with the current approach of the web.xml is that it is not modular. All the configuration details about one particular application is included in one single web.xml file. Assuming that if one single application is making use of one or more frameworks on top of it, there is no way to instruct the Servlet Container about the usage of other frameworks, the only option being is to edit the web.xml deployment descriptor. The <strong><em>Servlet 3.0</em></strong> specification addresses this issue by introducing <strong><em>web fragments</em></strong>.</p>
<p align="justify">A <em>web fragment</em> can be considered as one of the segment of the whole <em>web.xml</em> and it can be imagined that one or more web fragments constitute a single web.xml file. A web-fragment can include all the possible elements that are applicable for the web.xml. Consider a sample web-fragment file,</p>
<p><strong>web-fragment.xml</strong></p>
<pre class="brush: java; title: ; notranslate">
&lt;web-fragment&gt;
    &lt;servlet&gt;
        &lt;servlet-name&gt;myFrameworkSpecificServlet&lt;/servlet-name&gt;
        &lt;servlet-class&gt;myFramework.myFrameworkServlet &lt;/servlet-class&gt;
    &lt;/servlet&gt;

    &lt;listener&gt;
        &lt;listener-class&gt;myFramework.myFrameworkListener&lt;/listener-class&gt;
    &lt;/listener&gt;
&lt;/web-fragment&gt;
</pre>
<p align="justify">Typically a framework is bundled in the form of a jar file and it is the responsibility of that framework to define the web fragment file with the name <em>web-fragment.xml</em> in the <em>META-INF</em> directory of the jar file. During the application startup, it is the responsibility of the Container to scan the information that is found in the <em>/META-INF/web-fragment.xml</em> file available in the application&#8217;s classpath.</p>
<h3>Programmatic support for adding web components</h3>
<p align="justify">The specification also provides enhanced Pluggability where it provides options for adding servlets, filters, servlet mappings and filter mappings during the run time. Look into the following example code,</p>
<p><strong>SimpleServletContextListener.java</strong></p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.servlet30.newfeatures;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.annotation.WebServletContextListener;

@WebServletContextListener()
public class SimpleServletContextListener {

    public void contextInitialized(ServletContextEvent event){

        ServletContext context = event.getServletContext();

        String simpleServletName = &quot;simpleServlet&quot;;
        String simpleFilterName = &quot;simpleFilter&quot;;

        Map&lt;String, String&gt; initParams = new HashMap&lt;String, String&gt;();
        initParams.put(&quot;param1&quot;, &quot;value1&quot;);
        initParams.put(&quot;param2&quot;, &quot;value2&quot;);

        String[] urlPatterns = new String[]{&quot;/simple&quot;};

        context.addServlet(simpleServletName, &quot;description for simple servlet&quot;,
             &quot;net.javabeat.servlet30.newfeatures.SimpleServlet&quot;, initParams, -1, false);
        context.addServletMapping(simpleServletName, urlPatterns);

        context.addFilter(simpleFilterName, &quot;description for simple filter&quot;,
            &quot;net.javabeat.servlet30.newfeatures.SimpleFilter&quot;, initParams, false);
    }

    public void contextDestroyed(ServletContextEvent event){
    }
}
</pre>
<p align="justify">The code is pretty straightforward. It acquires the reference to <em>ServletContext</em> and makes use of the methods <em>addServlet()</em>, <em>addServletMapping()</em> and <em>addFilter()</em> for dynamically adding web components.</p>
<h2 id="AsynchronousSupport">Asynchronous processing in Servlet 3.0</h2>
<p align="justify">In a web application workflow, the client that initiates the request will be received by the <em>Web Container</em> and it is the responsibility of the <em>Web Container</em> to initiate the Servlet object by passing in the request and the response objects by calling in any of the request objects. Assume that the implementation code that tries to access external system, example a Database or a legacy system using JDBC or the JCA API&#8217;s is taking considerable amount of time for the execution to happen. In a normal environment the thread will get blocked and it will be made to wait until the data from the external system is available.</p>
<p align="justify">To avoid this waiting time or the block time, <strong><em>Servlet 3.0</em></strong> adds support for <em>asynchronous processing of request</em>. The request can be made to put into asynchronous mode by calling the method <em>ServletRequest.startAsync()</em> that returns a <em>AsyncContext</em> object. It is also possible to specify the timeout duration by calling the <em>ServletRequest.setAsyncTimeout()</em> method. In this case, the response can be committed via two means, one is to call the <em>complete()</em> method that is defined on the <em>AsyncContext</em> object and the other way is when the timeout duration that is originally set on the request object has expired.</p>
<p align="justify">It is also possible to add asynchronous listeners to the request object to receive notifications whether the asynchronous operation is completed or the timeout has happened. The following code does the same,</p>
<p><strong>SimpleAsyncListener.java</strong></p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.servlet30.newfeatures;

import java.io.IOException;

import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ServletRequest;

public class SimpleAsyncListener implements AsyncListener{

    public void onComplete(AsyncEvent event) throws IOException {
    }

    public void onTimeout(AsyncEvent event) throws IOException {
    }
}
</pre>
<p align="justify">To add this listener to the request object, use the following piece of code,</p>
<pre class="brush: java; title: ; notranslate">request.addAsyncListener(new SimpleAsyncListener());</pre>
<p align="justify">The same is reflected in the Web Servlet and the Servlet Filter annotations through the <code>asyncSupported</code> and <code>asyncTimeout</code> attributes,</p>
<p><strong>SimpleServlet.java</strong></p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.servlet30.newfeatures;

import javax.servlet.annotation.InitParam;
import javax.servlet.annotation.WebServlet;

@WebServlet(
    name = &quot;SimpleServlet&quot;,
    urlPatterns = {&quot;/simple&quot;},
    initParams = {
        @InitParam(name = &quot;param1&quot;, value = &quot;value1&quot;),
        @InitParam(name = &quot;param2&quot;, value = &quot;value2&quot;)},
    asyncSupported = true,
    asyncTimeout = 3000
)
public class SimpleServlet {

}
</pre>
<h2>Conclusion</h2>
<p align="justify">The article covered the new set of annotations like <em>@WebServlet</em>, <em>@ServletFilter</em> that can be used to directly decorate the web components: Servlet and Filter, which could have done previously only through the usage of deployment descriptors. However, it should be noted that the usage of annotations is intended still for developers and not for the others who typically play the role of assembler or deployer. The <strong>Servlet 3.0</strong> adds extensible support for plugging-in new frameworks or libraries without asking the developers to edit the deployment descriptor through <em>web fragments</em>. Finally the <em>asynchronous nature of request processing</em>, the possibility of adding asynchronous listeners along with the impacts in <em>@WebServlet</em> and <em>@ServletFilter</em> annotations were also discussed. Thank you for reading this article.</p>
<h2>Reference for Servlet 3.0</h2>
<ul>
<li><a href="http://jcp.org/en/jsr/detail?id=315" target="_blank">JSR 315 &#8211; Servlet 3.0 Soecification</a></li>
</ul>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2008/12/new-features-in-servlets-3-0/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Servlet 3.0</title>
		<link>http://www.javabeat.net/2008/10/servlet-3-0/</link>
		<comments>http://www.javabeat.net/2008/10/servlet-3-0/#comments</comments>
		<pubDate>Thu, 02 Oct 2008 00:51:23 +0000</pubDate>
		<dc:creator>JavaBeat</dc:creator>
				<category><![CDATA[Servlets]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=352</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Can’t wait to see Servlet 3.0 in action. More details about the specification and the current status is available in its JSR homepage. The introduction of support for non-blocking I/O takes Java Servlets to a new level and this, in my opinion,is the most significant stride in Servlet specification since it was introduced. The benefits [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>
Can’t wait to see <b><i>Servlet 3.0</i></b> in action.  More details about the specification and the current status is available in its <a href="http://jcp.org/en/jsr/detail?id=315">JSR homepage</a>. The introduction of support for non-blocking I/O takes Java Servlets to a new level and this, in my opinion,is the most significant stride in Servlet specification since it was introduced.  The benefits opened up by this new feature are several.  Here are some I can think of -</p>
<ul>
<li>
1) If a request requires a remote call that can take significant time, servlet container does not have to maintain a dedicated thread as the web tier waits for the service to complete.</li>
<li>
2) In case of a multi-part file upload, servlet container does not have to maintain a dedicated thread as the file is being uploaded over a slow network.
</li>
<li>
3) It is possible to have a Comet-style application, that keeps a client connection open and periodically pushes content on to client thus avoiding the need for client to poll for data.</li>
</ul>
<p>
<b><i>Servlet 3.0</i></b> will be officially part of <b><i>Java EE 6</i></b>.  The final version of <b><i>Java EE 6</i></b> specifications are expected sometime this year and it would take a while for the application servers to be fully compliant with it.  So we are looking at atleast a year or two before I can convince people in my company to use this.  Sometimes, it’s so exciting to see a new technology introduced, but yet frustrating that it will take a while before I can really start using it.  This is part and parcel of being in Java world and working in a cautious enterprise environment.
</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>
	This article is originally posted in <a href="http://ganeshmb.wordpress.com" target="_blank">Ganesh&#8217;s</a> blog.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2008/10/servlet-3-0/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to delete a cookie on server in a J2EE application</title>
		<link>http://www.javabeat.net/2008/09/how-to-delete-a-cookie-on-server-in-a-j2ee-application/</link>
		<comments>http://www.javabeat.net/2008/09/how-to-delete-a-cookie-on-server-in-a-j2ee-application/#comments</comments>
		<pubDate>Thu, 25 Sep 2008 00:50:45 +0000</pubDate>
		<dc:creator>JavaBeat</dc:creator>
				<category><![CDATA[Servlets]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=350</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>There is no direct method offered by servlet API to delete a cookie on server side. This is how you can go about doing it. 1) Loop through the cookies in the request object to locate the one that you want to delete. 1 2 3 4 5 for (Cookie cookie: request.getCookies()) { if (USER_COOKIE_NAME.equals(cookie.getName())) [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>
There is no direct method offered by servlet API to delete a cookie on server side. This is how you can go about doing it.
</p>
<p>
1) Loop through the cookies in the request object to locate the one that you want to delete.
</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">for (Cookie cookie: request.getCookies()) {
    if (USER_COOKIE_NAME.equals(cookie.getName())) {
         return cookie;
    }
}</pre></td></tr></table></div>

<p>
2) Set the maxAge property of the cookie to 0. This results in cookie expiring with immediate effect as soon as the client receives the response.
</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>
3) Optionally, set the value property to empty string.  This is not really required since the cookie is about to be expired.   However, this adds a sense of a clean and complete erasure if the cookie being deleted carries some critical, secure data.
</p>
<p>
4) Add this cookie to response. The cookie will be gone once the response is sent back to client!
</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">view plaincopy to clipboardprint
cookie.setMaxAge(0);
cookie.setValue(&quot;&quot;);
response.addCookie(cookie);</pre></td></tr></table></div>

<p>
	This article is originally posted in <a href="http://ganeshmb.wordpress.com" target="_blank">Ganesh&#8217;s</a> blog.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2008/09/how-to-delete-a-cookie-on-server-in-a-j2ee-application/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Servlet Life Cycle</title>
		<link>http://www.javabeat.net/2008/08/servlet-life-cycle/</link>
		<comments>http://www.javabeat.net/2008/08/servlet-life-cycle/#comments</comments>
		<pubDate>Fri, 01 Aug 2008 12:49:00 +0000</pubDate>
		<dc:creator>JavaBeat</dc:creator>
				<category><![CDATA[Servlets]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=220</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Before start writing the servlet, it is important to know the life cylce of every servlet instance created. Read What is Servlet? tips to know about the servlet basics. Servlet Life Cycle Methods The following are the life cycle methods of a servlet instance: init() service() destroy() We will look into the each method in [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>
	Before start writing the servlet, it is important to know the <b><i>life cylce</i></b> of every servlet<br />
	instance created. Read <a href="http://www.javabeat.net/tips/114-what-is-servlet.html" target="_blank">What is Servlet?</a> tips<br />
	to know about the <b><i>servlet basics</i></b>.
</p>
<h4>Servlet Life Cycle Methods</h4>
<p>
	The following are the <b><i>life cycle</i></b> methods of a servlet instance:</p>
<ul>
<li><i>init()</i></li>
<li><i>service()</i></li>
<li><i>destroy()</i></li>
</ul>
<p>	We will look into the each method in detail.
</p>
<h3>init()</h3>
<p>
	This method is called once for a <b><i>servlet instance</i></b>. When first time servlet is called, <b><i>servlet container</i></b> creates instance<br />
	of that <b><i>servlet</i></b> and loaded into the memory. Future requests will be served by the same instance without creating the new<br />
	instance. <b><i>Servlet</i></b> by default multithreaded application.init() method is used for inilializing servlet variables which are<br />
	required to be passed from the <b><i>deployment descriptor web.xml</i></b>. <b><i>ServletConfig</i></b> is passed as the parameter to <b><i>init()</i></b> method which stores<br />
	all the values configured in the <b><i>web.xml</i></b>. It is more convenient way to initialize the <b><i>servlet</i></b>.
</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<h3>service()</h3>
<p>
	This method is called for the each request. This is the entry point for the every servlet request and here we have to write our<br />
	businesslogic or any other processes. This method takes <b><i>HttpServletRequest</i></b> and <b><i>HttpServletresponse</i></b> as the parameters. It is not mandatory to<br />
	write this method, normally developers are interested in writing <b><i>doGet()</i></b> or <b><i>doPost()</i></b> methods which is by default called from the<br />
	<b><i>service()</i></b> method. If you override <b><i>service()</i></b>, it is your reponsibility to call the appropriate methods. If you are not overridden the<br />
	service() method, based on the types of the request the methods will be called.
</p>
<h3>destroy()</h3>
<p>
	This method will be called once for a instance.	It is used for releasing any resources used by the servlet instance. Most of the times it could be<br />
	database connections, Fill IO operations, etc. <b><i>destroy()</i></b> is called by the container when it is removing the instance from the <b><i>servlet container</i></b>.<br />
	<b><i>Servlet</i></b> instance is deleted or garbage collected by the container only when the web server issues shut down or the instance is not used for a long time.
</p>
<h3>Single Thread Model</h3>
<p>
Although it is standard to have one servlet instance per registered servlet name, it is possible for a servlet to elect instead to have a pool of instances created for each of its names, all sharing the duty of handling requests. Such servlets indicate this desire by implementing the <b><i>javax.servlet.SingleThreadModel</i></b> interface. This is an empty, tag interface that defines no methods or variables and serves only to flag the servlet as wanting the alternate life cycle. A server that loads a <b><i>SingleThreadModel</i></b> servlet must guarantee, according to the <b><i>Servlet API</i></b> documentation, &#8220;that no two threads will execute concurrently the service method of that servlet.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2008/08/servlet-life-cycle/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>New Features in Servlet 3.0</title>
		<link>http://www.javabeat.net/2008/07/new-features-in-servlet-3-0/</link>
		<comments>http://www.javabeat.net/2008/07/new-features-in-servlet-3-0/#comments</comments>
		<pubDate>Thu, 31 Jul 2008 12:46:51 +0000</pubDate>
		<dc:creator>JavaBeat</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Servlets]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=214</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Servlet 3.0 The next version for servlet technology is Servlet 3.0, which is planned to be released with JEE 6.0 in the last quarter of 2008. After the release of servlet 2.5 in spetember 2005, this is the new version with many new features included. Servlet 2.5 is released with JEE 5.0. Servlet 3.0 is [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h1>Servlet 3.0</h1>
<p>
	The next version for <b><i>servlet</i></b> technology is <b><i>Servlet 3.0</i></b>,<br />
	which is planned to be released with <b><i>JEE 6.0</i></b>	in the last quarter of 2008.<br />
	After the release of <b><i>servlet 2.5</i></b> in spetember 2005, this is the new version<br />
	with many new features included. <b><i>Servlet 2.5</i></b> is released with <b><i>JEE 5.0</i></b>.<br />
	<b><i>Servlet 3.0</i></b> is maintained by the 	<a href="http://jcp.org/en/jsr/detail?id=315">JSR 315</a>.<br />
	It is already submitted to the 	sun and started working on completing the specification.<br />
	Expected to be released in the later part of 2008.
</p>
<p>
	There is many site already discussing about the new features will be introduced in the <b><i>servlet 3.0</i></b> specification.<br />
	This tips will give you an basic idea on list of features in the specification. We will not lookinto details of<br />
	the each feature. Used <b><i>JSR 315</i></b> as the reference documentation to write this tips. The following are the<br />
	list of new features in <i>servlet 3.0</i> specification request.
</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<h4>Web framework pluggability</h4>
<ul>
<li><i>Almost all of the Java based web frameworks build on top of servlets. Most web frameworks today plugin either through servlets or through web.xml. Annotations to define some of the servlets, listeners, filters will help in making this possible. Programatic access to web.xml and dynamic changes to configuration of a webapp are desired features. This JSR will aim to provide the ability to seamlessly plugin different web frameworks into web appplications</i> </li>
</ul>
<h4>EOD</h4>
<ul>
<li><i>Annotations &#8211; use of annotations for the declarative style of programming</i></li>
<li><i>As part of the EoD effort the goal is to have zero configuration for web applications. The deployment descriptors would be used to override configuration</i></li>
<li><i>Generics &#8211; Use generics in the API where possible</i></li>
<li><i>Use of other language enhancements where possible to improve the usability of the API</i></li>
</ul>
<h4>Async and Comet support</h4>
<ul>
<li><i>Non-blocking input &#8211; The ability to receive data from a client without blocking if the data is slow arriving</i></li>
<li><i>Non-blocking output &#8211; The ability to send data to a client without blocking if the client or network is slow</i></li>
<li><i>Delay request handling &#8211; The comet style of Ajax web application can require that a request handling is delayed until either a timeout or an event has occurred. Delaying request handling is also useful if a remote/slow resource must be obtained before servicing the request or if access to a specific resource needs to be throttled to prevent too many simultaneous accesses</i></li>
<li><i>Delay response close &#8211; The comet style of Ajax web application can require that a response is held open to allow additional data to be sent when asynchronous events occur</i></li>
<li><i>Blocking &#8211; Non-blocking notification &#8211; The ability to notify push blocking or non-blocking events. Channels concept &#8211; The ability to subscribe to a channel and get asyncronous events from that channel. This implies being able to create, subscribe, unsubscribe and also apply some security restriction on who can join and who cannot</i></li>
</ul>
<h4>Security</h4>
<ul>
<li><i>Ability to login / logout</i></li>
<li><i>Self registration</i></li>
</ul>
<h4>Alignment</h4>
<ul>
<li><i>Alignment / requirements from REST JSR (JSR 311)</i></li>
<li><i>Alignment / requirements from JSF 2.0 JSR</i></li>
</ul>
<h4>Misc</h4>
<ul>
<li><i>Better welcome file support</i></li>
<li><i>ServletContextListener ordering</i></li>
<li><i>Container wide definition for init params</i></li>
<li><i>File upload &#8211; progress listener &#8211; where to store interim and final file</i></li>
<li><i>Clarifications of thread-safety issues</i></li>
</ul>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2008/07/new-features-in-servlet-3-0/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
