Pages

Subscribe Twitter Twitter

Monday, August 2, 2010

SERVLETS

Q) Servlet
Servlet is server side component, a servlet is small plug gable extension to the server and servlets are used to extend the functionality of the java-enabled server. Servlets are durable objects means that they remain in memory specially instructed to be destroyed.

Q) Servlet Life cycle

Public void init (ServletConfig config) throws ServletException
public void service (ServletRequest req, ServletResponse res) throws ServletException, IOException
public void destroy ()

First the servlet is constructed and then initialized with the init () method, this will call only once.
Any request from client is handled initially by the service () method before delegating to the doXxx () methods in the case of HttpServlet.
The servlet is removed from service, destroyed with the destroy () method, then garbaged collected and finalized. This will call only once. When your application is stopped (or) Servlet Container shuts down, your Servlet's destroy () method will be called. This allows you to free any resources you may have got hold of in your Servlet's init () method.

Q) ServletConfig & ServletContext
ServletConfig  ServletConfig object is used to obtain configuration data when it is loaded.
ServletContext ServletContext is used to obtain information about environment on which a servlet is running.

Q) Where the servlets will be loaded?
A) Address space of webserver.

Q) Are Servlets multithread?
A) Yes, the servlet container allocates a thread for each new request for a single servlet. Each thread of your servlet runs as if a single user were accessing using it alone, but u can use static variable to store and present information that is common to all threads, like a hit counter for instance.

Q) What happens to System.out & System.err output in a Servlet?
A) System.out goes to 'client side' and is seen in browser, while System.err goes to 'server side' and is visible in error logs and/or on console.

Q) Session Tracking
Session tracking is the capability of the server to maintain the single client sequential list.

Q) Servlet chaining
Is a technique in which two are more servlets cooperating in servicing a single client sequential request, where one servlet output is piped to the next servlet output. The are 2 ways (i) Servlet Aliasing (ii) HttpRequest

Servlet Aliasing  allows you to setup a single alias name for a comma delimited list of servlets. To make a servlet chain opens your browser and give the alias name in URL.

HttpRequest construct a URL string and append a comma delimited list of servlets to the end.

Q) HttpTunnelling
Is a method used to reading and writing serializes objects using a http connection. You are creating a sub protocol inside http protocol that is tunneling inside another protocol.

Q) Diff CGI & Servlet
 Servlet is thread based but CGI is not
 CGI allow separate process for every client request, CGI is platform dependent and servlet is platform independent.

Q) Diff GET & POST
 GET & POST are used to process request and response of a client.
 Get method is the part of URL, we send less amount of data through Get. The amount of information limited is 240-255 characters.
 Using POST we can send large amount of data through hidden fields.
 Get is to get the posted html data; POST is to post the html data.

Q) Diff Http & Generic Servlet
 HttpServlet class extends Generic servlet, so Generic servlet is parent and HttpServlet is child.
 Generic is from javax.servlet package, HttpServlet is from javax.servlet.Http package.
 Http implements all Http protocols, Generic servlet will implements all networking protocol
 Http is stateless protocol, which means each request is independent of previous one; In generic we cannot maintain the state of next page only main state of current page.
 A protocol is said to be stateless if it has n memory of prior connection.
 Http servlet extra functionality is capable of retrieving Http header information.
 Http servlet can override doGet (), doDelete (), doGet (), doPost (), doTrace (), generic servlet will override Service () method only.

Q) The Structure and Deployment of Modern Servlet Web Applications
A) /WEB-INF/web.xml
/WEB-INF/lib/ [any required jar files]
/WEB-INF/classes/ [all class files]

WAR-> WARfile can be placed in a server’s webapps directory

Q) Servlet mapping?
A)
watermelon
myservlets.watermelon


