Welcome to Scribd, the world's digital library. Read, publish, and share books and documents. See more
Download
Standard view
Full view
of .
Save to My Library
Look up keyword
Like this
18Activity
0 of .
Results for:
No results containing your search query
P. 1
ServletsFAQ

ServletsFAQ

Ratings: (0)|Views: 441 |Likes:
Published by soulbringer
Servlet FAQ J2EE Quenstions and answer
Servlet FAQ J2EE Quenstions and answer

More info:

Published by: soulbringer on Jul 13, 2009
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

06/29/2011

pdf

text

original

 
Servlets FAQ Page 1 of 31
Mohan
Servlets FAQ
How do I support both GET and POST protocol from the same Servlet?
The easy way is, just support POST, then have your doGet method call your doPost method:public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException{doPost(req, res);}Note that implementing the service() method is usually not what you want to do, since HttpServlet provides its ownimplementation of service() that turns around and calls doGet(), doPost(), etc.Lee Crocker (LCrocker@INFORMANT.COM): "It's probably cleaner not to override service() when extending HttpServlet. Theexisting service method just calls doGet(), doPost(), etc. as appropriate, so you can certainly override it if you feel like it,but then you wind up not only treating GET and POST identically, but also all other HTTP commands, like HEAD, TRACE, andOPTIONS. If you want GET and POST to do the same thing, just have doGet() and doPost() call the same private methodthat does all the work."
How do I fully shut down the server?
For JWS, under Windows, pressing control-C doesn't fully shut down the server. You should use the Admin Tool and click "ShutDown". (Or you can hit ctl-alt-del, find "JREW" in the list, and "End Task".)
My browser says "the server returned an invalid or unrecognized response" -- what gives?
This is probably due to a NullPointerException being thrown. There's a bug in JWS 1.1 whereby it doesn't correctly log theseexceptions.The solution is to put your doPost() method inside a try block and catch NullPointerException. See the debugging question inthis FAQ for more details and source code.
How do I get the name of the currently executing script?
Use req.getRequestURI() or req.getServletPath(). The former returns the path to the script including any extra path informationfollowing the name of the servlet; the latter strips the extra path info. For example:
URL
http://www.purpletech.com/servlets/HelloEcho/extra/info?height=100&width=200
GetRequestURI
 /servlets/HelloEcho/extra/info
GetServletPath
 /servlets/HelloEcho
getPathInfo
 /extra/info
