Servlet Programming Questions & Answers

Explore model answers categorized by subjects like Java, HTML, DBMS, and more.

Servlet Programming Questions & Answers

What is a servlet ?

Answer:

Servlets are the server side programs that runs on the server allow developer to add dynamic content and hand it to the web server and web server sent back to the client. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by Web servers. For such applications, Java Servlet technology defines HTTP-specific servlet classes. Servlets provide component-based, platform-independent methods for building Web-based applications, without the performance limitations of CGI programs.

The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets. All servlets must implement the Servlet interface, which defines life-cycle methods.


Typical uses for HTTP Servlets include :


    * Processing and/or storing data submitted by an HTML form.

    * Providing dynamic content, e.g. returning the results of a database query to the client.

    * Managing state information on top of the stateless HTTP, e.g. for an online shopping cart system which manages shopping carts for many concurrent customers and maps every request to the right customer.

 

Can we use the constructor, instead of init(), to initialize servlet?

Answer:
Yes. But you will not get the servlet specific things from constructor. So do not use constructor instead of init(). The original reason for init() was that ancient versions of Java couldn\'t dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor so you won\'t have access to a ServletConfig or ServletContext. Plus, all the other servlet programmers are going to expect your init code to be in init().

What is servlet context ?

Answer:

Servlet context defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. A servlet context object is one per web application per JVM and this object is shared by all the servlet. You can get and set the Servlet context object. You can use servelt context object in your program by calling directly getServletContext() or getServletConfig().getServletContext().



What is servlet mapping?

Answer:

Servlet mapping controls how you access a servlet. Servlet mapping specifies the web container of which java servlet should be invoked for a url given by client. For this purpose web container uses the Deployment Decriptor (web.xml) file. Servlets are registered and configured as a part of a Web Application. To register a servlet, you add several entries to the Web Application deployment descriptor.


Servlet Mapping : 


<servlet>

  <servlet-name>MyServlet</servlet-name>

  <servlet-class>myservlets.MappingExample</servlet-class>

</servlet>