watermelon
/fruit/summer/*


Q) Timeoutcan be overridden in web.xml?
A)
e.g.60


Q) Init parameter / Define context parameters?

HelloWorld2
examples.servlets.HelloWorld2

greeting
Welcome



Q) Tag Libraries?
A)
myTaglib
WEB-INF/myTLD.tld


Q) How many ways we can instantiate a class.?
A) Class.forName().newInstance() and new keyword

Q) Client pull & Server push?
Client pull
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.
Client pull information is sent to the client using the Refresh HTTP header. This header's value specifies the number of seconds to display the page before pulling the next one, and it optionally includes a URL string that specifies the URL from which to pull. If no URL is given, the same URL is used. Here's a call to setHeader() that tells the client to reload this same servlet after showing its current content for three seconds: setHeader("Refresh", "3");
And here's a call that tells the client to display Netscape's home page after the three seconds:
setHeader("Refresh", "3; URL=http://home.netscape.com");

Server push
server push because the server sends, or pushes, a sequence of response pages to the client.With server push, the socket connection between the client and the server remains open until the last page has been sent.

Q) How can a servlet refresh automatically if some new data has entered the database?
A) you can use client side refresh are server push

Q) Session Tracking techniques

(i) URL Rewriting
(ii) Hidden form Field
(iii) Persistence Cookies
(iv) Session Tracking API
(v) User Authorization

URL Rewriting
URL rewriting is a technique in which the requested URL is modified with the session id.
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.
http://server:port/servlet/Rewritten?sessionid=123 added parameter

Hidden form Field
Hidden form fields are HTML input type that are not displayed when read by the browser. They are sent back to the server when the form that contains them is submitted. You include hidden form fields with HTML like this:





In a sense, hidden form fields define constant variables for a form. To a servlet receiving a submitted form, there is no difference between a hidden field and a visible field.

Persistence Cookie
A cookie is a bit of information sent by a web server to a browser that can later be read back from that browser. When a browser receives a cookie, it saves the cookie and thereafter sends the cookie back to the server each time it accesses a page on that server, subject to certain rules. Because a cookie's value can uniquely identify a client, cookies are often used for session tracking. Because cookies are sent using HTTP headers, they should be added to the response before you send any content. Browsers are only required to accept 20 cookies per site, 300 total per user, and they can limit each cookie's size to 4096 bytes.

Sending cookies from a servlet

Cookie cookie = new Cookie ("ID", "123");
res.addCookie (cookie);

A servlet retrieves cookies by calling the getCookies () method of HttpServlet- Request:
public Cookie[] HttpServletRequest.getCookies()
This method returns an array of Cookie objects that contains all the cookies sent by the browser as part of the request or null if no cookies were sent. The code to fetch cookies looks like this:

Reading browser cookies from a Servlet

Cookie [] cookies = req. getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
String name = cookies [i]. getName ();
String value = cookies [i]. getValue();
}
}

A cookie, mycookie, can be Deleted using the following scriptlet:
<%
Cookie killMyCookie = new Cookie("mycookie", null);
killMyCookie.setMaxAge(0);
killMyCookie.setPath("/");
response.addCookie(killMyCookie);
%>

You can set the maximum age of a cookie with the cookie.setMaxAge(int seconds) method:
 Zero means to delete the cookie
 + value is the maximum number of seconds the cookie will live, before it expires
 - value means the cookie will not be stored beyond this browser session (deleted on browser close)

Session Tracking API
In Java the javax.servlet.http.HttpSession API handles many of the details of session tracking. It allows a session object to be created for each user session, then allows for values to be stored and retrieved for each session. A session object is created through the HttpServletRequest using the getSession() method:

HttpSession session = request.getSession(true);

This will return the session for this user or create one if one does not already exist.
Values can be stored for a user session using the HttpSession method putValue():

session.putValue("valueName", valueObject);

Session objects can be retrieved using getValue(String name), while a array of all value names can be retrieved using getValueNames(). Values can also be removed using removeValue(String valueName)



User Authorization
Servers can be set up to restrict access to HTML pages (and servlets). The user is required to enter a user name and password. Once they are verified the client re-sends the authorisation with requests for documents to that site in the http header.
Servlets can use the username authorisation sent with request to keep track of user data. For example, a hashtable can be set up to contain all the data for a particular user. When a user makes another request the user name can be used to add new items to their cart using the hashtable.

Q) Session
Session is a persistence network connection between client and server that facilitate the exchange of information between client and server. A session object created for each user persists on the server side, either until user closes the browser or user remains idle for the session expiration time.

As such there is no limit on the amount of information that can be saved in a Session Object. Only the RAM available on the server machine is the limitation. The only limit is the Session ID length(Identifier) , 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. Internally if the amount of data being saved in Session exceeds the predefined limit, most of the servers write it to a temporary cache on Hard disk.

HttpSession session = req.getSession(true); //Creating a Session instance
session.putValue ("MyIdentifier1", count1); // Storing Value into session Object
session.putValue ("MyIdentifier2", count2);
session.getValue(MyIdentifier1); // Prints value of Count
session.removeValue(MyIdentifier1); // Removing Valuefrom Session Object

Q) Cookie advantages & Disadvantages
Advantages Persistence offer efficient way to implement session tracking for each client request a cookie can be automatically provide a clients session id.
Disadvantage The biggest problem with cookies is that browser do not always accept cookies. Some times browser does not accept cookies. Browser only requires accepting 20 cookies per page and they can limit the cookie size to 4096 bytes. It cannot work if the security level set too high in browser. Cookies are stored in a plain text format so every one can view and modify them. We can put maximum 300 cookies for entire application.

Q) Advantages of Sessions over Cookies & URLRewriting?
 Sessions are more secure and fast because they are stored at server side. But sessions has to be used combindly with cookies (or) URLRewriting for maintaining client id that is session id at client side.
 Cookies are store at client side so some clients may disable cookies so we may not sure that the cookies which we are maintaining may work or not, if cookies are disable also we can maintain sessions using URLRewriting.
 In URLRewriting we cannot maintain large data because it leads to network traffic and access may be become slow. Where in sessions will not maintain the data which we have to maintain instead we will maintain only the session id.

Q) encodeURL & encodeRedirectURL
These are methods of HttpResponse object, “encodeURL” is for normal links inside your HTML pages, “encodeRedirectURL” is for a link your passing to response.sendRedirect().

Q) SingleThread model
SingleThreadModel is a tag interface with no methods. In this model no two threads will execute concurrently the service method of the servlet, to accomplish this each thread uses a free servlet instance from the servlet pool. So any servlet implementing this can be considered thread safe and it is not required synchronize access to its variables.
(or)
If a servlet implements this interface, the server ensures that each instance of the servlet handles only one service request at a time. Servers implement this functionality by maintaining a pool of servlet instances and dispatching incoming requests to free servlets within the pool. SingleThreadModel provides easy thread safety, but at the cost of increased resource requirements as more servlet instances are loaded at any given time.

public interface SingleThreadModel {
}



Q) Request Headers
User-agent: - Gives the information about client software, browser name, version and information about the machine on which it is running.
request.getHeader(“user-agent”);

Q) Why there is no constructor in servlet?
A) A servlet is just like an applet in the respect that it has an init() method that acts as a constructor, an initialization code you need to run should e place in the init(), since it get called when the servlet is first loaded.

Q) Why do you need both GET & POST methods in servlets?
A) A single servlet can be called from different HTML pages, so different method calls can be possible.

0 comments:

Post a Comment