GetQueryString
height=100&width=200This is useful if your form is self-referential; that is, it generates a form which calls itself again. For example:out.println("<FORM METHOD=POST ACTION=\"" +res.encodeURL(
req.getServletPath()
) +"\">");out.println("<INPUT NAME=value>");out.println("<INPUT TYPE=submit>");out.println("</FORM>");(encodeURL adds session information if necessary. See the Sun Servlet Tutorial and this FAQ's Session Tracking question.Note that this method was renamed from "encodeUrl" to the properly-capitalized "encodeURL" somewhere around version2.1 of the servlet spec.)Note that early versions of Java Web Server and some servlet engines had a bug whereby getRequestURI would also returnthe GET parameters following the extra path info.
How do I ensure that my servlet is thread-safe?
This is actually a very complex issue. A few guidelines:1.
 
The init() method is guaranteed to be called once per servlet instance, when the servlet is loaded. You don't haveto worry about thread safety inside this method, since it is only called by a single thread, and the web server willwait until that thread exits before sending any more threads into your service() method.2.
 
Every new client request generates a new thread; that thread calls the service() method of your servlet (whichmay in turn call doPost(), doGet() and so forth).3.
 
Under most circumstances, there is only one instance of your servlet, no matter how many client requests are inprocess. That means that at any given moment, there may be many threads running inside the service() method of your solo instance, all sharing the same instance data and potentially stepping on each other's toes. This meansthat you should be careful to
synchronize
access to shared data (instance variables) using the synchronizedkeyword.4.
 
Note that you need not (and should not) synchronize on local data or parameters. And especially you shouldn't
 
Servlets FAQ Page 2 of 31
Mohan
synchronize the service() method! (Or doPost(), doGet()
et al
.)5.
 
A simple solution to synchronizing is to always synchronize on the servlet instance itself using "synchronized (this){ ... }". However, this can lead to performance bottlenecks; you're usually better off synchronizing on the dataobjects themselves.6.
 
If you absolutely can't deal with synchronizing, you can declare that your servlet "implements SingleThreadModel".This empty interface tells the web server to only send one client request at a time into your servlet. From theJavaDoc:
"If the target servlet is flagged with this interface, the servlet programmer is guaranteed that no twothreads will execute concurrently the service method of that servlet. This guarantee is ensured by maintaining apool of servlet instances for each such servlet, and dispatching each service call to a free servlet. In essence, if theservlet implements this interface, the servlet will be thread safe."
Note that this is not an ideal solution, sinceperformance may suffer (depending on the size of the instance pool), plus it's more difficult to share data acrossinstances than within a single instance.7.
 
To share data across successive or concurrent requests, you can use either instance variables or class-staticvariables, or useSession Tracking.8.
 
The destroy() method is not necessarily as clean as the init() method. The server calls destroy
either
after allservice calls have been completed,
or
after a certain number of seconds have passed, whichever comes first. Thismeans that other threads might be running service requests at the same time as your destroy() method is called!So be sure to synchronize, and/or wait for the other requests to quit. Sun's Servlet Tutorial has an example of howto do this with reference counting.9.
 
destroy() can not throw an exception, so if something bad happens, call log() with a helpful message (like theexception). See the "closing a JDBC connection" example in Sun's Tutorial.
How do I use Session Tracking? That is, how can I maintain "session scope data" between servlets in the sameapplication?
Session Tracking is one of the most powerful features of Servlets and JSP. Basically, the servlet engine takes care of using Cookies inthe right way to preserve state across successive requests by the same user. Your servlet just needs to call a single method(getSession) and it has access to a persistent hashtable of data that's unique to the current user. Way cool.A point I haven't seen emphasized enough is that you should only add objects that are
serializable
to an HttpSession.Specifically, a JDBC Connection object is
not
serializable, so should not be added to the session (despite the example inJason Hunter's otherwise admirable
Java Servlet Programming
). If you'd like to associate a connection with a session, thenstore some arbitrary, unique handle in the session, then use that to key off your own hashtable of connections. (Make sureupon retrieval that the returned connection is not null, and if it is, create a new connection!)The reason is that sessions may, at the whim of the server, be swapped out to disk, in order to save memory or reboot theserver. This behavior can be disabled by setting a configuration parameter in your server or servlet engine. (I can'tremember offhand what these are -- please email me if you know.) From the spec:Some servlet engine implementations will persist session data or distribute it amongst multiple network nodes. Foran object bound into the session to be distributed or persisted to disk, it must implement the Serializable interface.
How can I detect whether the user accepted my cookie?
Here's a clever trick: use a redirect. Drop a cookie on the HttpServletResponse object, then call response.sendRedirect() to a "phasetwo" servlet. The "phase two" servlet then tests whether the cookie was sent back to it. If so, that means the user accepted thecookie the first time; if not, it means that either the client rejected the cookie, or the browser doesn't support cookies.Note that this technique only works if the "phase two" servlet is hidden from the user; if the user can jump directly to thetest phase, then the servlet can't tell the difference between newly-arrived clients and cookie-unfriendly clients. That meansyou should send a redirect from the test phase, to make sure the user doesn't have a chance to bookmark the test phase'sURL.
How do I integrate HTML design into my Servlet?
The question can be rephrased, "How can I design a work flow that incorporates HTML designers and programmers to build adynamically generated web site that will keep expanding and growing over time?" This is a special case of the intractable ContentManagement Problem of the Web in general. The real problem is to allow HTML designers (that is, humans) to use their favoriteHTML editing tools without learning Java, and to allow marketing people (arguably humans) to change the look of the site on a whim,without having to alter the database access code inside the servlet. (And vice versa -- to alter the business logic and data accesswithout altering the user interface.)There are many, many possibilities... The list below is not complete, but should give you some guidelines.
A. Hardcode HTML.
You can just put HTML inside of print statements in your Servlet's doGet() or doPost() method.
Pro:
easy to code, easy to understand for the programmer.
Con:
difficult to understand for the designer; when a change has to be made, the programmer has to wait for the designerto finish her HTML, then re-hard-code it all back into print statements, then make sure the generated HTML actually doeswhat the original HTML did. Basically, good for a hello world servlet, not good for a real web site.
 
