Академический Документы
Профессиональный Документы
Культура Документы
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);
}
}
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
Servlets are to servers; applets are to browsers. Unlike applets, however, servlets
have no graphical user interface.
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?
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?
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/
A: Cookies
SSL sessions
URL- rewriting
TOP
Q: Explain ServletContext.