You are on page 1of 9

SERVLETS

Question Request parameter How to find whether a parameter exists in the request object? (Servlets)
1.boolean hasFoo = !(request.getParameter("foo") == null ||
request.getParameter("foo").equals(""));
Answer
2. boolean hasParameter = request.getParameterMap().contains(theParameter);
(which works in Servlet 2.3+)
Question How can I send user authentication information while makingURLConnection? (Servlets)
You'll want to use HttpURLConnection.setRequestProperty and set all the appropriate
Answer
headers to HTTP authorization.
Question Can we use the constructor, instead of init(), to initialize servlet? (Servlets)
Yes , of course you can use the constructor instead of init(). There's nothing to stop you.
But you shouldn't. 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
Answer
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.
How can a servlet refresh automatically if some new data has entered the database?
Question (Servlets)
Answer You can use a client-side Refresh or Server Push
Question The code in a finally clause will never fail to execute, right? (Servlets)
Answer Using System.exit(1); in try block will not allow finally code to execute.
Question What is HttpTunneling? (Servlets)
HTTP tunneling is used to encapsulate other protocols within the HTTP or HTTPS
protocols. Normally the intra-network of an organization is blocked by a firewall and the
Answer network is exposed to the outer world only through a specific web server port , that listens
for only HTTP requests. To use any other protocol, that by passes the firewall, the protocol
is embedded in HTTP and send as HttpRequest.
Question What is Server Side Push and how is it implemented and when is it useful? (Servlets)
Server Side push is useful when data needs to change regularly on the clients application
or browser, without intervention from client. Standard examples might include apps like
Stock's Tracker, Current News etc. As such server cannot connect to client's application
automatically. The mechanism used is, when client first connects to Server, (Either
through login etc..), then Server keeps the TCP/IP connection open.
Answer It's not always possible or feasible to keep the connection to Server open. So another
method used is, to use the standard HTTP protocols ways of refreshing the page, which is
normally supported by all browsers.
<META HTTP-EQUIV="Refresh" CONTENT="5;URL=/servlet/stockquotes/">
This will refresh the page in the browser automatically and loads the new data every 5
seconds.
Question What are the phases in JSP? (Servlets)
Answer a) Translation phase ? conversion of JSP to a Servlet source, and then Compilation of
servlet source into a class file. The translation phase is typically carried out by the JSP
engine itself, when it receives an incoming request for the JSP page for the first time
b) init(), service() and destroy() method as usual as Servlets.
How many cookies can one set in the response object of the servlet? Also,
Question
are there any restrictions on the size of cookies? (Servlets)
If the client is using Netscape, the browser can receive and store 300 total
cookies
Answer
4 kilobytes per cookie (including name)
20 cookies per server or domain
Question What?s the difference between sendRedirect( ) and forward( ) methods? (Servlets)
A sendRedirect method creates a new request (it?s also reflected in browser?s URL )
where as forward method forwards the same request to the new target(hence the chnge is
NOT reflected in browser?s URL).
Answer
The previous request scope objects are no longer available after a redirect because it
results in a new request, but it?s available in forward.
SendRedirectis slower compared to forward.
Is there some sort of event that happens when a session object gets bound or unbound to
Question
the session? (Servlets)
HttpSessionBindingListener will hear the events When an object is added and/or remove
from the session object, or when the session is invalidated, in which case the objects are
Answer
first removed from the session, whether the session is invalidated manually or
automatically (timeout).
Question What do the differing levels of bean storage (page, session, app) mean? (Servlets)
page life time - NO storage. This is the same as declaring the variable in a scriptlet and
using it from there.
session life time - request.getSession(true).putValue "myKey", myObj);
Answer application level ? getServletConfig().getServletContext().setAttribute("myKey ",myObj )

