Interview Questions On Java,Java EE

Enter your email address:

Add to Technorati Favorites
Google PageRank Checker
Showing posts with label Servlet. Show all posts
Showing posts with label Servlet. Show all posts

Thursday, April 19, 2007

More Questions on Servlet

Continue reading...

Wednesday, April 18, 2007

Java Servlets and JSPs

Continue reading...

Tuesday, April 17, 2007

Session Tracking In Servlets

As HTTP is a stateless protocol, any interaction between client browser and servlet lasts as long as the browser is connected to server and the moment browser is closed this session is lost,in no way server will know anything about its client,if client access this server again.In applications where keeping a track of end user is must like in an online shopping or online banking applications,keeping a track of session between user and server is a must.In servlets, various mechanisms are suggested for maintaining session between both entities.One of them is through cookies.Cookies are server sent,small bits of text files which are stored in client browser and this is dependent upon whether client browser supports cookies or not.By default these cookies are deleted the moment client-server communication ends but they can persist for a specified period of time by a developer.When the browser access the same site again then already stored cookie in browser is exchanged with server.
Here is snippet of code, how you set maximum time till a coolie can be alive.

Cookie cookie = new Cookie ("user", "smart");
cookie.setMaxAge ( 60 * 60 * 24 * 365 );//setting max age here to one year.

// Add cookie to response
response.addCookie (cookie);

A cookie usually have name/key, value pair kind of information.But providing userId related information in a cookie can be a security risk, where computers are shared by different people.It gives an opportunity to others to sneak into your online resources.It is advisable to set maximum age of a cookie not too long and ideally a minute or two is good from security point of view.The sharing of state during session management should ideally not last long, for any long usage of state information,it should be stored in some persistent area like database.Due to security risks and some browsers which do not support cookies, it may not be an ideal choice if a widespread support is required for servlets from all browsers.

Other in trend approaches are:
-URL Rewriting
-Hidden Form Fields
-HttpSession object based session management

In URL rewriting,a URL is appended with some data automatically encoded each time when accessed through client browser.
If URL-rewriting is supported , it will allow some browsers without cookies support to access the servlet with session tracking. As an example, to encode a reference to a servlet, we could use the following code:

// HttpServletResponse.encodeUrl adds session data automatically
response.encodeUrl ( "/servlets/TestServlet" );

In URL rewriting, every local URL clicked is dynamically modified, or rewritten, to include extra information which can be in the form of extra path information, added parameters, or some custom, server-specific URL change.Usually it is limited to a unique session ID.

In hidden form fields, the html entry for a field will have attribute 'type' with a value as 'hidden', e.g.:
<input type ="hidden" name = "name" value="">.

So in this mechanism whenever the form is submitted, the name,value pair will be appended in get or post methods.It is better to use POST command in order to make sessionId invisible during request submission.

HttpSession object based session management has already been discussed in details in one of previous posts.
Continue reading...

How do you communicate between applet and servlet?

The communication between an Applet and Servlet can occur through 'Http Tunneling' with Object serialization.It is technique through which an applet can send data to servlet through object serialization bypassing firewall over HTTP.A socket connection is established from client to server and in the process if there is any firewall at client side then that can also be bypassed but does not work in case if there is a firewall on remote host server side.
Continue reading...

How do you make servlet thread-safe?

SingleThreadModel interface once implemented makes a servlet thread safe,though not in complete sense.It ensures that servlet handles only one request at a time. In this case only one thread will be able to execute service() method at a time.Though it affects the performance of the servlet to a great extent. In STM container creates multiple instances of servlet.This interface is deprecated from Servlet API version 2.4.

It does not resolve all thread safety related issues of a servlet, as most of session attributes and static variables can still be shared across multiple threads at the same time.The other ways to handle such situations can be avoid creating instance variables or synchronizing the block of code accessing those resources.

Continue reading...

What is the difference in between encodeRedirectURL and encodeURL?

encodeURL is used for all URLs in a servlet's output. It helps session ids to be encoded with the URL. Moreover it rewrites URLs relative to the current document.if the url is not starting with 'http//.' and encodes any parameters added with the request.addQueryParameter or request.addURLParameter methods.

As per Servlet API the encodeRedirectURL must ALWAYS be used within response.sendRedirect() commands.It is used for encoding session ids with URL but only while redirecting.
Continue reading...

If my browser does not support Cookie and my server sends a Cookie instance what will happen?

In such scenario, browser will not accept incoming cookie. Whenever the browser sends the new request,it will not send the session id to server.As client has not joined to server session through cookie,server will not have any information about client in such a way. However,session tracking could still be preformed by using URL rewriting or hidden form fields.
Continue reading...

Can you use System.exit in your servlet end code?

All the best...just kidding.
The answer is big 'No'.
At best, you'll get a security exception.At worst, you'll make the servlet engine, or maybe the entire web server, quit.

Continue reading...

How will you pass values from HTML to the servlet?

The values from an HTML page are passed to a servlet either through a GET or POST method. In a servlet, request.getParameter ("strParam") method is called in order to retrieve values from HTML form to a servlet end where String strParam represents the name of the input type OR values can be passed concatenated with URL itself which request the servlets receive.
Continue reading...

Why do GenericServlet and HttpServlet class implement Serializable interface?

In order to support HTTP session states, all servlet session data must be serializable.Moreover, servlets need to communicate over the network to Java objects(e.g. in Applet-Servlet communication),in such scenarios it becomes necessary to enable serialization of objects' states through implementation of Serializable interface.This is the way GenericServlet and HttpServlet classes have been designed by their designers to make them capable of serialization.
Continue reading...

What is the difference between doGet and doPost methods of HttpSe?

A GET or POST request is sent to servlet in order to expedite the request by calling corresponding doGet() and doPost() methods.