Servlets FAQ Page 3 of 31
Mohan
B. Server Side Includes (SSI).
Use the tag inside your HTML file (and rename it .shtml). The HTML designers will makepretty pages; your servlets will output small pieces of text that get spliced in to the web page by the server.
Pro:
separates UI (HTML) and code.
Con:
You have two possible end paths with SSI: either your servlet outputs many tiny bits of text with no HTML tags, oryour servlet outputs a big bunch of text with embedded HTML tags. In the first case, your code can't take advantage of itsknowledge of the structure of the data -- for example, you can't format an HTML table from a database. In the second case,you're back to hardcoding HTML, thus making it hard to change the look of your pages.
C. Presentation Templates.
This is a good way to put common navigation elements (button bar, credits, etc) on all of your pages. The technology is built in to the Java Web Server, and implemented by several (though not all) of the servletengines.
Pro:
you don't have to enter in the same common HTML for all the countless pages in your web site.
Con:
your servlet code still has to hardcode HTML if it wants to be powerful (see item B, SSI).
D. JSP
Java Server Pages. You write files in HTML format, and embed actual Java code inside the HTML. This is kind of likeusing JavaScript, only it's on the server, and it's real Java. This is directly parallel to Microsoft's ASP.
Pro:
it's really cool; you only need a single file to do both UI and layout code; you don't have to type "println" so much.
Con:
if you do anything interesting, then your HTML designers will get really confused looking at the interlaced Java andHTML code -- so make sure to put the complicated code inside a JavaBean where it belongs, not in the JSP page.The new version of the JSP spec has lots of features for integrating with JavaBeans, which is a great way to separate userinterface (JSP) from data and business logic (beans). See also the JSP FAQ (see our References section for a link).Halcyon Software has a product called Instant ASP, which allows you to execute Microsft IIS-style ASPs (including code inVBScript, Jscript, Perl, Java, and JavaScript) in any Servlet Engine. Also Live Software has CF_Anywhere, which executesCold Fusion CFML pages. See the References section for links.
E. Write your own page parser.
If for some reason you're not happy with the standard mechanisms for doing templates(see B-D above), you can always write your own parser. Seriously. It's not rocket science.
F. HTML Object Model Class Libraries
e.g. htmlKona, XML. With these class libraries, you write code and build an objectmodel, then let the objects export HTML. This doesn't really work for complicated layouts -- and forget about letting yourdesigner use an HTML editor -- but it can be useful when you have a highly dynamic site generating HTML, and you want toautomate the process. Unfortunately, you still have to learn HTML, if only to understand and validate the output. See theReferences section of this FAQ for a listing of some class libraries that can help.
G. Do it all yourself 
Develop a database-driven content management system. Think C|Net. It has a lot of standardcontent, but the database is king. HTML designers have little pieces of the page that they can play with, but ultimatelythey're just putting content into a database, and the site (servlet) is generating every page request dynamically. This sort of system is very difficult to design and build, but once you've built it, it can really pay off -- but only if you have dozens of writers, editors, designers, and programmers all working on the same site on an ongoing basis.For a brief list of alternate page template systems, see the References section of this FAQ.
How do I send email from a servlet?
with SMTP classes that make sending email very simple. if you are writing your own servlet you could grab one of the many SMTPimplementations from www.gamelan.com (search for SMTP and java). All the ones I've seen are pretty much the same -- open asocket on port 25 and drop the mail off. so you have to have a mail server running that will accept mail from the machine JServ isrunning on.
Are there any ISPs that will host my servlets?
The Adrenaline Group maintains a list of ISP's who host Java Servlets (http://www.adrenalinegroup.com/jwsisp.html) . Of these, afew have also said that they can host Java applications:
 
The Sphere (http://www.thesphere.com/)
 
Centralogic (http://www.centralogic.com/)
 
Electronaut (http://www.electronaut.com/)
What is the difference between URL encoding and URL rewriting?URL Encoding
is a process of transforming user input to a CGI form so it is fit for travel across the network -- basically, strippingspaces and punctuation and replacing with escape characters. URL Decoding is the reverse process. To perform these operations, call java.net.URLEncoder.encode() and java.net.URLDecoder.decode() (the latter was (finally!) added to JDK 1.2, aka Java 2).
Example:
changing "We're #1!" into "We%27re+%231%21"
URL Rewriting
is a technique for saving state information on the user's browser between page hits. It's sort of like cookies,only the information gets stored inside the URL, as an additional parameter. The HttpSession API, which is part of theServlet API, sometimes uses URL Rewriting when cookies are unavailable.
Example:
changing <A HREF="nextpage.html"> into

Activity (18)

You've already reviewed this. Edit your review.
1 thousand reads
1 hundred reads
Satish Marri liked this
rajaramansuresh liked this
rajaramansuresh liked this
balajismith liked this
nct_nct liked this
sattisrinivasa liked this

You're Reading a Free Preview

Download
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->