request level - The storage exists for the lifetime of the request, which may be forwarded
between jsp's and servlets
Is it true that servlet containers service each request by creating a new thread? If that is
Question true, how does a container handle a sudden dramatic surge in incoming requests without
significant performance degradation? (Servlets)
The implementation depends on the Servlet engine. For each request generally, a new
Thread is created. But to give performance boost, most containers, create and maintain a
thread pool at the server startup time. To service a request, they simply borrow a thread
Answer from the pool and when they are done, return it to the pool.
For this thread pool, upper bound and lower bound is maintained. Upper bound prevents
the resource exhaustion problem associated with unlimited thread allocation. The lower
bound can instruct the pool not to keep too many idle threads, freeing them if needed.
Question Can I just abort processing a JSP? (Servlets)
Yes. Because your JSP is just a servlet method, you can just put (whereever necessary) a
Answer
< % return; % >
Question What is URL Encoding and URL Decoding ? (Servlets)
URL encoding is the method of replacing all the spaces and other extra characters into their corres
Characters and Decoding is the reverse process converting all Hex Characters back their normal fo
For Example consider this URL, /ServletsDirectory/Hello'servlet/
Answer When Encoded using URLEncoder.encode("/ServletsDirectory/Hello'servlet/") the output is
http%3A%2F%2Fwww.javacommerce.com%2FServlets+Directory%2FHello%27servlet%2FThis
using
URLDecoder.decode("http%3A%2F%2Fwww.javacommerce.com%2FServlets+Directory%2FHel
Do objects stored in a HTTP Session need to be serializable? Or can it store any object?
Question (Servlets)
Yes, the objects need to be serializable, but only if your servlet container supports
persistent sessions. Most lightweight servlet engines (like Tomcat) do not support this.
Answer
However, many EJB-enabled servlet engines do. Even if your engine does support
persistent sessions, it is usually possible to disable this feature.
Question What is the difference between session and cookie? (Servlets)
The difference between session and a cookie is two-fold.
1) session should work regardless of the settings on the client browser. even if users
decide to forbid the cookie (through browser settings) session still works. there is no way
to disable sessions from the client browser.
2) session and cookies differ in type and amount of information they are capable of
Answer
storing.
Javax.servlet.http.Cookie class has a setValue() method that accepts Strings.
javax.servlet.http.HttpSession has a setAttribute() method which takes a String to denote
the name and java.lang.Object which means that HttpSession is capable of storing any
java object. Cookie can only store String objects.
Question What is the difference between ServletContext and ServletConfig? (Servlets)
Both are interfaces.
The servlet engine implements the ServletConfig interface in order to pass configuration
information to a servlet. The server passes an object that implements the ServletConfig
Answer interface to the servlet's init() method.
The ServletContext interface provides information to servlets regarding the environment
in which they are running. It also provides standard way for servlets to write events to a
log file.
Question What are the differences between GET and POST service methods? (Servlets)
A GET request is a request to get a resource from the server. Choosing GET
as the "method" will append all of the data to the URL and it will show up in
the URL bar of your browser. The amount of information you can send back
using a GET is restricted as URLs can only be 1024 characters. A POST
request is a request to post (to send) form data to a resource on the server. A
Answer
POST on the other hand will (typically) send the information through a socket
back to the webserver and it won't show up in the URL bar. You can send
much more information to the server this way - and it's not restricted to textual
data either. It is possible to send files and even binary data such as serialized
Java objects!
Question What is the difference between GenericServlet and HttpServlet? (Servlets)
GenericServlet is for servlets that might not use HTTP, like for instance FTP service.As
of only Http is implemented completely in HttpServlet.
Answer The GenericServlet has a service() method that gets called when a client request is made.
This means that it gets called by both incoming requests and the HTTP requests are given
to the servlet as they are
Question What is the Max amount of information that can be saved in a Session Object ? (Servlets)
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
Answer
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.
Question What is Servlet chaining? (Servlets)
Answer response object from one servlet is passed as request to another Servlet. Try this example
and you will come to know what servlet chaining is all about.
public class ServletA extends HttpServlet {
public void init(ServletConfig config) throws ServletException {}
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException {
String aValue = request.getParameter("valueA");
System.out.println("ServletA read: "+aValue);
request.setAttribute("ReadTheValue","Yes");
//do other servlet stuff...just don't open a write and output to the page....
request.getRequestDispatcher("/servletB").forward(req,resp);
}
}

public class ServletB extends HttpServlet {


public void init(ServletConfig config) throws ServletException {}
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException {
String aValue = request.getParameter("valueA");
System.out.println("ServletB also got the value: "+aValue);
System.out.println("ServletB also found attribute:
"+request.getAttribute("ReadTheValue"));
//finish the task and write to the page.
}
}

Advantages:
1) Chaining reduces the demand on a single servlet
2) Modular design
3) Enables different complex processes to be maintained by more than one person.
4) Allows steps in a process to be modified (eg servlet 1 -> servlet 2 or servlet 1 -> servlet
3 -> servlet 2, etc)
5) Removes the complexity in a single servlet
I am using servlets. I need to store an object NOT a string in a cookie. Is that possible?
Question The helpfile says BASE64 encoding is suggested for use with binary values. How can I do
that? (Servlets)
You could serialize the object into a ByteArrayOutputStream and then Base64 encode the
resulting byte[]. We must keep in mind the size limitations of a cookie and the overhead of
transporting it back and forth between the browser and the server.
Limitations are:
Answer * at most 300 cookies
* at most 4096 bytes per cookie (as measured by the characters that comprise the cookie
non-terminal in the syntax description of the Set-Cookie2 header, and as received in the
Set-Cookie2 header)
* at most 20 cookies per unique host or domain name

1. What is the servlet?

Servlets are modules that extend request/response-oriented servers, such as Java-


enabled web servers. For example, a servlet may be responsible for taking data
in an HTML order-entry form and applying the business logic used to update a
company's order database.

2. What's the difference between servlets and applets?

Servlets are to servers; applets are to browsers. Unlike applets, however, servlets
have no graphical user interface.

3. What's the advantages using servlets than using CGI?

Servlets provide a way to generate dynamic documents that is both easier to


write and faster to run. It is efficient, convenient, powerful, portable, secure and
inexpensive. Servlets also address the problem of doing server-side
programming with platform-specific APIs: they are developed with Java Servlet
API, a standard Java extension.

4. What are the uses of Servlets?

A servlet can handle multiple requests concurrently, and can synchronize