doGet is called in response to an HTTP GET request. This happens when users click on a link, or enter a URL into the browser's address bar. It also happens with some HTML FORMs (those with METHOD="GET" specified in the FORM tag).
doPost is called in response to an HTTP POST request. This happens with some HTML FORMs (those with METHOD="POST" specified in the FORM tag).
Both methods are called by the default (superclass) implementation of service in the HttpServlet base class. You should override one or both to perform your servlet's actions. You probably shouldn't override service().
There is a restriction of numbers of parameters to be sent through doGet method around 2k of data can be sent and moreover whole of URL is to be mentioned in case of doGet as mentioned below:
So it is always better to use doPost() when sending parameters from a FORM as it doesn't show off information related with password on the network etc.
Continue reading...

What is the difference between GenericServlet and HTTPServlet?

GenericServlet is an abstract class that defines a generic, protocol-independent servlet.Any protocol dependent servlet has to extend this class in order to provide a specific implementaion and override service method.e.g . HTTPServlet class extends GenericServlet class.
GenericServlet has a service(ServletRequest req, ServletResponse res) method which is called by the servlet container to allow the servlet to respond to a request.
HttpServlet extends GenericServlet and adds support for doGet(), doPost(), doHead() methods (HTTP 1.0) plus doPut(), doOptions(), doDelete(), doTrace() methods (HTTP 1.1). Both these classes are abstract.
Continue reading...

What is meant by Session tell me something about HttpSession?

A web client makes a request to a web server over HTTP. As long as a client interacts with the server through a browser on his or her machine,this interaction is called as session. HTTP is a stateless protocol. A client's each request is treated as a fresh one with no info of client to the server and the moment browser is closed, session is also closed. In an online shopping or web cart kind of application where session related information is critical for successive purchases made by a client, there have been suggested several techniques for session tracking in Java Servlets as mentioned below:

-Hidden form fields
-URL Rewriting
-HttpSession object

HttpSession is an interface, which belongs to javax.servlet.http. * package This provides a facility to identify a user across the several pages' requests by looking up the HttpSession object associated with the current request.
This is done by calling the getSession method of HttpServletRequest. If this returns null, you can create a new session, but this is so commonly done that there is an option to automatically create a new session if there isn't one already. Just pass true to getSession. Thus, your first step usually looks like this:

HttpSession session = request.getSession (true);

To ensure the session is properly maintained, this method must be called at least once before any output is written to the response.

You can add data to an HttpSession object with the putValue() method:

public void HttpSession.putValue(String name, Object value)

This method binds the specified object value under the specified name. Any existing binding with the same name is replaced.

To retrieve an object from a session, use getValue():

public Object HttpSession.getValue(String name)

This methods returns the object bound under the specified name or null if there is no binding.

You can also get the names of all of the objects bound to a session with getValueNames():

public String[] HttpSession.getValueNames()

This method returns an array that contains the names of all objects bound to this session or an empty (zero length) array if there are no bindings.

Finally, you can remove an object from a session with removeValue():

public void HttpSession.removeValue(String name)

This method removes the object bound to the specified name or does nothing if there is no binding. Each of these methods can throw a java.lang.IllegalStateException if the session being accessed is invalid.

More on session tracking in servlets...
Continue reading...

What is a Servlet Context?

A ServletContext interface empowers a servlet to view its environment. A servlet can use this interface to get following informations:

- Initial Web Application Parameters
- Application Scope for binding objects
- Virtual Directory Translation
- A common mechanism for Logging information

Each vendor provides specific ServletContext object but they all provide the same functionality defined by the ServletContext interface.

read more
Continue reading...

Why there are no constructors in servlets?

A servlet is just like an applet in the respect that it has an init() method that acts as a constrcutor. Since the servlet environment takes care of instantiating the servlet, an explicit constructor is not needed. Any initialization code you need to run should be placed in the init() method since it gets called when the servlet is first loaded by the servlet container.
Continue reading...

Can there be more than one instance of a servlet at one time ?

It is important to note that there can be more than one instance of a given Servlet class in the servlet container. For example, this can occur where there was more than one servlet definition that utilized a specific servlet class with different initialization parameters. This can also occur when a servlet implements the SingleThreadModel interface and the container creates a pool of servlet instances to use.
Continue reading...

What is the difference between CGI and servlets?

In traditional CGI, a new process is started with each client request and this will correspond to initiating a heavy OS level process each time when a client request comes. While in case of servlets JVM handles client requests at a web server end and each client request correspond to thread which consumes less resources as compared with CGI process, thus making CGI inefficient. In Java servlet, there is only a single instance, which answers all requests concurrently. This saves memory and allows a Servlet to easily manage persistent data.Java servlets resides in Servlet engine and are executed within sandbox making it more secure and robust.

Continue reading...

What is a servlet? Explain its lifecyle.

The Servlets are server side java programs, which are used to generate dynamic web content for a web clients. They reside inside a servlet container on a web server or an application server. The servlet container provides them a runtime environment.

If an instance of servlet is non existent then web container loads the servlet class and creates an instance of the servlet.Once the servlet instantiates, web container calls init() method on it to initialize the servlet.This process of initialization can be customized to allow servlet to read persistent configuration data,initialize resources like database connections etc. by overriding init() method of Servlet interface.If initialization of a servelet fails it throws UnavailableException.

Once initialization is done, web container invokes the service method, passing a request and response object depending upon incoming request.

If the container needs to remove the servlet(e.g.when web container is shutting down), it finalizes the servlet by calling the servlet's destroy method.

The javax.servlet.Servlet interface defines the three life-cycle method:-

public void init(ServletConfig config) throws ServletException

public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException

public void destroy()
Continue reading...

Interview Questions On Java,Java EE Copyright © 2017. Reads: best tracker