<servlet-mapping>

  <servlet-name>MyServlet</servlet-name>

  <url-pattern>com/*</url-pattern>

</servlet-mapping>


A developer can map all the servelts inside its web application.



What is session?

Answer:
A session refers to all the connections that a single client might make to a server in the course of viewing any pages associated with a given application. Sessions are specific to both the individual user and the application. As a result, every user of an application has a separate session and has access to a separate set of session variables. A session keeps all of the state that you build up bundled up so that actions you take within your session do not affect any other users connected to other sessions.

What Difference between GET and POST ?

Answer:

Difference between GET and POST : 

  * Client can send information to the server by two methods : GET and POST.

  * The GET method appends parameters (name/value) pairs to the URL. The length of a URL is limited, there is a character restriction of 255 in the URL.  so this method only works if there are only a few parameters.  

  * The main difference between GET and POST is, POST has a body. Unlike GET, parameters are passed in the body of the POST insteat of appending to the URL. We can send large number of data with the POST.  

  * \"GET\" is basically for just getting (retrieving) data whereas \"POST\" may involve anything, like storing or updating data, or ordering a product, or sending E-mail.

  * The data send with the GET method is visible at the browser\'s address bar. Don\'t send important and sensitive data with GET method, use POST.

  * Get is idempotent, means it has no side effects on re-requesting the same thing on the server.



What mechanisms are used by a Servlet Container to maintain session information?

Answer:

 The mechanisms used by a Servlet Container to maintain session information : 


a) Cookies


b) URL rewriting


c) Hidden form fields


d) SSL (using HTTPS protocol) Sessions



What are the different ways for session tracking?

Answer:

The concept of session tracking allows you to maintain the relation between the two successive request from the same client (browser). The browser sends the request to the server and server process the browser request generate the response and send back response to the browser. The server is not at all bothered about who is asking for the pages. The server (because of the use of HTTP as the underlying protocol) has no idea that these 2 successive requests have come from the same user. There is no connection between 2 successive requests on the Internet. 


There are three ways of tracking sessions : 

   * Using Cookies.

   * Using URL Rewriting.

   * Using Hidden Form Fields.


 

What is the difference between ServletContext and ServletConfig?

Answer:

ServletContext and ServletConfig are declared in the deployment descriptor. ServletConfig is one per servlet and can be accessed only within that specific servlet. ServletContext is one per web application and accessible to all the servlet in the web application.



How can a servlet refresh automatically?

Answer:

We can Refresh Servlet Page by two ways : one through client side and another through Server Push.


Client Side Refresh :

< META HTTP-EQUIV=\"Refresh\" CONTENT=\"5; URL=/servlet/MyServlet/\">



Server Side Refresh :

response.setHeader(\"Refresh\",5); 


This will update the browser after every 5 seconds


What is Server side push?

Answer:

The term \'server push\' generally means that a server pushes content to the browser client. Server push is a Netscape-only scheme for providing dynamic web content. Server side push is a mechanism that support real time connection to the server with the advantage of instant updates.

Server side push may be emulated in a number of ways.


    * The client polls the server at a certain interval, say every five minutes. This technique is typically used to update news information. The client does this by reloading a page every so often.

    * The client uses the \'multipart/x-mixed-replace\' content type when sending a response. The content type is expected to send a series of documents one after the other, where each one will replace the previous one. The server might delay between each part, which gives the illusion that the data is being updated after an interval. This technique requires a connection to stay open.

    

What is the Max amount of information that can be saved in a Session Object ?

Answer:
There is no limit for amount of information that can be seve into the session object. It depends upon the RAM available on the server machine. The only limit is the Session ID length which should not exceed more than 4K. If the data to be store is very huge, then it\'s preferred to save it to a temporary file onto hard disk, rather than saving it in session.

Why should we go for inter servlet communication?

Answer:

Due ot the following reason need inter servlet communication :


  * Two servlet want to communicate to complete the shopping cart.

  * One servlet handles the client request and forward it to another servlet to do some calculation or add some information to complete the view.

  * One servlet want to reuse the some methods of another servlet.

What is a output comment?

Answer:

A comment that is sent to the client in the viewable page source. The JSP engine handles an output comment as uninterpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page


source from your Web browser.

JSP Syntax

<!-- comment [ <%= expression %> ] -->


Example 1

<!-- This is a commnet sent to client on

<%= (new java.util.Date()).toLocaleString() %>

-->

What are the differences between a session and a cookie?

Answer:

Differences between a session and a cookie :

  * A cookie is a special piece of data with a bit of associated metadata that an HTTP server includes in an HTTP response. A session is a series of related HTTP requests and responses that

together constitute a single conversation between a client and server.

  * Cookies are stored at the client side whereas session exists at the server side.

  * A cookie can keep information in the user\'s browser until deleted, whereas you close your browser you also lose the session.

  * Cookies are often used to store a session id, binding the session to the user. 

  * There is no way to disable sessions from the client browser but cookies.

What is HttpTunneling?

Answer:

Encapsulating the information into the Http header and directed it to a server at the other end of the communication channel that takes the packets, strips the HTTP encapsulation headers and redirects the packet to its final destination.

HTTP-Tunnel acts as a socks server, allowing you to use your Internet applications safely despite restrictive firewalls and/or you not be monitored at work, school, goverment and gives you a extra layer of protection against hackers, spyware, ID theft\'s with our encryption. 

Reason For HTTP-Tunnel : 

    *  Need to bypass any firewall

    * Need secure internet browsing

    * Need to use favorite programs with out being monitored by work, school, ISP or gov.

    * Extra security for online transactions

    * Encrypt all your Internet traffic.

    * Need play online games

    * Visit sites that you are previously blocked

    * Prevent 3rd party monitoring or regulation of your Internet browsing and downloads

    * Use your favorite applications previously blocked

    * Hide your IP address

    * Make it next to impossible for you to identify online.

    * Free unlimited data transfer

    * Compatible with most major Internet applications

    * Secure and virus-free servers

    * 99% uptime

    * No spam, pop-ups, or banners


 In many cases it is not possible to establish a connection between JMS clients and a SwiftMQ message router or between two SwiftMQ message routers if one part stands behind a firewall. In general it exists a proxy server to which it is allowed exclusively to establish an internet connection by a firewall. To avoid this fact, an operation called HTTP tunneling is used. 


Why in Servlet 2.4 specification SingleThreadModel has been deprecated?

Answer:
Tere is no practical implementation to have such model. Whether you set isThreadSafe to true or false, you should take care of concurrent client requests to the JSP page by synchronizing access to any shared objects defined at the page level.

How can I set a cookie?

Answer:

The following program demonstrate that how to set the cookie :


import javax.servlet.*;

import javax.servlet.http.*;

public class MyServlet extends HttpServlet {

  public void doPost(HttpServletRequest request, HttpServletResponse response) {

    response.addCookie(new Cookie(\"cookie_name\", \"cookie_value\"));

    }

    

  public void doGet(HttpServletRequest req, HttpServletResponse res) {

    doPost(req, res);

    }

}


How will you delete a cookie?

Answer:

To delete cookie from servlet, get the cookie from the request object and use setMaxAge(0) and then add the cookie to the response object. 

    

     Cookie killMyCookie = new Cookie(\"mycookie\", null);

     killMyCookie.setMaxAge(0);

     response.addCookie(killMyCookie);


What is the difference between Context init parameter and Servlet init parameter?

Answer:

Context init parameter is accessible through out the web application and declared outside the <servlet>...</servlet> element tag in the deployment descriptor(DD) . Servlet init parameters are declared inside the <servlet>...</servlet> element and only accessible only to the that specific servlet. You can access the context init parameters using the getServletContext() method and Servlet init parameters using the getServletConfig() method. 


Declaring the Servlet init parameter in DD :

 

<servlet>  

   <servlet-name>My Page</servlet-name>

   <sevlet-class>/mypage</servlet-class>  

   <init-param>  

      <param-name>email</param-name>  

      <param-value>jalees786@gmail.com</param-value) </init-param>

</servlet>


Declaring the Context init parameter in DD :


<context-param>  

<param-name>webmaster</param-name>  

<param-value>jalees786@gmail.com</param-value>

</context-param> 



What are the different ways for getting a servlet context?

Answer:

The different ways for getting a servlet context :


  * ServletConfig.getServletContext()

  * GenericServlet implements ServletConfig, so HttpServlets all have a getServletContext() method

  * In a Filter you have access to the FilterConfig which is set in the init(FilterConfig fc) callback. You can use FilterConfig.getServletContext().

  * In a ServletContextListener or a ServletContextAttributeListener, the event passed to the listener methods has a getServletContext() method. 

What is the difference between an attribute and a parameter?

Answer:

Request parameters are the name/value pairs, and the result of submitting an HTML form. The name and the values are always strings. For example, when you do a post from html, data can be automatically retrieved by using request.getParameter() at the server side. Parameters are Strings, and generally can be retrieved, but not set. 

Attributes are objects, and can be placed in the request, session, or context objects. Because they can be any object, not just a String, they are much more flexible. You can also set attributes programatically using setAttribute() method, and retrieve them later using getAttribute() method.

How to make a context thread safe?

Answer:
To make the context scope thread safe, you need a lock on context object. To synchronize the context attribute is to synchronize on context object. If a thread gets a lock on context object, then you are guaranteed that only one thread at a time can be getting or setting the context attribute. It only works if all of the other code that manipulate the context attribuet also synchronizes on the servlet context.

What is the difference between setting the session time out in deployment descriptor and setting the time out programmatically?

Answer:

Setting the time out programmatically means calling setMaxInactiveInterval(int seconds) from your servlet.

Setting the session time out in deployment descriptor means declaratively setting the session timeout. The following setting in the deployment descriptor causes the session timeout to be set to 10 minutes:

<session-config>

<session-timeout>10</session-timeout>

</session-config> 


Setting the session time out in deployment descriptor allows you to modify the time easily, hard code it into the program requires recompilation overhead.

How can my application get to know when a HttpSession is removed?

Answer:

To get notified that a HttpSession is removed or created, you should implement the HttpSessionBindingListener in the class that implements the two of its method : sessionCreated() and sessionDestroyed(). If a session is created or destroyed, the  sessionCreated() or sessionDestroyed() method respectively will be called automatically. You must register this listener implementing class inside the <listener>...</listener> element in the deployment descriptor(web.xml) file.


How many cookies can one set in the response object of the servlet? Also, are there any restrictions on the size of cookies?

Answer:
A cookie has a maximum size of 4K, and no domain can have more than 20 cookies.

When a session object gets added or removed to the session, which event will get notified ?

Answer:

When an object is added or removed from a session, the container checks the interfaces implemented by the object. If the object implements the HttpSessionBindingListener, the container calls the matching notification method. 

If session is added then sessionCreated() method, and if session is removed then sessionDestroyed() method will be callled automatically by the web container.

What is URL Encoding and URL Decoding ?

Answer:

Some characters are not valid in URLs like & can\'t be placed in a URL query string without changing the meaning of that query string.


These problems can be be fixed by \'escaping\' them. This process involves scanning the text for those characters, and replacing them with a special character-code that browsers can interpret as the correct symbol, without actually using that symbol in your URL.


For example, the escaped character code for \'=\' is \'%3d\'. 



What is the difference between an applet and a servlet?

Answer:

Applets are client side java program that are dynamically downloaded over the internet and executed by browser. Servlets are server side program runs on the server. When a request come to server for the specific servlet, then servlet handles the client request, and send response back to the client. 

Servlet doesn\'t have GUI , while applet have GUI. Applet are very heavy to handle as compared to servlet.



What is life cycle of servlet?

Answer:

A web container manages the life cycle of the servlet :


  * Loading and Inatantiation: container load the servlet class at the first request to that servlet. The loading of the servlet depends on the attribute <load-on-startup> of web.xml file. Instantiation is done by calling the default constructor.

  * Initialization: calling the init() method.

  * Servicing the Request: calling the service() method and pass the HttpServletRequest and HttpServletResponse object as the parameters.

  * Destroying the Servlet: calling the destroy() method.

When init() and Distroy() will be called.

Answer:

Both init() and destroy() method called only once within its lifecycle.

The init() method will be called after instantaition of servlet, i.e. after the constructor calling. The destroy() method will be called when servlet is removed from the server, i.e. when server shuts down.

What is the use of setComment and getComment methods in Cookies ?

Answer:

A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. 


The setComment(java.lang.String purpose) method Specifies a comment that describes a cookie\'s purpose.The getComment() method returns the comment describing the purpose of the cookie, or null if the cookie has no comment.



Why we are used setMaxAge() and getMaxAge() in Cookies ?

Answer:

The \"public void setMaxAge(int expiry)\" method sets the maximum age of the cookie. After the specified time the cookie will be deleted.


The \"public int getMaxAge()\" method will return the maximum specified age of the cookie.



What is the use of setSecure() and getSecure() in Cookies ?

Answer:

The setSecure(boolean flag) method indicates to the browser whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL.

The getSecure() method returns true if the browser is sending cookies only over a secure protocol, or false if the browser can send cookies using any protocol.



How do you communicate between the servlets?

Answer:
Servlets can communicate using the request, session and context scope objects by setAttribute() and getAttribute() method. A servlet can placed the information in one of the above scope object and the other can find it easily if it has the reefrence to that object.

What is Servlet chaining?

Answer:

Servlet Chaining is a phenomenon wherein response Object (Output) from first Servlet is sent as request Object (input) to next servlet and so on. The response from the last Servlet is sent back to the client browser.

In Servlets, there are two ways to achieve servlet chaining using javax.servlet.RequestDispatcher:


   1. Include:


    RequestDispatcher rd = req.getRequestDispatcher(\"Servlet2\");

      rd.include(req, resp);


   2. Forward, where req is HttpServletRequest and resp is HttpServletResponse:


    RequestDispatcher rd = req.getRequestDispatcher(\"Servlet3\");

      rd.forward(req, resp);


How will you communicate from an applet to servlet?

Answer:

You can write a servlet that is meant to be called by your applet. 

Applet-Servlet Communication with HTTP GET and POST : 

The applet can send data to the applet by sending a GET or a POST method. If a GET method is used, then the applet must URL encode the name/value pair parameters into the actual URL string.

Communicating with Object Serialization :

Instead of passing each parameter of student information as name/value pairs, we\'d like to send it as a true Java object. Upon receipt of the this object, the servlet would add the this to the database.

Sending Objects from a Servlet to an Applet : 

After registering the object in the database. Now the servlet has to return an updated list of registered students that is then returned as a vector of  objects.

Can we call a servlet with parameters in the URL?

Answer:
Yes! We can call a servlet with parameters in the URL using the GET method. Parameters are appended to the URL separated with the \'?\' with the URL and if there are more than one parameter, these are separated with the \'&\' sign.

How do servlets handle multiple simultaneous requests?

Answer:
Servlets are under the control of web container. When a request comes for the servlet, the web container find out the correct servelt based on the URL, and create a separeate thread for each request. In this way each request is processed by the different thread simultaneously. 

Explain the directory structure of a web application?

Answer:

The directory structure of a web application consists of two parts.

A private directory called WEB-INF

A public resource directory which contains public resource folder.


WEB-INF folder consists of

1. web.xml file that consist of deployment information.

2. classes directory cosists of business logic.

3. lib directory consists of jar files.

What is pre initialization of a servlet?

Answer:
Servlets are loaded and initialized at the first request come to the server and stay loaded until server shuts down. However there is another way you can initialized your servlet before any request come for that servlet by saying <load-on-startup>1</load-on-startup> in the deployment descriptor. You can specify <load-on-startup>1</load-on-startup> in between the <servlet></servlet> tag.

What are the uses of ServletRequest?

Answer:

ServletRequest defines an object to provide client request information to a servlet. The servlet container creates a ServletRequest object and passes it as an argument to the servlet\'s service method.


A ServletRequest object provides data including parameter name and values, attributes, and an input stream. Interfaces that extend ServletRequest can provide additional protocol-specific data (for example, HTTP data is provided by HttpServletRequest. 


Packages that use ServletRequest :

  * javax.servlet  

  * javax.servlet.http  

  * javax.servlet.jsp

What are the uses of ServletResponse interface?

Answer:

ServletResponse interface defines an object to assist a servlet in sending a response to the client. The servlet container creates a ServletResponse object and passes it as an argument to the servlet\'s service method.

To send binary data in a MIME body response, use the ServletOutputStream returned by getOutputStream(). To send character data, use the PrintWriter object returned by getWriter(). To mix binary and text data, for example, to create a multipart response, use a ServletOutputStream and manage the character sections manually. 


Packages that use ServletResponse : 

  * javax.servlet  

  * javax.servlet.http  

  * javax.servlet.jsp  

  

How HTTP Servlet handles client requests?

Answer:

HTTP Servlet is an abstract class that must be subclassed to create an HTTP servlet suitable for a Web site. A subclass of HttpServlet must override at least one method, usually one of these: 

  * doDelete(HttpServletRequest req, HttpServletResponse resp) :  Called by the server (via the service method) to allow a servlet to handle a DELETE request.

  * doGet(HttpServletRequest req, HttpServletResponse resp) :  Called by the server (via the service method) to allow a servlet to handle a GET request.

  * doOptions(HttpServletRequest req, HttpServletResponse resp) :  Called by the server (via the service method) to allow a servlet to handle a OPTIONS request.

  * doPost(HttpServletRequest req, HttpServletResponse resp) :  Called by the server (via the service method) to allow a servlet to handle a POST request.

  * doPut(HttpServletRequest req, HttpServletResponse resp) :  Called by the server (via the service method) to allow a servlet to handle a PUT request.

  * doTrace(HttpServletRequest req, HttpServletResponse resp) :  Called by the server (via the service method) to allow a servlet to handle a TRACE request. etc.

  

Is HTML page a web component?

Answer:

No! Html pages are not web component, even the server-side utility classes are not considered web components. Static HTML pages and applets are bundled with web components during application assembly, but are not considered web components by the J2EE specification.



What is the web container?

Answer:

The Web container provides the runtime environment through components that provide naming context and life cycle management, security and concurrency control. A web container provides the same services as a JSP container as well as a federated view of the Java EE. Apache Tomcat is a web container and an implementation of the Java Servlet and JavaServer Pages technologies.


What is deployment descriptor?

Answer:

Deployment descriptor is a configuration file named web.xml that specifies all the pieces of a deployment. It allows us to create and manipulate the structure of the web application. Deployment descriptor describes how a web application or enterprise application should be deployed. For web applications, the deployment descriptor must be called web.xml and must reside in a WEB-INF subdirectory at the web application root. Deployment descriptor allows us to modify the structure of the web application without touching the source code.



Do objects stored in a HTTP Session need to be serializable? Or can it store any object?

Answer:
It\'s important to make sure that all objects placed in the session can be serialized if you are building a distributed applicatoin. If you implement Serializable in your code now, you won\'t have to go back and do it later. 

How can you implement singleton pattern in servlets ?

Answer:

Singleton is a useful Design Pattern for allowing only one instance of your class. you can implement singleton pattern in servlets by using using Servlet init() and <load-on-startup> in the deployment descriptor.


What is the difference between an application server and a web server?

Answer:

A web server deals with Http protocols and serves the static pages as well as it can ask the helper application like CGI program to generate some dynamic content. A web server handles the client request and hands the response back to the client.

An application server exposes business logic to client applications through various protocols, possibly including HTTP. An application server provides access to business logic for use by client application programs. In addition, J2EE application server can run EJBs - which are used to execute business logic. An Application server has a \'built-in\' web server, in addition to that it supports other modules or features like e-business integration, independent management and security module, portlets etc.


What is servlet exception?

Answer:

ServletException is a subclass of the Exception. It defines a general exception a servlet can throw when it encounters difficulty. ServletException class define only one method getRootCause() that returns the exception that caused this servlet exception. It inherit the other methods like fillInStackTrace, getLocalizedMessage, getMessage, printStackTrace, printStackTrace, printStackTrace, toString etc from the Throwable class.

Packages that use ServletException :

  * javax.servlet

  * javax.servlet.http

 

What is a WAR file?

Answer:

A Web archive (WAR) file is a packaged Web application. WAR files can be used to import a Web application into a Web server. The WAR file also includes a Web deployment descriptor file. There are special files and directories within a WAR file. The /WEB-INF directory in the WAR file contains a file named web.xml which defines the structure of the web application. If the web application is only serving JSP files, the web.xml file is not strictly necessary. If the web application uses servlets, then the servlet container uses web.xml to ascertain to which servlet a URL request is to be routed. One disadvantage of web deployment using WAR files in very dynamic environments is that minor changes cannot be made during runtime. WAR file is created using the standard Java jar tool. For example:


    cd /home/alex/webapps/mywebapp 

    jar cf ../mywebapp.war * 

What is a servlet filter?

Answer:

A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses. Filters typically do not themselves create responses, but instead provide universal functions that can be \"attached\" to any type of servlet or JSP page. Filters provide the ability to encapsulate recurring tasks in reusable units and can be used to transform the response from a servlet or a JSP page. Filters can perform many different types of functions:

  * Authentication

  * Logging and auditing

  * Data compression

  * Localization


The filter API is defined by the Filter, FilterChain, and FilterConfig interfaces in the javax.servlet package. You define a filter by implementing the Filter interface. A filter chain, passed to a filter by the container, provides a mechanism for invoking a series of filters. Filters must be configured in the deployment descriptor :


<!--Servlet Filter that handles site authorization.-->

<filter>

     <filter-name>AuthorizationFilter</filter-name>

     <filter-class>examples.AuthorizationFilter</filter-class>

     <description>This Filter authorizes user access to application components based upon request URI.</description>

     <init-param>

        <param-name>error_page</param-name>

        <param-value>../../error.jsp</param-value>

     </init-param>

</filter>


<filter-mapping>

     <filter-name>AuthorizationFilter</filter-name>

     <url-pattern>/restricted/*</url-pattern>

</filter-mapping>


What is Web resource ?

Answer:
Web Resource is bassically a Static or dynamic object, Which is contained in a Web application that can be referenced by a URL. 

I plugged in a version of Apache Xalan that I downloaded from the Apache Web site, and now I get errors when I try to transform documents. What is the problem?

Answer:
We must ensure that the version of Apache Xalan we download from the Apache Web site is compatible with Apache Xerces version 1.3.1. Because we can\'t plug in a different version of Apache Xerces , the only version of Apache Xerces that is compatible with WebLogic Server 6.1 is 1.3.1. The built-in parser and transformer have been modified by BEA to be compatible with each other.

What is Web server ?

Answer:
Web server is type of Software, Its use for the providing to the many type of services like access the Internet, an intranet, or an extranet. A Web server hosts Web sites, provides support for HTTP and other protocols, and executes server-side programs that perform certain functions.

GET and POST

Answer:
A client connects to a server and makes an HTTP reqest, The most freqesntly used method which is used for the Get and POST,GET method is designed for getting information while the POST method is designed for posting information.The Get method although it�s designed for reading information, can include as part of the request some of its own information,This information is passed as a
sequence of characters appended to the request URL in what�s called a query string. Placing the extra information in the URL in this way allows the page to be bookmarked or emailed like any other. Because GET requests theoretically shouldn�t need to send large amounts of information, some servers limit the length of URLs
and query strings to about 240 characters.its manily use for teh diff diff technique.GEt reqest is bassiclay well�why not, it works! Generally, this isn�t much of a problem. Just remember that GET requests, because they can be bookmarked so easily, should not be allowed to cause damage for which the client could be held responsible. In other words, GET requests should not be used to place an order, update a database, or take an explicit client action in any way.

History of Web Application

Answer:
Servlet basically use for the extend to the functionality of any server which server already enabled by the java server..

Servlet also used to create a dynamic contents create for the web pages and extend the functionality of the web server.its also use for the something changes in the web application.that  the reason web application provides a more interactive experience.

Power

Answer:
Servlet is a very important for the java language .its mianly full power of the core java API\'s :

networking and URL access.multimethod , image manipulation , data compression, database connectivity, and object serialization among others

We can use of the JNDI API.its a mainly third-party java classes and java beans component. We\'ll even be able to use newly introduced Enterprise JavaBeans components.its a servlet can use the third party code to handle tasks such as regular expression seacrhing which are following here 

:> data charting, > advanced database access, and > advanced networking.

Common Gateway Interface

Answer:
The Common Gateway Interface basically stands for the CGI. its a first practical technique for the dynamic content. is web server passes certain request for the external program the out of the application is sent by the client in place of a static file.CGi is only that technique which is make a possible to implement all sorts of new functionalities in a web pages and its quickly became to the fact standard and also implement on many we servers. its a very important functionality of the CGI . its program to create dynamic web pages is a side effect of its intended purpose  which is define there  : 

 > its standard method for an information server to talk with external application. 

> this life cycle is not so good its have a worst lif cycle. when server recives a reqest that access a CGI program its much crate a program for the new process to run the CGI prog.and the pass it for the environment variable and standard in put .

Portability

Answer:
its portable because servlet written i the java programming language and confirm to a well defined and widely accepted API.its a mainly highly portable system and across server implementation.we can develop on a servlet on a Windows NT machine running the java Web Server,its a portable but its not the stumbling block it so often is with applets, for two reasons. First, servlet portability is not mandatory.

Unlike applets, which have to be tested on all possible client platforms, servlets have to work only on the server machines that we are using for development and deployment.the Abstract Windowing Toolkit (AWT) that forms the basis of Java graphical user interfaces.

FastCGI

Answer:
CGI bassically a name in the market is FastCGI.its name to CGI given by the company . this is for the open market develope and fo the alterative to standerd CGI.its working just like as CGI.but litl bit is diff and its most imp diff.FastCGI creates a single persistant process for each FastCGI programe.

Extensibility and Flexibility

Answer:
The servlet API is designed to be easily extensible. Its mainly includes API classes that ate optimized for HTTP servlet.It is also possible that its support for HTTP servlets could be further enhanced.Servlets are also quite flexible. As we�ll see in the next chapter, an HTTP servlet can be used to generate a complete web page; it can be added to a static page
using a  tag.

mod_perl

Answer:
mod_perl basically use for the improving the performance of CGI.Its is module of the Apache server.its the embedded a copy of the Perl interpreter in to the Apache http executable its mainly provide the  access to Perl functionality ith in Apache.its only for the effect is that our CGI script are precompiled by the server,and its execute with out forking 

PerlEx

Answer:
PerlEx is basically developed by ActiveState, its only use for the improves the performance of CGI scripts, Which ocde is written by the perl language.that run on Windows NT web servers , PerlEx uses the web server�s native API to achieve its performance gains.

Integration

Answer:
Servlet basically very tightly integrated with the server.its mainly allow a servlet to cooperate in ways that a CGI prog.Server-specific extensions can do much of this, but the process is usually much more complex and error-prone.

Elegance

Answer:
its basically a servlet code is striking.This code is very clean and object oriented.modular, and amazingly simple.Even advanced operations, like cookie handling and session tracking, are abstracted into convenient classes.

Server Extension APIs

Answer:
Every where creates proprietary server extension APIs for their web servers. For example, Netscape providing an internal API called NSAPI and Microsoft provides ISAPI. Using one of these APIs, can write server extensions that enhance or change the base functionality of the server,allowing the server to handle tasks that were once relegated to external CGI programs.server extensions exist within the main process of a web server. Because server-specific APIs are basically linked as the C or C++ code, server extensions can run extremely fast and make full use of the server�s resources. Server extensions, Besides being difficult to develop and maintain, they pose significant security and reliability hazards: a crashed server extension can bring down the entire server.

Active Server Pages

Answer:
Microsoft basically developed a technique for generating dynamic web content, Which is called  Active Server Pages and its also called in the java programming language JSP.

ASP, an HTML page on the web server can contain snippets of embedded code. Which code is mainly use for the read and executed by the web server before it sends the page to the client. ASP is optimized for generating small portions of dynamic content.

Safety

Answer:
servlet is only component in the java programming which is make a program very safe because its written in java .servet is basically  a inherit the strong type safely of the java language/In this addition the servlet API is implemented to the type safe.its a very most important value in a CGI program its include the numeric values .its a similar type of server port no.

Efficiency and Endurance

Answer:
Servlet invocation is basically a heighly efficient .its normally a servlet is loaded.its generally remains in the server\'s memory as a single object instance.here server invokes the servlet to handle a request using a simple, lightweight method invocation\'s no process to spawn or interpreter to invoke , so the servlet can begin handling the request almost immediately. 

Servlet is basically are are naturally enduring objects. Because a servlet stays in the server�s memory as a single object instance, it automatically maintains its state andcan hold on to external resources, such as database connections, that may otherwise take several seconds to establish.

Server-side JavaScript

Answer:
Netscape is basically a technique its use for the server-side scripting, which is calls server-side JavaScript,and in the jaava programming language its also called as SSJS . 

Like ASP, SSJS basically use for the allow snippets of code to be embedded in HTML pages to generate dynamic web content. The difference is that SSJS uses JavaScript as the scripting language. With SSJS, web pages are 

precompiled to improve performance.

Java Servlets

Answer:
A servlet basically a generic server extension,its mainly use for the Java class that can be loaded dynamically to expand the functionality of a server, its a normally us with the web server. it can be place of CGI scripts. Its basiclay similar as a proprietary server extension

its except that ts run inside a Java Virtual Machine (JVM) on the server. thats why we can say that its safe and portable/its operate slowly with in th domain of te server.unlike applets, they do not require support for Java in the web browser.CGI and FastCGI which use multiple processes to handle separate programs and/or separate requests, servlets are all handled by separate threads within the web server process. its means that the servlet are also efficient and the scalable. because servlet run with in the web server.its can run very closely to the server.

Requests, Responses, and Headers

Answer:
Http is basically a simple and stateless protocol.its a client when such as a web browser its makes request the web server response and the transaction is done.when the client sends the request the first thing it specifies is an HTTP command called a method.and call the server the type of action it wants performed .

Support for Servlets

Answer:
Servlet is mainly designed for the portability.its also supported for all plateform which is also supports for java.its also work with all the major web server.java servlet is basically defined by the java s/w division of Sun Microsystem .and the first standard extension of sun microsystem .Its basically means that officially blessed by Sun and are part of the Java language, but they are not part of the core Java API.Sun has made publicly available a set ofclasses that provide basic servlet support. 

The javax.servlet and javax. servlet.http packages constitute this Servlet API. Version 2.0 of these classes comes bundled with the Java Servlet Development Kit (JSDK) for use with the JavaDevelopment Kit version 1.1.

Standalone Servlet Engines

Answer:

its a type of engine which is basically use for the servlet.its only support of the servlet.Engine has a 1 advantages its help foe everything works right out of the box.its  have a one disadvantage also .We have to wait for a new release of the web server to get the latest servlet support. Because servlets are still fairly new, this sort of server is still a bit of a rarity. As the various vendors upgrade their web servers, we expect that many of the servers will provide built-in support for servlets.this engines have a e extra qualities which is following here  : 

> Sun�s Java Web Serverunofficially considered the

reference implementation for how a servlet engine should support servlets. 

> The World Wide Web Consortium�s Jigsaw Server.

> Netscape�s Enterprise Server the most popular web server to provide built-in servlet support.

> Lotus�s Domino Go Webserver another popular web

server with built-in servlet support. Version 4.6.x supports only the early Servlet API 1.0; however, Lotus claims to be replacing its proprietary GWAPI server extension technology with Java servlets.

HTTP Basics

Answer:
HTTP bassiclaly a server side web programming.its very saftly skip this values. We might skim it to refresh our memory about the finer points of the GET and POST methods. If we are new to the world of server-side web programming,Its mainly use for the Web Client Programming . 

Add-on Servlet Engines

Answer:
its a type of pluginfor the existing server.its adds support to a server that was not originally designed with servlets in mind.Add-on servlet engines have been written for many servers including Apache,
Netscape’s FastTrack Server and Enterprise Server, Microsoft’s Internet Information
Server and Personal Web Server, O’Reilly’s WebSite, Lotus Domino’s Go Webserver, StarNine’s WebSTAR, and Apple’s AppleShare IP. This type of engine acts as a stopgap solution until a future server release incorporates servlet support.
         Its have a some properties which is foloowing here : 
> The Java-Apache project’s JServ module, a freely available servlet engine that
adds servlet support to the extremely popular Apache server.
> Live Software’s JRun, a freely available plug-in designed to support the full
Servlet API on all the popular web servers on all the popular operating systems.
> IBM’s WebSphere Application Server a plug-in that is being called an application server. It is designed to support the full Servlet API on several popular web servers on several popular operating systems.
> New Atlanta’s ServletExec, a plug-in designed to support the full Servlet API on several web servers on several operating systems.
> Gefion Software’s WAICoolRunner, a freely  available plug-in that supports most of the Servlet API on Netscape’s FastTrack Server and Enterprise Server versions 3.x and later, written in Java using Netscape’s WAI interface.
 

Embeddable Servlet Engines

Answer:
An Embedded engine is bassiclaly a lightweight servlet its development platform that can be anther application.its mainly become true server.its include the following : 
> Sun’s JavaServer Engine, a high-quality, high end framework for designing and building Java servers.
> Jef Poskanzer’s Acme.Serve, a freely available, simple web server that runs servlets “more or less compatible” with the Servlet API.
> Paralogic’s WebCore, a freely available but unsupported embeddable web server, written entirely in Java.

The Power of Servlets

Answer:
itsbassically a protraped as an alternative to other dynamic web content.its mianly offer a number of advantages over other apporoches : 
> portability
> power
> efficiency
> endurance
> saftey
> elegance
> integration
> flexibility

The Servlet API

Answer:
here we would like to discuss about the HTTP we can can move on and talk about the Servlet API that we'll using the create HTTP servlet or any kind of the using the two packages which are following here  : 
>  javax.servlet : This is bassically use the clases support only its generic , protocol independent servlet,
>  javax.servlet.http : These classes are
extended by the classes in the javax.servlet.http package to add HTTPspecific functionality.Every servlet must implement the javax.servlet.Servlet interface.extending one of two special classes : 
> javax.
> servlet.
> GenericServlet
> javax.servlet.http.HttpServlet
        

Writing Hello World

Answer:
We have an progrmae where we generate a Html page which is showing the HTTP servlet.this servlet says HELLO WORLD every time wen we access the brouwer.code is here  : 
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
 We have a secound programe which is a servlet who prints "Hello World"
out.println("");
out.println("Hello World");
out.println("");
out.println("Hello World");
out.println("");
}
}
            this servlet is bassically extends the HTTPServet,and overrides the doGet() method.this ethod is bassiclay use for the sendig  reqest to the server every time for this servlet.and the server incodes this method and passing it an HttpServletRequest object and an HttpServletResponse object.Which is represent tot he lient reqest.its object gives the nfo about the client.
          The HttpServletResponse represents the servlet’s response. A servlet can usethis object to return data to the client. This data can be of any content type, though the type should be specified as part of the response. A servlet can also use this object to set HTTP response headers.

Running Hello World

Answer:
When the develope the servlet its should have to two things : 
> API Class : Which is use for the compiling.and 
> the servlet Engine : as a web server its use for the deployemnt .
       the Servlet API class files, we have several options : 
> Install the Java Servlet Development Kit (JSDK), available for free at http://java.
sun.com/products/servlet/. JSDK Version 2.0 contains the class files for the Servlet
API 2.0, along with their source code and a simple web server that acts as aservlet engine for HTTP servlets. It works with JDK 1.1 and later. 
> Install one of the many full-featured servlet engines, each of which typically bundles the Servlet API class files.

Handling Form Data

Answer:
THe Hello World is not very exciting we 'll try to do somwthing new in ths code.


Introductions


If you don't mind I am asking, what is your good name?

The output of this code is sppear like this : IF If you don't ------------------------------- mind I am asking,| | what is your good| | name? ------------------------------- When the user submitt this details the from our code his/her name sent to the hello servlet becouse we’ve set the ACTION attribute to point to the servlet. The form is using the GET method, so any data is appended to the request URL as a query string. For example, if the user enters the name “Inigo Montoya,” the request URL is http:// server:8080/servlet/Hello?name=Inigo+Montoya. The space in the name is specially encoded as a plus sign by the browser because URLs cannot contain spaces.

Handling POST Requests

Answer:
Whne we would like to use the doGet() method then we know get two servlets.thats y we can change the Hello Servlt to that it can handle POST rqests as well.becouse we want to the same behavior with post as a GET.
    public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doGet(req, res);
}
Now the Hello servlet can handle form submissions that use the POST method:

Handling HEAD Requests

Answer:
A bet under teh covers magic makes it trivial to Handle HEAD Reqest.there is not method for the dead reqest like we know that dodead() mehtod.Any servlet that subclasses HttpServlet and implements
the doGet() method automatically supports HEAD requests,

Server-Side Includes

Answer:
All the servlets e know that the each and every thing is HTML pages .it would be so still plenty .its servlet can also be embeded inside HTML pages with something called server-side include (SSI) functionality..



If you see this text, it means that the web server
providing this page does not support the SERVLET tag.

             The code is attribute is psecialy specifies the class name or resisterd anme of the servlet to invoke.its code base attribute is optional.its servlet assume to be local.A server that supports SSI detects the  tag in the process of returning the page and substitutes in its place the output from the servlet.

Writing a Server-Side Include

Answer:
It is bassiclaly a very usefull contenct becuse the when its pages is primilalry static but its contain a few distinct dynamic portios.its assume we have to several pages that need to apply for the courrent time.The problem is easy with server-side includes. Each page can be written as a static HTML page with one or more SSI directives that call Java code to provide the times. The HTML could look something like this, saved to a file with an .shtml
extension:

Times!

The current time here is:


The current time in London is:

And the current time in New York is:

Servlet Chaining and Filters

Answer:
We can individual servlet can create content by generating a full page or by being used in a server-side include. Servlets can also cooperate to create content in a process called servlet chaining.
we know that the many servers that supports the servlets ,its reqest basscilaly can handle by the seqence of servlets .its frm the client brower is sent to by the first servlet i the chain.There are two common ways to trigger a chain of servlets for an incoming request. First, we can tell the server that certain URLs should be handled by an explicitly specified chain. we can tell the server to send all output of a particular
content type through a specified servlet before it is returned to the client, effectively
creating a chain on the fly. When a servlet converts one type of content into another, the technique is called filtering.
> Quickly change the appearance of a page, a group of pages, or a type of content.
> Take a kernel of content and display it in special formats,
> Support esoteric data types.

Creating a Servlet Chain

Answer:
Our first servlet chain example removes  tags from HTML pages. If you’re
not familiar with the  tag, be thankful. It is a tag recognized by many browsers in which any text between the  and  tags becomes a flashing distraction. Sure, it’s a useful feature when used sparingly. The problem is that many page authors use it far too often. It has become the joke of HTML.

Running Deblink

Answer:
firstly we would like to runn the Seblink the we are using the Java Wen Server the we should want to servlet chain enable .Go to managing the Web Service, go to the Setup section, select Site, and then select Options.
               there are two ways to trigger a servlet chain. A chain can be explicitly specified for certain requests, or it can be created on the fly when one servlet returns a content type that another servlet is registered to handle. We’ll use both techniques to run Deblink.First, we’ll explicitly specify that all files with a name matching the wildcard pattern *.html should be handled by the file servlet followed by the Deblink servlet. The file servlet is a core Java Web Server servlet used to retrieve files. Normally it is the only servlet invoked to return an HTML file. But here, we’re going to pass its output to Deblink before returning the HTML to the client. Go back to managing the Web Service, go to the Setup section, and select Servlet Aliases.

The Loophole

Answer:
its a basscilaly a technique.its not a html file with the html extension.We really want to specify that all text/html content should pass through the
Deblink servlet. The JavaServer Administration Tool does not yet include a graphical way to do this. Instead, we can make the change with a simple edit of a properties file. The properties file can be found at server_root/properties/server/
javawebserver/webpageservice/mimeservlets.properties. It contains directives like this:
java-internal/parsed-html=ssinclude
          To specify that all text/html content is passed through Deblink, we need to add
our own directive:
             text/html=Deblink

The Servlet Alternative

Answer:
The servlet Life Cycle is basiclaly aloows tot he servlet enines whihc is very use full for it .its use for the addereed both the performance and
resource problems of CGI and the security concerns of low-level server API programming. its may execute all its servlets in a single Java virtual machine (JVM). Because they are in the same JVM, servlets can efficiently share data with each other, yet they are prevented by the Java language from accessing one another’s private data. Servlets may also be allowed to persist between requests as object instances, taking up far less memory than full-fledged processes. we have a main important thing is that a servlet engine must conform to the following life cycle contract:
1. Create and initialize the servlet.
2. Handle zero or more service calls from clients.
3. Destroy the servlet and then garbage collect it.

A Single Java Virtual Machine

Answer:
Sngle Java Virtual Machine is very important for the Servlet Engines becouse all Ervlet Egines want to execute all servlet in a single JVM,When the server written in the java its only depend on the server.its called the java Web Server.IN a single process we would like to use the multiple web server then we chould be wite in another language .JVM be part of the server process maximizes performance because a servlet becomes, in a sense, just another low-level server API extension. Such a server can invoke a servlet with a lightweight context switch and can provide information about requests throughdirect method invocations.

Instance Persistence

Answer:
Now a days the code for a servlet is loaded, the server creates a single class instance. That single instance handles every request made of the servlet. This improves performance in three ways : 
> It keeps the memory footprint small.
> It eliminates the object creation overhead that would otherwise be necessary to create a new servlet object. A servlet can be already loaded in a virtual machine when a request comes in, letting it begin executing right away.
> It enables persistence. A servlet can have already loaded anything it’s likely to need during the handling of a request. For example, a database connection can be opened once and used repeatedly thereafter. It can even be used by a group of servlets. Another example is a shopping cart servlet that loads in memory the price list along with information about its recently connected clients. Yet another servlet may choose to cache entire pages of output to save time if it receives the same request again.

A Simple Counter

Answer:
For the dicussing Servet Life Cycle we have an exmaple which is shows that the counts and displays the number of times it has been accessed. the programe is following here  : 
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SimpleCounter extends HttpServlet {
int count = 0;
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
count++;
out.println("Since loading, this servlet has been accessed " +
count + " times.");
}
}
           Followng code is so simple its use only for the prnt and increment the instance variable which named is count.but its also shows the most important things is power of persistence.

A Simple Synchronized Counter

Answer:
Servlet Developers thingking is that all clients is alike a another thread which is calls the servlet via then following things : 
> service()method
> doGet()method
> doPost() method,if our servlets doing these three works eaisly then we need not worry about the interaction among these threads, works is there : 
> read from the request,
> write to the response,
> save information in local variables,
                

A Holistic Counter

Answer:
one instance per servlet” model is a bit of a gloss-over,Its main point is that each registered name for a servlet is associated with one
instance of the servlet. The name used to access the servlet determines which instance handles the request. This makes sense because the impression to the client should be that differently named servlets operate independently. Our SimpleCounter uses the count instance variable to track the
number of times it has been accessed. If, instead, it needed to track the count for all instances it can in some cases use a class, or
static, variable. These variables are shared across all instances of a class.

Servlet Reloading

Answer:
Servlet bassiclaly using the counters its mainly use for the anytime werecompiled one its count automtically began again 1.its a advantages of the application its not a bug, many servers are automatilaly reload the servlets after its class file.Servlet reloading may appear to be a simple feature, but it’s actually quite a trick—
and requires quite a hack. ClassLoader objects are designed to load a class just once. To get around this limitation and load servlets again and again, servers use custom class loaders that load servlets from the default servlets directory. This explains why the servlet classes are found in erver_root/servlets, even though that directory doesn’t appear in the server’s classpath.

Init and Destroy

Answer:
these methods are same as applets and servlet.A servlet init method is called by the server immediately after the server constructs the servlet’s instance. Depending on the server and its configuration, this can be at any of these times:
> When the server starts.
> When the servlet is first requested, just before the service() method is invoked
> At the request of the server administrator
               In any case, init() is guaranteed to be called before the servlet handles its first
request. 

A Counter with Init

Answer:
INit method is very omportant for the servlet becouse it can be use anything , its specifies only the initial value but its alos use for the default vaue for the sevlet variables and also they tell a servlet how to customize its behavior in some way.
We have a example which is shows somethng about the INIT() method : 
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class InitCounter extends HttpServlet {
int count;
public void init(ServletConfig config) throws ServletException {
super.init(config);
String initial = config.getInitParameter("initial");
try {
count = Integer.parseInt(initial);
}
catch (NumberFormatException e) {
count = 0;
}
}
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
count++;
out.println("Since loading (and with a possible initialization");
out.println("parameter figured in), this servlet has been accessed");
out.println(count + " times.");
}
}
           The init() method accepts an object that implements the ServletConfig interface.
It uses the config object’s getInitParameter() method to get the value for the init parameter named initial. This method takes the name of the parameter as a String and returns the value as a String. There is no way to get the value as any other type. 

A Counter with Init and Destroy

Answer:
We have an exmaple whihc is shown the The init() and destroy() pair can accomplish this, in this eample giving the servlet the ability to save its state in destroy() and load the state again in init(). servlet is following here  : 
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class InitDestroyCounter extends HttpServlet {
int count;
public void init(ServletConfig config) throws ServletException {
// Always call super.init(config) first (servlet mantra #1)
super.init(config);
// Try to load the initial count from our saved persistent state
try {
FileReader fileReader = new FileReader("InitDestroyCounter.initial");
BufferedReader bufferedReader = new BufferedReader(fileReader);
String initial = bufferedReader.readLine();
count = Integer.parseInt(initial);
return;
}
catch (FileNotFoundException ignored) { } // no saved state
catch (IOException ignored) { } // problem during read
catch (NumberFormatException ignored) { } // corrupt saved state
// No luck with the saved state, check for an init parameter
String initial = getInitParameter("initial");
try {
count = Integer.parseInt(initial);
return;
}
catch (NumberFormatException ignored) { } // null or non-integer value
// Default to an initial count of "0"
count = 0;
}
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
count++;
out.println("Since the beginning, this servlet has been accessed " +
count + " times.");
}
public void destroy() {
saveState();
}
public void saveState() {
// Try to save the accumulated count
try {
FileWriter fileWriter = new FileWriter("InitDestroyCounter.initial");
String initial = Integer.toString(count);
fileWriter.write(initial, 0, initial.length());
fileWriter.close();
return;
}
catch (IOException e) { // problem during write
}
}
}
               Servlet is always the unloaded state its save in the state name Whihc is Init-
DestroyCounter.initial. it use whe the supplied path is not presnt its save the server process which is in current state its directory usually server_root.
        Whe servlet loaded state its try to save cont to the file if ts the read fail ,the servlet checks if an init parameter specifies the starting
count. If that too fails, it starts fresh with zero.Servlets can save their state in many different ways. Some may use a custom file
format, as was done here. Others may save their state as serialized Java objects or put it into a database. Some may even perform journaling, a technique common to databases and tape backups, where the servlet’s full state is saved infrequently while a journal file stores incremental updates as things change.

Single-Thread Model

Answer:
Servlet instance is a resisterd name for thepert 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 javax.servlet.SingleThreadModel 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 SingleThreadModel servlet must guarantee, according to the Servlet API documentation, “that no two threads will execute concurrently the service method of that servlet.”

Background Processing

Answer:
Servlets can do more than simply persist between accesses. They can also execute between accesses. Any thread started by a servlet can continue executing even after the response has been sent. This ability proves most useful for long-running tasks whose incremental results should be made available to multiple clients. A background
thread started in init() performs continuous work while requesthandling threads display the current status with doGet(). It’s a similar technique
to that used in animation applets, where one thread changes the picture and another paints the display.

Last Modified Times

Answer:
Now we are dicussing about the servlets handle GET requests with the doGet() method.a web browser that repeatedly accesses PrimeSearcher should need to call doGet() only after the searcher thread has found a new prime. Until that time, any call to doGet() just generates the same page the user has already seen, a page probably stored in the browser’scache. What’s really needed is a way for a servlet to report when its output has changed. That’s where the getLastModified() method comes in.Most web servers, when they return a document, include as part of their response a Last-Modified header. An example Last-Modified header value might be :
        Tue, 06-May-98 15:41:02 GMT
           This header tells the client the time the page was last changed. That information alone is only marginally interesting, but it proves useful when a browser reloads a page. Most web browsers, when they reload a page, include in their request an If-Modified-Since header. Its structure is identical to the Last-Modified header :
       Tue, 06-May-98 15:41:02 GMT
                This header tells the server the Last-Modified time of the page when it was last downloaded by the browser. The server can read this header and determine if the file has changed since the given time. If the file has changed, the server must send the newer content. If the file hasn’t changed, the server can reply with a simple,short response that tells the browser the page has not changed and it is sufficient to redisplay the cached version of the document. For those familiar with the details of HTTP, this response is the 304 “Not Modified” status code. This technique works great for static pages: the server can use the file system to find out when any file was last modified. For dynamically generated content, though, such as that returned by servlets, the server needs some extra help. By itself, the best the server can do is play it safe and assume the content changes with every access, effectively eliminating the usefulness of the Last-Modified and If-Modified-Since headers.

Retrieving Information

Answer:
Servlets have a number of methods available to gain access to this information. For the most part, each method returns one specific result, if we compare this to the way environment variables are used to pass a CGI program its information, the servlet approach has several advantages:
> Stronger type checking. In other words, more help from the compiler in catching errors. A CGI program uses one function to retrieve its environment variables. Many errors cannot be found until they cause runtime problems. Let’s look at how both a CGI program and a servlet find the port on which its server is running.
      A CGI script written in Perl calls : 
        $port = $ENV{'SERVER_PORT'};
where $port is an untyped variable. A CGI program written in C calls :
         char *port = getenv("SERVER_PORT");
where port is a pointer to a character string. The chance for accidental errors is high. The environment variable name could be misspelled or the data type might not match what theenvironment variable returns.
         A servlet, on the other hand, calls : 
            int port = req.getServerPort()
      This eliminates a lot of accidental errors because the compiler can guarantee there are no misspellings and each return type is as it should be.
> Delayed calculation. When a server launches a CGI program, the value for each and every environment variable must be precalculated and passed, whether the CGI program uses it or not. A server launching a servlet has the option to improve performance by delaying these calculations and performing them on demand as needed.
> More interaction with the server. Once a CGI program begins execution, it is untethered from its server. The only communication path available to the program is its standard output. A servlet, however, can work with the server. 

CGI Environment    |       HTTP Servlet Method
  Variable         |     
--------------------------------------------------
SERVER_NAME        |req.getServerName()
SERVER_SOFTWARE    |getServletContext().
                   |getServerInfo()             
SERVER_PROTOCOL    |req.getProtocol()
SERVER_PORT        |req.getServerPort()
REQUEST_METHOD     |req.getMethod()
PATH_INFO          |req.getPathInfo()
PATH_TRANSLATED    |req.getPathTranslated()
SCRIPT_NAME        |req.getServletPath()
DOCUMENT_ROOT      |req.getRealPath("/")
QUERY_STRING       |req.getQueryString()
REMOTE_HOST        |req.getRemoteHost()
REMOTE_ADDR        |req.getRemoteAddr()
AUTH_TYPE          |req.getAuthType()
REMOTE_USER        |req.getRemoteUser()
CONTENT_TYPE       |req.getContentType()
CONTENT_LENGTH     |req.getContentLength()
HTTP_ACCEPT        |req.getHeader("Accept")
HTTP_USER_AGENT    |req.getHeader("User-Agent")
HTTP_REFERER       |req.getHeader("Referer")
--------------------------------------------------


Initialization Parameters : Getting an Init Parameter

Answer:
Each servlet which is resistered with name can have specific initialization parameters associated
with it. Init parameters are available to the servlet at any time; they are often used in init() to set initial or default values for a servlet or to customize the servlet’s behavior in some way.A servlet uses the getInitParameter() method to get access to its init parameters : 
public String ServletConfig.getInitParameter(String name)
             This method returns the value of the named init parameter or null if it does notexist .The return value is always a single String. It is up to the servlet to interpret the value.
The GenericServlet class implements the ServletConfig interface and thus provides direct access to the getInitParameter() method.* The method is usually called like this:
public void init(ServletConfig config) throws ServletException {
super.init(config);
String greeting = getInitParameter("greeting");
}
              A servlet that needs to establish a connection to a database can use its init parameters to define the details of the connection.

Initialization Parameters : Getting Init Parameter Names

Answer:
A Servlet bassiclay use for the all init parameters using getInitParameterNames() : 
public Enumeration ServletConfig.getInitParameterNames()
       This method returns the names of all the servlet’s init parameters as an Enumeration of String objects or an empty Enumeration if no parameters exist.It’s most often used for debugging. The GenericServlet class also makes this method directly available to servlets.

The Server : Getting Information About the Server

Answer:
The servlet is bassiclaly the much use full about the server in which it is excuting .its can find out the hostname, listening port, and server software, among other things. A servlet
can display this information to a client, use it to customize its behavior based on a particular server package, or even use it to explicitly restrict the machines onwhich the servlet will run.There are four methods that a servlet can use to learn about its server: two that are called using the ServletRequest object passed to the servlet and two that are called from the ServletContext object in which the servlet is executing.getServerName() and getServerPort(),respectively :
public String ServletRequest.getServerName()
public int ServletRequest.getServerPort()
                        The getServerInfo() and getAttribute() methods of ServletContext provide information about the server software and its attributes : 
public String ServletContext.getServerInfo()
public Object ServletContext.getAttribute(String name)

Locking a Servlet to a Server

Answer:
this server inforation is more productive for the uses ,Perhaps we want to sell it and, to limit the chance of unauthorized copying, we want to lock the servlet to your customer’s machine with a software license. Or,  alternatively, we’ve written a license generator as a servlet and want to make sure it works only behind our firewall. This can be done relatively easily because a servlet has instant access to the information about its server.

The Client : Getting Information About the Client Machine

Answer:
servlet has the ability to find out about the client machine and, for pages requiring authentication, about the actual user. This information can be used for logging access data, associating information with individual users, or
restricting access to certain clients.A servlet can use getRemoteAddr() and getRemoteHost() to retrieve the IP address and hostname of the client machine, respectively:
public String ServletRequest.getRemoteAddr()
public String ServletRequest.getRemoteHost()
            Both values are returned as String objects.The IP address or remote hostname can be converted to a java.net.
InetAddress object using InetAddress.getByName():
InetAddress remoteInetAddress = InetAddress.getByName(req.getRemoteAddr());

Restricting Access to the United States and Canada

Answer:
United States government’s policy restricting the export of strong encryption outside the United States and Canada, some web sites must be careful
about who they let download certain software. Servlets, with their ability to find out about the client machine, are well suited to enforce this restriction. These servlets can check the client machine and provide links for download only if the client appears to be coming from inside the United States or Canada.

Getting Information About the User

Answer:
Nearly every HTTP server has a built-in capability to restrict access to some or all of its pages to a given set of registered users. How you set up restricted access depends on the server, but here’s how it works mechanically. The first time a browser attempts to access one of these pages, the HTTP server replies that it needs special user authentication. When the browser receives this response, it usually pops open a window asking the user for a name and password appropriate for the page,Once the user enters his information, the browser again attempts to access the page, this time attaching the user’s name and password along with the request. If the server accepts the name/password pair, it happily handles the request. If, on
the other hand, the server doesn’t accept the name/password pair, the browser is again denied and the user swears under his breath about forgetting yet another password.

A Personalized Welcome

Answer:
We have an exmaple which is shows something : 
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class PersonalizedWelcome extends HttpServlet {
Hashtable accesses = new Hashtable();
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
// ...Some introductory HTML...
String remoteUser = req.getRemoteUser();
if (remoteUser == null) {
out.println("Welcome!");
}
else {
out.println("Welcome, " + remoteUser + "!");
Date lastAccess = (Date) accesses.get(remoteUser);
if (lastAccess == null) {
out.println("This is your first visit!");
}
else {
out.println("Your last visit was " + accesses.get(remoteUser));
}
if (remoteUser.equals("PROFESSOR FALKEN")) {
out.println("Shall we play a game?");
}
accesses.put(remoteUser, new Date());
}
// ...Continue handling the request...
}
}
      This servlet uses a Hashtable to save the last access time for each remote user. The first thing it does for each request is greet the person by name and tell us the time of his last visit. Then it records the time of this visit, for use next time. After that, it continues handling the request.

The Request : Request Parameters

Answer:
Each access to a servlet can have any number of request parameters associated with it. These parameters are typically name/value pairs that tell the servlet any extra information it needs to handle the request. Please don’t confuse these request parameters with init parameters, which are associated with the servlet itself.a servlet can receive parameters in a number of different
ways, every servlet retrieves its parameters the same way, using getParameter()
and getParameterValues() : 
public String ServletRequest.getParameter(String name)
public String[] ServletRequest.getParameterValues(String name)
           getParameter() returns the value of the named parameter as a String or null
if the parameter was not specified.* The value is guaranteed to be in its normal, decoded form. If the parameter has multiple values, the value returned is serverdependent. If there’s any chance a parameter could have more than one value, we should use the getParameterValues() method instead.

Generating a License Key

Answer:
we’re ready to write a servlet that generates a KeyedServerLock license key for any given host and port number. A key from this servlet can be used to unlock the KeyedServerLock servlet.we hav an exmaple which is shown something : 
import java.io.*;
import java.net.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class KeyedServerUnlock extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
PrintWriter out = res.getWriter();
// Get the host and port
String host = req.getParameter("host");
String port = req.getParameter("port");
// Convert the port to an integer
int numericPort;
try {
numericPort = Integer.parseInt(port);
}
catch (NumberFormatException e) {
numericPort = 80; // default
}
// Generate and print the key
// Any KeyGenerationException is caught and displayed
try {
long key = generateKey(host, numericPort);
out.println(host + ":" + numericPort + " has the key " + key);
}
catch (KeyGenerationException e) {
out.println("Could not generate key: " + e.getMessage());
}
}
// This method contains the algorithm used to match a key with
// a server host and port. This example implementation is extremely
// weak and should not be used by commercial sites.
//
// Throws a KeyGenerationException because anything more specific
// would be tied to the chosen algorithm.
//
private long generateKey(String host, int port) throws KeyGenerationException {
// The key must be a 64-bit number equal to the logical not (~)
// of the 32-bit IP address concatenated by the 32-bit port number.
byte hostIP[];
try {
hostIP = InetAddress.getByName(host).getAddress();
}
catch (UnknownHostException e) {
throw new KeyGenerationException(e.getMessage());
}
// Get the 32-bit IP address
long servercode = 0;
for (int i = 0; i < 4; i++) {
servercode <<= 8;
servercode |= (hostIP[i] & 255);
}
// Concatentate the 32-bit port number
servercode <<= 32;
servercode |= port;
// The key is the logical not
return ~servercode;
}
}
class KeyGenerationException extends Exception {
public KeyGenerationException() {
super();
}
public KeyGenerationException(String msg) {
super(msg);
}
} 
               This servlet can either generate a full page or act as a server-side include.

Path Information

Answer:
HTTP request can include something called “extra
path information” or a “virtual path.” In general, this extra path information is used to indicate a file on the server that the servlet should use for something. This path information is encoded in the URL of an HTTP request. An example URL looks like this:
   http://server:port/servlet/ViewFile/index.html
               This invokes the ViewFile servlet, passing "/index.html" as extra path information.
A servlet can access this path information, and it can also translate the "/index.html" string into the real path of the index.html file. What is the real path of "/index.html"? It’s the full file system path to the file—what the server would
return if the client asked for "/index.html" directly. This probably turns out to be document_root/index.html, but, of course, the server could have special aliasing that changes this. Besides being specified explicitly in a URL, this extra path information can also be
encoded in the ACTION parameter of an HTML form:
   
Word to look up: 

Getting path information

Answer:
A servlet can use the getPathInfo() method to get extra path information:
public String HttpServletRequest.getPathInfo()
This method returns the extra path information associated with the request or null if none was given. An example path is "/dictdefinitions.txt". The path information by itself, however, is only marginally useful. A servlet usually needs to know the actual file system location of the file given in the path info, which is where getPathTranslated() comes in:
public String HttpServletRequest.getPathTranslated()
              This method returns the extra path information translated to a real file system
path or null if there is no extra path information.

Ad hoc path translations

Answer:
Sometimes a servlet needs to translate a path that wasn’t passed in as extra path information.we can use the getRealPath() method for this task : 
public String ServletRequest.getRealPath
            This method returns the real path of any given “virtual path” or null if the translation cannot be performed. If the given path is "/", the method returns the document root,for the server. If the given path is getPathInfo(), the method returns the same real path as would be returned by getPathTranslated(). This method can be used by generic servlets as well as HTTP servlets. There is no CGI counterpart.

Getting MIME types

Answer:
Once a servlet has the path to a file, it often needs to discover the type of the file.
Use getMimeType() to do this  : 
public String ServletContext.getMimeType
             This method returns the MIME type of the given file or null if it isn’t known.
Some implementations return "text/plain" if the given file doesn’t exist.
Common MIME types are "text/html", "text/plain", "image/gif", and
"image/jpeg".
The following code fragment finds the MIME type of the extra path information:
String type = getServletContext().getMimeType(req.getPathTranslated())

Serving Files

Answer:
The Java Web Server itself uses servlets to handle every request. Besides being a showcase for the ability of servlets, this gives the server a modular design that allows the wholesale replacement of certain aspects of its functionality. For example, all files are served by the com.sun.server.http.FileServlet servlet,
registered under the name file and charged with the responsibility to handle the "/" alias,But there’s nothing to say that Sun’s FileServlet cannot be replaced. In fact, it can be, either by registering another servlet under the name file or by changing the "/" alias to use another servlet.

Determining What Was Requested

Answer:
A servlet bassiclaly use for the servlet method whih is use for the finding out exactly what file or servlet the client requested,No method directly returns the original Uniform Resource Locator (URL) used by the client to make a request. The javax.servlet.http.HttpUtils class, however, provides a getRequestURL() method that does about the same thing:*
public static StringBuffer HttpUtils.getRequestURL(HttpServletRequest req)
            a servlet doesn’t really need the request URL. It just needs the request URI, which is returned by getRequestURI():
public String HttpServletRequest.getRequestURI()
           This method returns the Universal Resource Identifier (URI) of the request. For
normal HTTP servlets, a request URI can be thought of as a URL minus the scheme, host, port, and query string.

Request URL               |Its URI Component
--------------------------------------------------
http://server:port/servlet|/servlet/Classname    |
/Classname                |                      |
--------------------------------------------------
http://server:port/servlet|/servlet              |
/registeredName           |/registeredName       |
--------------------------------------------------
http://server:port/servlet|/servlet/Classname a  |
/Classname?var=val        |                      |
--------------------------------------------------
http://server:port/servlet|/servlet/Classname    |
/Classname/pathinfo       |/pathinfo             |
--------------------------------------------------
http://server:port/servlet|/servlet/Classname    |
/Classname/pathinfo?var=val|/pathinfo            |
--------------------------------------------------
http://server:port        |/ssi.shtml            |
/ssi.shtml (SSI)          |                      |
--------------------------------------------------
http://server:port        |/alias.html           |
/alias.html               |                      |
--------------------------------------------------

         some situations it is enough for a servlet to know the servlet name under which
it was invoked. We can retrieve this information with getServletPath() : 
public String HttpServletRequest.getServletPath()
This method returns the part of the URI that refers to the servlet being invoked ornull if the URI does not directly point to a servlet. The servlet path does not include extra path information.

Request URL                 |Its Servlet Path    |
--------------------------------------------------
http://server:port/servlet  |/servlet/Classname  |
/Classname                  |                    |
--------------------------------------------------
http://server:port/servlet  |/servlet            |
/registeredName             |/registeredName     |
--------------------------------------------------
http://server:port/servlet  |/servlet/Classname  |
/Classname?var=val          |                    |
--------------------------------------------------
http://server:port/servlet  |/servlet/Classname  |
/Classname/pathinfo         |                    |
--------------------------------------------------
http://server:port/servlet  |/servlet/Classname  |
/Classname/pathinfo?var=val |                    |
--------------------------------------------------
http://server:port/ssi.shtml|null                |
 (SSI)                      |                    |
--------------------------------------------------
http://server:port/alias.html|/alias.html        |
(alias to a servlet)         |                   |
--------------------------------------------------

An Improved Counter

Answer:
We can make use of the request URI information to improve our counter servlet.A real counter has to be able to count accesses to pages other than itself. There are two elegant ways to accomplish this: use the counter as an SSI servlet embedded in a page or use the counter in a servlet chain where it can replace any instances of the  tag with the appropriate number. For each approach, a servlet can usethe getRequestURI() method to associate a separate count with each requested URI.

How It Was Requested

Answer:
Besides knowing what was requested, a servlet has several ways of finding out details about how it was requested. The getScheme() method returns the scheme used to make this request : 
      public String ServletRequest.getScheme()
           "http", "https", and "ftp", as well as the newer Java-specific schemes "jdbc" and "rmi". There is no direct CGI counterpart. in the case of the HTTP servlets, this method indicates whether the request was made over a secure connection using the Secure Sockets Layer (SSL), as indicated by the scheme "https", or if it was an insecure request, as indicated by the scheme "http".

Request Headers

Answer:
HTTP reqest and its respoces have a mnay no of associated HTTP "headers .these type of headers provides some extra information about the reqest/in this HTTP version its can e define the protocols are "literally dozens of possible headers; the HTTP Version 1.1 protocol includes even more.A servlet rarely needs to read the HTTP headers accompanying a request. Many of the headers associated with a request are handled by the server itself. Take, for example, how a server restricts access to its documents. The server uses HTTP headers, and servlets need not know the details. When a server receives a request for a restricted page, it checks that the request includes an appropriate Authorization header that contains a valid username and a password

Accessing header values

Answer:
HTTP header bassiclaly use for the accessong the objects which is named as HttpServletRequest object,its value cn be retrived as String, a long (representing a Date), or an int, using getHeader(), getDateHeader(), and getIntHeader(), respectively : 
public String HttpServletRequest.getHeader(String name)
public long HttpServletRequest.getDateHeader(String name)
public int HttpServletRequest.getIntHeader(String name)
           getHeader() returns the value of the named header as a String or null if the header was not sent as part of the request. The name is case insensitive, as it is for all these methods. Headers of all types can be retrieved with this method.

Headers in servlet chains

Answer:
serlet chain bassiclaly add an intresting twist which is define the "HOW CAN SERVLET HANDLES THE HEADER." The power and flexibility of this approach comes from the fact that a servlet can
intelligently process a previous servlet’s output, not only in body content, but in
header values,power comes with responsibilities: unless a chained servlet specifically reads
the previous servlet’s response headers and sends them as part of its own response,the headers are not passed on and will not be seen by the client. A well-behaved chained servlet always passes on the previous servlet’s headers, unless it has a specific reason to do otherwise.

Wading the Input Stream

Answer:
IN the servlet all reqests are handled by a ervlet has an input stream ,its similar as a servlet can write to a PrintWriter or OutputStream associated with its response
object, it can read from a Reader or InputStream associated with its request object. The data read from the input stream can be of any content type and of any length. The input stream has three purposes : 
> To pass a chained servlet the response body from the previous servlet.
> To pass an HTTP servlet the content associated with a POST request.
> To pass a non-HTTP servlet the raw data sent by the client To read character data from the input stream, 
           We should use getReader() to retrieve the input stream as a BufferedReader object : 
public BufferedReader ServletRequest.getReader() throws IOException 
The advantage of using a BufferedReader for reading character-based data is that it should translate charsets as appropriate. This method throws an IllegalStateException if getInputStream() has been called before on this same request.It throws an UnsupportedEncodingException if the character encoding of the input is unsupported or unknown.

Chaining servlets using the input stream

Answer:
A servlet in a servlet chain receives its response body from the previous servlet in the chain through its input stream.The pertinent section is shown again here : 
String contentType = req.getContentType(); // get the incoming type
if (contentType == null) return; // nothing incoming, nothing to do
res.setContentType(contentType); // set outgoing type to be incoming type
BufferedReader br = req.getReader();
String line = null;
while ((line = br.readLine()) != null) {
line = replace(line, "", "");
line = replace(line, "", "");
out.println(line);
}
          Notice the use of getContentType() to retrieve the content type of the previous servlet’s output. Also notice that getContentLength() is not used. We don’t need to use it because all read() and readLine() methods indicate that they have reached the end of the stream with special return values.

Handling POST requests using the input stream

Answer:
Its a rare occurrence when a servlet handaling a POSt request is forced to use its input stream to access the POST data. Typically, the POST data is nothing more than encoded parameter information, which a servlet can conveniently retrieve with its getParameter() method. A servlet can identify this type of POST request by checking the content type of the input stream. If it is of type application/x-www-form-urlencoded, the data can be retrieved with getParameter() and similar methods. 
         A servlet may wish to call the getContentLength() method before calling
getParameter() to prevent denial of service attacks. A rogue client may send an absurdly large amount of data as part of a POST request, hoping to slow the server to a crawl as the servlet’s getParameter() method churns over the data. A servlet can use getContentLength() to verify that the length is reasonable, perhaps less than 4K, as a preventive measure.

Receiving files using the input stream

Answer:
A servlet have a authority for the recive a file upload its input stream. We can see the importance of the file uploading is experimental and not supportd in all brower. The short summary is that any number of files and parameters can be sent as form data in a single POST request. methods creates a new MultipartRequest object to handle the specified request, saving any uploaded files to saveDirectory. Both constructors actually parse the multipart/form-data content and throw an IOException if there’s any problem. The constructor that takes a maxPostSize parameter also throws an IOException if the uploaded content is larger than maxPostSize.

Extra Attributes

Answer:
Servlet bassiclaly want to know about the reqest but its not possible to get the way for the information thats why its use the previously mentioned methods,In these cases, there is one last alternative, the getAttribute() method.
public Object ServletRequest.getAttribute(String name)
          This method return the value of the server specific attribute for the request or null
if the server does not support the named request attribute,This method allows a server to provide a servlet with custom information about a request.

The Structure of a Response

Answer:
HTTP servlet bassiclaly return the three type of values which is usefull for the client , which are fllowing as :
> A single status code.
> Any number of HTTP headers.
> A response body.
            An Status code is bassiclaly a type of integer value which is define the we aspect the status of responce.its only indicate the sucess or failure.and also it can take the client s/w to take further action to finish the request.
          The Response body is the main feature of the response. For an HTML page, the response body is the HTML itself. For a graphic, the response body contains the bytes that make up the image. A response body can be of any type and of any length; the client knows what to expect by reading and interpreting the HTTP headers in the response,A generic servlet is much simpler than an HTTP servlet—it returns only a response body to its client. It’s possible, however, for a subclass of GenericServlet to present an API that divides this single response body into a more elaborate structure, giving the appearance of returning multiple items.It’s important to understand this because even though a servlet programmer doesn’t have to know the details of the HTTP protocol, the protocol does affect the order in which a servlet can call its methods. Specifically, the HTTP protocol specifies that the status code and headers must be sent before the response body.

Sending a Normal Response

Answer:
We have an exmaple which is shown about the normal responce : 
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("");
out.println("Hello World");
out.println("");
out.println("Hello World");
out.println("");
}
}
            Here we can see that the its sevlet use two methods and a class that have been discussed here  : 
> The setContentType() method
> ServletResponse sets

Using Persistent Connections

Answer:
Persistant Connection is bassiclaly called as a 
“keep-alive” connections.its mainly use for the optimised the way servlets return content to the client .its only use for the how its HTTP connection works.When a client, such as a browser, wants to request a web document from a server, it begins by establishing a socket connection to the server. Over this connection,
the client makes its request and then receives the server’s response.A better approach is to use the same socket connection to retrieve more than one piece of a page, something called a persistent connection. The trick with a persistent
connection is that the client and server must somehow agree on where the server’s response ends and where the client’s next request begins.

HTML Generation

Answer:
HTML bassiclaly a alternate way .its generate bassiclaly for the servlets to send HTML content to clients.its mainly as one long String that is sent to the client. This strategy works fine for small web pages but it quickly becomes unwieldy for larger, more complicated pages. For that type of page, it’s sometimes helpful to use an HTML generation package.its bassiclaly provides the servlet with a set of classes that abstract
away the details of HTML, in particular, the HTML tags. The level of abstraction depends on the package: some put only the thinnest veneer above the HTML tags, leaving the nitty-gritty details to the programmer.

Generating Hello World

Answer:
we have an Code which is a HELLO WORLD programe in HTML.its mainly advantages for the rewritten to take of WebLogic’s htmlKona package, Code is here : 
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import weblogic.html.*;
public class HtmlKonaHello extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
ServletPage page = new ServletPage();
page.getHead().addElement(new TitleElement("Hello World"));
page.getBody().addElement(new BigElement("Hello World!"));
page.output(res.getOutputStream());
}
}
        All the HTML tags have been replaced with objects.this servlet only creats for the new ServletPage object that represents the web page it will return,its title "HELLO WORLD" basscially the pages  head section and a “Hello World!”
big string to its body section. Finally, the servlet outputs the page to its output stream. That’s how object-oriented HTML generation works: get a page object, add component objects to it, and send it to the output stream.One advantage of HTML generation should already be apparent: it ensures valid HTML. HTML generation eliminates the possibility for a misspelled  open tag or a forgotten  close tag.

Generating a Weather Forecast

Answer:
HTML generation works for a simple web page. Now let’s create a more complicated web page, so we can test how HTML generation scales to handle the harder challenges.Imagine a servlet creating this web page. Assuming the servlet already has access to
the current conditions and forecast information, we have a three stragies which are following here: 
> Constructing the HTML by hand
> Using an HTML generator
> Using an HTML generator creatively
          The first strategy, constructing the HTML by hand,A servlet implemented using this
strategy acts as a baseline against which we can compare the other two servlets.The second approach, using an HTML generator,constructs the
web page as a set of objects.The third strategy, using an HTML generator and some creativity takes the second servlet and simplifies it by reusing objects and subclassing.

Weather forecast constructed by hand

Answer:
its shows bassically a servlet crate sforecast page with out using HTML generation manually sending its content wrapped with almost a hunderd HTML tags.here static variable to use as its cntent and proceeds to nest that content among HTML tags, this approch presents a pretty page to the end user but it can leave the programmer counting tags and looking for the right
place to put the forgotten . The approach also has limited maintainability.Pulling out one HTML tag can result in the same cascading disaster we get when we pull on a knit sweater’s loose tail.

Weather forecast using HTML generation

Answer:
servlet have a type of structure whihc is ise HTML seneration packages to create an object-oriented representation of the web page. The most striking is its use of method chaining, where several methods are invoked on the same object with code like the following:
TableElement tab = new TableElement()
.setCellPadding(0)
.setCellSpacing(0);
         The whitespace here is irrelevant. The previous code is equivalent to:
TableElement tab = new TableElement().setCellPadding(0).setCellSpacing(0);\
             This chaining is possible because each “set” method returns a reference to the
object on which it was invoked—that reference is used to invoke the next “set” method. This trick comes in handy when using htmlKona.
         We may also wondering its object are declared as HtmlElement objects but created as StringElement objects or ImageElement objects, as with the following code:
HtmlElement image = new ImageElement(currentImage)
.setWidth(48)
.setHeight(35)
.asCenteredElement();

Weather forecast using HTML generation creatively

Answer:
Custom styles further abstract the HTML components on the page,a String surrounded by HTML tags is now a high-level page component. A servlet can fill these components with content and not worry about exactly how they will be displayed. Their display is left to the style class. Should it happen that the appearance needs to be changed, such as when we decide we want the extended forecast font to be bold, the change can be done with a single modification to the appropriate style. Subclassing also proves useful for more mundane tasks. It can be used to define basic HTML components that, for whatever reason, are not included in the HTML generation package. For example, htmlKona has no ServletElement class to represent an embedded  tag. This class could be written similarly to its AppletElement class by subclassing htmlKona’s ElementWithAttributes class.

HTML generation and databases

Answer:
Here we have a one ore most important feature which is potential close integration with a database. It’s not by coincidence that WebLogic packages htmlKona with its database-centric dbKona and jdbcKona—the packages work well together. We’ll leave the details to WebLogic’s
web site, but the general idea is that when we execute a query against a database, the returned result set can be thought of as a formatted table without a graphical representation. This result set table can be passed to the TableElement constructor to automatically display the query results in an HTML table on a web page.A subclass can also give special treatment to certain types of data, perhaps converting them into hyperlinks to other queries.

Status Codes

Answer:
our servlet examples have not set HTTP response status codes. We’ve been taking advantage of the fact that if a servlet doesn’t specifically set the status code, the server steps in and sets its value to the default 200 “OK” status code.
That’s a useful convenience when we are returning normal successful responses by using status codes, a servlet can do more with its response. For example, it can redirect a request or report a problem.The most common status code numbers are defined as mnemonic constants in the HttpServletResponse class.

Setting a Status Code

Answer:
A servlet can use setStatus() to set a response status code :
public void HttpServletResponse.setStatus(int sc)
public void HttpServletResponse.setStatus(int sc, String sm)
           Both of these methods set the HTTP status code to the given value. The code can
be specified as a number or with one of the SC_XXX codes defined within Http-ServletResponse. With the single-argument version of the method, the reason phrase is set to the default message for the given status code.
        If a servlet sets a status code that indicates an error during the handling of the
request, it can call sendError() instead of setStatus():
public void HttpServletResponse.sendError(int sc)
public void HttpServletResponse.sendError(int sc, String sm)
            A server may give the sendError() method different treatment than setStatus(). When the two-argument version of the method is used, the status message parameter may be used to set an alternate reason phrase or it may be used directly in the body of the response, depending on the server’simplementation.

Improving ViewFile Using Status Codes

Answer:
Without setting a status code, the best this servlet can do is write out an explanation
of the problem, ironically sending the explanation as part of a page that is supposed to contain the file’s contents. With status codes, however, it can do exactly what Sun’s FileServlet does: set the response code to SC_NOT_FOUND to
indicate that the requested file was not found and cannot be returned. Here’s the improved version : 
// Return the file
try {
ServletUtils.returnFile(file, out);
}
catch (FileNotFoundException e) {
res.sendError(res.SC_NOT_FOUND);
}

HTTP Headers : Setting an HTTP Header

Answer:
A servlet can set bassiclaly for the HTTP headers to provide extra information about its response. The HttpServletResponse class provides a number of methods to assist servlets in setting HTTP response headers. Use setHeader() to set the value of a header : 
public void HttpServletResponse.setHeader(String name, String value)
                 This method sets the value of the named header as a String. The name is case insensitive, as it is for all these methods. If the header had already been set, the new value overwrites the previous one. Headers of all types can be set with this method.
          any headers are there : 
> Cache-Control
> Pragma
> Connection
> Retry-After
> Expires
> Location
> WWW-Authenticate
> Content-Encoding

Redirecting a Request

Answer:
One of the useful things a servlet can do using status codes and headers is redirect a request. This is done by sending instructions for the client to use another URL in the response. Redirection is generally used when a document moves which is use for the send to the client to the new location for load balancing or for simple randomization which is choosing at random.

Client Pull

Answer:
Client pull is similar to redirection, with one major difference: the browser actually displays the content from the first page and waits some specified amount of time before retrieving and displaying the content from the next page. It’s called client pull because the client is responsible for pulling the content from the next page, its very usefull. its have a two reasons which is following here : 
> the content from the first page can explain to the client that the requested page has moved before the next page is automatically loaded.
> pages can be retrieved in sequence, making it
possible to present a slow-motion page animation.

When Things Go Wrong

Answer:
Many resons are there for the example : 
> bad parameters
> missing resources
> actual bugs.
        there are many problems are which is couse of the expected and unexpected.here wo points also there which is are following as :
> Limiting damage to the server.
> Properly informing the client.
        becouse servlet are written in Java, the potential damage they can cause to their
server is greatly minimized. A server can safely embed servlets,just as a web browser can safely embed downloaded applets. This safety is built on Java’s security features, including the use of protected memory, exception handling, and security managers.

Status Codes

Answer:
The simplest way for a servlet to report an error is to use the sendError() method to set the appropriate 400 series or 500 series status code.By using sendError() to set the status code, a servlet provides the server an opportunity to give the response special treatment.A servlet must be careful to catch and handle any errors before it sends any part of its response body.HTTP specifies that the status code and HTTP headers must be sent before the response body.once we have sent even one character of a response body, it may be too late to change our status code or our HTTP headers.

Logging

Answer:
Servlets have the ability to write their actions and their errors to a log file using the log() method :
public void ServletContext.log(String msg)
public void ServletContext.log(Exception e, String msg)
             The single-argument method writes the given message to a servlet log, which is
usually an event log file. The two-argument version writes the given message and exception’s stack trace to a servlet log. Notice the nonstandard placement of the optional Exception parameter as the first parameter instead of the last for this method.The GenericServlet class also provides a log() method:
public void GenericServlet.log(String msg)
          This is another version of the ServletContext method, moved to GenericServlet for convenience. This method allows a servlet to call simply :  
log(msg);
        to write to the servlet log.

Reporting

Answer:
logging errors and exceptions for the server administrator, during development it’s often convenient to print a full description of the problem along with a stack trace. Unfortunately, an exception cannot return its stack trace as a
String—it can only print its stack trace to a PrintStream or PrintWriter. To retrieve a stack trace as a String, we have to jump through a few hoops. We need to let the Exception print to a special PrintWriter built around a
ByteArrayOutputStream. That ByteArrayOutputStream can catch the output and convert it to a String. The com.oreilly.servlet.ServletUtils class has
a getStackTraceAsString() method that does just this : 
public static String getStackTraceAsString(Exception e) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
PrintWriter writer = new PrintWriter(bytes, true);
e.printStackTrace(writer);
return bytes.toString();
}

Exceptions

Answer:
Exception is bassically a thrown but its not catch the server only servlet catch the server .its not depend on the server it may pass the client the message and the stack trace, or it may not. It may automatically log the exception, or it may not. It may even call destroy() on the servlet and reload it, or it may not.server how can it designed and how its run a perticuar server its only optimized by the server behavior.a servlet requires special exception handling, it must catch its own exceptions and
handle them accordingly.
         There are some types of exceptions a servlet has no choice but to catch itself. A
servlet can propagate to its server only those exceptions that subclass IOException, ServletException, or RuntimeException. The reason has to do with method signatures. The service() method of Servlet declares in its throws clause that it throws IOException and ServletException exceptions. For it (or the doGet() and doPost() methods it calls) to throw and not catch anything else causes a compile time error. The RuntimeException is a special case exception that never needs to be declared in a throws clause. A common example is a NullPointerException.

HTTP status code

Answer:
Mnemonic Constant    |  Code   | Default Message |
--------------------------------------------------
| SC_OK              |   200   | OK              |
--------------------------------------------------
|   SC_NO_CONTENT    |   204   | No Content      |
--------------------------------------------------
SC_MOVED_PERMANENTLY |   301   |Moved Permanently|
--------------------------------------------------
SC_MOVED_TEMPORARILY |   302   |Moved Temporarily|
--------------------------------------------------
SC_UNAUTHORIZED      |   401   |Unauthorized     |
--------------------------------------------------
SC_NOT_FOUND         |   404   |Not Found        |
--------------------------------------------------
SC_INTERNAL_SERVER_ERROR| 500  |Internal Server  |
                               | Error           |
--------------------------------------------------
SC_NOT_IMPLEMENTED   |  501    |Not Implemented  |
--------------------------------------------------
SC_SERVICE_UNAVAILABLE| 503    |Service          |
                               |Unavailable      |
-------------------------------------------------

Usage of header : Cache-Control

Answer:
Specifies any special treatment a caching system should give to this document. The most common values are no-cache which is to indicate
this document should not be cached, no-store which is to indicate this document should not be cached or even stored by a proxy server, usually due to its sensitive contents, and maxage=
seconds which is to indicate how long before the document should be considered stale. 

Usage of header : Pragma

Answer:
The HTTP 1.0 equivalent of Cache-control, with no-cache as its only possible value.

HEader uses : Connection

Answer:
Used to indicate whether the server is willing to maintain an open connection to the client. If so, its value is set to keepalive. If not, its value is set to close. Most web servers handle this header on behalf of their servlets, automatically setting its value to keep-alive when a servlet sets its Content-Length header.

Header uses : Retry-After

Answer:
Specifies a time when the server can again handle requests, used with the SC_SERVICE_UNAVAILABLE status code. Its value is either an int that represents the number of seconds or a date string that represents an actual time.

Header uses : Expires

Answer:
Specifies a time when the document may change or when its information will become invalid. It implies that it is unlikely the document will change before that time.

header uses : Location

Answer:
Specifies a new location of a document, usually used with the status codes SC_CREATED, SC_MOVED_PERMANENTLY, and SC_MOVED_TEMPORARILY. Its value must be a fully qualified URL

Header uses : WWW-Authenticate

Answer:
Specifies the authorization scheme and the realm of authorization required by the client to access the requested URL. Used with the status code SC_UNAUTHORIZED.

Header uses : Content-Encoding

Answer:
Specifies the scheme used to encode the response body. Possible values are gzip and compress .Multiple encodings should be represented as a comma-separated list in the order in which the encodings were applied to the data.

Permanent unavailability.

Answer:
The servlet will not be able to handle client requests until some administrative action is taken to correct a servlet problem. For example, the servlet might be misconfigured, or the state of the servlet may be corrupted. Well written servlets will log both the error and the corrective action which an administrator must perform to let the servlet become available.

Temporary unavailability.

Answer:
The servlet bassiclay cannot handle more reqest right now,becouse system-wide problem. and we have also the problecm that third-tier server might not be accessible and insufficient memory or disk storage to handle requests also occurs . The problem may be self-correcting, such as those due to excessive load, or corrective action may need to be taken by an administrator.Network services may safely treat both types of exceptions as “permanent,” but good treatment of temporary unavailability leads to more robust network services. Specifically, requests to the servlet might be blocked for a servlet suggested amount of time, rather than being rejected until the service itself restarts.
    UnavailableException has two constructors : 
javax.servlet.UnavailableException(Servlet servlet, String msg)
javax.servlet.UnavailableException(int seconds, Servlet servlet, String msg)
        The two-argument constructor creates a new exception that indicates the given
servlet is permanently unavailable, with an explanation given by msg. The three argument
version creates a new exception that indicates the given servlet is temporarily unavailable, with an explanation given by msg. The duration of its unavailability is given by seconds. This time is only an estimate. If no estimate can be made, a nonpositive value may be used. Notice the nonstandard placement of the optional seconds parameter as the first parameter instead of the last. This may be changed in an upcoming release. UnavailableException provides the isPermanent(), getServlet(), and  getUnavailableSeconds() methods to retrieve information about an exception.

Images

Answer:
It’s relatively simple for a servlet to send an image as its response. As we may recall, this servlet can return any file under the server’s document root. When the file happens to be an image file, it detects that fact with the getMimeType() method and sets its response’s content type with setContentType() before sending the raw bytes to the client. This technique requires that we already have the needed image files saved on disk, which isn’t always the case. Often, a servlet must generate or manipulate an image before sending it to the client. Imagine, for example, a web page that contains an image of an analog clock that displays the current time. Sure, someone could save .But that someone isn’t me, and it shouldn’t be you. Instead, the
wise servlet programmer writes a servlet that dynamically generates the image of the clock face and its hands—or as a variant, a servlet that loads an image of the clock face and adds just the hands. And, of course, the frugal programmer also has the servlet cache the image to save server cycles.

Image Generation

Answer:
Each image format (GIF, JPEG, TIFF, etc.) represents one solution. Each image format defines a standard way to encode an image so that it can later be decoded for viewing or manipulation. Each encoding technique has certain advantages and limitations. For example, the compression used for GIF encoding excels at handling computer-generated images, but the GIF format is limited to just 256 colors. The compression used for JPEG encoding, on the other hand, works best on photo-realistic images that contain millions of colors, but it works so well because it uses “lossy” compression that can blur the photo’s details. Understanding image encoding helps us understand how servlets handle images.A servlet like ViewFile can return a preexisting image by sending its encoded representation unmodified to the client—the browser decodes the image for viewing. But a servlet that generates or modifies an image must construct an internal representation of that image, manipulate it, and then encode it, before sending it to the client.

Image Composition : Drawing over an image

Answer:
we’ve drawn our graphics onto empty images. In this section, we discuss how to take preexisting images and either draw on top of them or combine them to make conglomerate images. We also examine error handling in servlets that return images.One deceptively obvious technique for drawing over a preexisting image is to retrieve the Image with Toolkit.getDefaultToolkit().getImage(imagename), get its graphics context with a call to the getGraphics() method of Image, and then use the returned graphics context to draw on top of the image. Unfortunately, it isn’t quite that easy. The reason is that we cannot use getGraphics() unless the image was created with the createImage() method of Component. With the AWT,we always need to have a native peer in the background doing the actual graphics rendering.

Combining images

Answer:
A servlet can also combine images into one conglomerate image. Using this ability,
a building locator servlet could display an employee’s smiling face over her office,
instead of a red dot. The technique used for combining images is similar to the one we used to draw over the top of an image: the appropriate images are loaded, they’re drawn onto a properly created Image object, and that image is encoded for transmission.

Image Effects

Answer:
we look at how servlets can also perform special effects on images. For example, a servlet can
reduce the transmission time for an image by scaling down its size before transmission. Or it can add some special shading to an image to make it resemble a pressable button. 

Caching a converted image

Answer:
The process of creating and encoding an image can be expensive, taking both time and server CPU cycles. Caching encoded images can often improve performance dramatically. Instead of doing all the work for every request, the results can be saved and resent for subsequent requests. The clock face idea that we mentioned earlier is a perfect example. The clock image needs to be created at most once per minute. Any other requests during that minute can be sent the same image. A chart for vote tabulation is another example. It can be created once and changed only as new votes come in.

Image Effects in Filter Chains

Answer:
Performing special effects on an image works the same whether it happens in a filter chain or in a standard servlet. The only difference is that instead of loading the image from a file, a chained servlet receives its image as an encoded stream of bytes.

An Image of an Embedded Applet

Answer:
Applets are small Java programs that can be sent to a client for execution inside a web page they’ve been used to create everything from animations to interactive programs to static charts. Here we’re going to twist their use a bit. Instead of having the server send a program to the client for execution, we have it send just a picture of the program executing on the server. Now we’ll admit that replacing an executing applet with an image is hardly a fair trade, but it does has its advantages.

Server Push

Answer:
It’s called server push because the server sends, or pushes, a sequence of response pages to the client. Compare this to the client pull technique discussed in the last chapter, where it’s left to the client to get, or pull, each page from the server. Although the results of each technique are similar to the end user—the appearance of a sequence of pages—the implementation details and the appropriate uses of the two techniques are quite different. With server push, the socket connection between the client and the server remains open until the last page has been sent. This gives the server the ability to send page updates quickly and to control exactly when those updates are sent. As such, server push is ideal for pages that need frequent updates or pages that need server-controlled but somewhat infrequent updates. Note, however, that server push is not yet supported by Microsoft Internet Explorer, and extended use should be avoided, as it has been found to be harmful to the server’s available socket count.

Session Tracking

Answer:
The HTTP state problem can best be understood if we imagine an online chat forum where we are the guest of honor. Picture dozens of chat users, all
conversing with us at the same time. They are asking us questions, responding to our questions, and generally making us wish we had taken that typing course back in high school. Now imagine that when each participant writes to us, the
chat forum doesn’t tell us who’s speaking! All we see is a bunch of questions and statements mixed in with each other. In this kind of forum, the best we can do is hold simple conversations, perhaps answering direct questions. If we try to do anything more, such as ask someone a question in return, we won’t necessarily know when the answer comes back. This is exactly the HTTP state problem. The HTTP server sees only a series of requests—it needs extra help to know exactly
who’s making a request.The solution, as we may have already guessed, is for a client to introduce itself as it makes each request. Each client needs to provide a unique identifier that lets the server identify it, or it needs to give some information that the server can use to properly handle the request.

User Authorization

Answer:
One way to perform session tracking is to leverage the information that comes with user authorization. it occurs when a web server restricts access to some of its resources to only those clients that log in using a recognized username and password. After the client logs in, the username is available to a servlet through getRemoteUser().We can use the username to track a client session. Once a user has logged in, the
browser remembers her username and resends the name and password as the user views new pages on the site. A servlet can identify the user through her username and thereby track her session.

Hidden Form Fields

Answer:
One way to support anonymous session tracking is to use hidden form fields. As the name implies, these are fields added to an HTML form that are not displayed in the client’s browser. They are sent back to the server when the form that contains them is submitted. We include hidden form fields with HTML like this : 
... ...

URL Rewriting

Answer:
URL rewriting is another way to support anonymous session tracking. With URL rewriting, every local URL the user might click on is dynamically modified, or rewritten, to include extra information. The extra information can be in the form of extra path information, added parameters, or some custom, server-specific URL change. Due to the limited space available in rewriting a URL, the extra information is usually limited to a unique session ID. For example, the following URLs have been rewritten to pass the session ID 123 : 
http://server:port/servlet/Rewritten original
http://server:port/servlet/Rewritten/123 extra path information
http://server:port/servlet/Rewritten?sessionid=123 added parameter
http://server:port/servlet/Rewritten;$sessionid$123 custom change

Persistent CookiesS

Answer:
A fourth technique to perform session tracking involves persistent cookies. A cookie is a bit of information sent by a web server to a browser that can later be read back from that browser. Cookies were first introduced in Netscape Navigator. Although they were not part
of the official HTTP specification, cookies quickly became a de facto standard supported in all the popular browsers including Netscape 0.94 Beta and up and Microsoft Internet Explorer 2 and up. Currently the HTTP Working Group of the Internet Engineering Task Force (IETF) is in the process of making cookies an official standard as written in RFC 2109.

Working with Cookies

Answer:
Version 2.0 of the Servlet API provides the javax.servlet.http.Cookie class for working with cookies. The HTTP header details for the cookies are handled by the Servlet API, We create a cookie with the Cookie() constructor : 
            public Cookie(String name, String value)
                This creates a new cookie with an initial name and value. The rules for valid names and values are given in Netscape’s Cookie Specification and RFC 2109. A servlet can send a cookie to the client by passing a Cookie object to the addCookie() method of HttpServletResponse : 
public void HttpServletResponse.addCookie(Cookie cookie)

Shopping Using Persistent Cookies

Answer:
fetch the client’s session ID by iterating through the
cookies it received as part of the request. If no cookie contains a session ID, the
Servlet generates a new one using generateSessionId() and adds a cookie
containing the new session ID to the response. The rest of this servlet matches the URL rewriting version, except that this version doesn’t perform any rewriting. Persistent cookies offer an elegant, efficient, easy way to implement session tracking. Cookies provide as automatic an introduction for each request as we could hope for. For each request, a cookie can automatically provide a client’s session ID or perhaps a list of the client’s preferences. In addition, the ability to customize cookies gives them extra power and versatility. The biggest problem with cookies is that browsers don’t always accept cookies. Sometimes this is because the browser doesn’t support cookies. More often, it’s because the user has specifically configured the browser to refuse cookies.

The Session Tracking API

Answer:
servlet developers, it’s not always necessary for a servlet to manage its own sessions using the techniques we have just discussed. The Servlet API provides several methods and classes specifically designed to handle session tracking on behalf of servlets. In other words, servlets have built in session trackingmThe Session Tracking API, as we call the portion of the Servlet API devoted to session tracking, should be supported in any web server that supports servlets. The level of support, however, depends on the server

Session-Tracking Basics

Answer:
Session tracking is wonderfully elegant. Every user of a site is associated with a javax.servlet.http.HttpSession object that servlets can use to store or retrieve information about that user.A servlet uses its request object’s getSession() method to retrieve the current HttpSession object:
public HttpSession HttpServletRequest.getSession(boolean create)
This method returns the current session associated with the user making the request. If the user has no current valid session, this method creates one if create is true or returns null if create is false. To ensure the session is properly maintained, this method must be called at least once before any output is written to the response.

The Session Life Cycle

Answer:
A session either expires automatically, after a set time of inactivity or manually, when it is
explicitly invalidated by a servlet. When a session expires, the HttpSession object and the data values it contains are removed from the system,Beware that any information saved in a user’s session object is lost when the session is invalidated. If we need to retain information beyond that time,we should keep it in an external location and store a handle to the external data in the session object. 
          There are several methods involved in managing the session life cycle : 
> public boolean HttpSession.isNew()
> public void HttpSession.invalidate()
> public long HttpSession.getCreationTime()
> public long HttpSession.getLastAccessedTime()

Putting Sessions in Context

Answer:
When a user first accesses the site, that user is assigned a new HttpSession object and a unique session ID. The session ID identifies the user and is used to match the user with the HttpSession object in subsequent requests. Behind the scenes, the session ID is usually saved on the client in a cookie or sent as part of a rewritten URL. Other Implementations such as using SSL (Secure Sockets Layer) sessions, are also possible.
         A servlet can discover a session’s ID with the getId() method : 
public String HttpSession.getId()
           This method returns the unique String identifier assigned to this session.All valid sessions are grouped together in a HttpSessionContext object.

Storing Session IDs

Answer:
Every server that supports servlets should implement at least cookie-based session
tracking, where the session ID is saved on the client in a persistent cookie. Many web servers also support session tracking based on URL rewriting, as a fallback for browsers that don’t accept cookies. This requires additional help from servlets.For a servlet to support session tracking via URL rewriting, it has to rewrite every local URL before sending it to the client. The Servlet API provides two methods to perform this encoding : 
public String HttpServletResponse.encodeUrl(String url)
        This method encodes (rewrites) the specified URL to include the session ID and returns the new URL, or, if encoding is not needed or not supported, it leaves the URL unchanged.

Session Snoop

Answer:
The SessionSnoop servlet where most of the methods
discussed thus far in the  snoop information about the current session and other sessions on the server.This servlet begins with the same code as the SessionTracker servlet.whether it is a
new session, the session’s creation time, and the session’s last access time. Next the servlet displays whether the requested session ID came from a cookie or a URL and whether the requested ID is valid. Then the servlet iterates over
all the currently valid session IDs, displaying the number of times they have visited.this page. Finally, the servlet prints an encoded URL that can be used to reload this page to test that URL rewriting works even when cookies aren’t supported.

Session Binding Events

Answer:
Any object that implements the javax.servlet.http.HttpSessionBindingListener interface is notified when it is bound or unbound from a session. The interface declares two
methods, valueBound() and valueUnbound(), that must be implemented:
public void HttpSessionBindingListener.valueBound(
HttpSessionBindingEvent event)
public void HttpSessionBindingListener.valueUnbound(
HttpSessionBindingEvent event)
        The valueBound() method is called when the listener is bound into a session, and valueUnbound() is called when the listener is unbound from a session.
   The javax.servlet.http.HttpSessionBindingEvent argument provides access to the name under which the object is being bound (or unbound) with the getName() method : 
public String HttpSessionBindingEvent.getName()
          The HttpSessionBindingEvent object also provides access to the HttpSession object to which the listener is being bound (or unbound) with getSession():
public HttpSession HttpSessionBindingEvent.getSession()

Security

Answer:
Security is the science of keeping sensitive information in the hands of authorized users. On the web, this boils down to three important issues : 
> Authentication : Being able to verify the identities of the parties involved
> Confidentiality : Ensuring that only the parties involved can understand the communication
> Integrity : Being able to verify that the content of the communication is not changed
during transmission.
         Authentication, confidentiality, and integrity are all linked by digital certificate
technology. Digital certificates allow web servers and clients to use advanced cryptographic techniques to handle identification and encryption in a secure manner.

Retrieving Authentication Information

Answer:
A servlet can retrieve information about the server’s authentication using two methods, which is following here : 
> getRemoteUser()
> getAuthType()

Custom Authorization

Answer:
client authentication is handled by the web server. The server administrator tells the server which resources are to be restricted to which users, and information about those users is somehow made available to the server.This is often good enough, but sometimes the desired security policy cannot be implemented by the server. Maybe the user list needs to be stored in a format that is not readable by the server. Or maybe we want any username to be allowed, as
long as it is given with the appropriate “skeleton key” password. To handle these
situations, we can use servlets. A servlet can be implemented so that it learns about users from a specially formatted file or a  elational database; it can also be written to enforce any security policy we like .Such a servlet can even add, remove, or manipulate user entries—something that isn’t supported directly in the Servlet
API, except through proprietary server extensions.

HTTP Authentication

Answer:
the HTTP protocol provides built-in authentication support—called basic authentication—based on a simple challenge/response, username/password model. With this technique, the web server maintains a database of usernames and passwords and identifies certain resources as protected. When a user requests
access to a protected resource, the server responds with a request for the client’s
username and password. At this point, the browser usually pops up a dialog box
where the user enters the information, and that input is sent back to the server as part of a second authorized request. If the submitted username and password match the information in the server’s database, access is granted. The whole authentication process is handled by the server itself.

Form-based Custom Authorization

Answer:
Servlets can also perform custom authorization without relying on HTTP authorization,by using HTML forms and session tracking instead. It’s a bit more effort to give users a well-designed, descriptive, and friendly login page. For example, imagine we’re developing an online banking site, would we rather let the browser present a generic prompt for username and password or provide our customers with a custom login form that politely asks for specific banking credentials.

Digital Certificates

Answer:
Real applications require a higher level of security than basic and digest authentication
provide.They also need guaranteed confidentiality and integrity, as well as more reliable authentication.The key concept is public key cryptography. In a public key cryptographic system, each participant has two keys that are used to encrypt or decrypt information. One is the public key, which is distributed freely. The other is a private key, which is kept secret. The keys are related, but one can not be derived from the other. To demonstrate, assume Jason wants to send a secret message to Will.

Secure Sockets Layer (SSL)

Answer:
The Secure Sockets Layer protocol, or SSL, sits between the application-level protocol and the low-level transport protocol ,It handles the details of security management using
public key cryptography to encrypt all client server communication. SSL was introduced by Netscape with Netscape Navigator 1. It has since become the de facto standard for secure online communications and forms the basis of the Transport Layer Security (TLS) protocol currently under development by the Internet Engineering
Task Force.It provides authentication of the server, confidentiality, and integrity. Here’s how it works : 
> A user connects to a secure site using the HTTPS (HTTP plus SSL) protocol.
> The server signs its public key with its private key and sends it back to the browser.
> The browser uses the server’s public key to verify that the same person who signed the key actually owns it.
> The browser checks to see whether a trusted certificate authority signed the key. If one didn’t, the browser asks the user if the key can be trusted and proceeds as directed .
> The client generates a symmetric (DES) key for the session, which is encrypted with the server’s public key and sent back to the server. This new key is used to encrypt all subsequent transactions. The symmetric key is used because of the high computational cost of public key cryptosystems.

SSL Client Authentication

Answer:
Our security toolbox now includes strong encryption and strong server authentication but only weak client authentication,These are the same type of certificates that servers use, but they are registered to clients instead.Once a client has been authenticated, the server can allow access to protected resources such as servlets or files just as with HTTP authentication. The whole process occurs transparently, without inconveniencing the user. It also provides an extra level of authentication because the server knows the client with a John Smith certificate really is John Smith. The disadvantages of client certificates are that users must obtain and install signed certificates, servers must maintain a database of all accepted public keys, and servers must support SSL 3.0 in the first place. As of this writing, most do, including the Java Web Server.

Retrieving SSL Authentication Information

Answer:
As with basic and digest authentication, all of this communication is transparent to servlets. It is sometimes possible, though, for a servlet to retrieve the relevant SSL authentication information. The java.security package has some basic support for manipulating digital certificates and signatures. To retrieve a client’s digital information, however, a servlet has to rely on a server-specific implementation of the request’s getAttribute() method.

Running Servlets Securely

Answer:
CGI programs and C++ based plugins operate with relatively unfettered access to the server machine on which they execute.This isn’t so bad for an isolated programmer developing for a single web server, but it’s a security nightmare for internet service providers (ISPs), corporations, schools, and everyone else running
shared web servers.the problem isn’t just protecting the server from malicious CGI
programmers. The more troublesome problem is protecting from careless CGI programmers.
There are dozens of well-known CGI programming mistakes that could let a malicious client gain unauthorized access to the server machine. One innocuous-looking but poorly written Perl eval function is all it takes.

The Servlet Sandbox

Answer:
Servlets can use the same technology, if the web server implements it. Local servlets can be trusted to run without a security manager, or with a fairly lenient one. For the Java Web Server 1.1, this is what happens when servlets are placed in the default servlet directory or another local source. Servlets loaded from a remote source, on the other hand, are by nature suspect and untrusted, so the Java Web .Server forces them to run in a very restrictive environment where they can’t access the local file system, establish network connections, and so on.* All this logic is contained within the server and is invisible to the servlet, except that the servlet may see a SecurityException thrown when it tries to access a restricted resource. The servlet sandbox is a simple model, but it is already more potent than any other server extension technology to date.

Fine-grained Control

Answer:
This all-or-nothing approach to servlet permissions is useful, but it can be overly limiting. Consequently, some servlet engines have begun to explore a more finegrained protection of server resources,The Java Web Server 1.1 includes eight permissions that can be granted to servlets:
> Load servlet : Let the servlet load a named servlet.
> Write files : Let the servlet write any file on the local file system.
> Listen to socket : Allow the servlet to accept incoming socket (network) connections.
> Link libraries : Allow the loading of native libraries, such as the JDBC-ODBC bridge.
> Read files : Let the servlet read any file on the local file system.
> Open remote socket : Allow the servlet to connect to an external host.
> Execute programs : Permit the servlet to execute external programs on the server. This is useful for servlets that absolutely require access to some system utilities, but it is very dangerous: rm and del qualify as an external programs!
> Access system properties : Grant access to java.lang.System properties.

Access Controllers

Answer:
An access controller allows what might be called super-fine-grained permission control. Instead of granting a servlet the general ability to write files, with an access controller a servlet can be given the right to write to a single file—perfect
for a counter servlet,Access controllers work by placing individual pieces of code, often identified by digital signatures, into particular virtual domains. Classes in these domains can be
granted fine-grained permissions, such as the ability to read from the server’s document
root, write to a temporary directory, and accept socket connections. All permission policy decisions are managed by a single instance of the java.security. AccessController class. This class bases its policy decisions on a simple configuration file, easily managed using a graphical user interface.

Database Connectivity

Answer:
Webmasters have hooked online front ends to all manner of legacy systems, including package tracking and directory databases, as well as many
newer systems like online messaging, storefronts, and search engines. But webdatabase interaction comes with a price: database-backed web sites can be difficult to develop and can often exact heavy performance penalties,the Structured Query  Language (SQL) used to manipulate those databases, and the Java database connectivity (JDBC) API itself. Servlets, with their enduring life cycle, and JDBC, a well-defined database-independent database connectivity API, are an elegant and efficient solution for webmasters who need to hook their web sites to back-end databases.

Relational Databases

Answer:
The use of a flat file is fine for a small amount of data, but it can quickly get out of control. As the amount of data grows, access times slow to a crawl. And just finding data can become quite a challenge: imagine storing the names, cities, and email addresses of all pur The use of a flat file is fine for a small amount of data, but it can quickly get out of control. As the amount of data grows, access times slow to a crawl. And just finding data can become quite a challenge :  imagine storing the names, cities, and email addresses of all,One of the best solutions to this problem is a Relational Database Management
System (RDBMS). At the most basic level, an RDBMS organizes data into tables. These tables are organized into rows and columns, much like a spreadsheet. Particular rows and columns in a table can be related (hence the term “relational”) to one or more rows and columns in another table.

Servlets in the Middle Tier

Answer:
One common place for servlets, especially servlets that access a database, is in what’s called the middle tier. A middle tier is something that helps connect one endpoint to another,and along the way adds a little something of its own. The most compelling reason for putting a middle tier between a client and our
ultimate date source is that software in the middle tier,can include business logic. Business logic abstracts complicated low-level tasks into high-level tasks making the whole operation simpler and safer.Middleware uses business logic to abstract the ordering process. Middleware
accepts information about the order sanity-checks the information, verifies that the credit
card is valid, and enters the information into the database. Should the database change, the middleware can be updated without any changes in the client. Even if the orders database is temporarily replaced with a simple flat file order log, the middleware can present the same appearance to the client.

The JDBC API

Answer:
JDBC is a SQL-level API—one that allows you to execute SQL statements and retrieve the results, if any. The API itself is a set of interfaces and classes designed to perform actions against any database

JDBC Drivers

Answer:
The JDBC API, found in the java.sql package, contains only a few concrete classes. Much of the API is distributed as database-neutral interface classes that specify behavior without providing any implementation. The actual implementations
are provided by third-party vendors. An individual database system is accessed via a specific JDBC driver that implements the java.sql.Driver interface. Drivers exist for nearly all popular RDBMS systems, though few are available for free. Sun bundles a free JDBC-ODBC bridge driver with the JDK to allow access to standard ODBC data sources, such as a Microsoft Access database. However, Sun advises against using the bridge driver,There are four driver categories : 
> Type 1-JDBC-ODBC Bridge Driver : Type 1 drivers use a bridge technology to connect a Java client to an ODBC database service. Sun’s JDBC-ODBC bridge is the most common Type 1 driver. These drivers are implemented using native code.
> Type 2-Native-API Partly-Java Driver : Type 2 drivers wrap a thin layer of Java around database-specific native code libraries. For Oracle databases, the native code libraries might be based on the OCI,libraries, which were originally designed for C/ C++ programmers. Because Type 2 drivers are implemented using native code, in some cases they have better performance than their all-Java counterparts. They add an element of risk, however, because a defect in a driver’s native code section can crash the entire server.
> Type 3-Net-Protocol All-Java Driver : Type 3 drivers communicate via a generic network protocol to a piece of custom middleware. The middleware component might use any type of driver to provide the actual database access. WebLogic’s Tengah product line is an example. These drivers are all Java, which makes them useful for applet deployment and safe for servlet deployment.
> Type 4-Native-Protocol All-Java Driver : Type 4 drivers are the most direct of the lot. Written entirely in Java, Type 4 drivers understand database-specific networking protocols and can access the database directly without any additional software.

Getting a Connection

Answer:
The first step in using a JDBC driver to get a database connection involves loading the specific driver class into the application’s JVM. This makes the driver available later, when we need it for opening the connection. An easy way to load the driver class is to use the Class.forName() method : 
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         When the driver is loaded into memory, it registers itself with the java.sql.
DriverManager class as an available database driver. The next step is to ask the DriverManager class to open a connection to a given database, where the database is specified by a specially formatted URL. The method used to open the connection is DriverManager.getConnection(). It returns a class that implements the java.sql.Connection interface : 
Connection con =
DriverManager.getConnection("jdbc:odbc:somedb", "user", "passwd");

Executing SQL Queries

Answer:
The simplest way to execute a query is to use the java.sql.Statement class. Statement objects are never instantiated directly; instead, a program calls the createStatement() method of Connection to obtain a new Statement object:
Statement stmt = con.createStatement();
              A query that returns data can be executed using the executeQuery() method of Statement. This method executes the statement and returns a java.sql.
ResultSet that encapsulates the retrieved data:
ResultSet rs = stmt.executeQuery("SELECT * FROM CUSTOMERS");

Handling SQL Exceptions

Answer:
DBPhoneLookup encloses most of its code in a try/catch block. This block catches two exceptions: 
> ClassNotFoundException and 
> SQLException. 
      The former is thrown by the Class.forName() method when the JDBC driver class can not be loaded. The latter is thrown by any JDBC method that has a problem. SQLException objects are just like any other exception type, with the additional
feature that they can chain. The SQLException class defines an extra method,getNextException(), that allows the exception to encapsulate additional Exception objects. We didn’t bother with this feature in the previous example,
but here’s how to use it : 
catch (SQLException e) {
out.println(e.getMessage());
while((e = e.getNextException()) != null) {
out.println(e.getMessage());
}
}

Result Sets in Detail

Answer:
we should take a closer look at the ResultSet interface and the related ResultSetMetaData interfaceThe ResultSetMetaData interface provides a way for a program to learn about the underlying structure of a query result on the fly. We can use it to build an object that dynamically generates an HTML table from a ResultSet,

Handling Null Fields

Answer:
Handling null database values with JDBC can be a little tricky,A method that doesn’t return an object, like getInt(), has no way of indicating whether a column is null or whether it contains actual information.Any special value like -1, might be a legitimate value. Therefore, JDBC includes the wasNull() method in ResultSet, which returns true or false depending on whether the last column read was a true database null.

Updating the Database

Answer:
Most database-enabled web sites need to do more than just perform queries. When a client submits an order or provides some kind of information, the data needs to be entered into the database.When we know we were executing a SQL UPDATE, INSERT, or DELETE statement and we know we dont expect a ResultSet , We can use the executeUpdate() method of Statement. It returns a count that indicates the number of rows modified by the statement. It’s used like this : 
int count =
stmt.executeUpdate("DELETE FROM CUSTOMERS WHERE CUSTOMER_ID = 5");

Using Prepared Statements

Answer:
A PreparedStatement object is like a regular Statement object, in that it can be used to execute SQL statements. The important difference is that the SQL in a PreparedStatement is precompiled by the database for faster execution. Once a PreparedStatement has been compiled, it can still be customized by adjusting predefined parameters. Prepared statements are useful in applications that have to run the same general SQL command over and over,
PreparedStatement pstmt = con.prepareStatement(
"INSERT INTO ORDERS (ORDER_ID, CUSTOMER_ID, TOTAL) VALUES (?,?,?)");
// Other code
pstmt.clearParameters(); // clear any previous parameter values
pstmt.setInt(1, 2); // set ORDER_ID
pstmt.setInt(2, 4); // set CUSTOMER_ID
pstmt.setDouble(3, 53.43); // set TOTAL
pstmt.executeUpdate(); // execute the stored SQL

Reusing Database Objects

Answer:
we mentioned that the servlet life cycle allows for extremely fast database access. After JDBC for a short time, it will become evident that the major performance bottleneck often comes right at the beginning, when we are opening a database connection. This is rarely a problem for most applications and applets because they can afford a few seconds to create a Connection that is used for the life of the program. 

Reusing Database Connections

Answer:
JDBC for a short time, it will become
evident that the major performance bottleneck often comes right at the beginning, when we are opening a database connection. This is rarely a problem for most applications and applets because they can afford a few seconds to create a Connection that is used for the life of the program. 

Reusing Prepared Statements

Answer:
The PreparedStatement object is an ideal candidate because it can precompile a SQL statement. This usually saves only a few milliseconds, but if our site gets a few hundred thousand hits a day, that can add up pretty quickly.sharing objects other than connections poses a problem. Servlets must be thread safe, and accessing a PreparedStatement might require three or four method calls. If one thread calls the clearParameters() method of PreparedStatement right before another thread calls execute(), the results of execute() will be disastrous. Also, there’s the limitation that a Statement can
support only one query at the time .

Transactions

Answer:
we have failed to mention one important feature of modern relational database systems: transactions. Most service-oriented web sites need to do more than run SELECT statements and insert single pieces of data. SQL failure is not the only potential problem. If another user checks the account balance in between the credit and the debit, he will see the original balance. The database is shown in an invalid state.

Using Transactions with JDBC

Answer:
Transaction management with JDBC takes place via the Connection object,This means that every
SQL statement is executed as an individual transaction that is immediately committed to the database.We can check the status of auto-commit with the get AutoCommit() method. Once we have completed all of your SQL statements, we
call commit() to permanently record the transaction in the database. Or, if we encountered an error we call rollback() to undo it.

Optimized Transaction Processing

Answer:
There are several possibilities : 
> Synchronize the doPost() method. This means that each instance of the servlet deals with only one request at a time. This works well for very low traffic sites, but it does slow things down for our users because every transaction has
to finish before the next can start.
> Leave things as they are, but create a new Connection object for each transaction.
> Create a pool of Connection objects in the init() method and hand them out as needed.
> Create a single Connection object in the init() method and have the servlet
implement SingleThreadModel, so the web server creates a pool of servlet instances with a Connection for each.
> Implement session tracking in the servlet and use the HttpSession object to hold onto a Connection for each user.

Connection Pooling

Answer:
A connection pool canalso intelligently manage the size of the pool and make sure each connection
remains valid. A number of connection pool packages are currently available.Using a pooling driver like
this is the easiest way to implement connection pooling in our servlets. Pooling
drivers, however, have a little more operational overhead than standard drivers
because every JDBC class needs to be wrapped by another class. This is transparent to the programmer and won’t make much of a difference with most Java applications—but with a high-performance, high-volume servletapplication, every little performance gain helps.

Connections as Part of a Session

Answer:
directly binding a connection to the session, we’ve created a simple holder class that implements the HttpSessionBindingListner interface. We do this because database connections are the most limited resource in a JDBC application and we want to make sure that they will be released properly when no longer needed. The wrapper class also allows us to rollback any uncommitted changes. If a user leaves our hypothetical online shopping system before checking out, her transaction is rolled back when the session expires.

Advanced JDBC Techniques : Stored Procedures

Answer:
a few advanced techniques that use servlets and JDBC. First, we’ll examine how servlets can access stored database procedures. Then we’ll look at how servlets can fetch complicated data types, such as binary data large quantities of text, or even executable database-manipulation code, from a database.Most RDBMS systems include some sort of internal programming language. One
example is Oracle’s PL/SQL. These languages allow database developers to embed procedural application code directly within a database and then call that code from other applications. RDMBS programming languages are often well
suited to performing certain database actions; many existing database installations have a number of useful stored procedures already written and ready to go. Most introductions to JDBC tend to skip over this topic, so we’ll cover it here briefly.

Communication Options

Answer:
Our interest in stock trading has risen along with the Dow,We’ll use it solely as a reference point for
discussing the issues involved in applet-server communication,This stock tracking applet of ours needs to get a stock feed from some server
machine. Assuming it’s a normal, untrusted applet, there’s just one choice: the machine from which it was downloaded. Any attempt to connect to another machine results in a SecurityException,

HTTP and Raw Socket Connections

Answer:
here were two options for applet-server communication : 
> Have the applet establish an HTTP connection to a CGI program on the server machine. The applet acts like a browser and requests a page, parsing the response for its own use. The applet can provide information using a query string or POST data and can receive information from the returned
page. 
> Have the applet establish a raw socket connection to a non-HTTP server running on the server machine. The non-HTTP server can listen to a particular port and communicate with the applet using whatever custom protocol they agree upon.
         Having an applet make an HTTP connection to a CGI program works well for these reasons : 
> It’s easy to write. The applet can take advantage of the java.net.URL and
java.net.URLConnection classes to manage the communication channel, and the CGI program can be written like any other.
> It works even for applets running behind a firewall. Most firewalls allow HTTP connections but disallow raw socket connections.
> It allows a Java applet to communicate with a program written in any language. The CGI program doesn’t have to be written in Java. It can be in Perl, C, C++, or any other language.
> It works with applets written using JDK 1.0, so it works with all Java-enabled browsers.
> It allows secure communication. An applet can communicate with a secure server using the encrypted HTTPS (HTTP + SSL) protocol.

Servlets and Object Serialization

Answer:
Servlets are starting to replace slow-starting CGI programs, improving the performance of HTTP-based applet-server communication and making frequent applet-server communication feasible. While it’s true in the general case that the applet and the servlet still have to take time to reestablish their connection for each request and response, the applet no longer has to wait as the server launches a CGI program to handle each of its repeated requests.
        Java object serialization has simplified the issues involved with formatting responses. With both applets and servlets written in Java, it’s only natural that they should communicate by exchanging Java objects

The Hybrid Approach

Answer:
When RMI isn’t available, the bidirectional capabilities of the non-HTTP socket connection make it look fairly attractive. Unfortunately, that bidirectional communication becomes nonexistent communication when the applet ends up on the far side of a firewall. There’s always the old workhorse, HTTP communication. It’s straightforward to implement and works on every Java-enabled client.Perhaps the best solution is to use every solution, with servlets. Servlets make it possible to combine the HTTP, non-HTTP, and RMI applet-server communication techniques, supporting them all with a single servlet.

Daytime Server

Answer:
simple demonstration of each communication technique, we’re going to write an applet that asks its server for the current time of day. The applet first uses an HTTP connection, then a non-HTTP socket connection, and finally an RMI connection. Of course, an applet can normally get the current time from the system on which it’s running.

Text-based HTTP Communication : The servlet

Answer:
This is implementing the lowest-common-denominator approach—textbased HTTP communication.For the DaytimeApplet to retrieve the current time from the server, it has to communicate with a servlet that returns the current time.servlet’s class files should be placed in the standard location for servlets, typically server_root/servlets.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DaytimeServlet extends HttpServlet {
public Date getDate() {
return new Date();
}
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
out.println(getDate().toString());
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doGet(req, res);
}
}

Object-based HTTP Communication : The servlet

Answer:
we can have the DaytimeApplet receive the current
time as a serialized Date object.For backward compatibility, let’s change our DaytimeServlet to return a serialized Date only if the request asks for it by passing a "format" parameter with the
value "object".This technique can be used to send any primitive types and/or any Java objects that implement the Serializable interface, including a Vector that contains Serializable objects. Multiple objects can also be written to the same ObjectOutputStream, as long as the class receiving the objects reads them in the same order and casts them to the same types. we may notice that the servlet didn’t set the content type of the response to indicate
it contained a serialized Java object. The reason is that currently there are no
standard MIME types to represent serialized objects. This doesn’t really matter,though. A content type acts solely as an indication to the client of how to handle or display the response. If an applet already assumes it’s receiving a specific serialized Java object, everything works fine. Sometimes, though, it’s useful to use a custom MIME type.so that a servlet can indicate to
an applet the contents of its response.

Posting a serialized object

Answer:
Before we go on, we should look at one more method
from the HttpMessage class : sendPostMessage(Serializable). This method
helps an applet upload a serialized object to a servlet using the POST method. This object transfer isn’t particularly useful to our daytime server example .but we mention it because it can come in handy when an applet needs to upload complicated data structures to its server.The servlet can receive the type of the uploaded object as the subtype of the content type. Note that this sendPostMessage method uploads just one object at a time and uploads only serializable objects.

Socket Communication : The servlet

Answer:
an applet and servlet can communicate using non-
HTTP socket communication.The servlet’s role in this communication technique is that of a passive listener. Due to security restrictions, only the applet can initiate a socket connection. A
servlet must be content to listen on a socket port and wait for an applet to connect. Generally speaking, a servlet should begin listening for applet connections in its init() method and stop listening in its destroy() method. In between, for every connection it receives, it should spawn a handler thread to communicate with the client.
With HTTP socket connections, these nitty-gritty details are managed by the web server. The server listens for incoming HTTP requests and dispatches them as appropriate, calling a servlet’s service(), doGet(), or doPost() methods as necessary. But when a servlet opts not to use HTTP communication, the web server can’t provide any help. The servlet acts, in essence, like its own server and thus has to manage the socket connections itself.

RMI Communication : The servlet

Answer:
the code required for a servlet to make itself available via RMI communication can be ridiculously simple. First, we’ll lead we through the step-by-step instructions on how to make a servlet a remote object.all RMI remote objects must implement a specific interface. This
interface does two things: it declares which methods of the remote object are to be made available to remote clients, and it extends the Remote interface to indicate it’s an interface for a remote object.Every method made available via RMI must declare that it throws this exception. Although the method itself may not
throw the exception, it can be thrown by the system to indicate a network service failure. The code for DaytimeServlet remains mostly unchanged from its original version. In fact, the only changes are that it now implements DaytimeServer and extends  com.oreilly.servlet.RemoteHttpServlet, the superclass that allowsthis servlet to remain so unchanged. The servlet also implements a destroy()method that calls super.destroy().

The superclass

Answer:
A remote object needs to do two things to prepare itself for RMI communication: it needs to export itself and register itself. When a remote object exports itself, it begins listening on a port for incoming method invocation requests. When aremote object registers itself, it tells a registry server its name and port number, so that clients can locate it and communicate with it. This rewrite requires RemoteHttpServlet to do two things it wouldn’t have to do if it extended UnicastRemoteObject. First, it must declare that it implements the Remote interface. All remote objects must implement this interface, but normally, by extending UnicastRemoteObject, a class gets this for free. Still, the price for going it alone isn’t too bad, as the Remote interface doesn’t actually define any methods. An object declares that it implements Remote solely to express its desire to be treated as a remote object.The second thing RemoteHttpServlet has to do is manually export itself. Normally, this is performed automatically in the UnicastRemoteObject() constructor. But again, doing this without that constructor is not a problem. The UnicastRemoteObject class has a static exportObject(Remote) method that any Remote object can use to export itself. RemoteHttpServlet uses this method and exports itself with this single line : 
UnicastRemoteObject.exportObject(this); 
        Those two steps, implementing Remote and exporting itself, are done by RemoteHttpServlet in lieu of extending UnicastRemoteObject.*

A full-service servlet

Answer:
we need now is a single servlet that can make itself available via HTTP communication, non-HTTP socket communication, and RMI communication. A
servlet of this sort can extend a new superclass, com.oreilly.servlet. RemoteDaemonHttpServlet, implementing the capabilities discussed so far for
both an RemoteHttpServlet and a DaemonHttpServlet.

Chat Server

Answer:
RMI communication or the elegance of RMI callbacks.It also didn’t provide a compelling reason for why one servlet should support all the communication techniques—there was no state to maintain or complicated code base to collect in one location. So, before we end our discussion
of applet-servlet communication we can see more sophisticated example: a chat server, implemented as a servlet, that supports clients connecting via HTTP, non-HTTP sockets, and RMI.We’ll build this chat server using all three communication techniques so that it can take advantage of the best, most efficient solution for each client. For example, when the client supports RMI, the servlet can be treated as a remote object, and (where possible) it can treat the applet as a remote object, too. When the client doesn’t support RMI but can support direct socket communication, the chat server can utilize socket persistence and communicate with the client using a non-HTTP socket protocol. And, of course, when all else fails, the chat server can fall back to using HTTP. It would rather not fall back because HTTP, being stateless, requires that the client poll for updates. But for many clients, HTTP is the only choice.

The Design

Answer:
HTTP chat clients post their messages to the server using the HTTP POST method. The applet takes the new message from the TextInput component when the user hits Enter, URL-encodes the message, and posts it to the servlet as a
message parameter. It’s all very straightforward. What is a bit more complicated is how an HTTP chat client manages to get the other clients’ messages. It uses the HTTP GET method to receive each message, but it has a problem: it doesn’t know when exactly there’s a new message to get. This is the problem with a unidirectional
request/response communication paradigm. The client has to either periodically poll for updates or simulate bidirectional communication by making a series of blocking GET requests. By that we mean the chat client initiates a GET
request that blocks until the server decides it’s time to return something. For our example, we implement this simulated bidirectional communication.

The Servlet

Answer:
The broadcastMessage() method tells all listening clients when there’s a new message. It notifies HTTP clients by sending the message to the MessageSource; other clients it notifies directly by looping through its client list. For each of its socket-connected clients, it prints the message to the client’s socket. For each of its RMI clients, it calls the client’s setNextMessage(String) method. This is the
callback we’ve been talking about. If, at any point, there’s a problem with a socket or RMI client, it removes that client from its list. The two lists, socketClients and rmiClients, are populated as the servlet hears from clients. When a socket client connects, the servlet’s handleClient(Socket) method is called and the new client is added to the socketClients Vector. RMI clients have to add themselves to the list by invoking the servlet’s addClient(ChatClient) method.

The Dispatcher

Answer:
This servlet performs two duties. First, when this servlet is accessed without any request parameters, it prints a friendly welcome page asking the user which applet version is interested in using.when it’s accessed with a request parameter, it prints a page that contains the appropriate applet,URL used to access this dispatch servlet should contain the server’s true name, not localhost, so as to avoid RMI security problems.a servlet generates a page that contains an applet and passes information to the applet by manipulating the applet’s  tags. Any information the servlet wants to send to a new applet can be sent this way. In this example, the servlet sends the name returned by eq.getRemoteUser(). In another example, a servlet could tell the applet its browser type by sending it the string returned by req.getHeader("User-Agent").

Interservlet Communication

Answer:
interservlet communication bassiclaly use in three major reasons : 
> Direct servlet manipulation : A servlet can gain access to the other currently loaded servlets and perform some task on each.
> Servlet reuse : One servlet can use another’s abilities to perform a task,It was written as a server for chat applets, but it could be reused (unchanged) by another servlet that needed to
support an HTML-based chat interface.
> Servlet collaboration : The most common, situation involves two or more servlets sharing state information.session tracking is a special case of servlet collaboration.

Servlet Manipulation

Answer:
Direct servlet manipulation involves one servlet accessing the loaded servlets on its server and optionally performing some task on one or more of them. A servlet obtains information about other servlets through the ServletContext object. Use getServlet() to get a particular servlet : 
public Servlet ServletContext.getServlet(String name) throws ServletException
        This method returns the servlet of the given name, or null if the servlet is not
found. The specified name can be the servlet’s registered name (such as "file") or its class name.The server maintains one servlet instance per name, so getServlet("file") returns a different servlet instance than getServlet("com.sun.server.webserver .
FileServlet").

Servlet Reuse

Answer:
Another use for interservlet communication is to allow one servlet to reuse the abilities of another servlet. The major challenge with servlet reuse is for the “user” servlet to obtain the proper instance of “usee” servlet when the use servlet has not yet been loaded into the server,The obvious solutions don’t always work. getServlet() isn’t guaranteed to load the named servlet on all servers; it may just return null. Directly creating a new.instance of the usee servlet doesn’t work either, as the newly created servlet doesn’t have access to its own ServletConfig and ServletContext objects. Plus, the server would be using a different instance to handle client requests, leaving the new instance of the servlet without the right state information.

Servlet Collaboration

Answer:
Servlets have to cooperate, usually by sharing some information. We call communication of this sort servlet collaboration. Collaborating servlets can pass the shared information directly from one servlet to another through method invocations, as shown earlier. This approach requires each servlet to know the other servlets with which it is collaborating—an unnecessary burden.

Collaboration Through the System Properties List

Answer:
One simple way for servlets to share information is by using Java’s system-wide Properties list, found in the java.lang.System class. This Properties list holds the standard system properties, such as java.version and path.
separator, but it can also hold application-specific properties. Servlets can use the properties list to hold the information they need to share. A servlet can add (or change) a property by calling : 
System.getProperties().put("key", "value");
               That servlet, or another servlet running in the same JVM, can later get the value of the property by calling : 
String value = System.getProperty("key");
           The property can be removed by calling:
System.getProperties().remove("key");
              It’s best if the key for a property includes a prefix that contains the name of the
servlet’s package and the name of the collaboration group.

Using properties to sell burritos

Answer:
Despite the stern warnings, servlet collaboration through the system-wide Properties list works well for servlets that are sharing insensitive, noncritical, easily replaceable information. As a fun example, imagine a set of servlets that sell
burritos and share a “special of the day.” An administrative servlet could set the special of the day using the following code : 
System.getProperties().put("com.LaCostena.special.burrito", "Pollo Adobado");
System.getProperties().put("com.LaCostena.special.day", new Date());

Faster image chaining

Answer:
Servlets performing image effects in a servlet chain can boost their speed dramatically by using the system Properties list to pass their images. The first servlet takes an Image object encodes it to a stream of bytes, and passes the bytes to the next servlet. The receiving servlet decodes the bytes back into the original Image object. The technique works fine, but it can be prohibitively slow for large images. An alternative solution is for the first servlet to save the Image object itself in the system-wide Properties list, then pass on a small unique key by which the next servlet in the chain can locate the Image.

Collaboration Through a Shared Object

Answer:
A shared object can hold the pool of shared information and make it available to each
servlet as needed. In a sense, the system Properties list is a special case example
of a shared object. By generalizing the technique into sharing any sort of object,a servlet is able to use whatever shared object best solves its particular problem.
           Often the shared object incorporates a fair amount of business logic or rules for
manipulating the object’s data. This business logic protects the shared object’s actual data by making it available only through well-defined methods. It can enforce data integrity, trigger events to handle certain conditions, and basically
abstract lots of little data manipulations into a single method invocation. This capability isn’t available with the Properties list.

Collaboration Through Inheritance

Answer:
Its easiest technique for servlet collaboration is through inheritance. Each servlet interested in collaborating can extend the same class and inherit the same shared information. This simplifies the code for the collaborating servlets
and limits access to the shared information to the proper subclasses. The common superclass can hold a reference to the shared information, or it can hold the shared information itself.

Internationalization

Answer:
Many web servers also support a transparent solution, where a single URL can be used to view the same content in several languages, with the language chosen based on the preferences of the client.Although this technique creates the impression that a dynamic translation is
occurring, in reality the server just has several specially named versions of the static document at its disposal.

HTML Character Entities

Answer:
HTML 2.0 introduced the ability for specific sequences of characters in an HTML page to be displayed as a single character. The sequences, called character entities, begin with an ampersand (&) and end with a semi-colon (;). Character entities can either be named or numbered.

Unicode Escapes

Answer:
In Java, all characters, strings, and identifiers are internally composed of 16-bit,Unicode characters. Unicode was established by the Unicode Consortium, which describes the standard as follows, The Unicode Worldwide Character Standard is a character coding system designed to support the interchange, processing, and display of the written texts of the diverse languages of the modern world. In addition, it supports classical and historical texts of many written languages.Java’s use of Unicode is very important to this chapter because it means a servlet
can internally represent essentially any character in any commonly used written language.

Conforming to Local Customs

Answer:
A DateFormat object is created using a factory method that accepts a formatting style and a java.util.Locale object that identifies the target audience The most common Locale constructor accepts two parameters : 
> A two-character lowercase language
abbreviation and a two-character uppercase country code as defined by ISO-3166 .An empty string for the country code indicates the default country for the language.

Charsets

Answer:
every byte represents one of 256 possible characters and to further assume that the character a byte represents can be determined by looking up the byte value in some table. The default table is specified by the ISO-8859-1 standard, also called Latin-1. It contains byte-to-character mappings for the characters most commonly used in Western European languages.
Some charsets use single-byte characters in a fashion similar to ISO-8859-1, though with a different byte-to-character mapping,Other charsets use multibyte characters, where it may take more than one byte to represent a single character. This is most common with languages that contain thousands of characters, such as Chinese, Japanese, and Korean—often referred to
collectively as CJK.

Writing Encoded Output

Answer:
charsets bassically from the perspective of the browser, it’s time to return to the perspective of the servlet. A servlet’s role is to do the following : 
> Choose a charset and set it for the servlet.
> Get a PrintWriter for that charset.
> Output characters that can be displayed using that charset.Then it calls res.getWriter() just like always—except in this case the PrintWriter it receives is special. This PrintWriter encodes all the servlet’s output in the Shift_JIS charset because that charset is specified in the Content Type header. This second line is therefore equivalent to the following : 
PrintWriter out = new PrintWriter(
new OutputStreamWriter(res.getOutputStream(), "Shift_JIS"), true);

Reading and Writing Encoded Output

Answer:
Its bassiclaly can often be prohibitively slow to enter hundreds or thousands of Unicode escapes manually in Java source files. An easier option is to read localized text from an encoded file. For example, let’s assume the “Hello World” Japanese text we want to output is saved by someone on the localization team in a file named HelloWorld.ISO-2022-JP, using the ISO-2022-JP encoding to make things more interesting. A servlet can read this file and send the content to the browser using the Shift_JIS encoding.This servlet is essentially a character encoding converter. It reads the HelloWorld. ISO-2022-JP text encoded with ISO-2022-JP and internally converts it to Unicode. Then, it outputs the same text by converting from Unicode to Shift_JIS.

Multiple Languages : UCS-2 and UTF-8

Answer:
It is the best way to generate a page containing multiple languages is to output 16-bit Unicode characters to the client. There are two common ways to do this: UCS-2 and UTF-8. UCS-2 sends Unicode characters in what could be called their natural format, two bytes per character. All
characters, including US-ASCII characters, require two bytes. UTF-8 is a variable-length encoding. With UTF-8, a Unicode character is transformed into a 1-, 2-, or 3-byte representation. In general, UTF-8 tends to be more efficient than UCS-2 because it can encode a character from the US-ASCII charset using just 1 byte.

Writing UTF-8

Answer:
Earlier versions of Java throw an UnsupportedEncodingException when trying to get the PrintWriter, and the page is left blank. The problem is a missing charset alias. Java has had support for the UTF-8 encoding since JDK 1.1 was first introduced. Unfortunately, the JDK used the name “UTF8” for the encoding, while browsers expect the name “UTF-8.” So, who’s right? It wasn’t clear until early 1998, when the IANA (Internet Assigned Numbers Authority) declared “UTF-8” to be the preferred name.

Language Preferences

Answer:
There are two ways a servlet can know the language preferences of the client : 
> the browser can send the information as part of its request. Newer browsers, such as Netscape Navigator 4 and Microsoft Internet Explorer 4, allow users to specify their preferred languages.\
> servlet can know the language preferences of the client is by asking. For example, a servlet might generate a form that asks which language the client prefers.

Charset Preferences

Answer:
Accept-Language HTTP header, a browser may send an
Accept-Charset header that tells the server which charsets it understands. An Accept-Charset header value may look something like this : 
          iso-8859-1, utf-8 
          This indicates the browser understands ISO-8859-1 and UTF-8. If the Accept-Charset isn’t sent or if its value contains an asterisk (*), it can be assumed the client accepts all charsets.

Resource Bundles

Answer:
Using Accept-Language a servlet can determine the language in which it will speak to each client,A resource bundle holds a set of localized resources appropriate for a given locale.All resource bundles extend java.util.ResourceBundle. A servlet can load a resource bundle using the static method ResourceBundle.getBundle():
public static final
ResourceBundle ResourceBundle.getBundle(String bundleName, Locale locale)
            A servlet can pull phrases from a resource bundle using the getString() method of ResourceBundle : 
public final String resourceBundle.getString(String key)

The LocaleNegotiator Class

Answer:
LocaleNegotiator works by scanning through the client’s language preferences looking for any language for which there is a corresponding resource bundle. Once it finds a correspondence, it uses LocaleToCharsetMap to determine the
charset. If there’s any problem, it tries to fall back to U.S. English. The logic ignores the client’s charset preferences.The most complicated aspect of the LocaleNegotiator code is having to deal with the unfortunate behavior of ResourceBundle.getBundle(). The getBundle() method attempts to act intelligently

HTML Forms

Answer:
An HTML form is sent as part of a Japanese page. It asks the user for his name, which he enters as a string of Japanese characters.The answer to the first question is that all HTML form data is sent as a sequence of bytes. Those bytes are an encoded representation of the originalcharacters . With Western European languages, the encoding is the default, ISO-8859-1, with one byte per character.A servlet has two choices. First, a servlet can leave the form data in its raw encoded format, treating it essentially like a sequence of bytes—with each byte awkwardly stored as a character in the parameter string. This
tactic is useful only if the servlet does not need to manipulate the data and can be sure that the data is output only to the same user using the same charset. Alternatively, a servlet can convert the form data from its native encoded format to a Javafriendly Unicode string. This allows the servlet to freely manipulate the text and output the text using alternate charsets. There is one problem with this plan, however. Browsers currently provide no information to indicate which encoding was used on the form data.

The Hidden Charset

Answer:
The commonly accepted technique for tracking the charset of submitted form data is to use a hidden charset form field.* Its value should be set to the charset of the page in which it is contained. Then, any servlet receiving the form can read the value of the charset field and know how to decode the submitted form data.servlet reads the submitted text and converts it to Unicode,
then outputs the characters using the UTF-8 encoding. As a bonus, it also displays the received string as a Unicode escape string, showing what you would have to enter in a Java source file or resource bundle to create the same output. This lets the servlet act as a web-based native charset to Unicode string translator.

Receiving Multilingual Input

Answer:
It’s actually quite simple for a servlet to receive multilingual character data. The ServletRequest.getReader() method handles the task automatically. It returns a BufferedReader specially built to read the character encoding
of the input data. For example, if the Content Type of the servlet’s input is "text/html; charset=Shift_JIS", the BufferedReader is one that reads Shift_JIS characters. Because getReader() works automatically, it means our Deblink servlet and other chained servlets found throughout the book are already multilingual
friendly. No matter what charset is used for the content they receive, they always read the input characters correctly using getReader().

Parsing Parameters

Answer:
The parameter parser’s getIntParameter() method returns the specified parameter’s value as an int. It throws a NumberFormatException if the parameter cannot be converted to an int and a ParameterNotFoundException if the parameter isn’t part of the request. It also throws ParameterNotFoundException if the parameter had a value of the empty string. This often happens with form submissions for text fields when nothing is entered, something that for all intents
and purposes should be treated the same as a missing parameter. If it’s enough that a servlet use a default value if there’s a problem with a parameter, as is often the case, the code can be simplified even further : 
ParameterParser parser = new ParameterParser(req);
int count = parser.getIntParameter("count", 0);
         This second version of getIntParameter() takes a default value of 0 that is returned in lieu of throwing an exception.

ParameterParser Code

Answer:
The ParameterParser class contains more than a dozen methods that return request parameters—two for each of Java’s native types. It also has two
getStringParameter() methods in case we want to get the parameter in its raw String format.

Sending Email

Answer:
The servlet might want to send the feedback data to a mailing list of interested parties. Or imagine a servlet that encounters an unexpected problem and knows to send an email page to its administrator asking for help.A servlet has four choices for sending email : 
> It can manage the details itself—establishing a raw socket connection to a mail server and speaking a low-level mail transport protocol, usually the so-called Simple Mail Transfer Protocol.
> It can run on external command-line email program, if the server system has such a program.
> It can use the new JavaMail API, designed to support complicated mail handling, filing, and processing.
> It can use one of the many freely available mail classes that abstracts the details of sending email into simple, convenient method calls.

Using sun.net.smtp.SmtpClient

Answer:
It’s conveniently provided with Sun’s JDK and most
JVMs descended from it, but we should warn you that it’s unsupported and subject to change, Using it is simple : 
> Call SmtpClient smtp = new SmtpClient(). Optionally, pass the constructor the name of a host to use as the mail server, which replaces the default of localhost. Most Unix machines can act as SMTP mail servers.
> Call smtp.from specifying the address of the sender. The address doesn’t have to be valid.
> Call smtp.to specifying the address of the receiver.
> Call PrintStream msg = smtp.startMessage() to get an output stream for the message.
> Write any mail headers to the PrintStream. For example, "Subject: Customer feedback".
> Write the body of the mail message to the PrintStream.
> Call smtp.closeServer() to close the connection to the server and send the message.

Using Regular Expressions

Answer:
all the classes and capabilities Sun has added in JDK 1.1 and JDK 1.2, one feature still absent is a regular expression engine. Ah, well, not to worry. As with most Java features, if you can’t get it from Sun, a third-party vendor is probably
offering whatwe need at a reasonable price.
Several companies offer full-featured regular expression engines. One of the first was Thought, Inc., which developed VanillaSearch.

Improving Deblink with Regular Expressions

Answer:
Deblink has one serious limitation : 
> it’s case sensitive. It won’t remove , , , or . Sure, we could enumerate inside Deblink all the case combinations that should be removed, but regular expressions provide a much simpler alternative.
With a single regular expression, we can rewrite Deblink to remove the opening and closing blink tags, no matter how they are capitalized. The regular expression we’ll use is "". This matches both  and . With a case-insensitive mask set, this expression also matches , , and even . Any
occurrence of this regular expression can be replaced with the empty string, to completely deblink an HTML page.

Finger

Answer:
The finger program queries a computer for a list of currently logged in users. It’s available on virtually all Unix systems and some Windows NT
machines with networking capabilities. The finger program works by connecting to a finger daemon that listens on port 79. finger makes its
request of fingerd using a custom “finger” protocol, and fingerd replies with the appropriate information. Most Unix systems run fingerd, though many securityconscious
administrators turn it off to limit information that could be used for break-in attempts.
% finger
Login    Name            TTY Idle  When Office
jhunter  Jason Hunter    q0  3:13  Thu 12:13
ktaylor  Kristi Taylor   q1        Thu 12:18

Executing the Finger Command

Answer:
servlet first determines the “from” and “to”  addresses for the message. The default values are set in the FROM and TO variables, although a submitted form can include (probably hidden) fields that specify alternate from and to addresses. The servlet then begins an SMTP email message. It connects to the local host and
addresses the message. Next, it sets its headers and fills the body with the form data, ignoring the to and from variables. Finally, it sends the message and thanks the user for the submission. If there’s a problem, it informs the user and logs the exception.

Executing Finger with Arguments

Answer:
we want to pass an argument to the finger command. The usage is slightly different. exec() takes either a single string that specifies a command or an array of strings that specifies a command and the arguments to pass to that command.

Executing Finger with Redirected Output

Answer:
servlet wants access to the information retrieved by finger. It has two options: it can establish a socket connection to fingerd and make a request for information just like any other finger client, or it can execute the command-line
finger program to make the connection on its behalf and read the information from finger’s output.servlet uses the exec() command just like any other Java class would. It executes the finger command, then reads and prints the output. If there’s a problem, the servlet catches an exception and prints the stack trace to the user. This servlet assumes the finger command exists in the default search path. If that isn’t the case, change the command string to specify the path where finger can be
found.

Using Native Methods

Answer:
Native code, however, should not be used except when absolutely necessary, since if the native code run by a servlet goes south, the entire server goes down with it!The security protections in Java can’t protect the server from native code crashes.For this reason, it’s wise not to use the native JDBC-ODBC bridge from a servletbecause many ODBC drivers seem to have problems with multithreaded access.Native code also limits the platform independence of a servlet. While this may notmatter for custom-built servlets tied to a particular server, it’s something to remember.

Acting as an RMI Client

Answer:
Applet-Servlet Communication, we saw how a servlet can act as an RMI server. Here we turn the tables and see a servlet acting as an RMI client. By taking the role of an RMI client, a servlet can leverage the services of other servers to accomplish its task, coordinate its efforts with other servers or servlets on those
servers, and/or act as an proxy on behalf of applets that can’t communicate with RMI servers themselves.servlets and applets perform the same basic steps to access an RMI server. They both locate a registry using a hostname and port number, then use that registry to look up a reference to the remote object. The only significant difference is that a servlet must first ensure it’s running under the protection of a default security manager.

Debugging

Answer:
debugging phase is one of the hardest aspects of developing servlets. Servlets tend to involve a large amount of client/server interaction, making errors likely—but hard to reproduce. It can also be hard to track down the cause of non obvious errors because servlets don’t work well with standard debuggers, since they run inside a heavily multithreaded and generally complex web server.

Check the Logs

Answer:
Most servers output an error log where we can find a list of all the errors observed by the server and an event log where we find a list of interesting servlet events. The event log may also hold the messages logged by servlets through the log() method, but not always.find a list of interesting servlet events. The event log may also hold the messages logged by servlets through the log() method, but not always.we can see problems as they occur. Be sure to reset the buffer size to a reasonable value afterward.

Output Extra Information

Answer:
indication of the problem in the server’s logs, try having our servlet log extra information with the log() method. As we have habitually log stack traces and other error situations. During debugging, we can add a few temporary log() commands as a poor man’s debugger, to get a general idea of the code execution path and the values of the servlet’s variables. Sometimes it’s convenient to leave the log() commands in a servlet surrounded by if clauses so they trigger only when a specific debug init parameter is set to true.Extracting the extra information from the server’s logs can at times be unwieldy. To make the temporary debugging information easier to find, we can have a servlet output its debug information to the client,Not all servers have a console associated with a servlet’s System.out; some redirect the output to a file instead.

Use a Standard Debugger

Answer:
Sun provides a simple “servlet runner” server perfect for debugging servlets. This servlet runner acts as a small all-Java web server that is simpler and more lightweight than the Java Web Server—it handles only HTTP requests for servlets, and it doesn’t even serve files .The servlet runner can be executed from the command line as the servletrunner shell script on a Unix system or the servletrunner.exe program on Windows.To debug a servlet, we can debug sun.servlet.http.HttpServer, then watch as
HttpServer executes servlets in response to HTTP requests we make from a browser. This is very similar to how applets are debugged. The difference is that with applets, the actual program being debugged is sun.applet.AppletViewer.

Use a Third-Party Tool

Answer:
Third party tols promise to bring newapabilities and ease of use to the task of servlet debugging. LiveSoftware, maker of the popular JRun servlet plug-in, was the first company to market a tool for servlet debugging. The product, named
ServletDebugger, is designed to help programmatically test and debug a servlet.
ServletDebugger doesn’t require using HttpServer or a browser to make a request.The stub specifies everything: the servlet’s init parameters, the request’s HTTP headers, and the request’s parameters. Servlet Debugger is fairly straightforward and is well suited to automated testing.

Examine the Client Request

Answer:
Sometimes when a servlet doesn’t behave as expected, it’s useful to look at the raw HTTP request to which it’s responding.we were familiar with the structure of HTTP, we can read the request and see exactly where a servlet might get confused.* One way to see the raw request is to replace the web server process with a custom server application that prints out everything it receives.we can start this server listening on port 8080 by typing java SocketWatch 8080 in a
shell. Note that two applications can’t listen to the same socket at the same time .so we should first make sure there’s no other server listening on our chosen port. Once we have the server running, we can make HTTP requests to it as if it
were a normal web server.

Create a Custom Client Request

Answer:
catching and examining a client’s HTTP request,we may find it useful to create our own HTTP request. we can do this by connecting to the
server socket on which the web server is listening, then manually entering a properly
structured HTTP request. To establish the connection,we can use the telnet program, available on all Unix machines and most Windows machines with networking. The telnet program accepts as arguments the host and port number to which it should connect

Some Final Tips

Answer:
Here are some final tips on servlet debugging:
> Use System.getProperty("java.class.path") from our servlet to help debug classpath problems. Because servlets are often run from web servers with embedded JVMs, it can be hard at times to identify exactly what classpath the JVM is searching. The property "java.class.path" will tell us.
> Be aware that server_root/classes doesn’t reload and that server_root/servlets probably does.
> Ask a browser to show the raw content of the page it is displaying. This can help identify formatting problems. It’s usually an option under the View menu.
> Make sure the browser isn’t caching a previous request’s output by forcing a full reload of the page. With Netscape Navigator, use Shift-Reload; with Internet Explorer use Shift-Refresh.
> Verify that our servlet’s init() method takes a ServletConfig parameter and calls super.init(config) right away.

Performance Tuning

Answer:
Performance tuning servlets requires a slightly different mindset than performance tuning normal Java applications or applets. The reason is that the JVM running the servlets is expected to simultaneously handle dozens, if not hundreds,
of threads, each executing a servlet. These coexisting servlets have to share the resources of the JVM in a way that normal applications do not. The traditional performance tuning tricks still apply, of course, but they have a different impact when used in a heavily multithreaded system.

Go Forth, but Don’t Prosper

Answer:
Avoid concatenating several strings together. Use the append() method of StringBuffer instead. This too has always been good advice, but with servlets it’s particularly tempting to write code like this to prepare a string for later output :
String output ; 
output += "";
output += "Hello, " + user;
output += "";
             Although this code looks nice and neat, when it runs it executes as if written
roughly as follows, with a new StringBuffer and new String created on each line:
String output;
output = new StringBuffer().append("").toString();
output = new StringBuffer(output).append("Hello, ").toString();</pre>
    
  </div>
</div>

        
  

<!-- DBMS Q&A -->
<div class="container mt-3 question-block ">
  <div class="question-card">
    <h4>Limit Synchronization
</h4>
    <strong>Answer:</strong> 
    <pre>Synchronize whenever necessary, but no more. Every synchronized block in a servlet slows the servlet’s response time. Because the same servlet instance may handle multiple concurrent requests, it must, of course, take care to protect its
class and instance variables with synchronized blocks. All the time one request thread is in a servlet’s synchronized block, however, no other thread can enter the block. Therefore, it’s generally best to keep these blocks as small as possible.</pre>
    
  </div>
</div>

 

  


  <!-- Add more .question-card blocks as needed -->
</div>

<!-- Footer -->
<footer>
    <a href='?categoryFilter=Java SUB'>Java </a> | <a href='?categoryFilter=SQL SUB'>SQL </a> | <a href='?categoryFilter=JDBC SUB'>JDBC </a> | <a href='?categoryFilter=C SUB'>C </a> | <a href='?categoryFilter=Csharp SUB'>Csharp </a> | <a href='?categoryFilter=HTML SUB'>HTML </a> | <a href='?categoryFilter=JSP SUB'>JSP </a> | <a href='?categoryFilter=Servlet SUB'>Servlet </a> | <a href='?categoryFilter=JAVASCRIPT SUB'>JAVASCRIPT </a> | <a href='?categoryFilter=COLLECTION  SUB'>COLLECTION  </a> | <a href='?categoryFilter=SWING SUB'>SWING </a> | <a href='?categoryFilter=CSS SUB'>CSS </a> | <a href='?categoryFilter=PHP SUB'>PHP </a> | <a href='?categoryFilter=XML SUB'>XML </a> | <a href='?categoryFilter=SUB Query'> Query</a> | <a href='?categoryFilter=AJAX ASP.NET SUB'>AJAX ASP.NET </a> | <a href='?categoryFilter=net SUB'>net </a> | <a href='?categoryFilter=RDF SUB'>RDF </a> | <a href='?categoryFilter=CPP SUB'>CPP </a> | <a href='?categoryFilter=ASP.NET SUB'>ASP.NET </a> | <a href='?categoryFilter=Hibernate SUB'>Hibernate </a> | <a href='?categoryFilter=EJB SUB'>EJB </a> | <a href='?categoryFilter=XSLT SUB'>XSLT </a> | <a href='?categoryFilter=JSF SUB'>JSF </a> | <a href='?categoryFilter=Ant SUB'>Ant </a> | <a href='?categoryFilter=TESTING SUB'>TESTING </a> | <a href='?categoryFilter=Struts SUB'>Struts </a> | <a href='?categoryFilter=WML SUB'>WML </a> | <a href='?categoryFilter=WMLSCRIPT SUB'>WMLSCRIPT </a> | <a href='?categoryFilter=DHTML SUB'>DHTML </a> | <a href='?categoryFilter=XHTML SUB'>XHTML </a> | <a href='?categoryFilter=VBSCRIPT SUB'>VBSCRIPT </a> | <a href='?categoryFilter=E4X SUB'>E4X </a> | <a href='?categoryFilter=AJAX SUB'>AJAX </a> | <a href='?categoryFilter=SOAP SUB'>SOAP </a> | <a href='?categoryFilter=Spring SUB'>Spring </a> | <a href='?categoryFilter=RSS SUB'>RSS </a> | <a href='?categoryFilter=XFORMS SUB'>XFORMS </a> | <a href='?categoryFilter=WSDL SUB'>WSDL </a> | <a href='?categoryFilter=XLXP SUB'>XLXP </a> | <a href='?categoryFilter=XPATH SUB'>XPATH </a> | <a href='?categoryFilter=XMLSCHEMA SUB'>XMLSCHEMA </a> | <a href='?categoryFilter=HR SUB'>HR </a> | <a href='?categoryFilter=HTMLDOM SUB'>HTMLDOM </a> | <a href='?categoryFilter=DTD SUB'>DTD </a> | <a href='?categoryFilter=EXCEL SUB'>EXCEL </a> | <a href='?categoryFilter=XQUERY SUB'>XQUERY </a> | <a href='?categoryFilter=Linux'>Linux</a> | <a href='?categoryFilter=Unix'>Unix</a> | <a href='?categoryFilter=VB SUB'>VB </a> | <a href='?categoryFilter=ASP SUB'>ASP </a> | <a href='?categoryFilter=ADO.NET SUB'>ADO.NET </a> | <a href='?categoryFilter=DATABASE SUB'>DATABASE </a> | <a href='?categoryFilter=J2ME SUB'>J2ME </a> | <a href='?categoryFilter=WEBSERVICE SUB'>WEBSERVICE </a> | <a href='?categoryFilter=WPF SUB'>WPF </a> | <a href='?categoryFilter=Silverlight SUB'>Silverlight </a> | <a href='?categoryFilter=UTIL SUB'>UTIL </a> | <a href='?categoryFilter=POI SUB'>POI </a> | <a href='?categoryFilter=IO SUB'>IO </a> | <a href='?categoryFilter=RMI SUB'>RMI </a> | <a href='?categoryFilter=Android SUB'>Android </a> | <a href='?categoryFilter=itext SUB'>itext </a> | <a href='?categoryFilter=Javamail SUB'>Javamail </a> | <a href='?categoryFilter=Lang SUB'>Lang </a> | <a href='?categoryFilter=WCF SUB'>WCF </a> | <a href='?categoryFilter=Spring Boot SUB'>Spring Boot </a> | <a href='?categoryFilter=Spring Batch SUB'>Spring Batch </a> | <a href='?categoryFilter=Core Java SUB'>Core Java </a> |   <p>© 2025 R4R Knowledge Hub | Educational Templates by Rajesh</p>
</footer>

<!-- Script for Filter and Theme Toggle -->
<script>
  // Filter Function
  document.getElementById("categoryFilter").addEventListener("change", function() {
    const selected = this.value;
    document.querySelectorAll(".question-block").forEach(block => {
      block.style.display = selected === "all" || block.classList.contains(selected) ? "block" : "none";
    });
  });

  // Dark Mode Toggle
  const toggleBtn = document.getElementById("themeToggle");
  toggleBtn.addEventListener("click", () => {
    document.body.classList.toggle("bg-dark");
    document.body.classList.toggle("text-light");
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs/prism.js"></script>
</body>
</html>