requests. This allows servlets to support systems such as on-line conferencing.
Servlets can forward requests to other servers and servlets. Thus servlets can be
used to balance load among several servers that mirror the same content, and to
partition a single logical service over several servers, according to task type or
organizational boundaries.

5. What's the Servlet Interface?


The central abstraction in the Servlet API is the Servlet interface. All servlets
implement this interface, either directly or, more commonly, by extending a
class that implements it such as HttpServlet.

Servlets-->Generic Servlet-->HttpServlet-->MyServlet.

The Servlet interface declares, but does not implement, methods that manage the
servlet and its communications with clients. Servlet writers provide some or all of
these methods when developing a servlet.

6. When a servlet accepts a call from a client, it receives two objects. What are they?

ServeltRequest: which encapsulates the communication from the client to the


server.

ServletResponse: which encapsulates the communication from the servlet back


to the client.

ServletRequest and ServletResponse are interfaces defined by the javax.servlet


package.

7. What information that the ServletRequest interface allows the servlet access to?

Information such as the names of the parameters passed in by the client, the
protocol (scheme) being used by the client, and the names of the remote host
that made the request and the server that received it. The input stream,
ServletInputStream.Servlets use the input stream to get data from clients that use
application protocols such as the HTTP POST and PUT methods.

8. What information that the ServletResponse interface gives the servlet methods for
replying to the client?

It Allows the servlet to set the content length and MIME type of the reply.
Provides an output stream, ServletOutputStream and a Writer through which the
servlet can send the reply data.

9. If you want a servlet to take the same action for both GET and POST request,
what should you do?

Simply have doGet call doPost, or vice versa.

10. What is the servlet life cycle?


Each servlet has the same life cycle:
A server loads and initializes the servlet (init())
The servlet handles zero or more client requests (service())
The server removes the servlet (destroy()) (some servers do this step only when
they shut down)
11. Which code line must be set before any of the lines that use the PrintWriter?

setContentType() method must be set before transmitting the actual document.

12. How HTTP Servlet handles client requests?

An HTTP Servlet handles client requests through its service method. The service
method supports standard HTTP client requests by dispatching each request to a
method designed to handle that request.

13. When using servlets to build the HTML, you build a DOCTYPE line, why do you
do that?

I know all major browsers ignore it even though the HTML 3.2 and 4.0
specifications require it. But building a DOCTYPE line tells HTML validators
which version of HTML you are using so they know which specification to
check your document against. These validators are valuable debugging services,
helping you catch HTML syntax errors.

http://validator.w3.org/ and
http://www.htmlhelp.com/tools/validator/

are two major online validators.

Q: Explain the life cycle methods of a Servlet.

A: The javax.servlet.Servlet interface defines the three methods


known as life-cycle method.
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, then initialized wih the init() method.
Any request from client are 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()


methid, then garbaged collected and finalized.
TOP

Q: What is the difference between the


getRequestDispatcher(String path) method of
javax.servlet.ServletRequest interface and
javax.servlet.ServletContext interface?

A: The getRequestDispatcher(String path) method of


javax.servlet.ServletRequest interface accepts parameter the path to
the resource to be included or forwarded to, which can be relative to
the request of the calling servlet. If the path begins with a "/" it is
interpreted as relative to the current context root.

The getRequestDispatcher(String path) method of


javax.servlet.ServletContext interface cannot accepts relative paths.
All path must sart with a "/" and are interpreted as relative to curent
context root.
TOP

Q: Explain the directory structure of a web application.

A: 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
2. classes directory
3. lib directory
TOP

Q: What are the common mechanisms used for session


tracking?

A: Cookies
SSL sessions
URL- rewriting
TOP

Q: Explain ServletContext.

A: ServletContext interface is a window for a servlet to view it's


environment. A servlet can use this interface to get information such
as initialization parameters for the web applicationor servlet
container's version. Every web application has one and only one
ServletContext and is accessible to all active resource of that
application.
TOP

Q: What is preinitialization of a servlet?

A: A container doesnot initialize the servlets ass soon as it starts


up, it initializes a servlet when it receives a request for that servlet
first time. This is called lazy loading. The servlet specification defines
the <load-on-startup> element, which can be specified in the
deployment descriptor to make the servlet container load and initialize
the servlet as soon as it starts up. The process of loading a servlet
before any request comes in is called preloading or preinitializing a
servlet.
[ Received from Amit Bhoir ] TOP

Q: What is the difference between Difference between


doGet() and doPost()?

A: A doGet() method is limited with 2k of data to be sent, and


doPost() method doesn't have this limitation. A request string for
doGet() looks like the following:
http://www.allapplabs.com/svt1?p1=v1&p2=v2&...&pN=vN
doPost() method call doesn't need a long text tail after a servlet name
in a request. All parameters are stored in a request itself, not in a
request string, and it's impossible to guess the data transmitted to a
servlet only looking at a request string.
[ Received from Amit Bhoir ] TOP

Q: What is the difference between HttpServlet and


GenericServlet?

A: A GenericServlet has a service() method aimed to handle


requests. 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.
[ Received from Amit Bhoir ]

You might also like