Servlets Faqs-->3
26)
What is the difference between the 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().
27)
What is the difference between encodeRedirectUrl and encodeURL?
encodeURL
and encodeRedirectURL are methods of the HttpResponse object. Both rewrite a
raw URL to include session data if necessary. (If cookies are on, both are
no-ops.)
encodeURL
is for normal links inside your HTML pages.
encodeRedirectURL
is for a link you're passing to response.sendRedirect(). It has slightly
different syntax requirements too gory to get into here.
28)
Can I use System.exit() in servlets?
Gack!
No no no no no...
At
best, you'll get a security exception. At worst, you'll make the servlet
engine, or maybe the entire web server, quit. You don't really want to do that,
huh? :-)
29)
I am opening a single JDBC connection in my init() method. Do I need to synchronize
on the Connection or the Statement object?
You
shouldn't have to. If your JDBC driver supports multiple connections, then the
various createStatement methods will give you a thread-safe, reentrant,
independent Statement that should work OK, even if other requests/threads are
also accessing other Statements on the same Connection.
Of
course, crossing your fingers never hurts... Many
early JDBC drivers were not re-entrant.
The modern versions of JDBC drivers should work OK, but there are never any
guarantees.
Using
connection pooling will avoid the whole issue, plus will lead to improved
performance. See this FAQ for more information.
30)
How can I determine the name and version number of the servlet or JSP engine
that I am using?
From
within a servlet, you can invoke the ServletContext.getServerInfo() method as
follows:
String thisServer=
getServletConfig().getServletContext().getServerInfo();
If
you are using JSP, you can use this expression:
<%= application.getServerInfo() %>
31)
How can I get the absolute URL of a servlet/JSP page at runtime?
You
can get all the necessary information to determine the URL from the request
object. To reconstruct the absolute URL from the
scheme,
server name, port, URI and query string you can use the URL class from
java.net. The following code fragment will determine your page's absolute URL:
String file = request.getRequestURI();
if (request.getQueryString() != null) {
file += '?' + request.getQueryString();
}
URL reconstructedURL = new URL(request.getScheme(),
request.getServerName(),
request.getServerPort(),
file);
out.println(URL.toString());
32)
Why do GenericServlet and HttpServlet implement the Serializable interface?
GenericServlet
and HttpServlet implement the Serializable interface so that servlet engines
can "hybernate" the servlet state when the servlet is not in use and
reinstance it when needed or to duplicate servlet instances
for better load balancing. I don't know if or
how current servlet engines do this, and it could have serious implications,
like breaking references to objects gotten in the init() method without the
programmer knowing it. Programmers should be aware of this pitfall and
implement servlets which are stateless as possible, delegating data store to
Session objects or to the ServletContext. In general stateless servlets are
better because they scale much better and are cleaner code.
33)
How does one choose between overriding the doGet(), doPost(), and
service()
methods?
The
differences between the doGet() and doPost() methods are that they are called
in the HttpServlet that your servlet extends by its service() method when it
recieves a GET or a POST request from a HTTP protocol request.
A
GET request is a request to get a resource from the server. This is the case of
a browser requesting a web page. It is also possible to specify parameters in
the request, but the length of the parameters on the whole is limited. This is
the case of a form in a web page declared this way in html: <form method="GET">
or <form>.
A
POST request is a request to post (to send) form data to a resource on the
server. This is the case of of a form in a web page declared this way in html:
<form method="POST">. In this case the size of the parameters
can be much greater.
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 (you must do the parsing
yourself).
The
HttpServlet instead has doGet() and doPost() methods that get called when a
client request is GET or POST. This means that the parsing of the request is
done by the servlet: you have the appropriate method called and have
convenience methods to read the request parameters.
NOTE: the doGet() and
doPost() methods (as well as other HttpServlet methods) are called by the
service() method.
Concluding,
if you must respond to GET or POST requests made by a HTTP protocol client
(usually a browser) don't hesitate to extend HttpServlet and use its
convenience methods.
If
you must respond to requests made by a client that is not using the HTTP
protocol, you must use service().
34)
How do servlets differ from RMI? What are the advantages and disadvantages of
each technology?
Servlets
extend the server-side functionality of a website. Servlets communicate with
other application(s) on that server (or any other server) and perform tasks
above and beyond the "normal" static HTML document. A servlet can
receive a request to get some information through EJB from one or more
databases, then convert this data into a static HTML/WML page for the client to
see, for example. Even if the servlet talks to many other applications all over
the world to get this information, it still looks like it happened at that
website.
RMI
(Remote Method Invocation) is just that - a way to invoke methods on remote
machines. It is way for an application to talk to another
remote machine and execute different methods, all the while appearing as if the
action was being performed on the local machine.
Servlets
(or JSP) are mainly used for any web-related activity such as online banking, online grocery stores, stock trading, etc. With
servlets, you need only to know the web address and the pages displayed to you
take care of calling the different servlets (or actions within a servlet) for
you. Using RMI, you must bind the RMI server to an IP and port, and the client
who wishes to talk to the remote server must know this IP and port, unless of
course you used some kind of in-between lookup utility, which you could do with
(of all things) servlets.
35)
How can we use a servlet as a proxy for communications between two applets?
One
way to accomplish this is to have the applets communicate via TCP/IP sockets to
the servlet. The servlet would then use a custom protocol to receive and push
information between applets. However, this solution does have firewall problems
if the system is to be used over and Internet verses an Intranet.
36)
How can I design my servlet/JSP so that query results get displayed on several
pages, like the results of a search engine? Each page should display, say, 10
records each and when the next link is clicked, I should see the next/previous
10 records and so on.
Use
a Java Bean to store the entire result of the search that you have found. The
servlet will then set a pointer to the first line to be displayed in the page
and the number of lines to display, and force a display of the page. The Action
in the form would point back to the servlet in the JSP page which would
determine whether a next or previous button has been pressed and reset the
pointer to previous pointer + number of lines and redisplay the page. The JSP
page would have a scriplet to display data from the Java Bean from the start
pointer set to the maximum number of lines with buttons to allow previous or
next pages to be selected. These buttons would be displayed based on the page
number (i.e. if first then don't display previous button).
37)
How do I deal with multi-valued parameters in a servlet?
Instead
of using getParameter() with the ServletRequest, as you would with
single-valued parameters, use the getParameterValues() method. This returns a
String array (or null) containing all the values
of
the parameter requested.
38)
How can I pass data retrieved from a database by a servlet to a JSP page?
One
of the better approaches for passing data retrieved from a servlet to a JSP is
to use the Model 2 architecture as shown below:
Basically,
you need to first design a bean which can act as a wrapper for storing the
resultset returned by the database query within the servlet.
Once the bean has been instantiated and initialized by invoking its setter
methods by the servlet, it can be placed within the request object and
forwarded to a display JSP page as follows:
com.foo.dbBean bean = new
com.foo.dbBean();
//call setters to initialize bean
req.setAttribute("dbBean",
bean);
url="..."; //relative url for
display jsp page
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(url);
rd.forward(req, res);
The
bean can then be accessed within the JSP page via the useBean tag as:
<jsp:useBean id="dbBean"
class="com.foo.dbBean" scope="request"/>
...
<%
//iterate through the rows within dbBean and
//access the values using a scriptlet
%>
Also,
it is best to design your application such that you avoid placing beans into
the session unless absolutely necessary. Placing large objects within the
session imposes a heavy burden on the performance of the servlet engine. Of
course, there may be additional design considerations to take care of -
especially if your servlets are running under a clustered or fault-tolerant
architecture.
39)
How can I use a servlet to generate a site using frames?
In
general, look at each frame as a unique document capable of sending its own
requests and receiving its own responses. You can create a top servlet (say,
FrameServlet) that upon invocation creates the frame layout you desire and sets
the SRC parameters for the frame tags to be another servlet, a static page or
any other legal value for SRC.
---------------------- SAMPLE
----------------------
public void doGet(HttpServletRequest
request,
HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = new PrintWriter
(response.getWriter());
out.println("");
out.println("Your Title");
// definingthe three rows of Frames for
the main page
// top : frm_1
// middle : frm_2
// bottom : frm_3
out.println("");
out.println("");
out.println("");
out.println("");
out.println("");
out.println("");
out.println("");
out.close();
-------------------------- END
------------------------------------------
Where
MenuServlet and DummyServlet provide content and behavior for the frames
generated by FrameServlet.
40)
What is HTTP tunneling, in the general sense?
HTTP
tunneling is a general technique whereby arbitrary data may be sent via an HTTP
connection to and from CGI scripts or Java Servlets on a Web server. This is
done by serializing the data to be transmitted into a stream of bytes, and
sending an HTTP message with content type "application/octet-stream".
HTTP
tunneling is also referred to as Firewall tunneling.
41)
How do I handle FORMs with multiple form elements (e.g. radio buttons) using
the same name?
For
radio buttons, the HTML spec assumes that a given group of buttons will have
the same NAME and different VALUEs; the browser makes sure that only one button
per group name will be selected (at most). So you can just call
request.getParameter("groupname").
<input type="radio"
name="topping" value="cheese" checked>Cheese
<input type="radio"
name="topping" value="pepperoni">Pepperoni
<input type="radio"
name="topping" value="anchovies">Anchovies
If
the user selects "Pepperoni" then
request.getParameter("topping") will return the string
"pepperoni".
For
lists using the <select multiple> FORM tag, multiple values can be
returned for the same parameter name. When that can happen, use request.getParameterValues("param")
which returns a String[] you can iterate through.
It's
bad form (so to speak), but you can also duplicate other element types, like
Name 1: <input type="text"
name="name" value="Dick">
Name 2: <input type="text"
name="name" value="Jane">
These
also get returned in an array by request.getParameterValues().
42)
How do I separate presentation (HTML) from business logic (Java) when using
servlets?
Almost
anybody who has ever written a servlet can identify with this one. We all know
it's bad for to embed HTML code in our java source; it's lame to have to
recompile and re-deploy every time you want an HTML element to look a bit
different. But what are our choices here? There are two basic options;
1.
Use JSP: Java
Server Pages allows you to embed Java code or the results of a servlet into
your HTML. You could, for instance, define a servlet that gives a stock quote,
then use the tag in a JSP page to embed the output. But then, this brings up
the same problem; without discipline, your content/presentation and program
logic are again meshed. I think the ideal here is to completely separate the
two.
2.
Use a templating/parsing system: Hmm...I know you're about to rant about
re-inventing the wheel, but it's not that bad (see below). Plus, it really does
pay to take this approach; you can have a group of programmers working on the
Java code, and a group of HTML producers maintaining the interface. So now you
probably want to know how to do it...so read on.
Use
SSI!
Remember
SSI? It hasn't gotten much attention in recent years because of embeddable
scripting languages like ASP and JSP, but it still remains a viable option. To
leverage it in the servlet world, I believe the best way is to use an API
called SSI for Java from Areane. This API will let you emulate SSI commands
from a templating system, and much more. It will let you execute any command on
any system, including executing java classes! It also comes with several
utility classes for creating stateful HTML form elements, tables for use with
iteration, and much more. It's also open source, so it's free and you can tweak
it to your heart's content! You can read the SSI for Java documentation for
detailed info, but the following is an example of its use.
Here's
the servlet:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import com.areane.www.ssi.*;
public class SSITemplatingServlet
extends HttpServlet {
private String templateFilesDirectory =
"d:\\projects\\idemo\\templates\\"; //Holds path to template files
/**Handles GET requests; defers every request to the POST processor*/
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException,
IOException, FileNotFoundException {doPost(req, res);}
/**Handles all requests. Processes the request,
*saves the values, parses the file, then feeds the file to the out
stream*/
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException, FileNotFoundException {
HttpSession ses = req.getSession(true);
Properties context = null;
if((context = (Properties)ses.getValue("user.context")) ==
null) { //if properties doesn't already exist, create it.
context = new Properties();
}
//Write parameters to Properties object
Enumeration paramNames = req.getParameterNames();
String curName, curVal;
while(paramNames.hasMoreElements()) {
curName =
(String)paramNames.nextElement();
curVal =
req.getParameter(curName);
context.setProperty(curName,
curVal);
}
//Save the values to the session
ses.putValue("user.context", context);
//Parse the page and stream to the client
String templateName = req.getParameter("template"); // Get the
file name of the template to use
res.setContentType("text/html");
SsiPage page = SsiParser.parse(this.templateFilesDirectory +
templateName); //Parsing occurs here
page.write(res.getWriter(), context); //Stream to the client
page = null; //clean up
}
}
Now,
just create a template file, pass the servlet the template file name, and have
at it!
43)
For an HTML FORM with multiple SUBMIT buttons, how can a servlet ond
differently for each button?
The
servlet will respond differently for each button based on the html that you
have placed in the HTML page. Let's explain.
For
a submit button the HTML looks like <input type=submit name="Left"
value="left">. A servlet could extract the value of this submit by
using the getParameter("Left") from the HttpRequest object. It
follows then that if you have HTML within a FORM that appears as:
<input type=submit
name="Direction" value="left">
<input type=submit
name="Direction" value="right">
<input type=submit
name="Direction" value="up">
<input type=submit
name="Direction" value="down">
Then
the getParameter("Direction") from the HttpRequest would
extract the value pressed by the user, either "left",
"right", "up" or "down". A simple comparision in
the servlet with the these values could occur and processing based on the
submit button would be performed.
Similiarly,for
submit buttons with different names on a page, each of these values could be
extracted using the getParameter() call and acted on. However, in a
situation where there are multiple buttons, common practice would be to use one
name and multiple values to identify the button pressed.
44)
What is meant by the term "business logic"?
"Business
logic" is just a fancy way of saying "code." :-)
More
precisely, in a three-tier architecture, business logic is any code that is not
specifically related to storing and retrieving data (that's "data storage
code"), or to formatting data for display to the user (that's
"presentation logic"). It makes sense, for many reasons, to store
this business logic in separate objects; the middle tier comprises these
objects. However, the divisions between the three layers are often blurry, and
business logic is more of an ideal than a reality in most programs. The main point
of the term is, you want somewhere to store the logic and "business
rules" (another buzzword) of your application, while keeping the division
between tiers clear and clean.
45)
How can I explicitly unload a servlet or call the destroy method?
In
general, you can't. The Servlet API does not specify when a servlet is unloaded
or how the destroy method is called. Your servlet engine (ie the implementation
of the interfaces in the JSDK) might provide a way to do this, probably through
its administration interface/tool (like Webshpere or JWS). Most servlet engines
will also destroy and reload your servlet if they see that the class file(s)
have been modified.
46)
What is a servlet bean?
A
servlet bean is a serializable servlet that follows the JavaBeans component
architecture, basically offering getter/setter methods.
As
long as you subclass GenericServlet/HttpServlet, you are automatically
Serializable.
If
your web server supports them, when you install the servlet in the web server,
you can configure it through a property sheet-like interface.
47)
Why do we need to call super.init(config) in the init method of a servlet?
Just
do as you're told and you won't get hurt! :-)
Because
if you don't, then the config object will get lost. Just extend HttpServlet,
use init() (no parameters) and it'll all work ok.
From
the Javadoc: init() - A convenience method which can be overridden so that
there's no need to call super.init(config).
48)
What is a servlet engine?
A
"servlet engine" is a program that plugs in to a web server and runs
servlets. The term is obsolete; the preferred term now is "servlet
container" since that applies both to plug-in engines and to stand-alone
web servers that support the Servlet API.
49)
Which is the most efficient (i.e. processing speed) way to create a server
application that accesses a database: A Servlet using JDBC; a JSP page using a
JavaBean to carry out the db access; or JSP combined with a Servlet? Are these
my only choices?
Your
question really should be broken in two.
1-What
is the most efficient way of serving pages from a Java object?. There you have
a clear winner in the Servlet. Althought if you are going to change the static
content of the page often is going to be a pain because you'll have to change
Java code. The second place in speed is for JSP pages. But, depending on your
application, the difference in speed between JSP pages and raw servlets can be
so small that is not worth the extra work of servlet programming.
2-What
is the most efficient way of accessing a database from Java?. If JDBC is the
way you want to go the I'd suggest to pick as many drivers as you can
(II,III,IV or wathever) and benchmark them. Type I uses a JDBC/ODBC bridge and
usually has lousy performance. Again, go for the simplest (usually type IV driver)
solution if that meets you performance needs.
For
database applications, the performance bottleneck is usually the database, not
the web server/engine. In this case, the use of a package that access JDBC with
connection pooling at the application level used from JSP pages (with or
withouth beans as middleware) is the usual choice. Of course, your applications
requirements may vary.
50)
How can I change the port of my Java Web Server from 8080 to something else?
It
is very simple. JAVA WEB SERVER comes with remote Web administration tool. You
can access this with a web browser.
Administration
tool is located on port 9090 on your web server. To change port address for web
server:
- Access tool
(http://hostname:9090)
- Enter User
Id/Password (by default it is admin/admin)
- Select service
(Web service)
- Click on
"manage" button. You will get a popup screen with all settings.
- Click on network
tree node, On right hand side you will get text box for entering port no.
- Change port
number with desire one.
- click on restart button.
0 comments:
Post a Comment