Servlets FAQ From Jguru
Servlets FAQ From Jguru
Location: http://www.jguru.com/faq/Servlets
Ownership: http://www.jguru.com/misc/user-agree.jsp#ownership.
That depends.
For developing servlets, just make sure that the JAR file containing javax.servlet.* is
in your CLASSPATH, and use your normal development tools (javac and so forth).
For running servlets, you need to set the CLASSPATH for your servlet engine. This
varies from engine to engine. Each has different rules for how to set the CLASSPATH,
which libraries and directories should be included, and which libraries and directories
should be excluded. Note: for engines that do dynamic loading of servlets (e.g.
JRun, Apache Jserv, Tomcat), the directory containing your servlet class files shoud
not be in your CLASSPATH, but should be set in a config file. Otherwise, the servlets
may run, but they won't get dynamically reloaded.
The Servlets 2.2 spec says that the following should automatically be included by the
container, so you shouldn't have to add them to your CLASSPATH manually.
(Classloader implementations are notoriously buggy, though, so YMMV.)
This applies to webapps that are present on the filesystem, and to webapps that
have been packaged into a WAR file and placed in the container's "webapps"
directory. (e.g. TOMCAT_HOME/webapps/myapp.war)
jre/lib/ext
Other servlet engines have their own conventions. Usually on the file system it's
"servlets" and in a URL it's "/servlet" (which is an alias or virtual path).
TOMCAT_HOME/webapps/ROOT/WEB-INF/classes
C:\Program Files\Allaire\JRun\servers\default\default-app\WEB-INF\classes
I'm not quite sure about this, but I believe that only...
Author: Roceller Alvarez (http://www.jguru.com/guru/viewbio.jsp?EID=41828), Apr
28, 2000
I'm not quite sure about this, but I believe that only works on JRUN.
How do I support both GET and POST protocol from the same Servlet?
Location: http://www.jguru.com/faq/view.jsp?EID=144
Created: Sep 3, 1999 Modified: 2000-08-10 10:04:27.869
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)
The easy way is, just support POST, then have your doGet method call your doPost
method:
See also:
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
try
{
CurrentSession =
request.getSession(/*false*/);
doSafeGetOrPost(request, response,
CurrentSession);
}
catch(Throwable t)
{
System.out.println("Error caught by
doSafeGetOrPostWrapper:\n"+t+"\n");
t.printStackTrace();
System.out.println("Writing to log...");
CurrentSession = request.getSession();
this.getServletContext().log("Error",
t);
System.out.println("...ok.");
try
{
ServletUtils.sendHttpError(t, request,
response);
}
catch(Throwable tr)
{
}
}
}
The same happens when you use an IDE such as IBM Visual Age for Java.
When you create a new Servlet, Visual Age for Java automatically creates the
init(), doGet(..), doPost(..), and performTask(..) method. It also invokes the
performTask(..) method from within the doGet(..) and doPost(..) methods.
So, now when the user invokes either of the doGet() or doPost() method from the
HTML Form using GET and POST, the query is automatically redirected to
performTask(..) method.
For JWS, under Windows, pressing control-C doesn't fully shut down the server. You
should use the Admin Tool and click "Shut Down". (Or you can hit ctl-alt-del, find
"JREW" in the list, and "End Task".)
The solution is to put your doPost() method inside a try block and catch
NullPointerException. See the debugging question in this FAQ for more details and
source code.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
http://myserver.foo.com/servlet/HelloHttpServlet?name=Fred
Comments and alternative answers
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=200
This is useful if your form is self-referential; that is, it generates a form which calls
itself again. For example:
Note that early versions of Java Web Server and some servlet engines had a bug
whereby getRequestURI would also return the GET parameters following the extra
path info.
Thanks
Avinash
(Note that the server will also allocate a new instance if you register the
servlet with a new name and, e.g., new init parameters.)
4. Note that you need not (and should not) synchronize on local data or
parameters. And especially you shouldn't synchronize the service()
method! (Or doPost(), doGet() et al.)
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 the JavaDoc: "If the target servlet is
flagged with this interface, the servlet programmer is guaranteed that no two
threads will execute concurrently the service method of that servlet. This
guarantee is ensured by maintaining a pool of servlet instances for each such
servlet, and dispatching each service call to a free servlet. In essence, if the
servlet implements this interface, the servlet will be thread safe."
Note that this is not an ideal solution, since performance may suffer
(depending on the size of the instance pool), plus it's more difficult to share
data across instances than within a single instance.
See also What's a better approach for enabling thread-safe servlets and JSPs?
SingleThreadModel Interface or Synchronization?
7. To share data across successive or concurrent requests, you can use either
instance variables or class-static variables, or use Session Tracking.
Point 6: What is the initial size of the pool? Assume there is only one instance of the
servlet that implements singlethreadmodel. Does more request imply more instances (
as opposed to more thread when the servlet does not implement SingleThread)? If so,
what is the maximum servlet instances? Does it depend on the resource?
Does the thread associated with the client request guaranteed to have the sole access
and ownership of HttpServletRequest and HttpServletResponse objects? To put it the
other way, do I need to synchronize access to these objects (HttpServletRequest and
HttpServletResponse)?
6. The thread pool size is determined by the engine; there should be a config
parameter. Every request that comes in while another request is being processed
spawns a new instance, up to a certain number of instances. After that, they stall.
Again, the numbers are up to the engine.
2. You definitely always are the only one who has the Request and Response objects,
so don't bother synchronizing on them. They're per client request, remember.
This setup sounds good to me, but I have not tried it yet. Any comments?
How do I use Session Tracking? That is, how can I maintain "session scope
data" between servlets in the same application?
Location: http://www.jguru.com/faq/view.jsp?EID=151
Created: Sep 3, 1999 Modified: 2000-09-10 10:49:31.243
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)
Session Tracking is one of the most powerful features of Servlets and JSP. Basically,
the servlet engine takes care of using Cookies in the 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 <mono>HttpSession</mono>. Specifically, a JDBC
Connection object is not serializable, so should not be added to the session (despite
the example in Jason Hunter's otherwise admirable Java Servlet Programming). If
you'd like to associate a connection with a session, then store some arbitrary, unique
handle in the session, then use that to key off your own hashtable of connections.
(Make sure upon 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 the server. This behavior can be disabled by
setting a configuration parameter in your server or servlet engine. (I can't remember
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. For an object bound into the session to be
distributed or persisted to disk, it must implement the Serializable interface.
Comments and alternative answers
Re: Also see the FAQ What servlet code corresponds to...
Author: Aditya Sharma (http://www.jguru.com/guru/viewbio.jsp?EID=1151271),
Mar 10, 2004
Sorry i feel it is just an explanation by words.A small illustration of code for
session tracking will help
Re[2]: Also see the FAQ What servlet code corresponds to...
Author: Link Tree (http://www.jguru.com/guru/viewbio.jsp?EID=1212794),
Nov 24, 2004
Very simple code - let say that the
public void doPost(HttpServletRequest request,
HttpServletResponse response){
...
//lets take the session obj
HttpSession session = request.getSession(true);
//now let us take the user name assosiated with this session
String currUserLogin = (String)
session.getAttribute("currentUserLogin")
...
//now we do the work according to the user name
doSomeWork(currUserLogin);
...
}
You should do the same thing in the login servlet where you take the user
name and use the addAttribute() of the session obj.
Is there a way to include jsessionid in a hidden field (in a form) rather than
in the URL (by the URL rewriting mechanism ) ? I saw that
HttpSessionContext class was deprecated for security reason, but for
security reasons too i would like to know if there is a way to prevent the
jessionid from being logged in the HTTP server log files (of course without
using cookies) ? Thanks in advance.
How can I detect whether the user accepted my cookie?
Location: http://www.jguru.com/faq/view.jsp?EID=152
Created: Sep 3, 1999 Modified: 2000-09-06 16:35:12.955
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)
Note that this technique only works if the "phase two" servlet is hidden from the
user; if the user can jump directly to the test phase, then the servlet can't tell the
difference between newly-arrived clients and cookie-unfriendly clients. That means
you should send a redirect from the test phase, to make sure the user doesn't have a
chance to bookmark the test phase's URL.
The question can be rephrased, "How can I design a work flow that incorporates
HTML designers and programmers to build a dynamically generated web site that will
keep expanding and growing over time?" This is a special case of the intractable
Content Management Problem of the Web in general. The real problem is to allow
HTML designers (that is, humans) to use their favorite HTML 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 access without 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 designer to finish her HTML, then re-hard-code it all
back into print statements, then make sure the generated HTML actually does what
the original HTML did. Basically, good for a hello world servlet, not good for a real
web site.
B. Server Side Includes (SSI). Use the <SERVLET> tag inside your HTML file (and
rename it .shtml). The HTML designers will make pretty 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, or your servlet outputs a big bunch of text with
embedded HTML tags. In the first case, your code can't take advantage of its
knowledge 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.
D. JSP Java Server Pages. You write files in HTML format, and embed actual Java
code inside the HTML. This is kind of like using 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 and HTML 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 user interface (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 in VBScript, Jscript, Perl, Java, and
JavaScript) in any Servlet Engine. Also Live Software has CF_Anywhere, which
executes Cold 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 object model, then let the objects export HTML.
This doesn't really work for complicated layouts -- and forget about letting your
designer use an HTML editor -- but it can be useful when you have a highly dynamic
site generating HTML, and you want to automate the process. Unfortunately, you still
have to learn HTML, if only to understand and validate the output. See the
References 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 standard content, but the database is king. HTML designers
have little pieces of the page that they can play with, but ultimately they'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.
XMLC
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Oct 27, 2001
A great new "third way" solution -- with templates on one side, and servlets on the
other -- is XMLC.
Faced with the problem of separating presentation from code, XMLC takes the radical
step of... (drumroll please...) actually separating the presentation from the code!
The presentation "layer" is literally an HTML file. The code "layer" is a servlet (or
any Java class) that reaches into the HTML file and changes its content, based on
"ID" attributes embedded inside the HTML tags. (The way it accomplishes this is by
compiling the HTML file into a Java class and data structure, but that's almost beside
the point.)
GSP and GnuJSP both come with SMTP classes that make sending email very simple.
if you are writing your own servlet you could grab one of the many SMTP
implementations from www.gamelan.com (search for SMTP and java). All the ones
I've seen are pretty much the same -- open a socket 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 is running on.
See also the JavaMail FAQ for a good list of Java mail resources, including SMTP and
POP classes.
See also
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Sep 20, 2001
This thread: Re: Automatically send and get mails using servlet...
Some examples
Author: Chris Lack (http://www.jguru.com/guru/viewbio.jsp?EID=326717), Sep 21,
2001
I've written an "EMailClient" class for sending e-mails for my guestbook entries. I've
also done an "InBox" servlet class that lists e-mails in your pop mail in-box so that
you can delete or bounce them before downloading to your PC. Have a look at the
code, it might help -
By the way you'll need JavaMail and Java Activation foundation from Sun if you've
not already downloaded them. You don't need your own mail server.
The Adrenaline Group maintains a list of over 50 ISP's who host Java Servlets
(http://www.adrenalinegroup.com/jwsisp.html) . Another list is at
http://www.servlets.com.
Those that our gurus (you) have had specific experience with include:
A few ISPs have also said that they can host Java applications:
Please report any experiences, good or bad, you have with these services to this
thread.
See also What ISPs provide hosting services which include JSP support?
Web Hosting
Author: dufunk Eugene Rozum
(http://www.jguru.com/guru/viewbio.jsp?EID=1193732), Aug 17, 2004
Prokmu jsp hosting offers the best quality/price JSP/Servlet services!
http://www.servlets.net http://www.tricreations.co...
Author: Melanie Munden (http://www.jguru.com/guru/viewbio.jsp?EID=138305),
Aug 30, 2000
http://www.servlets.net
http://www.tricreations.com
• http://www.webappcabaret.com
• http://www.mycgiserver.com
CWI Hosting (http://www.cwihosting.com)
Author: Scott Barstow (http://www.jguru.com/guru/viewbio.jsp?EID=226863), Oct
11, 2001
Do not use these guys. I have had nine kinds of grief with them, and their support is
less than adequate. I have had outages of three days, and mail outages of three - four
days.
Joost
MyServletHosting.com
Author: Walter Meyer (http://www.jguru.com/guru/viewbio.jsp?EID=23642), Mar 27,
2002
I've been with MyServletHosting.com for over a year. The experience was great at
first, but over that last 5 or 6 months, stability has really degraded.
When I contact tech support they always apologize and say they're in the middle of
moving their clients to more stable servers.
Maybe they'll straighten everything out in the future, but for now, I'm looking for a
new host.
Re: Scorpions.net
Author: John Colucci (http://www.jguru.com/guru/viewbio.jsp?EID=816265),
Mar 28, 2002
I am with Scorpions.net for about 8 months now. I have personal and business
sites there. They use Tomcat,iPlanet, Java web server. Oracle hosting is super
cheap and no set up fees. So far I am happy with them. John.
Rimu Hosting
Author: Peter B (http://www.jguru.com/guru/viewbio.jsp?EID=1071364), Mar 29,
2003
Try http://rimuhosting.com
Rimu Hosting provide Virtual Dedicated servers. That includes 128MB of memory,
8GB of disk space, and 30GB of transfers.
Accounts come with JBoss and include JDK1.4, JSP, EJB and servlet support. You
don't share the Java VM and you get to configure JBoss the way you need it.
Other features include SSH root access, Webmin CP, MySQL, PHP, Redhat Linux.
A customer who just signed up pointed that our plans now come with 4GB of disk.
Our Red Hat file systems have been updated to use Java 1.4.2, JBoss 3.2.1 as well
a choice of a recent Tomcat or Jetty servlet engine.
URL Encoding is a process of transforming user input to a CGI form so it is fit for
travel across the network -- basically, stripping spaces 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).
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 the
Servlet API, sometimes uses URL Rewriting when cookies are unavailable.
(Unfortunately, the method in the Servlet API for doing URL rewriting for session
management is called encodeURL(). Sigh...)
There's also a feature of the Apache web server called URL Rewriting; it is enabled by
the mod_rewrite module. It rewrites URLs on their way in to the server, allowing you
to do things like automatically add a trailing slash to a directory name, or to map old
file names to new file names. This has nothing to do with servlets. For more
information, see the Apache FAQ
(http://www.apache.org/docs/misc/FAQ.html#rewrite-more-config) .
You must HTML-escape characters in fields that your servlet sends as default values
inside form fields, for instance
I have written a utility method for transforming Unicode strings into HTML strings
with properly escaped entities at Purple Code site. Look for
com.purpletech.util.Utils.java, method htmlescape() and htmlunescape().
Also in the email world you may run across "quoted-printable" and "base64" as
the 2 main "content-transfer-encodings" to protect message content during
transmission. The Web standards were developed based on the earlier email
standards (e.g. changing a blank space into "%20", in URL encoding, comes
originally from the email "quoted-printable" content-transfer-encoding), so it
helps to read about both.
Basically, the applet pretends to be a web browser, and the servlet doesn't know the
difference. As far as the servlet is concerned, the applet is just another HTTP client.
(Of course, you can write a servlet that is meant to be called only by your applet, in
which case it *does* know the difference. You can also open a ServerSocket on a
custom TCP port, and have your applet open a Socket connection. You must then
design and implement a custom socket-level protocol to handle the communication.
This is how you could write, e.g., a Chat applet communicating with a servlet. In
general, a custom protocol requires more work than HTTP, but is more flexible.
However, custom protocols have a harder time getting through firewalls.)
For more detail, you can see the Sun Web Server FAQ
(http://www.sun.com/software/jwebserver/faq/faq.html) Questions C8
(http://www.sun.com/software/jwebserver/faq/faq.html#c8) and C9
(http://www.sun.com/software/jwebserver/faq/faq.html#c9) .
See also:
Beware!
Author: tommy Palm (http://www.jguru.com/guru/viewbio.jsp?EID=483108), Aug
24, 2001
There is a typo on the Sun FAQ
(http://www.sun.com/software/jwebserver/faq/faq.html#c8).
It says "
out.println(URLEncoder.encode("key1") + "=" +
URLEncoder.encode("value1"));
out.println(URLEncoder.encode("&key2") + "=" +
URLEncoder.encode("value2"));
The last line of code should be
out.println("&"+URLEncoder.encode("key2") + "=" +
URLEncoder.encode("value2"));
Otherwise the parameters is not seperated since the URLEncoder encodes the '&'.
First off, you should always do your own exception handling. An uncaught exception
can silently kill your servlet, and if you don't know where to look in the log files, or if
your server has a bug in it whereby it silently swallows certain exceptions, you'll
have no idea where the trouble is.
The following code sets up a catch block that will trap any exception, and print its
value to standard error output and to the ServletOutputStream so that the
exception shows up on the browser (rather than being swallowed by the log file).
Chances are that any error is in your code; the exception shows you what line the
problem happened at. (If you see "Compiled Code" instead of line numbers in the
exception stack trace, then turn off the JIT in your server.)
res.setContentType("text/html");
ServletOutputStream out = res.getOutputStream();
try {
// do your thing here
...
}
catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
out.println("
");
out.print(sw.toString());
out.println("
");
}
Lately, I've started catching all Throwables, just in case. I know this is bad form but
what are you gonna do?
Next, you should make liberal use of the log() method, and you should keep your
own log files. Again, don't trust the server to do the right thing. Also, printing the log
after every request can help debugging because you can immediately see the output
of your servlet without going into the server-side log files. (Another problem this
avoids is that some servlet engines forget to flush their logs after each request, so
even if you go to the server, you won't see the most recent log messages.)
Here's some source code you can add to any HttpServlet that keeps an in-memory
log:
You should remember to use servletrunner (renamed "JSDK WebServer" with the
JSDK version 2 -- run with the script startserver) to debug your servlet. It's a tool
that ships with the JSDK that basically starts up a miniature web server that runs
your servlet inside itself. It means you don't have to stop and restart your real web
server every time you recompile your servlet. It also affords a more pure
environment, so you can make sure your servlet truly conforms to the spec before
you try to run it inside a (possibly buggy or nonstandard) servlet engine. (Note that
Tomcat does not have a replacement for servletrunner :-(.)
A few IDEs support servlet debugging. Symantec Cafe claims to have a fairly robust
system for doing visual source-level debugging of servlets (as well as RMI, CORBA,
and EJB objects). [If anyone has any experience with Cafe or other IDEs, please
email &feedback;.] May Wone ([email protected]) writes:
This is my second servlet project, and this debugging technique has enhanced my
productivity many folds. I am able to set code break points, step through each line of
code, inspect all the objects visible to this class as well as view the objects in the
current stack. I can also view, suspend, resume threads.
jRun also claims to have excellent log file support as well as some debugging
facilities.
Another way to debug servlets is to invoke JWS with java_g and then attach to the
process using any debugger that is capable of attaching to a running Java process
given a debug password. To do this invoke JWS as follows:
Sun does not advertise this mechanism which in my mind is the only way to debug
non-trivial servlets.
Doing this ensures that you are up-to-date with the standards, as the Servlet engine
shipped with JBuilder 2.01 is not the latest.
See also Are there any IDE's which will help me debug...
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Aug 14, 2000
See also Are there any IDE's which will help me debug JSPs?
This link gives a list of products that use Java P...
Author: Aprameya Paduthonse (http://www.jguru.com/guru/viewbio.jsp?EID=4707),
Feb 1, 2001
This link gives a list of products that use Java Platform Debugger Architecture
(JPDA) and all of them are supposed to support remote debugging.
http://java.sun.com/products/jpda/using.html
To acheive this:
• Make sure the source code is present in your Tomcat installation dir
(hereinafter referred to as TID and the Java Installation directory as JID).
If you don't have it, get if from jakarta and install it in the TID.
• The main class must be set to org.apache.catalina.startup.Bootstrap (you
should see this once the source is added to your project path)
• The VM parameters are set to:
o -Djava.endorsed.dirs ="TID\bin;TID\common\lib"
o -classpath "JID\lib\tools.jar;TID\bin\bootstrap.jar"
o -Dcatalina.base="TID"
o -Dcatalina.home="TID"
o -Djava.io.tmpdir="TID\temp"
• Program parameter must contain start
Finally make sure that you do not compile anything by setting the appropriate dirs in
the "Compiler" option
Re: Debugging using IntelliJ IDEA
Author: Walter Rumsby (http://www.jguru.com/guru/viewbio.jsp?EID=544477), Apr 1, 2002
I'm using IDEA (Ariadana) Build 602 - a preview release of the next version along with Tomcat
3.3a on Windows 2000.
1. In Run/Debug - Remote tab of Project Properties dialog choose to add a new default
configuration (with the "+" button).
2. Copy the JVM settings in the dialog box, eg. mine look like the following:
3. Open the bin/tomcat.bat file in your Tomcat directory and go to the :startServer label
(Unix open the tomcat.sh file, I guess). A few lines below the label should be the
following:
Add the JVM parameters you copied from IDEA into that line, so you have something
like:
4. If Tomcat is running stop it and restart it. Once it is up and running again, set a
breakpoint somewhere in your Java source with IDEA and then click on the bug icon,
choose debug and you should now be able to use IDEA's debugger to debug your servlet.
-classic
to the list of options shown above. Therefore, the resulting option look like this
-classic -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:
transport=dt_socket,server=y,suspend=n,address=5000
TOMCAT_OPTS
variable was put there so the it can be set to the value of all of these additional
parameters.
• I just downloaded the binary version of catalina 4.0.3 and installed it.
• I then downloaded the src version of the above and just copied in the
source code directory into the above installation so that I could then point
Idea's to this source (No Compilation of this source was done).
• Make sure that this source directory is included in the exclusions list of the
"Compiler" options otherwise Idea's will attempt to compile this catalina
source as well
• Finally, maybe the remote debugging option below is neater, IMHO
How do I create an image (GIF, JPEG, etc.) on the fly from a servlet?
Location: http://www.jguru.com/faq/view.jsp?EID=159
Created: Sep 3, 1999 Modified: 2001-12-16 12:47:29.26
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)
To create an image or do image processing from Java, there are several packages
and classes available. See the Purple Servlet References for a list.
Once you have an image file in your servlet, you have two choices:
1. Write the file to disk and provide a link to it. Make sure you write it to a
location that's in your web server directory tree (not just anywhere on the
server's disk). You can use the Java 2 JPEGCodec class, or Acme Labs'
GIFEncoder class, to turn a Java Graphics into an image file or bytestream.
(Note that in some servlet engine setups, the servlet directory is not
accessible by the web server, only by the servlet engine, which means you
won't be able to access it through an http:// URL.) You can either send an
IMG tag in the HTML your servlet is outputting, or send an HTTP redirect to
make the browser download the image directly (as its own page).
Pro: the image can be cached by the browser, and successive requests don't
need to execute the servlet again, reducing server load.
Con: the image files will never be deleted from your disk, so you'll either have
to write a script to periodically clean out the images directory, or go in and
delete them by hand. (Or buy a bigger hard disk :-) ).
2. Output the image directly from the servlet. You do this by setting the
Content-type header to image/gif (for GIFs), or image/jpeg (for JPEGs).
You then open the HttpResponse output stream as a raw stream, not as a
PrintStream, and send the bytes directly down this stream using the write()
method.
You can also use JIMI to read and write images in many formats, including GIF, JPEG,
TIFF (TIF), PNG, PICT, Photoshop, BMP, Targa, ICO, CUR, Sunraster, XBM, XPM, and
PCX.
See also:
File f = new
File(System.getProperty("user.home")+"\\zoewrap.jpg");
JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(new
FileInputStream(f));
BufferedImage image =decoder.decodeAsBufferedImage() ;
On the client side, the client's browser must support form-based upload. Most
modern browsers do, but there's no guarantee. For example,
<FORM ENCTYPE='multipart/form-data'
method='POST' action='/myservlet'>
<INPUT TYPE='file' NAME='mptest'>
<INPUT TYPE='submit' VALUE='upload'>
</FORM>
The input type &quot;file&quot; brings up a button for a file select box on
the browser together with a text field that takes the file name once selected. The
servlet can use the GET method parameters to decide what to do with the upload
while the POST body of the request contains the file data to parse.
When the user clicks the "Upload" button, the client browser locates the local file and
sends it using HTTP POST, encoded using the MIME-type multipart/form-data.
When it reaches your servlet, your servlet must process the POST data in order to
extract the encoded file. You can learn all about this format in RFC 1867.
Unfortunately, there is no method in the Servlet API to do this. Fortunately, there are
a number of libraries available that do. Some of these assume that you will be
writing the file to disk; others return the data as an InputStream.
• JavaMail also has MIME-parsing routines (see the Purple Servlet References).
• JSPSmart has a free set of JSP for doing file upload and download.
Please note that you can't access a file on the client system directly from a servlet;
that would be a huge security hole. You have to ask the user for permission, and
currently form-based upload is the only way to do that.
[This FAQ based on earlier posts by Thomas Moore, Detlef Pleiss (dpleiss@os-
net.de), and others.]
Could someone show me some code examples really working with the
com.oreilly.servlet.MultipartRequest?
I have built an applet to download scanned files from a client machine to a server.
I use the java class MultipartRequest in a servlet on my application server. It
works fine with an HTML page sending a form with a type 'File' button using
method POST .
In my applet, I use the class HttpMessage with the method InputStream
sendPostMessage(java.io.Serializable obj)passing in the File to send. It sends
some data but the servlet fails in decodind the multipart/form_data htpp message
because of no boundary.
Can anyone help with telling me what I have to do or providing an example of
uploading a single file from an applet to a servlet.
Thanks
Arnaud Palazzi
Question
Author: Olga Narvaez
(http://www.jguru.com/guru/viewbio.jsp?EID=1062530), Mar 3, 2003
Hi Arnaud, I have to uploading a single file from an applet to a servlet. Did
you do it? could you explain it to me? Kind Regards, Olga N.
You may need to pass in the location of the "incoming" directory as a servlet
initialization parameter.
-Alex]
if(submitButton.equals(multi.getParameter("Submit")))
{
out.println("Files:");
Enumeration files = multi.getFileNames();
while (files.hasMoreElements()) {
String name = (String)files.nextElement();
String filename = multi.getFilesystemName(name);
String type = multi.getContentType(name);
File f = multi.getFile(name);
FileReader fs = new FileReader(f);
BufferedReader in = new BufferedReader(fs);
String s, s2 = new String();
while((s = in.readLine())!= null) {
s2 += s + "\n";
}
fileContent = s2;
//session.setAttribute("fileContent", fileContent);
//out.println(in.readLine());
out.println("name: " + name);
out.println("filename: " + filename);
out.println("type: " + type);
if (f != null) {
out.println("f.toString(): " + f.toString());
out.println("f.getName(): " + f.getName());
out.println("f.exists(): " + f.exists());
out.println("f.length(): " + f.length());
out.println("fileContent: " + fileContent);
}
in.close();
}
}
Thanks.
Re: The free class files from JSPSmart are the easiest...
Author: zong zhang (http://www.jguru.com/guru/viewbio.jsp?EID=491205), Sep
17, 2001
Hi Iain,
I am interested in the JspSmart as you mentioned. But i just want to up load file to
Web server using servlet, not Jsp, can I still use JspSmart?
If I can, beside web Server like IIS and Jsp engine, what else do I need?
I am a beginner, I am a bit confused, is JSP a component of java SDK? do I need
to download Jsp as well?
Re: Re: The free class files from JSPSmart are the easiest...
Author: Iain Delaney (http://www.jguru.com/guru/viewbio.jsp?EID=255644),
Sep 18, 2001
I'm not sure why you would want to use a servlet and not JSP, because they are
really the same thing. A JSP source file compiles into a servlet, so you get the
same result in the end.
That said, all you need is a web server and a JSP engine, and all App Servers
are JSP servers. There are also some free JSP servers about.
You don't need to download anything else, since the JSP server and the Java
SDK will do all of the work. There are some good introductions to JSP on this
site, on the Sun Java site, and there are a number of good books available now,
too.
Re: The free class files from JSPSmart are the easiest...
Author: Asar Khan (http://www.jguru.com/guru/viewbio.jsp?EID=502635), Sep
24, 2001
Hi, I've just started using these classes and I cannot get them to work as a JSP
although it does work as a servlet.
if ( request.getServerName().equalsIgnoreCase("localhost")
) {
id = 0;
}
else {
id = 1;
}
System.err.println(fid);
try {
ff.initialize( pageContext );
ff.downloadFile( fid,"application/pdf" );
}
catch ( java.io.IOException e ) {
if ( e instanceof java.io.FileNotFoundException ) {
response.sendRedirect("\tip\file_not_found.html");
}
else {
throw e;
}
}
catch ( Exception e ) {
e.printStackTrace(System.err);
throw e;
}
%>
As a servlet:
package tip;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.jspsmart.upload.*;
res.sendRedirect("/tip/file_not_found.html");
}
catch ( IOException ex ) {
ex.printStackTrace(System.err);
}
}
else {
e.printStackTrace(System.err);
}
}
catch ( Exception e ) {
e.printStackTrace(System.err);
}
}
}
It works.
Re[2]: The free class files from JSPSmart are the easiest...
Author: Jim Alexander
(http://www.jguru.com/guru/viewbio.jsp?EID=516718), Feb 6, 2002
I also had a problem with using jspSmartUpload to download a file... The same
dang IllegalStateException.
But the servlet mechanism works great. I'm sticking with this approach.
Re[3]: The free class files from JSPSmart are the easiest...
Author: Heather Elich
(http://www.jguru.com/guru/viewbio.jsp?EID=541447), Apr 11, 2002
Does your servlet upload work for all file types, such as Word and Excel
documents?
Re[3]: The free class files from JSPSmart are the easiest...
Author: piski pai (http://www.jguru.com/guru/viewbio.jsp?EID=868214), May 6, 2002
There is cheap and good component,may be this help.
http://www.codecadet.com/components/ComponentDetail.aspx?ComponentID=Xqmwa46KLe
Re[3]: The free class files from JSPSmart are the easiest...
Author: Ken Kong (http://www.jguru.com/guru/viewbio.jsp?EID=912448),
Aug 21, 2002
I used the smartupload's download method and it work well for me and
able to download many types of files (.doc, .ppt, .jpg ... etc) However,
when I tried to download a certificate (.crt), the "illegalStateException:
outputstream has been used.." error message resulted. I am aware of that
tomcat will print an empty line in JSP tag. But I just don't know why it
works for certain files only. Any idea?
Thks.
on the contrary,I acn get the "SmartUpload" classes to work as a jsp but
it does not work as a servlet
Author: w qs (http://www.jguru.com/guru/viewbio.jsp?EID=790498), Mar 11,
2002
on the contrary,I can get the "SmartUpload" classes to work as a jsp but it does
not work as a servlet,can you give me your complete code of the
servlet£¿£¿thanks!! my email:[email protected]
« previous beginning next »
Since JDK 1.1, Java comes with a package called JDBC (Java Database
Connectivity). JDBC allows you to write SQL queries as Java Strings, pass them to
the database, and get back results that you can parse. To learn how to write JDBC
code, check the tutorials on Sun's web site, and read the Javadoc API documentation
for package java.sql. To install JDBC on your system, you need to locate a JDBC
Driver for your particular database and put it in your classpath. Fortunately, most
databases these days ship with a 100% Pure Java driver (also known as a "Type IV"
driver), including Oracle, Sybase, Informix, etc. Check the documentation for your
database engine for installation instructions.
Since opening a connection to a database can take a relatively long time (upwards of
10 seconds or more), you probably don't want to create the connection in your doGet
method. Instead, create the connection in the init() method and save it in an
instance variable. Remember to close the connection in your destroy() method.
Alternately, you could use a Connection Pool, which opens several database
connections at once, then doles them out to individual threads as needed. This
solves a number of problems with the one-connection method outlined above
(basically, it's better at dealing with multiple simultaneous requests and with
transactions). A good free connection pool implementation is available at Java
Exchange (http://www.javaexchange.com/) . Connection pools also ship with many
popular application servers, including BEA WebLogic (http://weblogic.beasys.com/)
(formerly Tengah). This product is also available separately as jdbcKona
(http://www.weblogic.com/docs/classdocs/API_jdbc.html) More information on
Connection Pooling is available at the JSP FAQ, Question 13
(http://www.esperanto.org.nz/jsp/jspfaq.html#q13) .
From the tomcat-user mailing list, here is some code for storing a JDBC connection in
an instance variable:
From: "Koen Dejonghe" <[email protected]>
To: [email protected]
Subject: Re: JDBC and permanent connections
Date: Fri, 19 May 2000 17:20:06 CEST
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
try {
//Register the JDBC driver
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch( Exception e ) {
e.printStackTrace();
}//end catch
}//end init()
try {
[...]
Statement st = con.createStatement();
[ more JDBC code ]
}
catch (SQLException e) {
[ ... ]
}
}
Comments and alternative answers
If you are going into the fridge to grab the mustard then
you would open the fridge grab the mustard and close
the fridge.
you wouldn't open the fridge grab the mustard close the
fridge then open the fride and grab the relish? would
you?
Think that u need mustard in the morning and relish in the afternoon. You
think that it is better to kept fridge door open till afternoon.
Similarly when request comes to the servlet open connection, process the
request and close it after serving the request.
Database is a valuable resource for any application. You shouldn't keep it open
for long time.
cheers...
Jayaramu
Thanks,ilana
This means you can only use same username/password, how can you do it if you
need to signon?
Author: Eric Wang (http://www.jguru.com/guru/viewbio.jsp?EID=748928), Feb 6,
2002
If multi people need to access database, they need to sign on to look for data, then you
can't put connection in "init" method. Am i right?
Re: This means you can only use same username/password, how can you do it
if you need to signon?
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Feb 6,
2002
Yes, that's right; however, usually these systems are architected such that the
*database* username/password is different from the *web* username/password.
The servlet is the security gateway, verifying if web user X has permission to do
DB action Y. This is a better architecture for security (since then you don't have
the DB password being transmitted in HTTP packets, and/or into the brains of
users who may do bad things with it).
Re[2]: This means you can only use same username/password, how can
you do it if you need to signon?
Author: Eric Wang (http://www.jguru.com/guru/viewbio.jsp?EID=748928),
Feb 6, 2002
But if you have hundreds of users, how can you know that "user X has
permission to do DB action Y". It's too difficult to maintain such a map
between db users and web users. Thank you for you reply.
Re[3]: This means you can only use same username/password, how can
you do it if you need to signon?
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3),
Feb 6, 2002
I said it was a more secure architecture. I didn't say it was *easy* :-)
It's a judgement call. You need to talk with your DBA to figure out some
things like...
Are there really 1000 different users with 1000 different sets of access
rights, or are there 990 users in one group (role) and 10 in another group?
Is there a way to get an automatic feed of database user IDs from the DB to
the servlet?
Good luck!
Re[4]: This means you can only use same username/password, how
can you do it if you need to signon?
Author: Eric Wang
(http://www.jguru.com/guru/viewbio.jsp?EID=748928), Feb 6, 2002
Thank you very much, I really appreciate your help.
abot getContext()
Author: pawan kumar (http://www.jguru.com/guru/viewbio.jsp?EID=1259382), Aug
24, 2005
connection is established through getContext(). According to servlet 2.1 specification
its depricated due to security reason. How its can be done without this.
You can make your JSPs thread-safe by having them implement the
SingleThreadModel interface.
With this, instead of a single instance of the servlet generated for your JSP page
loaded in memory, you will have N instances of the servlet loaded and initialized,
with the service method of each instance effectively synchronized. You can typically
control the number of instances (N) that are instantiated for all servlets
implementing SingleThreadModel through the admin screen for your JSP engine.
How do I prevent the output of my JSP or Servlet pages from being cached
by the browser?
Location: http://www.jguru.com/faq/view.jsp?EID=377
Created: Nov 5, 1999 Modified: 2000-12-20 10:28:09.657
Author: Govind Seshadri (http://www.jguru.com/guru/viewbio.jsp?EID=14)
You will need to set the appropriate HTTP header attributes to prevent the dynamic
content output by the JSP page from being cached by the browser.
Just execute the following scriptlet at the beginning of your JSP pages to prevent
them from being cached at the browser. You need both the statements to take care
of some of the older browser versions.
<%
response.setHeader("Cache-Control","no-cache"); //HTTP 1.1
response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching
at the proxy server
%>
[Based on feedback (below), I have changed this scriptlet slightly. If the above fails,
try changing the first line to
However, please note that there are some problems with disabling page caching
under IE 5.0 due to the unique buffering requirements of the browser. Please see the
Microsoft knowledge base for details:
http://support.microsoft.com/support/kb/articles/Q222/0/64.ASP
http://support.microsoft.com/support/kb/articles/Q234/2/47.ASP
Maze
How do I prevent the output of my JSP or Servlet pages from being cached by
the browser?
Author: Amritha Shetty (http://www.jguru.com/guru/viewbio.jsp?EID=876060), May
13, 2002
Hi I have tried the code <% response.setHeader("Cache-Control","no-cache");
response.setHeader("Pragma","no-cache"); response.setDateHeader ("Expires", 0);
%> for not cacheing. But it is not working. Could you please help in solving my
problem. I am using Internet Explorer 5.0. I put this code at the starting of the JSP
page. Please suggest me solution for my problem.
Re: How do I prevent the output of my JSP or Servlet pages from being
cached by the browser?
Author: B B (http://www.jguru.com/guru/viewbio.jsp?EID=875134), May 23,
2002
I have solved this problem by following one of the MSDN articles referred above.
I am using IE5.0. Besides doing this at the top of the JSP:
<%
response.setHeader("Cache-Control","no-cache"); //HTTP 1.1
response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", -1);
%>
Re[2]: How do I prevent the output of my JSP or Servlet pages from being
cached by the browser?
Author: Amritha Shetty
(http://www.jguru.com/guru/viewbio.jsp?EID=876060), May 24, 2002
Thanks B B for your reply. I tried this code. But it didn't work. Is there any
other way to solve this problem.
Re[2]: How do I prevent the output of my JSP or Servlet pages from being
cached by the browser?
Author: Josh R (http://www.jguru.com/guru/viewbio.jsp?EID=974768), Aug 2,
2002
Yep, I'm having the same problem. The solutions posted on this page do not
keep the jsp page from caching. The only way I've found to keep it from
caching is to change the cache settings on the internet browser. This is not a
good solution for an enterprise level application (I can't expect my clients to
set their browsers when they use the application). There must be a way to keep
the page from caching, but except for the random param generation suggested
above (which is bad since there still the chance that it will randomly generate
the same number twice), I've yet to find any that works.
Re[2]: How do I prevent the output of my JSP or Servlet pages from being
cached by the browser?
Author: Josh R (http://www.jguru.com/guru/viewbio.jsp?EID=974768), Aug 2,
2002
My posted solution does work, but if you are still having trouble, remember to
clear the cache (tools: Internet Options...) before testing it.
Re[3]: How do I prevent the output of my JSP or Servlet pages from
being cached by the browser?
Author: kennedy alagappan
(http://www.jguru.com/guru/viewbio.jsp?EID=878585), Aug 8, 2002
Josh, I am using IE5.0 and I cleared the cache before testing. I did include
this in the begining and end of my jsp <HEAD> <META HTTP-
EQUIV="PRAGMA" CONTENT="NO-CACHE"> </HEAD> and used
this on top of my jsp <% response.setHeader("Cache-Control","no-cache");
//HTTP 1.1 response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setHeader ("Expires", "0"); //prevents caching at the proxy server
%> It still taking the data from cache. Do you have any clue, what might
be wrong here. I will appreciate your help. Thank you, Kind Regards,
Kalagappan
The following code snippet shows how a servlet instantiates a bean and initializes it
with FORM data posted by a browser. The bean is then placed into the request, and
the call is then forwarded to the JSP page, Bean1.jsp, by means of a request
dispatcher for downstream processing.
public void doPost (HttpServletRequest request,
HttpServletResponse response) {
try {
govi.FormBean f = new govi.FormBean();
String id = request.getParameter("id");
f.setName(request.getParameter("name"));
f.setAddr(request.getParameter("addr"));
f.setAge(request.getParameter("age"));
//use the id to compute
//additional bean properties like info
//maybe perform a db query, etc.
// . . .
f.setPersonalizationInfo(info);
request.setAttribute("fBean",f);
getServletConfig().getServletContext().getRequestDispatcher
("/jsp/Bean1.jsp").forward(request,
response);
} catch (Exception ex) {
. . .
}
}
The JSP page Bean1.jsp can then process fBean, after first extracting it from the
default request scope via the useBean action.
About your second question... all depends on where the JSP and servlets are, same or
different hosts.
• If all the resources are in the same host, then you can have many approachs.
One is using HttpSession. JSP and servlets for the same client can access the
same HttpSesion, you can leave values there.
• If the JSP and servlets are in different host then you can use Statefull EJB per
user and use them as temporal storage (this implies that the values you want to
share are Serializable, cause they are send over the net).
The following code example demonstrates how request chaining can be implemented
using a combination of JSPs and servlets.
Consider the following JSP page, say Bean1.jsp, which essentially instantiates the
bean fBean, places it in the request, and forwards the call to the servlet JSP2Servlet.
Observe the way the bean is instantiated - here we automatically call the bean's
setter methods for properties which match the names of the posted form elements,
while passing the corrosponding values to the methods.
The servlet JSP2Servlet now extracts the bean passed to it from the request, makes
changes using the appropriate setters, and forwards the call to another JSP page
Bean2.jsp using a request dispatcher. Note that this servlet, acting as a controller,
can also place additional beans if necessary, within the request.
try {
FormBean f = (FormBean) request.getAttribute ("fBean");
f.setName("Mogambo");
// do whatever else necessary
getServletConfig().getServletContext().
getRequestDispatcher("/jsp/Bean2.jsp").
forward(request, response);
} catch (Exception ex) {
. . .
}
}
The JSP page Bean2.jsp can now extract the bean fBean (and whatever other beans
that may have been passed by the controller servlet) from the request and extract its
properties.
<html>
<body>
Within JSP2
</body>
</html>
Servlet chaining
Author: Bojan Kraut (http://www.jguru.com/guru/viewbio.jsp?EID=525806), Oct 20,
2001
Hi! I'm working on a MVC architecture, where I have to forward request to another
servlet. If I redirect my request to a jsp or html file It works fine, but if I try to
forward it to a servlet it doesn't work. The source code of my controller is: import
javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Mediator extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) {
processRequest(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) {
processRequest(request, response);
}
public void processRequest(HttpServletRequest request, HttpServletResponse
response) {
try {
if (request.getParameter("ACTION") != null) {
getServletConfig().
getServletContext().
getRequestDispatcher(request.getParameter("TO")).
forward(request, response);
}
} catch(ServletException e1) {
e1.printStackTrace();
} catch(IOException e2) {
e2.printStackTrace();
} catch (Exception e3) {
e3.printStackTrace();
}
}
}
Any help appreciated.
Bojan
You can always wring out some efficiency by making use of a StringBuffer or
ByteArray.
For example, instead of sending your HTML to the client using a PrintWriter or some
other output stream, you can write it out to a StringBuffer, and send it to the client
using just one write invocation. Of course, you'll have to indicate the length of your
data stream in the HTTP header too as shown below:
• using StringBuffers,
• removing unecessary objects creation,
• if you use EJBs, caching home interfaces, caching JNDI contexts,
• basically : optimizing your 20% of code that executes 80% of the time.
• Check Java Performance and Scalability, Volume 1 (Server-Side
programming techniques) from Dov Bulka, published by Addison-Wesly
ISBN :0201704293.
• Or check IBM's white papers on Serverside programming 16 Best Practices.
Although the SingleThreadModel technique is easy to use, and works well for low
volume sites, it does not scale well. If you anticipate your users to increase in the
future, you may be better off implementing explicit synchronization for your shared
data. The key however, is to effectively minimize the amount of code that is
synchronzied so that you take maximum advantage of multithreading.
Also, note that SingleThreadModel is pretty resource intensive from the server's
perspective. The most serious issue however is when the number of concurrent
requests exhaust the servlet instance pool. In that case, all the unserviced requests
are queued until something becomes free - which results in poor performance. Since
the usage is non-deterministic, it may not help much even if you did add more
memory and increased the size of the instance pool.
How can I enable session tracking for JSP pages if the browser has disabled
cookies?
Location: http://www.jguru.com/faq/view.jsp?EID=1045
Created: Nov 15, 1999 Modified: 2001-08-01 15:14:52.715
Author: Govind Seshadri (http://www.jguru.com/guru/viewbio.jsp?EID=14)
URL rewriting essentially includes the session ID within the link itself as a
name/value pair. However, for this to be effective, you need to append the session ID
for each and every link that is part of your servlet response.
Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp,
interact with each other. Basically, we create a new session within hello1.jsp and
place an object within this session. The user can then traverse to hello2.jsp by
clicking on the link present within the page.Within hello2.jsp, we simply extract the
object that was earlier placed in the session and display its contents. Notice that we
invoke the encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if
cookies are disabled, the session ID is automatically appended to the URL, allowing
hello2.jsp to still retrieve the session object.
Try this example first with cookies enabled. Then disable cookie support, restart the
brower, and try again. Each time you should see the maintenance of the session
across pages.
Do note that to get this example to work with cookies disabled at the browser, your
JSP engine has to support URL rewriting.
hello1.jsp
hello2.jsp
Easier Way
Author: allan jsmithguru (http://www.jguru.com/guru/viewbio.jsp?EID=1145856),
Mar 13, 2004
This is from the taglib user guide at
http://jakarta.apache.org/struts/userGuide/struts-html.html#link
Just use the html taglib to write your link and you don't have to worry about cookies
or the encode() method.
Is there a way to include jsessionid in a hidden field (in a form) rather than in the
URL (by the URL rewriting mechanism ) ?
I saw that HttpSessionContext class was deprecated for security reason, but for
security reasons too i would like to know if there is a way to prevent the jessionid
from being logged in the HTTP server log files (of course without using cookies) ?
Thanks in advance.
Yes, you can invoke the JSP error page and pass the exception object to it from
within a servlet. The trick is to create a request dispatcher for the JSP error page,
and pass the exception object as a javax.servlet.jsp.jspException request attribute.
However, note that you can do this from only within controller servlets. If your
servlet opens an OutputStream or PrintWriter, the JSP engine will throw the following
translation error:
java.lang.IllegalStateException:
Cannot forward as OutputStream or Writer has already been obtained
The following code snippet demonstrates the invocation of a JSP error page from
within a controller servlet:
Automatic in 2.3?
Author: Bill Kayser (http://www.jguru.com/guru/viewbio.jsp?EID=726636), Jan 18,
2002
My reading of the Servlet 2.3 spec is that this will happen automatically if you specify
error pages in the web.xml file. However, Catalina (tomcat 4.0) doesn't seem to
implement this. So I don't know...
try {
} catch (Throwable t) {
No. A JTA transaction must start and finish within a single invocation (of the
service() method). Note that this question does not address servlets that maintain
and manipulate JDBC connections, including a connection's transaction handling.
What's the difference between the JSDK and the JSWDK? And what's the
current version?
Location: http://www.jguru.com/faq/view.jsp?EID=3082
Created: Dec 21, 1999 Modified: 2000-06-03 15:15:11.954
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)
The kit for developing servlets, containing the Servlet API classes and tools, used to
be called the Java Servlet Development Kit (JSDK). Then Sun renamed the Java
Development Kit (JDK) to the Java 2 Software Development Kit (J2SDK). Since
J2SDK sounds a lot like JSDK, the Servlet team renamed JSDK to JavaServer Web
Development Kit (JSWDK). (They also added support for JSPs.)
Here's where it gets confusing. When they renamed it, they also renumbered it. So
the JSWDK 1.0 is actually more recent than the JSDK 2.1. It's also confusing that
when people want to develop servlets, they have to download something called a
JavaServer Web Development Kit, which sounds like it should be used to develop
servers, not servlets.
A further confusion is that the Servlet spec is developed independently from the JSP
spec, and they both have different version numbers than the JSDK and JSWDK.
Tomcat contains code based on JSWDK, as well as a lot of new stuff, and it will be
the supported Servlet and JSP implementation from now on. No further work will be
done on JSDK or JSWDK.
See What version of the Servlets or JSP specification is supported by my favorite
servlet product? for a summary of the spec versions supported by each product.
How does the performance of JSP pages compare with that of servlets? How
does it compare with Perl scripts?
Location: http://www.jguru.com/faq/view.jsp?EID=3149
Created: Dec 21, 1999 Modified: 2001-08-01 15:15:28.403
Author: Govind Seshadri (http://www.jguru.com/guru/viewbio.jsp?EID=14)
The performance of JSP pages is very close to that of servlets. However, users may
experience a perceptible delay when a JSP page is accessed for the very first time.
This is because the JSP page undergoes a "translation phase" wherein it is converted
into a servlet by the JSP engine. Once this servlet is dynamically compiled and
loaded into memory, it follows the servlet life cycle for request processing. Here, the
jspInit() method is automatically invoked by the JSP engine upon loading the servlet,
followed by the _jspService() method, which is responsible for request processing
and replying to the client. Do note that the lifetime of this servlet is non-
deterministic - it may be removed from memory at any time by the JSP engine for
resource-related reasons. When this happens, the JSP engine automatically invokes
the jspDestroy() method allowing the servlet to free any previously allocated
resources.
Subsequent client requests to the JSP page do not result in a repeat of the
translation phase as long as the servlet is cached in memory, and are directly
handled by the servlet's service() method in a concurrent fashion (i.e. the service()
method handles each client request within a seperate thread concurrently.)
There have been some recent studies contrasting the performance of servlets with
Perl scripts running in a "real-life" environment. The results are favorable to servlets,
especially when they are running in a clustered environment. For details, see:
Note that spawning a separate process can actually improve performance since it
allows you to use separate hosts, or multiple hosts, to load-balance servlet execution.
How can I download a file (for instance, a Microsoft Word document) from a
server using a servlet and an applet?
Location: http://www.jguru.com/faq/view.jsp?EID=3696
Created: Dec 29, 1999 Modified: 2001-07-23 09:19:32.296
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)
You may also want to check the web server configuration to make sure the
approprate MIME-type configuration is set. If your servlet is the one fetching the
document (or creating it on the fly), then it must set the MIME-type using
response.setContentType("application/ms-word") or equivalent.
I've installed the JSWDK and it says I've run out of environment space when
I try to start the server. How do I increase the amount of environment
space under Windows?
Location: http://www.jguru.com/faq/view.jsp?EID=3903
Created: Jan 3, 2000 Modified: 2000-06-03 14:35:40.648
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
The end of your CONFIG.SYS file should include a line like the following:
This assumes your COMMAND.COM file is in your root level C: directory and you wish
your shells to start in that directory, too. The 4096 is the new environment size. You
can increase this to a larger number if that is still a problem.
No. The RequestDispatcher can only send a message to a servlet or JSP running
inside the same servlet engine. You either have to open a socket, use native code, or
use Runtime.exec() to spawn a process on the web server host.
Comments and alternative answers
Can a servlet add request parameters into a request object before passing
on the request to another servlet or jsp?
Location: http://www.jguru.com/faq/view.jsp?EID=4920
Created: Jan 13, 2000 Modified: 2000-06-03 14:37:55.388
Author: Joy Mangaliman (http://www.jguru.com/guru/viewbio.jsp?EID=4919)
I am currently doing this - passing a request object to a jsp. However, you need JRun
to do so. JRun has some packages included which define classes called
JRunServletRequest and JRunServletResponse which are extensions of
HttpServletRequest and HttpServletResponse. JRunServletRequest has the method
setAttribute which allows the setting of request parameters. JRunServletResponse
has the method callPage which allows the JRunServletRequest to be passed to the
servlet/jsp.
- Joy Mangaliman ([email protected])
Comments and alternative answers
Workarounds
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jan 9, 2003
See http://www.jguru.com/forums/view.jsp?EID=1016603
• use a RequestDispatcher
• use a URLConnection or HTTPClient
• send a redirect
• call getServletContext().getServlet(name) (deprecated, doesn't work in 2.1+)
- Alex ]
It depends on what you mean by "call" and what it is you seek to do and why you
seek to do it.
If the end result needed is to invoke the methods then the simplest mechanism
would be to treat the servlet like any java object , create an instance and call the
mehods.
If the idea is to call the service method from the service method of another servlet,
AKA forwarding the request, you could use the RequestDispatcher object.
If, however, you want to gain access to the instance of the servlet that has been
loaded into memory by the servlet engine, you have to know the alias of the servlet.
(How it is defined depends on the engine.) For example, to invoke a servlet in JSDK
a servlet can be named by the property
myname.code=com.sameer.servlets.MyServlet
The code below shows how this named servlet can be accessed in the service method
of another servlet
public void service (HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
...
MyServlet ms=(MyServlet)
getServletConfig().getServletContext().getServlet("myname");
...
}
That said, This whole apporach of accessing servlets in another servlets has been
deprecated in the 2.1 version of the servlet API due to the security issues. The
cleaner and better apporach is to just avoid accessing other servlets directly and use
the RequestDispatcher instead.
How do i do it? I cannot treat the servlet as just another class as i want to call the
method on a particular instance of the servlet.
whats the best way to this, given that getServletNames() and getServlet(String s) are
deprecated?
I want to save the state of a servlet, which is done when the saveState() method of the
servlet is called. If i place the method in a common object then i will also have to pass
all the properties of that servlet to that object. and i wnat to control the savestate()
methods of several servlets. this will become extremely tedious.
thanks nitin
As for tedium, it will be just as tedious to locate N servlets and call their saveState()
methods as to locate N objects and call their saveState() methods.
How can I access or create a file or folder in the current directory from
inside a servlet?
Location: http://www.jguru.com/faq/view.jsp?EID=5272
Created: Jan 17, 2000 Modified: 2000-06-03 14:39:10.347
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)
Since there's no telling which directory the servlet engine was launched from, you
should always use absolute pathnames from inside a servlet. Usually I pass in the
root directory in an InitParameter, and create File objects relative to that directory.
Comments and alternative answers
That avoids making any assumptions about where on the server your files end up.
Re: ...unless it's part of the WAR
Author: leo leung (http://www.jguru.com/guru/viewbio.jsp?EID=575344), Dec 6,
2001
I don't think that works if it is inside a WAR file. Base on the J2EE spec. the
getRealPath() should return null. :(
How can I maintain "application scope data" in Servlets or JSPs as ASPs do?
Location: http://www.jguru.com/faq/view.jsp?EID=5879
Created: Jan 20, 2000 Modified: 2000-08-25 08:51:32.021
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)
In the Servlets 2.1 spec, you can set a Servlet Context Attribute. For example,
getServletContext().setAttribute("counter", new foo.Counter()); . You can
also access (or initialize) these Attributes as Application Scope Beans in a JSP, using
<jsp:useBean scope="application">.
Comments and alternative answers
An alternative way would be to create a class say Class A which would inherit the
HttpServlet class. All application level data can be placed in it.
All the servlets which need to share the application level data would inherit Class A.
This approach would work in all implementations and make maintainability easier. In
case data is to be added/removed, changes are necessary only in Class A
The servers involved in handling and processing a user's request break down into a
few basic types, each of which may have one or more tasks it solves. This flexibility
gives developers a great deal of power over how applications will be created and
deployed, but also leads to confusion over what server is able to, or should, perform
a specific task.
The web server may need to execute an application in response to the users request.
It may be generating a list of news items, or handling a form submission to a guest
book. If the server application is written as a Java Servlet, it will need a place to
execute, and this place is typically called a Servlet Engine. Depending on the web
server, this engine may be internal, external, or a completely different product. This
engine is continually running, unlike a traditional CGI environment where a CGI
script is started upon each request to the server. This persistance gives a servlet
connection and thread pooling, as well as an easy way to maintain state between
each HTTP request. JSP pages are usually tied in with the servlet engine, and would
execute within the same space/application as the servlets.
There are many products that handle the web serving and the servlet engine in
different manners. Netscape/iPlanet Enterprise Server builds the servlet engine
directly into the web server and runs within the same process space. Apache requires
that a servlet engine run in an external process, and will communicate to the engine
via TCP/IP sockets. Other servers, such as MS IIS don't officially support servlets,
and require add-on products to add that capability.
When you move on to Enterprise JavaBeans (and other J2EE components like JMS
and CORBA) you move into the application server space. An Application Server is
any server that supplies additional functionality related to enterprise computing -- for
instance, load balancing, database access classes, transaction processing,
messaging, and so on.
EJB Application Servers provide an EJB container, which is the environment that
beans will execute in, and this container will manage transactions, thread pools, and
other issues as necessary. These application servers are usually stand-alone
products, and developers would tie their servlets/JSP pages to the EJB components
via remote object access APIs. Depending on the application server, programmers
may use CORBA or RMI to talk to their beans, but the baseline standard is to use
JNDI to locate and create EJB references as necessary.
Now, one thing that confuses the issue is that many application server providers
include some or all of these components in their product. If you look at WebLogic
(http://www.beasys.com/) you will find that WebLogic contains a web server, servlet
engine, JSP processor, JMS facility, as well as an EJB container. Theoretically a
product like this could be used to handle all aspects of site development. In practice,
you would most likely use this type of product to manage/serve EJB instances, while
dedicated web servers handle the specific HTTP requests.
See also: What is the difference between an Application Server and a Web Server?
http://serverwatch.internet.com/webservers.html
how to decide up on the which servlet enebled web server to use for developing a web
based application ?
Good Response Paul Danckaert !
Author: Jeevie S (http://www.jguru.com/guru/viewbio.jsp?EID=3836), Sep 5, 2001
I came across this response after a long time from it's post date, but it's very good.
No. It provides a fair bit of housekeeping that you'd just have to do yourself. If you
need to do something regardless of whether the request is e.g., a POST or a GET,
create a helper method and call that at the beginning of e.g., doPost() and doGet().
Comments and alternative answers
In other words, your servlet class that extends HttpServlet should not override the
service(...) method because:
• You can add support for different behaviors for different request types by
overriding the appropriate doXXX(...) method. This makes sense since a
servlet should not return a "successful" response (i.e. status code in the 200
range) for a DELETE request unless it actually did delete the requested
resource.
• The default service(...) method supports modification dates
(i.e.conditional GET requests) by using the
getLastModified(HttpServletRequest) method (which you can override
to improve performance).
• You get automatic support for TRACE, OPTIONS, and HEAD requests (although
you can override the doHead(...) method (in servlets 2.3+) to improve
performance).
Of course, you could override service directly (to "improve" performance by reducing
the number of method calls) and include the appropriate logic to replace the
aforementioned functionality, but why re-invent the wheel?
Check out:
http://java.sun.com/aboutJava/communityprocess/jsr/jsr_053_jspservlet.html
Basically, after you've written a bunch of servlets from scratch, you'll proabably be
irked by having to do the same sorts of things over and over again. A good
framework helps to minimize how much of that rot that you have to do.
WebMacro
Most Application Servers contain their own frameworks. See this question on the
FAQ.
Yes. There is a comprehensive list of mailing lists at The Purple Servlet Resource List.
Be sure to check out the Sun's SERVLET-INTEREST mailing list. Subscribe by sending
an email to
[email protected]
with a message body of:
subscribe SERVLET-INTEREST
There's also an advanced servlet list, albeit with very low traffic (as of 3/20/00). More
info can be found here.
Essentially you return a page that has as its onLoad event code that opens a page
and gets your new data.
<head>
...
<script language="javascript">
function bustOut(){
var newWin = window.open("the real url", ....); // params and stuff
Eat at Joe's
</body>
</html>
You could set this up as a static html page to redirect to with "the real url" being
encoded in a query string.
If you are unclear as to how to read the query string using JavaScript I'd recommend
a good JavaScript reference. O'Reilly (who else) publishes two good books that would
help with this: Javascript: The Definitive Guide by David Flanagan and Dynamic
HTML by Danny Goodman
Another way to open a new browser window is to use the target element, i.e.:
Write the above string to your servlet's output page and it'll provide a way out of the
current browser window and into a new one.
Thanks in advance
Irfan
Eat at Joe's
</body>
</html>
opens a new session. In other words, even if the new window is a .jsp page, user
objects stored in the main window does not pass to the popup window. Is there any
way to keep the session other than using cookie? Parameters can be passed by putting
It depends :-)
There are a lot of products, and each has advantages and disadvantages. For a
more-or-less full list of servlet engines and servlet-enabled web servers, see The
Purple Tech Servlet Resource List.
The most popular servlet engines seem to be JRun and JServ. Both of these work
inside the open-source Apache Web Server (easily the most popular HTTP server).
Tomcat is the latest-and-greatest open-source servlet/JSP engine using code from
Sun, Apache and JServ. ServletExec is reportedly very stable in high-volume sites --
but the other servlet engines are being used on some high-volume sites as well.
If you have experience with or opinions about any of these products, please add
feedback to this FAQ.
The point is -- this is still the World Wide Web! HTTP is a file transfer protocol;
downloading files what it's for!
Solution 2: Open the file from your servlet using java.io classes, and shove the
bytes down the response stream. Make sure to set the content type to match the
type of file, e.g. response.setContentType("image/gif") or
response.setContentType("application/x-msword"). This technique is a little
more expensive, but allows you to do things like security checks, or to access files
that are on your web server host, but outside the HTTP directory structure.
For source code to a servlet that "downloads" (actually it's uploading, and the client
is downloading, right?) a text file, see this FAQ answer.
Another way to look at it is, there are three directory trees you need to worry about:
1. webapp
2. webapp/WEB-INF
3. the rest of your file system
To download a file from within the webapp, you can use plain old <A HREF> or <IMG
SRC>.
To download a file from anywhere else -- including the webapp/WEB-INF under WEB-
INF -- you need to call a servlet that opens the file and spits out the contents as
described above.
Note that the user your servlet engine is running as must have permission to access
that file, or you will get a server error.
See also
• Can I force the browser to save a downloaded file with a name I specify,
rather than the name of the URL?
• How do I read and output a text file from a Servle...
• How do I open and redirect to a popup window from a...
• Servlets:Files:Downloading subtopic
SO that the page will always be saved to the users harddrive. But I have a
problem. When I have a link to my download page the first browser window pops
up and says "Run from location.." or "Save file as...".
But if I say Save it the name displayed is some random characters with a .JSP
extension. If I save "Run from current location" it then has another save box pop
up where I can then save the file and the correct filename is displayed.
Has anyone seen this before and does anyone have a suggestion as to how to fix
it?
Thanks,
Brien
So how to avoid this and have the popup window still ?? If any solution is
reached can you inform please.
Thanks.
response.setContentType(p.getContentType());
response.setHeader("Content-Disposition", "filename=\"" +
p.getFileName() + "\";");
response.setContentLength(p.getSize());
InputStream is = p.getInputStream();
OutputStream oout = response.getOutputStream();
byte[] b = new byte[4 * 1024];
int len = 0;
response.setHeader("Content-Disposition", "filename=\"" +
p.getFileName() + "\";");
Whatever I try I couldn't get a perfect result from this code…
• If I leave the code as
response.setHeader("Content-Disposition", "filename=\"" +
p.getFileName() + "\";");
then:
If the file can be shown in the browser, then it is shown:
e.g. x.jpg c.bmp a.eml note.txt
but not worked for a .doc file and a .mp3 file I couldn't
understand why???(Content-Type: APPLICATION/OCTET-
STREAM).
One more thing: it did it well for c.bmp, whose content-type
was also APPLICATION/OCTET-STREAM
response.setHeader("Content-Disposition", "attachment;
filename=\"" + p.getFileName() + "\";");
http://www.jguru.com/faq/view.jsp?EID=252010
Re: In my servlet I am trying to let the user download… (By
seema bhatnagar)
So the only problem with the last case is that IT CAN`T get the
correct filenames to where to save the parts.
Thanks for any suggestions.. I`m sure that solving that problem
will form a useful documentation for that kind of "Downloading
File From Server" issue.
ostr.flush();
} catch(Exception ex){
ex.printStackTrace(System.out);
} finally{
try {
if(istr!=null) istr.close();
if(ostr!=null) ostr.close();
} catch(Exception ex){
System.out.println("Major Error Releasing
Streams: "+ex.toString());
}
}
try {
resp.flushBuffer();
} catch(Exception ex){
System.out.println("Error flushing the
Response: "+ex.toString());
}
}
Jonathan
the logic behind the code is right.. the problem is with IE,
and with the way they handle the
response.setHeader("Content-Disposition",
"attachment;filename=\"" + fname + "\";");
Servlet is as follows:
public void service(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException
res.setContentType("application/ms-excel");
// Init Locals
OutputStream os = res.getOutputStream();
// Validate Method
if(method.compareToIgnoreCase("POST") != 0)
out.println("Error:");
out.close();
return;
try
{
if(strCsvData != null)
{
res.setHeader("Content-Disposition",
"attachment;filename=test.csv")
;
res.setIntHeader("Content-length",
chCsvData.length);
out.write(chCsvData);
out.flush();
else
out.close();
catch (Exception e)
{
out.close();
finally
{
if(out != null)
out.close();
if(osw != null)
osw.close();
The above code shows the open/save dialog TWICE (!?) before 'opening' it in
excel. This does not happen if I save it on the disk. I tried different combinations
of setContentType(), Content-Disposition, content-length, flush so-on without
success. What should be the combination so that a user can view it in excel (not in
the browser)?
I found that if there were spaces in the filename I needed to use something like this:
From the developer's point of view, the "concurrency problem" is simply that if your
object is to be accessed from multiple threads, you need to take steps to ensure that
your object is thread safe. Otherwise, your object may end up in an invalid state and
may not behave as you expected. It makes no difference whether the accessor
threads are running on the same processor or different processors; it is the internals
of the JVM and the operating system that guarantee consistency of the address
space across CPUs.
Look at this article, they explain exactly how to solve your problem through Object
Serialization.
http://www.j-nine.com/pubs/applet2servlet/Applet2Servlet.html
Have fun.
See also:
• How can my applet communicate with my servlet?
• When you communicate with a servlet from an Applet, how can you ensure
that the session information is preserved? That is, how do you manage
cookies in applet-servlet communication?
[Without seeing your source code, it's hard to debug. This sort of question should be
asked on a mailing list (like advanced-servlets or tomcat-user) instead of a FAQ.
Good luck. -Alex]
// finish up
out.println("</body></html>");
}
}
[Note: I have now successfully compiled and run the above example. You asked for
working source, you got it :-)]
You may want to do more than just copy the file; look in the java.io package for
classes that help you process a file, like StreamTokenizer.
Pay attention to the use of an InitParameter to provide a root on the file system.
That way your servlet can be used on other servers without hardcoding a file path.
Also note the use of a finally block to close the file. This way, even if the reading
throws an exception, the file will be closed. This is important on a server, since file
descriptors are limited, and you don't want any leaks, since the server will be up for
a very long time (hopefully!).
Whenever you access local resources, you have to consider security holes. For
instance, if you make a file name based on a FORM parameter, you should validate it,
to make sure if a hacker sends in, e.g., "/etc/passwd" as his user name, he won't
actually get the system password file.
[Yes, that's the concurrency problem we're talking about :-) -Alex]
uploading file
Author: badrinath punchagnula
(http://www.jguru.com/guru/viewbio.jsp?EID=898666), Jul 16, 2002
hi , Your code for reading a file is working perfectly thanks for the help. Can u help
me regarding the uploading of file. I want to design my component of uploading of
file, but i m not able to move further from reading the parameter contents. EXample:
<input type=file name="filesend"> now if iwont to retrive the contents from the
"filesend" parameter by using getParameter() it is giving error so what i should use
inisted of that Can u help me out of this thanks in advance
What are the Servlet equivalents to all the CGI environment variables?
Location: http://www.jguru.com/faq/view.jsp?EID=11699
Created: Feb 5, 2000 Modified: 2000-05-29 11:55:28.339
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)
The following CGI environment variables, and their descriptions, were taken from the
CGI specification, at http://hoohoo.ncsa.uiuc.edu/cgi/env.html. Please see
http://java.sun.com/products/servlet/2.2/javadoc/index.html for a full description of
the Servlet Request object. It allows direct access to many things that are not
available as CGI environment variables, including Parameters, Cookies, HTTP
Headers, and Sessions.
Found Answer
Author: Mike Reedy (http://www.jguru.com/guru/viewbio.jsp?EID=98127), Jul 17,
2001
With this fragment of Apache .conf file:
<Directory /home/httpd/cgi-bin>
AuthType Basic
AuthName CommonApp
the REMOTE_USER was set in the CGI environment but was not seen by JAVA
servlets.
The fix found was to add the following directive to the Apache .conf file:
<Location /myServlets>
AuthType Basic
AuthName CommonApp
Before :
<directory /> (whole site, all ports with virtual hosts)
AuthName "MY AUTH NAME"
AuthType Basic
PerlAuthenHandler blabla (I use mod_perl for auth)
require valid-user
</directory>
NOT OK : req.getRemoteUser() => null
[I think this means "Please show me some source code" -- again, anyone? -Alex]
source
Author: Laura Currea (http://www.jguru.com/guru/viewbio.jsp?EID=450934), Jul 6,
2001
Some sample code would be great.
Re: source
Author: harsh tib (http://www.jguru.com/guru/viewbio.jsp?EID=459891), Jul 31,
2001
import java.io.*;
import java.net.*;
import java.util.*;
import java.lang.*;
import javax.servlet.*;
import javax.servlet.http.*;
source
Author: piero corsani (http://www.jguru.com/guru/viewbio.jsp?EID=462654), Jul 26,
2001
some source code would be really great
Source Code....
Author: harsh tib (http://www.jguru.com/guru/viewbio.jsp?EID=459891), Jul 31,
2001
import java.io.*;
import java.net.*;
import java.util.*;
import java.lang.*;
import javax.servlet.*;
import javax.servlet.http.*;
i use this sample to store others session variables like jdbc connections, my
'listener' seem to be delete in last, so i lost the references to the connections before
to close them.
At the beginning, i have put my connections in context but for a reason i don't
explain, and the db administrator too, i have lost the connection : connection reset
by server. So i put all in session.
Someone have an idea how to intercept the end of the session to close the
connections and not the end of only one variable ?
good luck
yudan maivar
Why use JSP when we can do the same thing with servlets?
Location: http://www.jguru.com/faq/view.jsp?EID=12776
Created: Feb 9, 2000 Modified: 2001-07-02 20:10:44.801
Author: Govind Seshadri (http://www.jguru.com/guru/viewbio.jsp?EID=14) Question
originally posed by praveen baswa
(http://www.jguru.com/guru/viewbio.jsp?EID=12529
[Original question: Why should I use JSP when there is already servlet technology
available for serving dynamic content?]
While JSP may be great for serving up dynamic Web content and separating content
from presentation, some may still wonder why servlets should be cast aside for JSP.
The utility of servlets is not in question. They are excellent for server-side
processing, and, with their significant installed base, are here to stay. In fact,
architecturally speaking, you can view JSP as a high-level abstraction of servlets that
is implemented as an extension of the Servlet 2.1 API. Still, you shouldn't use
servlets indiscriminately; they may not be appropriate for everyone. For instance,
while page designers can easily write a JSP page using conventional HTML or XML
tools, servlets are more suited for back-end developers because they are often
written using an IDE -- a process that generally requires a higher level of
programming expertise.
When deploying servlets, even developers have to be careful and ensure that there is
no tight coupling between presentation and content. You can usually do this by
adding a third-party HTML wrapper package like htmlKona to the mix. But even this
approach, though providing some flexibility with simple screen changes, still does not
shield you from a change in the presentation format itself. For example, if your
presentation changed from HTML to DHTML, you would still need to ensure that
wrapper packages were compliant with the new format. In a worst-case scenario, if a
wrapper package is not available, you may end up hardcoding the presentation
within the dynamic content. So, what is the solution? One approach would be to use
both JSP and servlet technologies for building application systems.
This answer is excerpted from my Javaworld article Understanding JavaServer Pages Model 2 Architecture
[See also Why use EJB when we can do the same thing with servlets?]
Comments and alternative answers
JSP = servlet
Author: Chris Johnson (http://www.jguru.com/guru/viewbio.jsp?EID=402517), Apr
27, 2001
Under the covers, JSPs are servlets. When you execute a JSP, your code is slammed
into a predefined JSP-servlet framework, compiled and executed (and cached). JSP is
merely a productity tool for people (like most of us) who don't want to write servlets
from the ground up when we don't have to.
Using JSP's and Servlets...
Author: thomas dietrich (http://www.jguru.com/guru/viewbio.jsp?EID=413665), Jul
3, 2001
Hello,
The need for jsp is so that the presentation layer is seperate from the the
implimentation layer.
• If a client wants you to double space between each line of text, does it make
sense to give that job to a high priced java developer or a meddium priced web
developer?
• Why if it's a just a cosmetic change, do you have redeploy a newly complied
servlet, when just uploading an updated jsp works?
• Why would you want the backend code and the web page together, since most
'code-jockeys' have no visual taste. :)
So, my answer to your question it's an issue of time, money and job seperation of
skills for team work.
Sincerely,
Thomas Dietrich
Can I call a JSP, then have it return control to the original JSP, like a
subroutine or method call?
Location: http://www.jguru.com/faq/view.jsp?EID=13118
Created: Feb 10, 2000 Modified: 2000-10-09 14:00:05.479
Author: Govind Seshadri (http://www.jguru.com/guru/viewbio.jsp?EID=14) Question
originally posed by Alex Chaffee PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=3
Yes. That is exactly the purpose served by the <jsp:include> action. The syntax of
the include action is:
<jsp:include page="relativeURL" flush="true" />
You can have the include action anywhere within your JSP page, and the relative URL
specified for the page attribute may point to either a static (.html) or dynamic
resource like a servlet or JSP. Since the include action is handled during the request
processing phase, it makes sense to include only resources which generate some
dynamic content. The included resource is also automatically forwarded the request
and response objects of the invoking JSP page. For example, the action:
<jsp:include page="/examples/jsp/copyright.jsp"flush="true"/>
results in the output of copyright.jsp being included inline within the response of
invoking JSP page.
There is however a limitation. The included JSP or servlet resource cannot change
the HTTP headers. For example, they cannot set cookies, since they are sent to the
browser via the HTTP headers.
Why does this code make my JVM crash when I put it in a JSP or bean?
Author: Chris Shank (http://www.jguru.com/guru/viewbio.jsp?EID=440892), Jun 18,
2001
Using iPlanet 4.1 on solaris. When I try to open a URL connection I get a jvm_abort()
error. The entire JVM restarts. I think this is a bug. Anyone come across something
similar?
Re: Why does this code make my JVM crash when I put it in a JSP or bean?
Author: Chad Hinkel (http://www.jguru.com/guru/viewbio.jsp?EID=512320), Oct
5, 2001
I am having the same problem when trying to open a URLConnection and then
reading the input. I have tried numerous workarounds with no luck. Any Ideas?
Re: Re: Why does this code make my JVM crash when I put it in a JSP or
bean?
Author: Chris Shank (http://www.jguru.com/guru/viewbio.jsp?EID=512438),
Oct 5, 2001
Ifound it was the JVM. Check if you are using 1.2.2 JVM and upgrade to a 1.3
JVM. good luck
See also
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jul 19, 2001
URLConnection.connect() time
================================================
It downloaded all the content of the file, but it put in extra ^M in my files...thus
conrrupting it.. Can anyone help?? Thanks!
This occur when a file from windows platform got saved in a unix platform. the
'\n' (new line) charecter gets converted into ^M charecter in unix file system. u
shall cahnge this by using dos2unix command in unix platform.
Thanks Muthu
i want to get response from jsp file and save it to .htm file
Author: danko greiner (http://www.jguru.com/guru/viewbio.jsp?EID=569721), Dec
10, 2001
is it possible?
See also
• NT-Service-howto.html
• http://members.xoom.com/yy_sun/jsplauncher/
• Jsrvany
For JWS:
Near the end of the installation program you will be asked if you want to have the
Java Web Server start automatically on system reboot. (That is, whether you want to
install the Java Web Server as an NT Service).
If you click Yes: An entry will be added to the Control Panels -> Services and the
JavaWebServer NT Service will be started up automatically every time you restart
your system.
If you click No: No entry will be made in the Control Panel's Services panel.
If you change your mind later, the product documentation provides instructions for
how to setup the web server to start automatically. For instructions, see the file:
[server_root]\doc\en\administration\server_start_Win.html
Comments and alternative answers
Use Jsrvany.
Author: Tom Copeland (http://www.jguru.com/guru/viewbio.jsp?EID=1396), Apr 3,
2000
Use Jsrvany.
How do you shut down JServ safely if you've started it (manual mode), such
that the destroy() methods of the existing servlet classes are invoked?
Location: http://www.jguru.com/faq/view.jsp?EID=13648
Created: Feb 12, 2000 Modified: 2000-06-03 14:48:47.409
Author: jae Roh (http://www.jguru.com/guru/viewbio.jsp?EID=13427) Question
originally posed by jae Roh (http://www.jguru.com/guru/viewbio.jsp?EID=13427
use the -r or -s flags. Straight from the command line usage info for java
org.apache.jserv.JServ with no args:
Usage: java org.apache.jserv.JServ [config file] [options]
Options:
-v : show version number
-V : show compile settings
-s : tell running ApacheJServ to shutdown
-r : tell running ApacheJServ to do a graceful restart
Note: please, specify the configuration file for the [-s] [-r] options.
How do I send information and data back and forth between applet and
servlet using the HTTP protocol?
Location: http://www.jguru.com/faq/view.jsp?EID=14163
Created: Feb 14, 2000 Modified: 2000-06-03 14:49:17.19
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by zhu jiang (http://www.jguru.com/guru/viewbio.jsp?EID=14031
Use the standard java.net.URL class, or "roll your own" using java.net.Socket.
See the HTTP spec at W3C for more detail.
Note: The servlet cannot initiate this connection! If the servlet needs to
asynchronously send a message to the applet, then you must open up a persistent
socket using java.net.Socket (on the applet side), and java.net.ServerSocket
and Threads (on the server side).
Because the HTTP header information is written before the embedded servlet is
executed, embedded servlets cannot perform any functions which require writing to
the HTTP header. For this reason, the following restrictions apply to servlets
embedded in .shtml pages:
• No cookies
• No redirects
• No errors or status (HttpServletResponse.sendError() or sendStatus())
• No setHeader()
• No setting of the content length
Can I get the path of the current servlet where it lives on the file system
(not its URL)?
Location: http://www.jguru.com/faq/view.jsp?EID=14839
Created: Feb 16, 2000 Modified: 2000-02-18 06:55:24.122
Author: Anthony Marsh (http://www.jguru.com/guru/viewbio.jsp?EID=14838)
Question originally posed by John Maring
(http://www.jguru.com/guru/viewbio.jsp?EID=12155
Try using:
request.getRealPath(request.getServletPath())
An example may be:
out.println(request.getRealPath(request.getServletPath()));
Comments and alternative answers
getRealPath()
Author: Parveen m (http://www.jguru.com/guru/viewbio.jsp?EID=560649), Nov 27,
2001
I have used the method but its throwing null i.e unable to translate path,is there any
other way around.Thanks
Re: getRealPath()
Author: Pradeep Kanwar (http://www.jguru.com/guru/viewbio.jsp?EID=544776),
Mar 28, 2002
is your file in a *.war since the method cannot translate file path for a file kept in
wars
Re: getRealPath()
Author: Antoine Diot (http://www.jguru.com/guru/viewbio.jsp?EID=1174272),
Jun 27, 2004
request.getRealPath() is deprecated. Use the following instead:
ServletContext context = session.getServletContext();
String realContextPath =
context.getRealPath(request.getContextPath());
getRealPath
Author: naren dra (http://www.jguru.com/guru/viewbio.jsp?EID=1169158), May 7,
2004
it will give please try this by typing the context path
request.getRealPath("servlet/filename.javaorclass") and try this
request.getRealPath(request.getServletPath())
How to determine the client browser version? Also, how to check if it allows
cookies?
Location: http://www.jguru.com/faq/view.jsp?EID=14907
Created: Feb 16, 2000 Modified: 2001-10-29 05:51:40.523
Author: Ramakrishna puppala (http://www.jguru.com/guru/viewbio.jsp?EID=14906)
Another name for "browser" is "user agent." You can read the User-Agent header
using request.getUserAgent() or request.getHeader("User-Agent")
It's not enough to tell if the browser might possibly support cookies; you also must
tell if the user has enabled or disabled cookies. For that, you must drop a test cookie
on the browser, then see if it gets sent back. A servlet that does this is called
CookieDetector, at http://www.purpletech.com/code/.
[Keywords: identify client browser, determine client browser, check version of client
browser]
This cannot be done automatically. There are no properties (in the web servers that I
have used) or APIs that would make a servlet or JSP use url rewriting instead of
cookies. URL rewriting needs to be done manually. That is, you need to create a
session and then send that session id through URL rewriting in the servlet response.
Subsequently, you need to retrieve the session id from the form field in the request
and retrieve the session object using that id.
Comments and alternative answers
Just settng this configuration in resin.conf enables url-rewriting in all links and form
actions (I suppose)
<session-config>
<enable-url-rewriting>true
</enable-url-rewriting>
</session-config>
sessionid
Author: ravi kumar pinnasi (http://www.jguru.com/guru/viewbio.jsp?EID=1199524),
Sep 16, 2004
how to create an SessionID in jsp
Re: sessionid
Author: M. washu (http://www.jguru.com/guru/viewbio.jsp?EID=1217388), Dec
21, 2004
Hi all,
Is there a way to include jsessionid in a hidden field (in a form) rather than in the
URL (by the URL rewriting mechanism ) ?
I saw that HttpSessionContext class was deprecated for security reason, but for
security reasons too i would like to know if there is a way to prevent the jessionid
from being logged in the HTTP server log files (of course without using cookies) ?
Thanks in advance.
Should I use the SingleThreadModel interface or provide explicit
synchronization to make my JSP pages and servlets thread safe?
Location: http://www.jguru.com/faq/view.jsp?EID=15653
Created: Feb 18, 2000 Modified: 2000-12-06 17:23:26.122
Author: Govind Seshadri (http://www.jguru.com/guru/viewbio.jsp?EID=14)
You can have a any servlet implement the SingleThreadModel interface. JSP pages
implement this in the background when you specify
<%@ page isThreadSafe="false" %>
Although the SingleThreadModel technique is easy to use, and works well for low
volume sites, it does not scale well. If you anticipate your users to increase in the
future, you may be better off implementing synchronization for your variables. The
key however, is to effectively minimize the amount of code that is synchronzied so
that you take maximum advantage of multithreading.
Also, note that SingleThreadModel is pretty resource intensive from the server's
perspective. The most serious issue however is when the number of concurrent
requests exhaust the servlet instance pool. In that case, all the unserviced requests
are queued until something becomes free - which results in poor performance. Since
the usage is non-deterministic, it may not help much even if you did add more
memory and increased the size of the instance pool.
Thread safety
Author: Surya Sun (http://www.jguru.com/guru/viewbio.jsp?EID=729798), Jan 22,
2002
But i guess as far as servlets are concerned to some extent servlets are thread safe,
until unless you wont use global level variables. In which case either you need to use
single thread model or sychronization. As said Single Thread Model may sometimes
be a overhead as far as performance is concerned.
Dan
http://sourceforge.net/projects/httpunit
How can I daisy chain servlets together such that the output of one servlet
serves as the input to the next?
Location: http://www.jguru.com/faq/view.jsp?EID=17012
Created: Feb 22, 2000 Modified: 2000-06-03 14:51:21.917
Author: Sylvain GIBIER (http://www.jguru.com/guru/viewbio.jsp?EID=11408)
Question originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7
There are two common methods for chaining the output of one servlet to another
servlet :
To chain servlets together, you have to specify a sequential list of servlets and
associate it to an alias. When a request is made to this alias, the first servlet in the
list is invoked, processed its task and sent the ouptut to the next servlet in the list as
the request object. The output can be sent again to another servlets.
To accomplish this method, you need to configure your servlet engine (JRun,
JavaWeb server, JServ ...).
For example to configure JRun for servlet chaining, you select the JSE service (JRun
servlet engine) to access to the JSE Service Config panel. You have just to define a
new mapping rule where you define your chaining servlet.
Let say /servlets/chainServlet for the virtual path and a comma separated list of
servlets as srvA,srvB.
So when you invoke a request like http://localhost/servlets/chainServlet, internally
the servlet srvA will be invoked first and its results will be piped into the servlet srvB.
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.
Comments and alternative answers
Use the same technique as you would use to display a file (or any other stream). See
http://www.jguru.com/jguru/faq/view.jsp?EID=159 and
http://www.jguru.com/jguru/faq/view.jsp?EID=3696 for more details.
What are the steps involved in setting up JServ on Apache to run Servlets?
Location: http://www.jguru.com/faq/view.jsp?EID=20716
Created: Mar 6, 2000 Modified: 2000-06-03 14:52:31.564
Author: manohar ms (http://www.jguru.com/guru/viewbio.jsp?EID=20704) Question
originally posed by Sunny Kumar
(http://www.jguru.com/guru/viewbio.jsp?EID=7578
The following page has got a very good document on how to install and configure
apache Jserv : http://www.magiccookie.com/computers/apache-jserv/#Basic
installation
regards
Man
All the dbms provide the facility of locks whenever the data is being modified. There
can be two scenarios:
1. Multiple database updates on different rows, if you are using servlets the
servlets will open multiple connections for different users. In this case there is
no need to do additional programming.
2. If database updates are on the same row then the rows are locked
automatically by the dbms, hence we have to send requests to the dbms
repeatatively until the lock is released by dbms.
This issue is dealt with in the JDBC documentation; look up "Transactions" and "auto-
commit". It can get pretty confusing.
How can I use servlets to make sure a user has logged in before I handle
the request?
Location: http://www.jguru.com/faq/view.jsp?EID=21659
Created: Mar 8, 2000 Modified: 2000-06-03 14:54:09.028
Author: Sylvain GIBIER (http://www.jguru.com/guru/viewbio.jsp?EID=11408)
Question originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7
Since a JSP page is nothing else than a servlet, you can look at this FAQ entry :
http://www.jguru.com/jguru/faq/view.jsp?EID=16898.
What is the difference between GenericServlet and HttpServlet?
Location: http://www.jguru.com/faq/view.jsp?EID=22381
Created: Mar 9, 2000 Modified: 2000-03-09 20:02:10.329
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by premchandar jonnala
(http://www.jguru.com/guru/viewbio.jsp?EID=18613
GenericServlet is for servlets that might not use HTTP, like for instance FTP servlets.
Of course, it turns out that there's no such thing as FTP servlets, but they were
trying to plan for future growth when they designed the spec. Maybe some day there
will be another subclass, but for now, always use HttpServlet.
Comments and alternative answers
servlets
Author: Anuradha Aggarwal (http://www.jguru.com/guru/viewbio.jsp?EID=534290),
Oct 30, 2001
1.generic servlet is superclass for HttpServlet. 2.httpservlet class can also have
service() method.it's not necessary that you can only have doGet() and doPost()
method defined. 3.Generic servlet is used for small data transfer whereas HttpServlet
is used for huge data transfer.
Re: servlets
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Mar 6,
2003
> 3.Generic servlet is used for small data transfer
> whereas HttpServlet is used for huge data transfer.
Huh? Where'd you hear that? This is total propaganda! Lies, lies, lies! :-)
Anyway, just use HttpServlet. GenericServlet was due to a bad case of premature
abstraction. (Fortunately, there is medication available now to treat that condition.
It's called "refactoring".)
Re[2]: servlets
Author: vidyadhar joshi
(http://www.jguru.com/guru/viewbio.jsp?EID=1190813), Aug 4, 2004
how do you use refactoring to acheive that medication. alex can you throw
some light on it
Re[3]: servlets
Author: kishore pillarisetty
(http://www.jguru.com/guru/viewbio.jsp?EID=1240865), Apr 25, 2005
generic servlets class of the javax.servlet package is used to cerate servlets
which can work in any protocols(i.e;not only using HTML format).. where
as httpservlets are used to create http servlets ans it is derived from generic
servlets.Serilaization is possible in servlets ,because generic servlets
extends Java.io.Serializable interface
Sharing sessions between a servlet and a JSP page is straight forward. JSP makes it
a little easy by creating a session object and making it availabe already. In a servlet
you would have to do it yourself. This is how:
//create a session if one is not created already now
HttpSession session = request.getSession(true);
//assign the session variable to a value.
session.putValue("variable","value");
in the jsp page this is how you get the session value:
<%
session.getValue("varible");
%>
Comments and alternative answers
This is exactly what I am looking for, but how did...
Author: Dewayne Richardson (http://www.jguru.com/guru/viewbio.jsp?EID=10342),
Apr 4, 2000
This is exactly what I am looking for, but how did the .jsp file get invoked from the
servlet?
But does it work the other way, ie if you store the object in the JSP first and then try
and access it in a Servlet. Because I cant seem to figure it out, the Vector I have stored
from the jsp always return a Null value
Search Comment On FAQ Entry How do you share session objects between
servlets and JSP
Author: srikant noorani (http://www.jguru.com/guru/viewbio.jsp?EID=742554), Jan
31, 2002
instead of putValue and getValue ( deprecated ) use getAttribute and setAttribute
Re: Search Comment On FAQ Entry How do you share session objects
between servlets and JSP
Author: Iain Rundle (http://www.jguru.com/guru/viewbio.jsp?EID=784872), Mar
7, 2002
Hi
I have a one servlet which is opened and closed continually by JSP pages
everytime the servlet creates a new session. So the second JSP getAttribute values
are blank.
All I want is the create a session variable that is constant and is passed from one
JSP page to a servlet and that I can view on a second JSP page
Based on Sun's Java Servlet API ServletContext.log() logs messages to the servlet
log file. The name and type of the servlet log file is specific to the servlet engine, but
it is usually an event log. To get the log OutputStream depends on the specific
servlet engine. For IBM's WebSphere, you can look in the
com.sun.server.log.TraceLog class. For the J2EE SDK, the class is
com.sun.enterprise.log.Log.
public GzipServlet()
{
}
}
More code
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Dec 13, 2002
The following code actually returns a compressing PrintWriter that you can print to
directly, sparing you the whole String-building problem. It wouldn't take much effort
to give yourself a MyServlet superclass that does this for all servlets (or for a subset
of servlets that want it).
http://lists.over.net/pipermail/mod_gzip/2001-January/003803.html
See also
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Dec 13, 2002
Is there a way to compress the result of the JSP and return it to the browser? Most
browsers support GZIP and I have compressed straight HTML and also used this
technique with XML/XSL. Btw, I am using a servlet-centric approach.
How can I include content from a URL, not from a local file?
Location: http://www.jguru.com/faq/view.jsp?EID=23327
Created: Mar 12, 2000 Modified: 2000-06-03 14:55:43.746
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Gilbert Banks
(http://www.jguru.com/guru/viewbio.jsp?EID=17542
You would need to read in the content from the URL and place it in the file yourself.
See http://www.jguru.com/jguru/faq/view.jsp?EID=13198 for an example of this,
but use a Reader stream instead of an InputStream as you'll be working with
character data.
Comments and alternative answers
Now you can just refer to variable content in your page, or alternatively the tag will
write the content from the URL straight to a file (useful for parsing RDF data etc).
Just because Jason Hunter says JSPs mix content and presentation doesn't mean that
*all* uses of JSP *always* exemplify bad design practice. In fact, quite the opposite.
In fact, your last sentence seems to indicate that you might not quite appreciate that
we're trying to distinguish *content* from *presentation* from *data access* from
*business logic* (all separate, yet blurred at the edges, like all abstract ideals).
try {
yahoo.openConnection();
}
catch (MalformedURLException e) {
System.out.println(e.getMessage());
}
try {
outfile.writeBytes(inputLine);
catch(Exception e) {
System.out.println(e.getMessage());
}
in.close();
}
}
Authentication/Session issues?
Author: Shash Chatterjee (http://www.jguru.com/guru/viewbio.jsp?EID=125367),
Nov 5, 2001
Although custom tags or the netwrok-stream reader solutions are wonderful ways of
including output from arbitrary URLs into a JSP, I have run into one problem.
If the URLs being accessed are authenticated using session variables, then these
methods fail because the browsers session is different from that created for the
network connection used by the custom-tag or the java.net URL class.
You can set the maximum age of a cookie with the setMaxAge(int seconds)
method:
• A positive value is the maximum number of seconds the cookie will live,
before it expires
• A negative value means the cookie will not be stored beyond this browser
session (deleted on browser close)
• Zero means to delete the cookie
Most web servers support HTTP-Authentication. Thus, once the servlet is loaded, the
user has already been authenticated. You can learn more about this from:
http://www.trudat.com/computer/authentication/authentication.html and
http://www.trudat.com/computer/authenti.htm.
[The above technique uses browser-based authentication, which has the advantage
that it's standard and well-supported across browsers, but the disadvantage of using
an ugly dialog box with very little extra information. An alternate technique is to
write a servlet or JSP that asks your user for his login information; this gives you a
lot of control but can be tricky to implement correctly. Finally, there is FORM-based
login; see What is FORM based login and how do I use it? for details on this new
spec-based functionality. -Alex]
The author says that the real URL for that page is...
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Apr 24, 2000
The author says that the real URL for that page is
http://www.tapsellferrier.co.uk/Servlets/FAQ/authentication.html. Apparently the
above URL was an unauthorized copy... Use this one instead. Note that it also has
source code for a Base64 encoder/decoder class.
I don't believe so. If you really need this, use a cookie-based authentication scheme
instead. When the user logs in, drop a single cookie with a long randomly-generated
string into their browser. [The SecureRandom class would help here. -Alex]
Keep a database table or in-memory hash mapping these cookie values to local data
about the user.
To log off, just erase the token from the server's token list. That's guaranteed to work
even if the user rejects the cookie update needed to erase the cookie from the browser.
Re: well, people, i've seen with my own eyes how a web...
Author: Roger Hand (http://www.jguru.com/guru/viewbio.jsp?EID=292314), May
8, 2001
In the vast majority of cases the info is from a cookie from a previous session.
How can I find out the number of live sessions within my servlet engine
using either JSP or servlets?
Location: http://www.jguru.com/faq/view.jsp?EID=24079
Created: Mar 14, 2000 Modified: 2001-08-01 15:18:57.539
Author: Volker Stolz (http://www.jguru.com/guru/viewbio.jsp?EID=24071) Question
originally posed by Qiang Bai (http://www.jguru.com/guru/viewbio.jsp?EID=22135
There is no easy way to this as all the required functions have been deprecated in
JSP 1.1 for security reasons. [FAQ Manager NOTE - For earlier JSP users, scroll to
end for a working answer for there.]
[FAQ Manager addition - The following was submitted by both Peter Wang and Roger
Valade for earlier JSP versions. It does not run in the 3.1 version of Tomcat.]
<%@ page import="java.util.*" %>
<html>
<head>
<meta http-equiv="Refresh" content=90>
<title>Active Sessions</title>
</head>
<%!
final String getActiveSessionData( final HttpServletRequest request
)
{
final StringBuffer data = new StringBuffer();
int counter = 0;
final HttpSession curSession = request.getSession(
true );
final String curSessionId = curSession.getId();
final HttpSessionContext context =
curSession.getSessionContext();
for ( final Enumeration sessionIds = context.getIds();
sessionIds.hasMoreElements(); )
{
final String sessionId = (String)
sessionIds.nextElement().toString();
// if ( curSessionId == sessionId )
// {
// continue;
// }
String userId = sessionId;
long creation = 0;
long lastAccess = 0;
See also
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Feb 14, 2002
Finding server sessions
Stumped
Author: Mark Schnitzius (http://www.jguru.com/guru/viewbio.jsp?EID=1140487),
Jan 21, 2004
I'm trying to implement a session counter that limits the number of users that can be
using our servlet at a given time, and have a few questions on the approach presented
here.
1. Our servlet runs without a database. Is there an alternate place that I can store the
count of sessions? Perhaps on a class variable on my HttpSessionBindingListener
class? Or would that not work?
session.putValue("logon.sqlnotifier",new SqlNotifier(sql));
"upon creation of a new session." Where exactly do I put this code such that it will be
called upon the creation of a new session?
AdvTHANKSance,
--Mark
Re: Stumped
Author: Kal Pitansson (http://www.jguru.com/guru/viewbio.jsp?EID=1227614), Feb 16,
2005
Use the sessionCreated method of HttpSessionListener
http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/http/HttpSessionListener.html
Hope you are using a Servlet 2.3 compliant server. The putValue above doesn't look too
good. That's been deprecated ages ago and some servers are pulling support for it.
While I am still making changes to a servlet code, how can I make a servlet
reload every time I test it?
Location: http://www.jguru.com/faq/view.jsp?EID=24607
Created: Mar 15, 2000 Modified: 2003-01-11 07:02:36.296
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Rodolfo Ruiz
(http://www.jguru.com/guru/viewbio.jsp?EID=2326
It depends on the web server you are using to test your servlet. For instance, with
Tomcat, you would replace the WAR file and the server notices the change and loads
the new servlet on the next request, without having to restart the server.
[Short answer: for Tomcat, add reloadable="true" to the <Context> tag for that
web application.
Note that there is a bug in Tomcat where replacing the WAR file doesn't work; you
also have to delete the unpacked directory under TOMCAT/webapps/foo (for
TOMCAT/webapps/foo.war).
If you are not using WAR file deployment, simply replacing the servlet classfile
should work, as long as the class file is stored in webapp/WEB-INF/classes, or
replacing the JAR file in webapp/WEB-INF/lib/foo.jar.
-Alex]
To tell Tomcat to check the modification dates of the class files of requested
servlets and reload ones that have changed since they were loaded into the server's
memory. This degrades performance in deployment situations, so is turned off by
default. However, if you fail to turn it on for your development server, you'll have
to restart the server every time you recompile a servlet that has already been
loaded into the server's memory.
Define properties for each web application. This is only needed if you want to set
non-default properties, or have web application document roots in places other
than the virtual host's appBase directory.
and insert the following line just below it:
<DefaultContext reloadable="true"/>
Be sure to make a backup copy of server.xml before making the above change.
David
In order to use secure sockets, you need an SSL implementation. this is not provided
in the Java 2 SDK.
If you are running an applet, the major browsers provide support for HTTPS through
the java.net.URL class - simply specify a protocol of "https" in your URL string and
the details are handled for you.
If you are running a standalone application, or want to use SSL over your own
sockets and avoid using URL or URLConnection, then you need to obtain an
implementation of the Java Secure Socket Extension, or JSSE.
What is a servlet?
Location: http://www.jguru.com/faq/view.jsp?EID=24796
Created: Mar 15, 2000 Modified: 2000-03-15 22:06:50.489
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by sushil tyagi
(http://www.jguru.com/guru/viewbio.jsp?EID=24787
A servlet is a way of extending your web server with a Java program to perform
tasks previously dealt with by CGI scripts or proprietary server extension
frameworks. For more information, visit Sun's Servlet API home at
http://java.sun.com/products/servlet/.
Comments and alternative answers
servlets
Author: sarfaraz khan (http://www.jguru.com/guru/viewbio.jsp?EID=1222271), Jan
20, 2005
a servlet is scalable,multithreaded,secure java application.it extends the capability of a
web server to perform task.a servlet is used to deploy dinanamic contents in web
pages.
Is there any method to unload a servlet from Web Server memory without
restarting the server?
Location: http://www.jguru.com/faq/view.jsp?EID=25210
Created: Mar 16, 2000 Modified: 2000-06-03 15:00:45.724
Author: Andreas Schaefer (http://www.jguru.com/guru/viewbio.jsp?EID=25162)
Question originally posed by vishnu vardan
(http://www.jguru.com/guru/viewbio.jsp?EID=6483
How do I setup a Servlet as an RMI client (and not get an RMI Security
exception in the process)?
Location: http://www.jguru.com/faq/view.jsp?EID=25918
Created: Mar 19, 2000 Modified: 2000-08-13 16:39:20.301
Author: Dieter Wimberger (http://www.jguru.com/guru/viewbio.jsp?EID=25708)
Question originally posed by John Collins
(http://www.jguru.com/guru/viewbio.jsp?EID=21866
I think this depends a lot on the JDK you are using to run your Servlet Engine.
• Platform 2 (JDK 1.2, 1.3): take a look at the security policy. Refer to the
documentation for setting correct java.net.SocketPermission entries, plus
maybe File Access Permissions and in some cases ClassLoader permissions.
• Platform 1 (JDK 1.1.x): The only real way I found to circumvent my problems
was to implement my own RMI SecurityManager. Therefore simply extend the
java.rmi.RMISecurityManager class and implement your own policy overriding
specific permission check methods. Most likely those will be: checkConnect,
checkRead, checkWrite. But I suggest to examine the API doc of the
RMISecurityManger to find out more.
To set that SecurityManager you have to add following line to your Servlet init()
method:
You have to make sure that the servlet engine and JVM you are using...
1) use a security manager
2) the security manager does something meaningful
3) the security policy is meaningful
Try these flags in the command that starts java -Djava.security.manager -Djava.
security.policy==.\foo.policy
try
{
System.out.println( h2o + "Information..." + h2c );
System.out.println( " Security Manager: " +
System.getSecurityManager().getClass().getName() + p );
System.out.println( " ClassLoader: " +
this.getClass().getClassLoader() + p );
// weblogic.utils.classloaders.GenericClassLoader gcl =
(weblogic.utils.classloaders.GenericClassLoader)this.getClass().getClassLoader();
// gcl.setDebug( true );
try
{
System.out.println( h2o + "Attempting file write to d:/Java..." + h2c
);
File f = new File( "d:/Java/blah.txt" );
FileWriter fw = new FileWriter( f );
fw.write( "test\n" );
fw.close();
System.out.println( " -- allowed -- " + p );
}
catch( Exception e ) { System.out.println( " -- rejected -- " +
e.getMessage() + p ); }
try
{
System.out.println( h2o + "Attempting file write to
d:/Java/TestServlet..." + h2c );
File f = new File( "d:/Java/TestServlet/blah.txt" );
FileWriter fw = new FileWriter( f );
fw.write( "test\n" );
fw.close();
System.out.println( " -- allowed -- " + p );
}
catch( Exception e ) { System.out.println( " -- rejected -- " +
e.getMessage() + p ); }
try
{
System.out.println( h2o + "Attempting file read to c:/Ntdetect..." +
h2c );
File f = new File( "c:/Ntdetect.com" );
FileReader fr = new FileReader( f );
int c = fr.read();
System.out.println( " -- allowed -- " + p );
}
catch( Exception e ) { System.out.println( " -- rejected -- " +
e.getMessage() + p ); }
try
{
System.out.println( h2o + "Attempting file read to
c:/weblogic/weblogic.properties..." + h2c );
File f = new File( "c:/weblogic/weblogic.properties" );
FileReader fr = new FileReader( f );
int c = fr.read();
System.out.println( " -- allowed -- " + p );
}
catch( Exception e ) { System.out.println( " -- rejected -- " +
e.getMessage() + p ); }
try
{
System.out.println( h2o + "Attempting to connect to yahoo.com..." +
h2c );
Socket s = new Socket( "yahoo.com", 8080 );
System.out.println( " -- allowed -- " + p );
}
catch( Exception e ) { System.out.println( " -- rejected -- " +
e.getMessage() + p ); }
try
{
System.out.println( h2o + "Attempting to connect to hacker.com..." +
h2c );
Socket s = new Socket( "hacker.com", 8080 );
System.out.println( " -- allowed -- " + p );
}
catch( Exception e ) { System.out.println( " -- rejected -- " +
e.getMessage() + p ); }
try
{
System.out.println( h2o + "Attempting to listen on port 37337..." +
h2c );
ServerSocket s = new ServerSocket( 37337 );
Socket c = s.accept();
System.out.println( " -- allowed -- " + p );
}
catch( Exception e ) { System.out.println( " -- rejected -- " +
e.getMessage() + p ); }
try
{
System.out.println( h2o + "Attempting to listen on port 7001..." +
h2c );
ServerSocket s = new ServerSocket( 7001 );
Socket c = s.accept();
System.out.println( " -- allowed -- " + p );
}
catch( Exception e ) { System.out.println( " -- rejected -- " +
e.getMessage() + p ); }
/*
try
{
System.out.println( h2o + "Attempting native call..." + h2c );
native0( 1 );
System.out.println( " -- allowed -- " + p );
}
catch( Exception e ) { System.out.println( " -- rejected -- " +
e.getMessage() + p ); }
*/
try
{
System.out.println( h2o + "Attempting exec..." + h2c );
Runtime.getRuntime().exec( "dir" );
System.out.println( " -- allowed -- " + p );
}
catch( Exception e ) { System.out.println( " -- rejected -- " +
e.getMessage() + p ); }
try
{
System.out.println( h2o + "Attempting system exit..." + h2c );
System.exit( 3 );
System.out.println( " -- allowed -- " + p );
}
catch( Exception e ) { System.out.println( " -- rejected -- " +
e.getMessage() + p ); }
System.out.println("</BODY></HTML>");
How can I use Servlets to add entries to the password list in Apache? I tried
to invoke the htpasswd.exe but it doesn't work.
Location: http://www.jguru.com/faq/view.jsp?EID=25920
Created: Mar 19, 2000 Modified: 2000-06-21 11:09:56.77
Author: Dieter Wimberger (http://www.jguru.com/guru/viewbio.jsp?EID=25708)
Question originally posed by Jimmy Chou
(http://www.jguru.com/guru/viewbio.jsp?EID=10496
Your servlet needs write access to the AuthUserFile specified in the access file (Check
the Apache Documentation on that).
Then you need some utility implmenting a standard C crypt() in Java. Those are
freely available from different Java resource pages.
Now just open the file and append(!) a line that has the following format:
[username]:[crypted password] Don't forget there are certain security issues
regarding what you want to do. I would not recommend to do this within security
sensible environments.
Comments and alternative answers
This answer would be a lot more useful if it included...
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jun 21, 2000
This answer would be a lot more useful if it included a pointer to the crypt code, and
some Java source implementing it.
Htpasswd
Author: Ben Steeples (http://www.jguru.com/guru/viewbio.jsp?EID=469295), Aug
22, 2001
I've tried this, by using the htpasswd -nb options, and then calling it from java using
exec(). But to no avail. Has anyone got the crypt() function for java?
I have stored image files in a database. Is there any way to display that
image in a web browser by querying the database?
Location: http://www.jguru.com/faq/view.jsp?EID=26164
Created: Mar 20, 2000 Modified: 2000-06-21 13:58:08.889
Author: Dieter Wimberger (http://www.jguru.com/guru/viewbio.jsp?EID=25708)
Question originally posed by chandra sekar
(http://www.jguru.com/guru/viewbio.jsp?EID=20353
I would recommend you to retrieve the image via JDBC from a simple HTTP servlet.
• Ensure to set the correct Mime type. This has to be done calling
HttpServletResponse.setContentType(String type);
e.g. myHttpServletResponse.setContentType("image/jpeg");
• Ensure that your RDBMS does not limit result sizes (i.e. check the manuals if
you get half images, and always the same block sizes).
• Attach ?<param>=<value> to your src URL to specify the picture to be
retrieved. This param can be retrieved within your service method very
simple, using:
HttpServletRequest.getParameter(String name);
The HTML tag for the image would then be something like follows:
<img src="http://www.mydomain.com/PictureServlet?id=35">
(Sure you can use more params if you need to do so.)
• Use some simple or sophisticated caching algorithm to limit your systems
load.
Thanks!
How can I load a DLL (native library) and run something inside the DLL from
a Servlet using JNI on JavaWebServer in Windows NT?
Location: http://www.jguru.com/faq/view.jsp?EID=27401
Created: Mar 22, 2000 Modified: 2000-04-05 04:12:47.367
Author: Marius Scurtescu (http://www.jguru.com/guru/viewbio.jsp?EID=8459)
Question originally posed by Dae-Ki Kang
(http://www.jguru.com/guru/viewbio.jsp?EID=20222
Is there anything special about JavaWeb Server so only JNI is not working? Probably
not, all you have to do is to learn how to use JNI. I used "Essential JNI" by Rob
Gordon.
Comments and alternative answers
Source code
Author: Emerson manoj (http://www.jguru.com/guru/viewbio.jsp?EID=549298), Nov
16, 2001
I need the source code for the above query. my id is [email protected]
third is a silly thing which i did but it works put the dll file in your web module so
that you can read it create a file and copy the contents to of dll to that file. File
myfile = new File("yourdll.dll"); copy the contents of the dll to myfile. call
System.loadLibrary("yourdll"); it works
Regards
Vutharkar siddhartha
What is a cookie?
Location: http://www.jguru.com/faq/view.jsp?EID=28166
Created: Mar 24, 2000 Modified: 2000-09-17 21:51:40.637
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by G.EBY NAYAGAM
(http://www.jguru.com/guru/viewbio.jsp?EID=12837
Prior to the Servlets 2.2 API, there was no standard location. The 2.2 API adds the
javax.servlet.context.tmpdir attribute to the servlet context that defines where
to write something:
File directory =
(File)getServletContext().getAttribute("javax.servlet.context.tmpdir");
File file = File.createTempFile("prefix", ".tmp", directory);
FileWriter out = new FileWriter(file);
Comments and alternative answers
out and err should go to console for Java-based servlet engines. Some servlet
engines (a.k.a. containers in Servlets 2.2) block System.out and System.err for
servlets, so you may want to use ServletContext.log() or use your own log
function.
Read your servlet engine documentation to find out where it stores its log files.
Typically, a servlet container redirects standard out (System.out) and standard error
(System.err) to separate log files when it starts up. So in that sense the answer is
totally implementation dependent: where does your servlet container keep its logs?
Usually this is configurable by the user. There should be options in configuration files
for your servlet container to prevent stdout and stderr from being redirected, or to
redirect them to the files of your choice.
But in another sense, the answer is no different from any other Java or non-Java
application. If you or your servlet container do not redirect these output streams to a
file, then they go to the default devices for these streams on your computer. Typically
that means they both write to the terminal from which you first executed the servlet
container program.
Note: don't forget the log() method of the Servlet API. This offers another way to log
messages from your servlet container without calling System.out and System.err
every time. The log() method usually writes to an event log separate from any logging
of stdout and stderr.
Scott Stirling
See also
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Mar 1, 2002
See Where do System.out and System.err go in Tomcat?
How can an applet or application pass data to and read output from a CGI
script or Servlet?
Location: http://www.jguru.com/faq/view.jsp?EID=31753
Created: Apr 3, 2000 Modified: 2000-11-28 09:36:42.914
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question
originally posed by Clarence Robinson
(http://www.jguru.com/guru/viewbio.jsp?EID=22627
To pass data to a CGI program or Servlet, you need to use the GET or POST method
in HTTP. The data is sent as key=value pairs separated by ampersands. To do this in
Java, we use the URLConnection class, which takes care of the details of the HTTP
protocol for us. The only thing we have to specify is the URL of the server and the
data to be sent.
import java.net.*;
import java.io.*;
Note that is works not just for CGI scripts and Servlets, but for any server-side
mechanism you use to handle GET and POST requests, for instance a JSP page.
How do I limit the number of simultaneous requests to my servlet?
Location: http://www.jguru.com/faq/view.jsp?EID=32389
Created: Apr 5, 2000 Modified: 2000-04-06 11:06:13.902
Author: Benoit Xhenseval (http://www.jguru.com/guru/viewbio.jsp?EID=3363)
Question originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7
It is a servlet engine parameter, for instance JRun allows you to set up the number of
maximum concurrent threads.
The above worked a treat, but I need to get a list of files at a remote directory, and
only download the newest one.
Any amount of data can be stored there because the session is kept on the server
side.
The only limitation is sessionId length, which shouldn't exceed ~4000 bytes - this
limitation is implied by HTTP header length limitation to 4Kb since sessionId may be
stored in the cookie or encoded in URL (using "URL rewriting") and the cookie
specification says the size of cookie as well as HTTP request (e.g. GET
/document.html\n) cannot be longer then 4kb.
Where can I find out more info about WAR (Web Archive) files?
Location: http://www.jguru.com/faq/view.jsp?EID=33163
Created: Apr 6, 2000 Modified: 2000-06-21 15:18:47.829
Author: Spencer Marks (http://www.jguru.com/guru/viewbio.jsp?EID=24112)
Question originally posed by Spencer Marks
(http://www.jguru.com/guru/viewbio.jsp?EID=24112
The JSP Spec v 2.2 is a good starting point.
http://java.sun.com/products/servlet/2.2
Comments and alternative answers
WAR file can be created using WINZIP of windows or jar -cvf option of the jar
utility.
and deploy it any where UNIX/Linux/Window etc where ever you production server
is.
You can also know how to build the war file using the ANT builder info at :
ant.apache.org
you can use the jsp-examples in your default jakarta-tomcat installation to create a
simple WAR file.
eg: /jsp-examples examples can be created a WAR file by simply zipping it. and
renaming it to .war
make sure the path is there is no nested folders eg: when you zip jsp-examples try
unzipping it also and dont find a nested folder of jsp-examples\jsp-examples\WEB-
INF
start jakarta
and u can browse it simple isnt it :) but you should try to use the ANT tool. to make
.war files and .ear files
When you communicate with a servlet from an Applet or an application, how
can you ensure that the session information is preserved? That is, how do
you manage cookies in applet-servlet communication?
Location: http://www.jguru.com/faq/view.jsp?EID=33978
Created: Apr 9, 2000 Modified: 2001-07-26 21:17:22.905
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Benoit Xhenseval
(http://www.jguru.com/guru/viewbio.jsp?EID=3363
For sessions, your best bet is to have the servlet rewrite the URLs to include the
session information. With cookies read I am writing an application that retrieves a
URL, but that URL requires a cookie. Is there a way to hold that cookie within my
application and send it back to the URL when requested? Essentially, you can send
the cookie back easily with HTTP. For instance,
urlConnection.setRequestProperty("cookie",_cookie); Where the _cookie is coming
from a previous call: String _cookie = urlConnection.getHeaderField("set-cookie");
See also:
Multiple cookies are all sent on the same line, with some ungodly heinous delimiter
syntax. See the cookies spec and this FAQ for more details.
And did you your tests for more versions of java (1.1.4, 1.3, 1.4.2)? Is this
behaviour described in Applet specification or is it an accident?
ASP works only in IIS and Apache Server. It is also possible for these web servers to
run servlet programs by using a specific servlet engine.
You can invoke a servlet program from ASP by redirecting the request to the URL of
the servlet.
[Updated Nov 20, 2002 to remove old description and point at some articles. TJP]
jGuru.com Case-Study.
How can you logout a user (invalidate his Session) when a user directly
closes his browser window?
Location: http://www.jguru.com/faq/view.jsp?EID=34927
Created: Apr 11, 2000 Modified: 2000-06-21 15:33:13.885
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Jiger Patel (http://www.jguru.com/guru/viewbio.jsp?EID=30998
Short answer: you can't. Fortunately, sessions expire automatically after a period of
time; check your servlet engine documentation to see how to set this timeout period.
There is no onClose handler, it is the onUnload handler that you want. The problem
is you want a page to be 'loaded' when the window is closing. In order to load a page
you have to have a window.... So you would have to somehow abort the close (I
don't know if this is possible), or open a new window with your URL, and rely on that
document to close it's own window (which I have seen pop up a dialog box warning
on occasion...)
If anyone figures out a way to make this work, please let us know.
I decided to make the best of a bad situation, and after a View Source, I composed the
following solution to this question. I haven't actually tested it in a JSP server yet, but
it should work.
unload.html:
<script language="JavaScript">
<!--
function UnLoad() {
window.open("close.html");
}
// -->
</script>
<body onUnload='UnLoad()'>
</body>
close.jsp:
</script>
<body onload='Load()'>
Session invalidated
</body>
The only thing I don't know is, if the close.jsp will actually get called before the
window closes. If it does not, then you can get similar behavior by using
window.open("close.jsp", "closer");
where specifying the name "closer" is opens a second window that then loads
close.jsp. Unfortunately, as Daniel mentioned, this second close brings up a dialog
box asking the user if it's OK to close the window.
All things considered, you're probably better off letting the session die of natural
causes.
Hi,
Thanks
Shiva
This method is not possible to implement using just the servlet session API,
since there is no way(to my knowledge anyway) to query a live session's state,
let alone a dead one.
Hope this helps.
Thanks Shiva
It looks me the above approach works for http communication between Applet
and Servlet in both IE and Netscape browsers. When I tried to convert http
calls to https then this technique works only in IE. While closing the
browser,Netscape doesn't send any commands to the server.I really don't know
why it doesn't work for https communication? or because f security issues it
won't send ny commands to the server. It throws FileNotFoundException for
the url.
Thanks
Shiva Dacherla
Alternative way
Author: Yan Shtarker (http://www.jguru.com/guru/viewbio.jsp?EID=547411), Nov
14, 2001
Couldn't you just force that same window to open again when the user exits using quit
or close. This will allow you to provide an Exit or Logout button on the page which
the users would have to use in order to exit that page.
My question is, how can you call on invalidate() in a jsp session using this
button?? It doesn't seem clear how html or javascript for that matter can be used to
call on JSP objects like httpsession.
Regrads,
Yan
Solution overview:
Watch-dog style popup window which periodically checks the status of the window which ope
location to the logout page, which clears session data from the users table. Limitations:
• JavaScript-and-popup-based; this approach will have limited use out on the WWW.
• Tested in Mozilla 1.4, Opera 7.1. NOT tested in NS or IE.
1) Include the JS function to show the popup watchdog window into every (generated) page:
function PopupWatchdog()
{
var sWDURL = "watchdog.php";
var sOWin;
var sWinName = "wdwin";
var sWinOpts =
"align=center,location=no,menubar=no,titlebar=no,toolbar=no,height=54,width=
sOWin=window.open(sWDURL, sWinName, sWinOpts);
sOWin.blur();
window.focus();
}
function startWatching()
stopWatching();
timerID = setInterval("doLogout()",800);
timerRunning = true;
function stopWatching()
if(timerRunning) {clearInterval(timerID) };
timerRunning = false;
}
function doLogout()
stopWatching();
self.location='logout.php?forced=1';
window.resizeTo(800,600);
startWatching();
</SCRIPT>
</HEAD>
<BODY onload="startWatching();" BGCOLOR="#000000" onUnload="stopWatching();">
</BODY>
</HTML>
Notes:
a) In Opera, the popunder works - it goes behind the current window, this doesn't work in Moz
b) In Opera, at least, once the parent window is closed, 'window.opener' returns null or undefin
accessible after the window is closed, but that's untrue for Opera at least.. that's why I'm check
behave differently..??
d) It used to be watchdog.html earlier, I switched it to php to stop it being cached by the brows
whatever cache-control directives work for JSP (please pardon my ignorance- never worked w
e) I keep the window small initially to avoid irritating the user when it first pops (up/under), th
to what you want!
Well, that's it - hope this helps someone!
Regards,
Edgar D'Souza
(e d g a r =at= l i n u x =dot= n e t)
Not really. You shouldn't be concerned about thread management when writing a
servlet. Leave that up to the servlet engine. It may be using techniques like thread
pooling, load balancing, and activation/passivation strategies to optimize
performance. In fact, most EJB servers do use thread pooling "behind the scenes."
All you need to worry about as a servlet author is that your servlets are thread-safe.
See this FAQ for more details on thread safety and servlets.
If you want to spawn threads on your own, say to run a chat server, you may use
thread pooling, but make sure you understand the interaction with the servlet
engine.
If you want to share data between servlets, you can use Attributes. See the
documentation on ServletContext for more information.
If you want to open up, for example, several JDBC connections that will be shared
among several servlets, you can define a "behind the scenes" initialization servlet
that has an init() method that opens the connections and adds them as Attributes.
You then configure your servlet engine to initialize that servlet on startup (rather
than on request). That way as soon as the engine boots, your init servlet will run and
open the connections. (This servlet may never be called on its own! You can leave
the service method undefined, or provide status or debugging information.)
Also, naturally, you should remember to close the connections in the servlet's destroy
method.
I believe JRun and Java Web Server both support servlet chaining (in non-standard
ways, naturally). If you know of any others that do, please submit a feedback.
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().
See also:
• How do I support both GET and POST protocol from the same Servlet?
• How does one choose between overriding the doGet(), doPost(), and service()
methods?
• What is the difference between POST and GET methods? What about PUT,
DELETE, TRACE, OPTIONS, and HEAD?
Re: Basically the browser always asks for pages via GET,...
Author: Jandler Mayer (http://www.jguru.com/guru/viewbio.jsp?EID=910380),
Jun 17, 2002
Sending data via GET also brings up a security issue since they (data) are
appended in the URL. It would be very bad to see something like password there.
As a rule of thumb, if you need to send data, you are better off with POST for
various reasons that are mentioned above.
The alternative would be to scan the whole page looking for URLs which is nasty and
unreliable and slow. This way it's just nasty :-)
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? :-)
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.
How can I determine the name and version number of the servlet or JSP
engine that I am using?
Location: http://www.jguru.com/faq/view.jsp?EID=35085
Created: Apr 11, 2000 Modified: 2000-06-21 15:58:37.148
Author: Govind Seshadri (http://www.jguru.com/guru/viewbio.jsp?EID=14) Question
originally posed by Govind Seshadri PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=14
Doesn't work
Author: Kevin St. Clair (http://www.jguru.com/guru/viewbio.jsp?EID=1192485), Aug
11, 2004
I believe your suggestions return the Application server versions.
Servlet Engine:
<%= session.getServletContext().getMajorVersion()
%>.<%= session.getServletContext().getMinorVersion() %>
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:
javax.servlet.http.HttpUtils
I took your suggestion but sent your "file" through a StringTokenizer to get just the
directory path. I then used this path to create our URL. I used this URL as a "BASE
HREF" in our JSP, which appears to have cleared up our problem.
Yes you can. SAP has provided classes for its BAPI methods that you can you use in
your servlets. Those are available from your SAP front-end CD. Also you will be
needing middleware to connect to SAP from your servlets.
Comments and alternative answers
Do you mean that by using JCO, I just need the JCO lib in my tomcat and
servlets can use the available classes in the JCO?
According to the Servlet Specification 2.2 (not the generated API documents, which
are vague on the matter), the object returned is an array of type
java.security.cert.X509Certificate.
The KavaChart software, a commercial Java based solution for charts and graphs, is
the only servlet based solution of which I am aware.
Comments and alternative answers
Also, see the Purple Servlet Resource List, in the images section.
• Currently Microsoft Explorer has VML built in, so you can send VML directly
(in the Microsoft site you can find a VML graph example).
• Another solution is SVG. You can find a hands-on example of XML2SVG
transformation with XSL in Transforming XML into SVG . The result can be
transformed in PDF with SVG2PDF or in JPG with the IBM SVG viewer or
with any other viewer (the CSIRO SVG Viewer is easy to use) and the result is
sent to the client.
• Another possibility is to send SVG data to the client and use a plugin like the
ADOBE SVG plugin or an applet with a Java Viewer like the IBM SVG
viewer or with any other viewer.
Re: JFreeChart
Author: David Gilbert (http://www.jguru.com/guru/viewbio.jsp?EID=19371), Mar
22, 2002
Just a note that JFreeChart is still under active development and has moved to:
http://www.object-refinery.com/jfreechart/index.html
Regards,
Dave Gilbert
www.object-refinery.com
Re[2]: JFreeChart
Author: Guido Laures (http://www.jguru.com/guru/viewbio.jsp?EID=948147),
Jul 13, 2002
Cewolf is a JSP tag library based on JFreeChart. See
http://cewolf.sourceforge.net
• MonarchCharts
• Protoview JFCSuite PowerChart
• ExpressChart
<HTML>
<SCRIPT>
function display()
{
data.transformNodeToObject(ss.XMLDocument,
resultTree.XMLDocument);
document.write(resultTree.xml);
}
</SCRIPT>
<XML id="data"></XML>
<XML id="ss"></XML>
<XML id="resultTree"></XML>
</HTML>
Here "../servlet/SQLResult" is a servlet URL.
Comments and alternative answers
Javascript + Servlet
Author: Ashish Malgi (http://www.jguru.com/guru/viewbio.jsp?EID=768237), Feb
22, 2002
Why are you giving example of XML ? Give normal example of Javascript code
using tags like < SCRIPT language="Javascript"> <----- YOur code -----> <-- Servlet
invokation --> </Script>
What is the difference between Java Servlets and Java ServerPages (JSP)?
Location: http://www.jguru.com/faq/view.jsp?EID=39696
Created: Apr 24, 2000 Modified: 2000-11-08 21:03:36.084
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Rasto Toscak
(http://www.jguru.com/guru/viewbio.jsp?EID=37399
Medium answer: Both use server-side Java to dynamically generate web pages. The
source code to a JSP looks like HTML, with Java embedded inside funny tags (*); the
source code to a servlet looks like Java, with HTML embedded in out.print(...)
statements. Both use the Servlet API to communicate with the web server and the
client. In fact, a JSP gets compiled into a servlet, so they're almost identical in terms
of expressive power. The choice is, whether you're more comfortable coding your
pages in Java or in JSP-style HTML; and since you can call a JSP from a Servlet and
vice versa, you don't have to make an either-or decision.
Long answer: See the Servlet FAQ and the JSP FAQ for all the information you need
about both technologies.
(*) "Funny tags:" JSP can contain (a) normal HTML tags, (b) JSP tags like
<jsp:include>, (c) custom tags, (d) scriptlets (Java code surrounded with <% and
%>).
To understand what "server push" means you must remember that the web operates
in an event-driven way; the events can come from clients or servers.
• In the normal Web client-server scenario, the browser asks the server for the
web pages. This is called "pull", because the client "pulls" the data from the
server. The events, in this case, come from the client.
• Sometimes it is necessary to have the server send data to the client; a typical
case is that of stock data, which must change constantly on the web page to
remain in sync with actual data, even if the client doesn't request it by
clicking on a request button. This is called "push", because the server
"pushes" the data to the client. The events, in this case, come from the
server.
[However, even with so-called server-push, the server cannot actually initiate a TCP
connection to the client. Instead, the server leaves the initial connection open; after
the first chunk of data (a whole page, or a partial page, or a single image) is sent,
the client is then waiting around for the server to send the next piece of information.
Note that this means that the server has to keep its sockets open, which can be
expensive. Using an HTML Refresh (e.g. <META HTTP-EQUIV="Refresh"
CONTENT="4;URL=http://www.example.com">) may be a better solution. -Alex]
On Javaworld you can find an explanation on how to implement server push with
servlets in Pushlets, Part 1: Send events from servlets to DHTML client browsers. It
describes of a pushlet framework.You may visit the pushlet Website through
http://www.justobjects.nl/ to see how development is progressing, to run examples,
and to download the framework source.
Pushlets
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Dec 4, 2002
See Pushlets. They also have a yahoo group at:
http://groups.yahoo.com/group/pushlet/
Yes. In the following code, pageName is a String containing the URL to include.
String encodedPageName = response.encodeUrl(pageName);
this.getServletConfig().getServletContext().getRequestDispatcher(enco
dedPageName).include(request, response);
How do I build Apache with DSO support, to use Tomcat and mod_jserv?
Location: http://www.jguru.com/faq/view.jsp?EID=40693
Created: Apr 26, 2000 Modified: 2000-06-21 15:42:24.376
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)
You have to add the '--enable-module=so' option to your 'configure' call in order to
enable DSO, i.e.:
./configure --prefix=/usr/local/apache
--enable_rule=SHARED_CORE --enable-module=so
(Thanks to Peter Theill from the Tomcat User Mailing List.)
Comments and alternative answers
Personally I am using the Jigsaw Web Server from the World Wide Web Consortium
and I do not encouter the problem: if I send a redirect the new page automatically
loads.
Another possibility is to send a META refresh as a response page, so that the browser
calls the page you want to redirect to after your response loads. To be sure, put the
redirect link on the page, just in case.
TempWriter.print("<HTML><HEAD>"+
"<META HTTP-EQUIV=\"Refresh\"
CONTENT=\"5";URL=\""+PageName+"\">"+
"</HEAD><BODY>Redirecting to: <A href="+PageName+"
\">"+PageName+"</A></BODY></HTML>");
TempWriter.flush();
TempWriter.close();
Comments and alternative answers
You can append a phony argument to the end of the URL so the browser doesn't think
you're redirecting to the same page:
response.sendRedirect( "/myUrl?phony=baloney" );
Where do I store image files so my servlet's HTML pages can display them?
Location: http://www.jguru.com/faq/view.jsp?EID=41060
Created: Apr 27, 2000 Modified: 2000-06-21 15:44:48.111
Author: Nicola Ken Barozzi (http://www.jguru.com/guru/viewbio.jsp?EID=39153)
Question originally posed by viren s
(http://www.jguru.com/guru/viewbio.jsp?EID=31692
Anywhere you want [under your server's document root], just remember to use the
correct path relative to the one of the servlet.
A servlet is seen by the browser just by its URL. Browsers doesn't see the difference
between a file, a servlet or a JSP. Servlets are usually grouped in a directory which is
mapped to a directory URL. [You must put the image files in a directory off of the
document root, which is not where the servlet class files are, but will probably be
near JSP and HTML files. -Alex]
-root
|
-servlet
| |
| *MyServlet
| *TestServlet
|
-images
| |
| *Duke.gif
| *Web.gif
|
-MyHtmlFiles
|
*Main.html
*Login.html
Here the servlet and the MyHtmlFiles directory are in the same position relative to
the images directory. This means that you should write the link to the image in the
servlet as you would in the html files in the MyHtmlFiles directory.
<img src="../images/Duke.gif">
or
<img src=" /images/Duke.gif">
Retrieving cookie data is a little awkward. You cannot ask for the cookie with a
specific key. You must ask for all cookies and find the specific one you are interested
in. And, it is possible that multiple cookies could have the same name, so just finding
the first setting is not always sufficient. The following code finds the setting of a
single-valued cookie:
int sum = 0;
Cookie theCookie = null;
Cookie cookies[] = request.getCookies();
if (cookies != null) {
for(int i=0, n=cookies.length; i < n; i++) {
theCookie = cookies[i];
if (theCookie.getName().equals(SUM_KEY)) {
try {
sum = Integer.parseInt(theCookie.getValue());
} catch (NumberFormatException ignored) {
sum = 0;
}
break;
}
}
}
Also, Jun Inamori has written a great tutorial walkthrough on compiling and installing
Apache with Tomcat and JServ at http://www.oop-reserch.com/tomcat_3_1/.
http://apache.wrox.co.uk/projsp/chap05/index.shtml#74
Comments and alternative answers
Also
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Sep 18, 2001
http://www-105.ibm.com/developerworks/education.nsf/dw/java-onlinecourse-bytitle
See: Building a Java chat server
And...
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Dec 23, 2001
My own MessageServer chat server doesn't have a servlet interface yet, but it'd be
great if you'd like to write one...
}
Good luck!
Comments and alternative answers
Get the cookie from the request object and use setMaxAge(0) and then add the
cookie to the response object.
See also How can I delete a cookie from within a JSP page?
Comments and alternative answers
Not working
Author: alpesh shah (http://www.jguru.com/guru/viewbio.jsp?EID=968357), Jul 29,
2002
I tried to delete cookie by setting MaxAge to 0 but when i again tried to get cookie
from the request object on next page it returned same cookie with 0 maxage (got from
getMaxAge()) and again on next page i could retrieve same cookie with cookie's
getValue() method.I don't want cookie to be retrieved once i delete it.But even after
deletion cookie file exist and cookie is always available even after setting MaxAge to
0.Can't I remove cookie file?
c.setMaxAge(0);
response.addCookie(c);
Best Regards
In the Java Servlet Specification v2.2, section 6.1, support has been added which
gives the servlet developer a lot more information and at least some hope of portably
being able to control the buffering.
It depends on the servlet engine. Each has its own type of config file in which you
can set the names and values of init parameters; these get passed to the servlets (or
JSPs) via the getInitParameter() call.
For Tomcat and JSWDK, edit the conf/web.xml file. See also this FAQ.
Please add information about other servlet engines as feedback to this FAQ.
Feedback to this FAQ has additional information about initiating an HTTP connection
from Java.
Java:API:Servlets:Message Passing
Author: Peter Forrest (http://www.jguru.com/guru/viewbio.jsp?EID=717754), Jan 12,
2002
The most straight-forward means of communication by Servlets on separate servers is
using HTTP, according to the Java (tm) Tutorial.
In servlets however, only one process is spawned, and that process contains the JVM.
Each request will cause the JVM to create a new thread that will be responsible for
creating the output that will be the result. Creating a thread requires much less
resources to start up, both CPU and memory.
This approach can make servlets much more efficient than even an optimized C
program acting as a CGI, simply because of the much reduced overhead.
However, there are upcoming standards around CGI that use the same approach with
threads instead of processes, such as the Perl FastCGI module. So the above holds
true for the comparision with a 'normal' CGI, not necessarily with all variants.
Undoubtedly there are other advantages, but I stop here. I just want to add that:
How can I get the version of the Servlet API that is being used by a
servlet/JSP engine?
Location: http://www.jguru.com/faq/view.jsp?EID=43716
Created: May 2, 2000 Modified: 2000-06-21 16:01:18.957
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Sajeev Anand
(http://www.jguru.com/guru/viewbio.jsp?EID=14623
So, for example, JSWDK 1.0.1, which supports the Servlets spec 2.1, would return
"2" for getMajorVersion() and "1" for getMinorVersion().
From a JSP, you can use the implicit application object to access the ServletContext.
For example:
Major: <%=application.getMajorVersion()%>
Minor: <%=application.getMinorVersion()%>
Jason Hunter's com.oreilly.servlet package has some code for determining this in an
allegedly more robust manner.
See also How can I determine the name and version number of the servlet or JSP
engine that I am using?
Minor: <%=application.getMinorVersion()%>
What servlet engines support clustering -- that is, sharing of session data
across multiple load-balanced web servers?
Location: http://www.jguru.com/faq/view.jsp?EID=44035
Created: May 3, 2000 Modified: 2001-05-21 16:06:51.894
Author: Chanan Braunstein (http://www.jguru.com/guru/viewbio.jsp?EID=44032)
Question originally posed by John Mitchell PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=4
[Short list:
• JRun 3.0
• IBM WebSphere
• BEA WebLogic
• Enhydra (open-source app server from Lutris)
JRun 3.0 (Right now in RC1) will support clustering with an add-on. check
http://www.allaire.com for info.
The WebSphere Performance Pack also has a load balancer called Secureway
Network Dispatcher.
[Monte Kluemper:]
WebLogic server has supported robust clustering of servlets, EJBs, etc. for over a
year!
<Context path="/YourContext">
.......
<Manager className="org.apache.catalina.session.PersistentManager"
debug="10"
checkInterval="1"
saveOnRestart="true"
maxActiveSessions="-1"
minIdleSwap="-1"
maxIdleSwap="0"
maxIdleBackup="0">
<Store className="org.apache.catalina.session.JDBCStore"
debug="100"
connectionURL="jdbc:mysql://localhost/tomcat?user=abc&password=efg"
driverName="org.gjt.mm.mysql.Driver"
sessionDataCol="session_data"
sessionIdCol="session_id"
sessionLastAccessedCol="last_access"
sessionMaxInactiveCol="max_inactive"
sessionTable="tomcat.tomcat_sessions"
sessionValidCol="valid_session">
</Store>
</Manager>
.......
</Context>
Hope that future version of Tomcat will have sth. like RealTimePersistentManager.
The JRun product from Allaire adds a global.jsa file with events for session and
application.
Comments and alternative answers
using global.jsa
Author: Pankaj Modi (http://www.jguru.com/guru/viewbio.jsp?EID=387091), Apr 2,
2001
Is global.jsa supported by "all jsp supporting web servers" or just "JRun"?
disagree as well
Author: Frans Verhoef (http://www.jguru.com/guru/viewbio.jsp?EID=428343), May
25, 2001
sessions are only good as long as you're happy using them in only one context. It
doesn't even work everywhere on the same domain.
Disadvantage
Author: Horatiu Ripa (http://www.jguru.com/guru/viewbio.jsp?EID=752343), Feb 12,
2002
The main disadvantages of session:
1. Often they make your pages statefull, that means that refresh, back, forward
buttons can be a problem. Also opening a new window (Ctrl+N or file/new/window)
opens a new window in the same session, and there's a lot of mess with that, both
browsers are changing the same session. In my experience I had problems even with
different instances of the IE on the same machine. You are highly dependent on the
correct implementation of the web server.
2. If you want to use server clusters, because you are using session the user is directed
to the same server (the sessions are not common for different servers, and you'll have
to use a statefull type), so when a server fails, all the users connected to that server are
disconnected. All the other techniques does not require statefull clusters, and if your
pages are stateless, they are automatically redirected to another server without any
problem for the user. Also the loading is better balanced.
But the decision you have to take is depending on the particular app you are
developping.
How do I pass session information from a JSP to a Applet. Can I pass them
as parameters or can I talk back from an Applet to the JSP page?
Location: http://www.jguru.com/faq/view.jsp?EID=45661
Created: May 7, 2000 Modified: 2000-08-14 10:15:35.454
Author: Pete Lyons (http://www.jguru.com/guru/viewbio.jsp?EID=41793) Question
originally posed by David Sanderson
(http://www.jguru.com/guru/viewbio.jsp?EID=44421
The easiest way to pass session info is through the applet parameters. The following
example code uses some scriptlet tags to set the parameters of the applet.
<applet code="foo.class" width="100" height="100">
<%
for (x = 0; x < session.fooData.getCount(); x++) {
%>
<param name="<%= session.fooData.getName(x) %>"
value="<%= session.fooData.getValue(x) %>">
<% } %>
</applet>
If you want to have the applet be able to talk back to the server as it runs you can
do that too. In this case the applet should not communicate with the JSP that hosted
it but rather with a servlet running in the same web application. Both the JSP and the
servlet would share the same session info so you have access to the same data. The
following example uses serialized object to pass the information back and forth but
you could form the requests and responses with plain text or xml or whatever. The
applet needs to open a connection to the web application, post a request and listen
for the response.
try {
// Open the connection
URL url = new URL(getCodeBase(), "myServlet");
URLConnection uc = url.openConnection();
The servlet that handles the post would be pretty simple too. It just needs to read
the request, figure out what the request was and return the correct data.
try {
// Read the resquest
ObjectInputStream ois =
new ObjectInputStream(req.getInputStream());
MyRequest myRequest =
(MyRequest) ois.readObject();
However, there's nothing keeping you from writing your own state management
code, using URL rewriting, hidden fields, or the like, for use in parallel windows on
the same machine.
The easiest thing to do is not to worry about the session, but to send a parameter from
the client (as a hidden field in a form, or a GET parameter in the URL) each time the
client makes a request. This parameter could specify the doctor, so that the servlet
would return information on the doctor appropriate to each page.
If you are really hooked on having a separate session for each, you will need to use
URL rewriting as a means of specifying the session ID on each page. If you try to use
a cookie-based system, it will be defeated by users who hit their browsers' forward
and back buttons instead of using the navigation tools that you provide.
see
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Feb 2, 2002
see Getting duplicate session id
Consider this..
Author: S M (http://www.jguru.com/guru/viewbio.jsp?EID=1059986), Feb 24, 2003
Refer to the below link.
http://developer.java.sun.com/developer/bugParade/bugs/4223650.html
In this page, there is a reference to another bug 4109888. Now when I click on the
link, am taken to a page about 4109888. But when I do a right-click and "open in new
window", I am taken to a login page.
Now both windows were created off the same browser instance, so how was the
server able to distinguish between the two windows of the same instance?
See also this question in the JSP FAQ for a list of JSP-using sites.
How do you manage sessions if the web servers are load balanced onto
more than one server?
Location: http://www.jguru.com/faq/view.jsp?EID=46481
Created: May 9, 2000 Modified: 2000-05-10 17:11:21.008
Author: Nicola Ken Barozzi (http://www.jguru.com/guru/viewbio.jsp?EID=39153)
Question originally posed by Pedro Jr. Urgello
(http://www.jguru.com/guru/viewbio.jsp?EID=16961
Distributed Applications
A few clarifications were also made in 2.2 with regards to distributed applications, in
which application components can be spread across multiple back-end server
machines.
How does one choose between overriding the doGet(), doPost(), and
service() methods?
Location: http://www.jguru.com/faq/view.jsp?EID=47730
Created: May 11, 2000 Modified: 2000-08-10 10:06:08.528
Author: Nicola Ken Barozzi (http://www.jguru.com/guru/viewbio.jsp?EID=39153)
Question originally posed by Amit Srivastava
(http://www.jguru.com/guru/viewbio.jsp?EID=46445
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().
See also:
• How do I support both GET and POST protocol from the same Servlet?
• What is the difference between the doGet and doPost methods?
• What is the difference between POST and GET methods? What about PUT,
DELETE, TRACE, OPTIONS, and HEAD?
What is the best way of implementing a web application that uses JSP,
servlet and EJB technologies all together following a Model View Controller
(MVC) architecture?
Location: http://www.jguru.com/faq/view.jsp?EID=48001
Created: May 11, 2000 Modified: 2000-06-21 11:05:30.729
Author: Dan Christopherson (http://www.jguru.com/guru/viewbio.jsp?EID=39644)
Question originally posed by christophe hillegeer
(http://www.jguru.com/guru/viewbio.jsp?EID=43669
[See the Sun J2EE Blueprints for "an integrated set of documentation and examples
that describe and illustrate 'best practices' for developing and deploying component-
based enterprise applications using the J2EE platform" including some good
architecture whitepapers and source code. -Alex]
Hmm, 'Best Way' is a bit rough - there are several 'good' ways, and the usual set of
trade-offs between them. (I'm a consultant - I have to start any answer with "It
depends...", otherwise they revoke my whiteboard privileges)
The main thing you need to keep in mind as you design this sort of a system is that
you want the interface into the EJB's to be rather narrow: in any flow, the ideal is to
call one EJB method (hopefully on a stateless session bean), and let it make calls to
entities on your behalf, then hand back the data you need to display.
How you display it depends: you can either embed beans on your JSPs and let the
beans make that hopefully-one EJB call, or you can post to a servlet, let that make
the call, then forward to the JSP for display. The second of these is more flexible and
gives you more leverage to hide, change, and enforce your site's structure. The first,
however, will be easier for developers new to this web thing to follow.
Essentially, I'm saying that Entity beans are your model, your controller is Session
beans (maybe with a bit of help from servlets or beans), and your JSPs, beans and
servlets are your View.
One thing to note here: this discussion strongly implies that your EJBs are capable of
externalizing their state as some number of very simple 'value objects' (not EJBs
themselves, just something we can pass back and forth). These value objects are
probably tuned tightly to a workflow, and will be produced by that session bean. This
way the traffic between the EJB (server) and the JSP/Servlet (client) is tuned to what
the client needs, while the transaction load on the server is minimized.
The architecure involves a MVC with the controllers being entity and session beans.
We are moving away from using entity beans unless there are many transactions
involved. These ejbs pass back value objects as specified in the blueprints by sun.
We also use bulk accessor session beans which go directly to the database and also
call some other session or entity beans.
J2EE architecture
Author: Mindy Couleur (http://www.jguru.com/guru/viewbio.jsp?EID=1175354), Jun
1, 2004
I am new to J2EE and am wondering if you can expand on your answer a bit. I've
noticed that much of the logic that I see in Servlets could go in EJB's. I'm wondering
just how thin the servlet layer should be. I also would like to confirm some RMI logic
flow. As far as I understand..... JSP calls Servlet Remote interface then Servlet call
EJB remote interface....reply goes back to servlet then servlet forwards to JSP for
display. Is that considered the best way to separate the layers?
Sending WML is no different than sending back HTML. The only difference is you
have to setup the MIME type in the response:
response.setContentType("text/vnd.wap.wml");
IMHO yes.
We are presently running Tomcat (servlet & jsp requests) with Apache (graphics,
perl, html) on 9 Solaris/Sparc servers servicing over 10 million servlet/jsp
transactions per day.
I need to determine a version of tomcat and apache plus the connector module. I think
knowing what you are using will help greatly.
Could you let me knw what version of the following you are using?
jdk:
solaris:
apache:
tomcat:
Do you have any pointers on documentation, other than the jakarta project docs?
Did you use any special configuration that deviated from what any jakarta docs say or
reccommend?
Thanks,
-Bronson
Chances are you have an "=" char in the value of your cookie. Make sure you URL
encode the value of your cookie before setting it.
How do servlets differ from RMI? What are the advantages and
disadvantages of each technology?
Location: http://www.jguru.com/faq/view.jsp?EID=49828
Created: May 16, 2000 Modified: 2000-06-21 16:29:19.035
Author: Shaun Childers (http://www.jguru.com/guru/viewbio.jsp?EID=30243)
Question originally posed by mehdi lababidi
(http://www.jguru.com/guru/viewbio.jsp?EID=48184
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.
For more detailed information regarding servlets and RMI refer to following sun sites:
http://www.java.sun.com/products/servlet/index.html and
http://developer.java.sun.com/developer/onlineTraining/rmi/ [(the last link is a
tutorial by JGuru!)].
How can I call one servlet from another servlet, where each of them is at a
different web server?
Location: http://www.jguru.com/faq/view.jsp?EID=50791
Created: May 17, 2000 Modified: 2003-01-08 15:28:50.432
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Venkateswaran Muthuswamy
(http://www.jguru.com/guru/viewbio.jsp?EID=47714
See How can my applet communicate with my servlet? and How do I call one servlet
from another servlet?
Servlets are effectively a Java version of CGI scripts, which are written in Perl, C,
C++, UNIX shell scripts, etc. There are however, a few important differences.
When a CGI program (or script) is invoked, what typically happens is that a new
process is spawned to handle the request. This process is external to that of the
webserver and as such, you have the overhead of creating a new process and
context switching, etc. If you have many requests for a CGI script, then you can
imagine the consequences! Of course, this is a generalization and there are wrappers
for CGI that allow them to run in the same process space as the webserver. I think
ISAPI is/was one of these.
Java Servlets on the other hand actually run inside the webserver (or Servlet
engine). The developer writes the Servlet classes, compiles them and places them
somewhere that the server can locate them. The first time a Servlet is requested, it
is loaded into memory and cached. From then on, the same Servlet instance is used,
with different requests being handled by different threads.
Of course, being Java, the compiled Servlet classes can be moved from one Servlet
compatible webserver to another very easily. CGI programs or scripts on the other
hand may be platform dependent, need to be recompiled or even webserver
dependent.
Take a look at the Servlet product page for more details about Servlets.
Where can I find a method that returns a properly escaped HTML string
from a given string of raw HTML?
Location: http://www.jguru.com/faq/view.jsp?EID=51171
Created: May 18, 2000 Modified: 2000-05-18 07:48:14.63
Author: Rob Edmondson (http://www.jguru.com/guru/viewbio.jsp?EID=35309)
Question originally posed by Sharif Rahman
(http://www.jguru.com/guru/viewbio.jsp?EID=47415
[FAQ Manager note: See also How can an applet or application pass parameters to
and read output from a CGI script? .]
Comments and alternative answers
Is this question about encoding URL GET parameters, i.e. changing spaces to '+', or
about encoding data to be displayed on an HTML page that may have '<','>', and '&' in
it?
You've given the answer for the first, but not the case of of HTML escape encoding.
You'd want to do this if you're writing a guestbook (or FAQ entry system) and you
don't want the submitter to be able to submit HTML. I ended up writing a small loop
using StringBuffer.replace() to replace '<' with '<', etc.
I rolled my own
Author: Greg Wolfe (http://www.jguru.com/guru/viewbio.jsp?EID=426310), May 22,
2001
The encoding/decoding is fairly simple. The character set that HTML encoding uses
is ISO-8859-1. Here is a useful table:
private static String[] specialCharsTable =
{
null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null,
-gwolfe
Yes, there is a bug in Tomcat 3.1 (and possibly other servlet engines). To send a
cookie through a redirect, you must set the headers manually. [email protected]
suggests:
Cookie long_term = new Cookie(LONG_TERM_COOKIE_NAME, user_name);
long_term.setMaxAge(60*60*24*4);
long_term.setPath("/Blah");
response.addCookie(long_term);
response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
response.setHeader("Location",REDIRECT_PAGE);
Comments and alternative answers
Your solution works perfectly.
Author: Shalabh Nigam (http://www.jguru.com/guru/viewbio.jsp?EID=47481), May
22, 2000
Your solution works perfectly.
In such a case(cookies getting mixed up)too do you think that setting the headers
manually would prevent the problem?
Thanks
Anbu
What servlet code corresponds to the various "scope" values for the
<jsp:useBean> tag?
Location: http://www.jguru.com/faq/view.jsp?EID=53309
Created: May 21, 2000 Modified: 2002-10-30 23:00:49.748
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)
The jsp:useBean tag is very powerful. It allows you to declare a variable using a
single syntax, but produces code that (a) either initializes the variable, or locates it if
it's already been initialized, and (b) stores it in one of a number of locations,
depending on its scope.
In order to share variables between JSPs and Servlets, you need to know how to
create and to access variables from inside your servlet code. Following are examples
which should help you understand how to do this.
----------------------------------------------------------------------
In this example, when the Counter bean is instantiated, it is placed within the servlet
context, and can be accessed by any JSP or servlet that belongs to the application
(i.e. belongs to the same servlet context).
foo.Counter counter =
(foo.Counter)getServletContext().getAttribute("counter");
if (counter == null) {
counter = new foo.Counter();
getServletContext().setAttribute("counter", counter);
}
----------------------------------------------------------------------
In this example, when the Counter bean is instantiated, it is placed within the
current session, and can be accessed by any JSP or servlet during a subsequent
request by the current user.
In this example, when the Counter bean is instantiated, it is placed within the
current request object, and can be accessed by any JSP or servlet during a the same
request; e.g., if a RequestDispatcher is used, or if <jsp:include> or <jsp:forward>
sends the request to another servlet or JSP.
foo.Counter counter =
(foo.Counter)request.getAttribute("counter");
if (counter == null) {
counter = new foo.Counter();
request.setAttribute("counter", counter);
}
----------------------------------------------------------------------
In this example the Counter bean is instantiated as a local variable inside the JSP
method. It is impossible to share a page scope variable with another JSP or Servlet.
The servlet equivalent of the above useBean action is:
What servlet code corresponds to the various "scope" values for the
<jsp:useBean> tag?
Author: Sridhar kancharlapalli
(http://www.jguru.com/guru/viewbio.jsp?EID=479357), Aug 19, 2001
Re: What servlet code corresponds to the various "scope" values for the
<jsp:useBean> tag?
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Aug 20,
2001
Aw, shucks. You're welcome. :-)
Re: For jsp page script, more info about page scope.
Author: Roger Hand (http://www.jguru.com/guru/viewbio.jsp?EID=292314), Oct
2, 2001
Oops! Instead of
pageContext.setAttribute("counter", MyPhoneNumberBean);
it should've been . . .
pageContext.setAttribute("counter", counter);
(That's what I get for copy and pasting ...)
Do note for those of you using the older servlet/jsp APIs that you need to use
pageContext.setAttribute("counter", counter,
PageContext.SESSION_SCOPE);
pageContext.getAttribute("counter", PageContext.SESSION_SCOPE);
hope this works, if not please let me know how you are creating and storing the
bean in the servlet thanks, sreeni
Question
Author: mark faine (http://www.jguru.com/guru/viewbio.jsp?EID=1122412), Oct 18,
2003
In your example for request scope:
Is there really any need to check for the existence of the bean in the request scope? In
other words, wouldn't any subsequent access to the servlet be a new reqeust? I'm just
imagining the requestdispatcher being used to forward to a JSP/servlet, now unless
that JSP/servlet immediately forwards back to the servlet there would't be a need to
check the request context for the counter bean?
-Mark
Re: What servlet code corresponds to the various "scope" values for the
jsp:useBean tag?
Author: Steven Hines (http://www.jguru.com/guru/viewbio.jsp?EID=1131441), Dec
2, 2003
You, my friend, are an absolute hero!
One way to force servlets to go down the https path is to define your web server to
only allow secure connections when accessing servlets. In IIS this can be
accomplished through the definition if ISAPI filters. The ISAPI filter can instruct the
web server to route all requests that end with a pre-defined prefix to the servlet
engine. The trick is to then define files, with the predefined extension, in the web
servers directory. For example, if the servlet's name is MyServlet a file with the name
MyServlet.xxx would be placed on the web server. All calls to this file would be
routed to the servlet engine. And IIS would be used to force all calls to the
MyServlet.xxx file to go through https. The JRun servlet engine has examples of how
to do this documented on their web page.
The whole issue of propagation of authentication context from client to the EJB
server is still evolving - both in terms of the specification as well as vendor offerings.
According to the current Java 2 specification (page 224):
"the container is the authentication boundary between callers and components
hosted by the caller. For inbound calls it is the container's responsibility to make an
authentic representation of the caller identity available to the component".
The JAAS 1.0 specification extends the types of principals and credentials that can be
associated with the client but it is also evolving.
Thus given the container implementation that is required to drive this whole thing,
the answer depends on your app vendor - some like Weblogic (WLE), Websphere
provide security plug-ins/SDKs that can enable the propagation. Other vendors are
close behind. Check your vendor plug-in.
Can we pass security context from resin to weblogic?. Can JAAS help use
here?.
How can I cache the results of my servlet, so the next request doesn't have
to go through all the calculation / database access / other time-consuming
stuff all over again?
Location: http://www.jguru.com/faq/view.jsp?EID=54322
Created: May 23, 2000 Modified: 2000-05-26 17:01:45.921
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)
Jason Hunter, author of the O'Reilly Servlets book, has written a nice little class
called CacheHttpServlet. If your servlet subclasses CacheHttpServlet and overrides
one method, the superclass takes care of caching the last response.
Note that as written, it only caches one version; if you have multiple possible pages
based on request parameters, it won't be as effective. Someone should probably
extend this class to handle multiple pages.
What is the difference between POST and GET methods? What about PUT,
DELETE, TRACE, OPTIONS, and HEAD?
Location: http://www.jguru.com/faq/view.jsp?EID=56472
Created: May 25, 2000 Modified: 2000-08-10 10:06:51.465
Author: Simon Brown (http://www.jguru.com/guru/viewbio.jsp?EID=44588)
Question originally posed by Amisha Patel
(http://www.jguru.com/guru/viewbio.jsp?EID=52054
GET and POST basically allow information to be sent back to the webserver from a
browser (or other HTTP client for that matter).
Imagine that you have a form on a HTML page and clicking the "submit" button
sends the data in the form back to the server, as "name=value" pairs.
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 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!
The Servlet spec allows you to implement separate Java methods implementing each
HTTP method in your subclass of HttpServlet. Override the doGet() and/or doPost()
method to provide normal servlet functionality. Override doPut() or doDelete() if you
want to implement these methods. There's no need to override doOptions() or
doTrace(). And the superclass handles the HEAD method all on its own.
The full specs for HTTP are available (if you're interested) can be found on the
w3c.org site. See also the JavaDoc for HttpServlet.
[Edited/enhanced by Alex]
See also:
• How do I support both GET and POST protocol from the same Servlet?
• What is the difference between the doGet and doPost methods?
• How does one choose between overriding the doGet(), doPost(), and service()
methods?
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).
There are many of methods to accomplish this. One way is to use the Pager Tag
Library, recently discussed at Implementing Page Scrolling on the servlet mailing list.
You may also want to look through the list Archives for other ideas.
Comments and alternative answers
The problem with the ResultSet object in the JDBC1.2.2...
Author: Alexandros Kotsiras (http://www.jguru.com/guru/viewbio.jsp?EID=64209),
Jun 3, 2000
The problem with the ResultSet object in the JDBC1.2.2 version is that it is not
scrollable. It is scrollable in the latest JDBC2.0 version which only the latest versions
of the RDBMS support. Note that you can still use a JDBC2.0 Type 4 driver (eg.
classes12.zip for Oracle) with an RDBMS that does not support JDBC2.0 features
(like Oracle 8.1.5) but you won't be able to use the new JDBC2.0 functionality. The
new features can only be used if the RDBMS supports them by itself like Oracle
8.1.6.
I found very useful the CachedRowSet API from Sun which is an extension to
java.sql. After you create your ResultSet object you wrap it arround a CachedRowSet
object which is disconnected and scrollable. It's like putting all you result records in a
Collection object but the CachedRowSet does this job for you plus it offers all the
methods that you need to scroll like : next(), previous(), relative(numberOfRows),
getRow(rowPosition), size() (to determine the number of records in your ResultSet)
etc.
Then you just need to put it in the users session, retrieve from the next page, scroll to
the appropriate position and display a range of records.
The above approach might not be the appropriate one if you have a very large
ResultSet since the CachedRowSet object that you will store in the session will take a
lot of memory. For ResultSets of some hundrends of records you should be fine. It
can be downloaded from the Sun/JDBC page at http://java.sun.com/products/jdbc/
The servlet then uses the count in its logic to determine the next set of records to
display.
This is NOT the same as re-executing the query and somehow restricting the number
of values returned to a page-full.
I actually want the resultset retained on the server side, since it seems this would be
MUCH more efficient for complex ad-hoc multi-table join queries on large tables
(which is what we do.)
this sounds like a good idea but how can i retrieve the total number of records
even after I set the rownum range?
eg. select rownum y, emp_name from emp where city='newyork' the total
number of employees.
I need to retrieve the total number so that I can determine the number of pages
needed to display all the records. (with PageCount=RecordSize/PageSize)
where PageSize is the rownum range.
Pls help..
See also
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Feb 13, 2002
• How can I cache the results of my servlet, so the next request doesn't have to
go through all the calculation / database access / other time-consuming stuff
all over again?
Search Reasult
Author: Birendar Waldiya (http://www.jguru.com/guru/viewbio.jsp?EID=1131260),
Dec 1, 2003
One more way to acheive the result, in a page wise display of page r is by using
Scrollable ResultSet every time you want to get the next page shift the cursor to that
particular point in ResultSet.absolute(int) method.
How do I upload a file using a Java client (not a browser) and HTTP POST?
Many of the examples show how a HTML page can be constructed to select
the file and do the POST, but I need to do it from a java client.
Location: http://www.jguru.com/faq/view.jsp?EID=62798
Created: Jun 2, 2000 Modified: 2001-07-23 10:27:35.199
Author: Richard Raszka (http://www.jguru.com/guru/viewbio.jsp?EID=7963)
Question originally posed by Sean Woodhouse
(http://www.jguru.com/guru/viewbio.jsp?EID=14628
[Note: the following example works, but it does not encode the POSTed file in the
multipart/* format expected by servlets as described in How do I upload a file to my
servlet?. Perhaps another Guru could submit some feedback ...? -Alex]
Use the URLConnection class to upload a file to a web site and a servlet that
understands how to read that file.
import java.net.*;
import java.io.*;
try
{
HTTP_post post = new HTTP_post();
post.u = new URL("http://myhost/servlet");
// Read Response
InputStream in = uc.getInputStream();
int x;
while ( (x = in.read()) != -1)
{
System.out.write(x);
}
in.close();
}
catch (IOException e)
{
e.printStackTrace(); // should do real exception
handling
}
}
}
At Servlet end
Perform a getInputStream to read the input and send the data to a file.
Example:
InputStream in = request.getInputStream();
BufferedReader r = new BufferedReader(new
InputStreamReader(in));
StringBuffer buf = new StringBuffer();
String line;
while ((line = r.readLine())!=null) {
buf.append(line);
}
String s = buf.toString();
Comments and alternative answers
I agree with Alex, the approach I have taken is to provide a simple method to
demonstrate how to upload a file to a servlet
If a full HTTP Client is required. Then I would recommend HTTP_Client Version 0.3-
2 written by Ronald Tschalär.
This provides a reasonably complete client with multipart/* format if that is required.
Documentation is sufficient to write clients with the standard JavaDoc supplied, and
combined with the servlet found in How do I upload a file to my servlet? should
provide a solution to most situations.
import java.io.*;
import java.net.*;
InputStream is = null;
OutputStream os = null;
boolean ret = false;
String StrMessage = "";
String exsistingFileName = "C:\\account.xls";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
byte[] buffer;
String urlString =
"http://localhost:8080/FileUpload/requestupload";
try
{
//------------------ CLIENT REQUEST
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-
data;boundary="+boundary);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens +
lineEnd);
// close streams
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex)
{
System.out.println("From ServletCom CLIENT REQUEST:"+ex);
}
try
{
inStream = new DataInputStream ( conn.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
System.out.println("Server response is: "+str);
System.out.println("");
}
inStream.close();
}
catch (IOException ioex)
{
System.out.println("From (ServerResponse): "+ioex);
}
Thanks
Selva
i'm trying to make a http proxy (with some additional features) which is
able to forward multipart/form-data requests. I tried your code and it
works fine. There's only one drawback: files which come with the request
are fully written to the forwarding request before it is sent. How do i get
the request to be processed by the server while writing the files content at
the client (streaming behaviour)? Are there any other client
implementations able to do this?
Thanx a lot
Mirko
When you use readLine() to read data over a socket at the servlet end, you're
making the very bad assumption that the data is text, not binary. Don't do this.
Similarly, if you use println() to write data over a socket, you're assuming the data
is text and that the protocol uses the same line terminator as your client. You leave
yourself open to nasty problems if you do this.
Related FAQs:
• What's the difference between the JSDK and the JSWDK? And what's the
current version?
jo! 1.0b3
Author: Roger Chung-Wee (http://www.jguru.com/guru/viewbio.jsp?EID=448003),
Jun 30, 2001
Tomcat 4.0
Author: sachin walia (http://www.jguru.com/guru/viewbio.jsp?EID=472972), Sep 19,
2001
Tomcat 4.0 supports fully Servlet 2.3 (servlet filters) and JSP 1.2 including inbuilt
support for J2EE API's like javax.transaction.*, jndi, javax.sql.* thereby making all
the web applications hosted on it fully compatible with any major application servers.
When should one use applets and when should one use servlets?
Location: http://www.jguru.com/faq/view.jsp?EID=64403
Created: Jun 3, 2000 Modified: 2000-06-03 22:44:09.3
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by swati m (http://www.jguru.com/guru/viewbio.jsp?EID=64343
Applets run inside browsers, and servlets run inside servers. So broadly speaking,
use applets when you need dynamism on the client side, and use servlets when you
need dynamism on the server side.
Servlets can produce any HTML (or indeed, any file type), and therefore are much
more versatile than applets. Servlets can tailor the HTML they produce based on the
browser type (as specified in the "User-Agent" header), and thus can produce output
that will work in virtually any client, including WAP browsers or the like. Applets are
notoriously poorly supported, and even in browsers that ostensibly have Java
support, don't work consistently.
Servlets can also produce HTML with embedded JavaScript, which allows a fair
amount of dynamic behavior on browsers which support it.
However, due to the infuriating limitations and bugs in JavaScript, sometimes you've
just got to have an applet to get the client-side behavior you want. In these cases,
take comfort in the fact that you can generate HTML containing APPLET tags from
inside a servlet.
What is the best way to convert HTML to XML, separating the content(data)
from presentation in HTML? Are there any Java API's that we can make use
of?
Location: http://www.jguru.com/faq/view.jsp?EID=66681
Created: Jun 6, 2000 Modified: 2000-10-11 09:33:33.868
Author: Brill Pappin (http://www.jguru.com/guru/viewbio.jsp?EID=60239) Question
originally posed by Praveen Paranjay
(http://www.jguru.com/guru/viewbio.jsp?EID=40359
Try Cocoon and ECS, or JetSpeed from the Apache group (java.apache.org).
There aren't really any APIs specifically for doing this. What do you want to do with
the HTML-data after it has been converted to XML? If all you want to do is display it
again using different style-sheets you should consider converting the HTML to
XHTML. XHTML is simply an XML compliant form of HTML
If you want to convert the HTML to XML compliant with a DTD or schema of your own
making then doing it can pose many problems. It all depends on the HTML. Do all
the HTML-files use the same "template"? Then it is possible to write a program to
convert it. If they are all different it is probably easy to do it by hand.
Comments and alternative answers
Out of the box -- probably not unless MS started shipping the RMI classes. There's a
little bit of RMI used in the admin of Tomcat. Other than that, it should run just fine.
IBM has apparently packaged up the RMI classes missing from the Microsoft JVM and
is distributing them at http://www.alphaworks.ibm.com/formula/RMI. Other options
would be to get the RMI classes from Microsoft (although it is not clear they can be
redistributed), or to download the JDK from Sun and manually grab just the RMI
class, or just don't use the online administration tools that require RMI.
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.
Comments and alternative answers
How can I pass data retrieved from a database by a servlet to a JSP page?
Location: http://www.jguru.com/faq/view.jsp?EID=73439
Created: Jun 12, 2000 Modified: 2000-08-14 11:16:49.756
Author: Govind Seshadri (http://www.jguru.com/guru/viewbio.jsp?EID=14) Question
originally posed by senthil kumar
(http://www.jguru.com/guru/viewbio.jsp?EID=57182
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:
The bean can then be accessed within the JSP page via the useBean tag as:
If a servlet which does some significant task gets hit with enough
concurrent users, it will eventually throw a java.lang.OutOfMemory
exception. Is there a graceful way to handle/avoid this?
Location: http://www.jguru.com/faq/view.jsp?EID=64889
Created: Jun 13, 2000 Modified: 2000-06-17 13:01:57.72
Author: Simon Wong (http://www.jguru.com/guru/viewbio.jsp?EID=44276) Question
originally posed by J Majik (http://www.jguru.com/guru/viewbio.jsp?EID=61152
Because the initial memory occupied by the JVM is only 2Mb, you can assign more
memory for the JVM such that the OutOfMemory Error won't occur.
There is a non-standard parameter -Xmsn for the java launcher, where n is the
multiple of 1024 greater than 2Mb. See
http://java.sun.com/j2se/1.3/docs/tooldocs/win32/java.html for more about this
option.
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.
out.println("<html>");
out.println("<head>Your Title</head>");
out.println("<body>");
out.println("</body></html>");
out.close();
-------------------------- END
------------------------------------------
Where MenuServlet and DummyServlet provide content and behavior for the frames
generated by FrameServlet.
Hope this helps.
See http://www.coolservlets.com/developer/tips/tip...
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jun 14, 2000
See http://www.coolservlets.com/developer/tips/tip02.html
But see
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jul 23, 2001
But see Why do Frames suck? for the reasons not to.
From a servlet running in IIS under Windows, is it possible to kick off an rsh
command to run a script on a remote UNIX machine?
Location: http://www.jguru.com/faq/view.jsp?EID=69592
Created: Jun 14, 2000 Modified: 2000-06-14 13:41:34.172
Author: Vincent Cirel (http://www.jguru.com/guru/viewbio.jsp?EID=69061) Question
originally posed by Augustine Wan
(http://www.jguru.com/guru/viewbio.jsp?EID=28441
Just off the top of my head, the following (pseudo code) is how I'd stab at it; should
point in the right direction anyway. If you want a response you'll need to create the
corresponding DataInputStream.
import java.net.*
DataOutputStream outStream;
outStream.writeBytes(rshStr);
outStream.write(13);
outStream.write(10);
outStream.flush();
This assumes you have rsh set up on the host and you send an appropriate
username with the command if required.
Hope this helps.
Vincent
The original design of servlets was rather simplistic; it conceived of a single request
and a single response stream. As it evolved, it has added bits and pieces (like the
RequestDispatcher) to allow more servlet-to-servlet communication, including, and
forwarding, but it is still mostly inadequate to do things like filtering or capturing the
output of another Servlet.
Rumor has it that the next version of the Servlet specification will have explicit
support for this, but until then, there are a number of solutions.
The simplest solution is to use the URL class to initiate an HTTP connection from your
servlet. Specify the URL of the target servlet, and capture the result from the URL's
InputStream. See How can I include content from a URL, not from a local file? and
How can I download files from a URL using HTTP?.
Also, Resin has a feature called Servlet Filtering that may do what you want.
See also
• How can I daisy chain servlets together such that the output of one servlet
serves as the input to the next?
• How do I capture a request and dispatch the exact request (with all the
parameters received) to another URL?
Comments and alternative answers
HttpServletResponseWrapper
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jan 21, 2003
As of Servlet 2.3 spec, you can theoretically use HttpServletResponseWrapper and
override it to capture data written to its output stream.
[The Servlet 2.2 spec seems to address this, mentioning that calling
ServletRequest.getAttribute(String) with the attribute value
javax.servlet.request.X509Certificate will return the client certificate. I
presume it will be an instance of a subclass of
java.security.cert.X509Certificate. Now what about the server certificate?]
Client authentication
Author: Flavio Cesar (http://www.jguru.com/guru/viewbio.jsp?EID=488065), Aug 31,
2001
Do you have a sample source code doing client authentication through SSL ?
What servlet engine have you tried ?
Are there benchmarks available for the various servlet engines? Which one
shows better performance on my favorite platform?
Location: http://www.jguru.com/faq/view.jsp?EID=71682
Created: Jun 17, 2000 Modified: 2000-06-17 12:18:32.59
Author: Prasad Thammineni (http://www.jguru.com/guru/viewbio.jsp?EID=36479)
Question originally posed by max headroom
(http://www.jguru.com/guru/viewbio.jsp?EID=54255
Attached are two benchmarks. Use these benchmarks for informational purposes
only and not for product selection. The list of servlet engines is not complete. You will
see that WebSphere is notably missing from the benchmark.
http://www.objexcel.com/workingjava.htm#Servlet Engine Performance
http://www.mortbay.com/software/iX.html
Comments and alternative answers
Has anybody found any more recent benchmarks? The servlet engines mentioned
have all been replaced by newer versions or products.
The file.properties file should be present in the same directory as the class file
loading the properties.
In general:
// set Age
c.setMaxAge((int)iAge);
// send it back with the HTTP response
response.addCookie(c);
• Setting iAge < 0 indicates the default behavior of "death to the cookie upon
browser exit"
• Setting iAge = 0 indicates that the browser should delete the cookie
immediately.
• Setting iAge > 0 specifies the max age of the cookie before expiration (in
seconds) = iAge
response.setHeader("Set-Cookie","name=value; expires=date");
where date = Wdy, DD-Mon-YYYY HH:MM:SS GMT (ie. Monday, 12-Jun-2000
17:24:00 GMT).
One reason I can think of where you might want to use the setHeader method is if
you need to set an expiration date > 68.1 years future. The largest +(int) value
allowed is 2147483647 or about 68.1 years.
Note that in either case cookies are sent back using HTTP headers. Therefore, you
should add them to the response BEFORE you send any content back to the browser.
HTTP tunneling is a method that RMI uses to make calls through a local firewall.
To get across firewalls, which disallow regular outbound TCP connections but permit
HTTP through a proxy server, RMI makes use of HTTP tunneling by encapsulating the
RMI calls within an HTTP POST request. The reply too is sent back as HTTP-
encapsulated data.
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".
Refer to:
See also
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jun 23, 2001
See also: Re: What is HTTP Tunneling?Why servlets are a bett...
How do I start with servlets using Microsoft IIS and Windows NT?
Location: http://www.jguru.com/faq/view.jsp?EID=74589
Created: Jun 17, 2000 Modified: 2000-08-24 19:00:58.142
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Emilian Luca
(http://www.jguru.com/guru/viewbio.jsp?EID=68127
Many servlet engines exist as plugins to IIS. Tomcat and JRun seem to be the most
popular.
See
Yes, obviously, since session objects are stored in RAM, they are dependent on the
amount of RAM installed on your server machine, and the RAM allocated to the
servlet engine VM. See this FAQ for more information on avoiding OutOfMemory
errors.
How do I "load balance" my application? That is, I want to redirect the user
to another server if the number of users is over a threshold.
Location: http://www.jguru.com/faq/view.jsp?EID=74630
Created: Jun 17, 2000 Modified: 2000-09-28 19:42:11.599
Author: Prasad Thammineni (http://www.jguru.com/guru/viewbio.jsp?EID=36479)
Question originally posed by Anand Naik
(http://www.jguru.com/guru/viewbio.jsp?EID=44857
To implement the basic HTTP request load balancing you would need a load balancer
like CISCO Director (hardware based) or IBM WebSphere Network
Dispatcher(software based). Implementing a load balancer would allow you to spray
HTTP requests across multiple Web Server/Servlet Engines (node) within a cluster.
If using Servlet Sessions make sure that you configure the load balancer for
stickiness. Stickiness guarantees that all requests from a client are delivered to the
same Servlet Engine. Also, if you want to guarantee that your session data survives
node failures you have to persistent your session state to a shared database and re-
construct it in case of failure.
Advanced Servlet Engines like IBM WebSphere Application Server Adv. Edition
support persistent sessions out of the box, whereas Java Web Server does not.
Beyond simple HTTP request load balancing you cannot implement advanced load
balancing capabilities with Java Web Server.
You can do it using an HTML form, a Servlet and the class MultipartRequest of the
O'Reilly package avaiable at http://www.servlets.com/resources/com.oreilly.servlet/.
In this zip file (named cos.zip) you can found all the information you need to upload
a file using a browser and a servlet.
Remember that the file you upload is stored in the server filesystem, so remember to
remove it after sending your E-mail.
I tried also another way that worked perfectly, but is more complicated.
I wrote three classes :
• A mine DataSource for handling a stream of byte with a filename and a
content type
• An ExtendedMultipartRequest class that extracts the parts from the stream
of the Servlet (similar to the one provided by O'Reilly)
• A MultipartInputStream for reading the InputStream of the servlet line by
line
For creating a message I passed each data (bytes), content-type, and filename
parsed by my ExtendedMultipartRequest class to my DataSource. Then I built a
DataHandler using this DS and a Message using this as Content... It worked
perfectly!!!
Comments and alternative answers
See also
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jul 23, 2001
See also How do I upload a file to my servlet? and the topic Servlets:Files:Uploading
How do I handle FORMs with multiple form elements (e.g. radio buttons)
using the same name?
Location: http://www.jguru.com/faq/view.jsp?EID=82970
Created: Jun 21, 2000 Modified: 2000-07-06 12:33:06.353
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Morgan Sheets
(http://www.jguru.com/guru/viewbio.jsp?EID=51204
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
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">
How can I take advantage of introspection and have a servlet process the
entire form like I can using the JSP directive
<jsp:setProperty name="formHandler" property="*"/> ?
Location: http://www.jguru.com/faq/view.jsp?EID=86920
Created: Jun 25, 2000 Modified: 2000-06-25 14:30:23.972
Author: Govind Seshadri (http://www.jguru.com/guru/viewbio.jsp?EID=14)
You can make use of the HttpUtils class to gain similar introspective functionality
within servlets. It may not be as elegant as the introspection feature provided by the
servlet engine when using JSPs, but still, it works fine.
For example, let's assume that you've created your form as:
You can automagically create a Hashtable object from the parsed key-value pairs of
the POSTed data within doPost() of the servlet via the following snippet:
Hashtable h =
HttpUtils.parsePostData(request.getContentLength(),request.getInputStre
am());
String[] one = (String[])h.get("one");
String[] two = (String[])h.get("two");
String[] three = (String[])h.get("three");
//print out the value of 1st input element
pw.println("<h2>One: "+one[0]+"</h2>
");
pw.println("<h2>Two: "+two[0]+"</h2>
");
");
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 <servlet> 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.
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.*;
Now, just create a template file, pass the servlet the template file name, and have at
it!
Comments and alternative answers
If you want to separate html-code and logic you can just put them in different classes.
But in my opinion this solution is reasonable only if different people are working on
html-code and logic.
But even if one man is doing all the job html-code generation and logic MUST be
separated in different procedures.
Faced with the problem of separating presentation from code, XMLC takes the radical
step of... (drumroll please...) actually separating the presentation from the code! The
presentation "layer" is literally an HTML file. The code "layer" is a servlet (or any
Java class) that reaches into the HTML file and changes its content, based on "ID"
attributes embedded inside the HTML tags. (The way it accomplishes this is by
compiling the HTML file into a Java class and data structure, but that's almost beside
the point.)
The servlet creates XML documents - only. Your business logic specifies what these
XML documents look like (essentially the changing business data on a page).
Associate this XML document with an XSLT (XSL Transformation language) file.
Have an XML parser apply the XSLT stylesheet to the file and produce an XHTML
file. This is served to the browser as HTML. You place all static image tags, text and
table constructs in the XSLT file (it takes a little learning but you can easily create
dynamic tables with this). Visit www.xml.com for some ideas about how to do this.
Re: Use XML ...
Author: Tripp Lilley (http://www.jguru.com/guru/viewbio.jsp?EID=1743), Jun 10,
2004
The purist in my likes this solution, but the pragmatist in me points out that part of
the reason for the proliferation of "raw HTML"-based templating systems is the
fact that designers just plain like working in what they're used to: HTML.
Besides, there's no reason your app can't spit out XML then run it through XMLC,
so that you have the best of both worlds. You have pure, clean XML on tap for
when you want to do some transformation (XSL-FO, anyone?,) but your basic,
bread-and-butter HTML templating is about as native as you can get.
For an HTML FORM with multiple SUBMIT buttons, how can a servlet
respond differently for each button?
Location: http://www.jguru.com/faq/view.jsp?EID=87441
Created: Jun 29, 2000 Modified: 2000-06-29 16:54:48.087
Author: Richard Raszka (http://www.jguru.com/guru/viewbio.jsp?EID=7963)
Question originally posed by Shubham Mehta
(http://www.jguru.com/guru/viewbio.jsp?EID=85149
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:
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.
Comments and alternative answers
The only way I have found of doing this is to use plain old images with onClick
events firing javascript which will amend the submission URL with a parameter
indicating the different image clicked. Plain the backside, but it works.
The browser submits foo.x=_x and foo.y=_y, (_x,_y) being the coordinates in the
image where the mouse click occurred.
This does mean that you can't have multiple TYPE=IMAGE buttons and branch
on the VALUE=, so what I do is assign a different NAME= to each button and
parse it. Example:
...
// ...
}
}
The otherwise very instructive servlet code for the Duke's BooksStore example at
Java Developer Connection has the following code fragment for
BookStoreServlet.java:
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher( ....some server resource
...);
if (dispatcher == null) {
System.out.println("There was no dispatcher");
// No dispatcher means the html file could not be found.
response.sendError(response.SC_NO_CONTENT);
}
else {
System.out.println("There is a dispatcher");
HttpSession session = request.getSession();
dispatcher.forward(request, response);
}
The manner in which the value of dispatcher is tested and the comment that
follows definitely create the impression that the return value of
ServletContext.getRequestDispatcher() could be used to determine whether the
server resource supplied as the argument to the method is actually present at its
specified location.
You can use the following servlet to verify that the return value of
ServletContext.getRequestDispatcher() is non-null regardless of the presence or
the absence of the html file that is mentioned as the argument to the method. In
either case, the message "There is a dispatcher" will be printed out in the window in
which the servlet engine is running.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
if (dispatcher == null) {
System.out.println("There was no dispatcher");
response.sendError(response.SC_NO_CONTENT);
}
else {
System.out.println("There is a dispatcher");
dispatcher.forward(request, response);
}
}
}
The lines that are commented out are for verifying that the servlet does indeed work
for a file that is actually present at the specified location. If you are just starting out
with servlets, the following additional comments might be helpful. (These comments
apply specifically to a Windows NT environment.)
whereas for jsdk2.1, it can sit in the same directory as the servlet.
see:
http://www.weblogic.com/docs51/classdocs/API_ejb/EJB_deployover.html#1054622
Regards
Anoop Sehdev
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.
[Note: My HttpSessions are persistent (disk swap), so if the handle is not serializable
I will have troubles when the HttpSession is restored. ]
Test result:
I have used the handle for locating local and remote EJB. I have no problem about
storing the handle inside the HttpSession and swapping the HttpSession. However if
some problem arise about the swap of the HttpSession, you may could keep the
HttpSession in memory.
Test conditions:
BEA Weblogic 4.5.1 (uses EJB 1.0 and allow keep HttpSessions in memory). Windows
NT 4.0
Observations:
I'm a little surprised about the test since I keep in mind that handles could only be
used for locating local EJB's not remote ones (wrong?).
You can refer to the url below for more info and a...
Author: kishore_k_v k (http://www.jguru.com/guru/viewbio.jsp?EID=202022), Sep
11, 2000
You can refer to the url below for more info and a clear picture on this topic although
i think you know the answers.
http://www.weblogic.com/docs51/classdocs/API_ejb/EJB_design.html#1022000
Yes! :-)
Q: Did the chicken cross the road to get to the other side?
A: Yes.
(Feel free to submit feedback containing code and advice for how to do this printing
thing properly.)
How do I get the Duke's Bookstore servlet example at the Java Developer
Connection to work under Servlet API version 2.2 (and Tomcat 3.1)?
Location: http://www.jguru.com/faq/view.jsp?EID=98986
Created: Jul 9, 2000 Modified: 2000-07-10 12:39:58.58
Author: Avi Kak (http://www.jguru.com/guru/viewbio.jsp?EID=26410)
The Duke's Bookstore example at the Java Developer Connection is indeed very
instructive. As currently posted, this example works for JSDK 2.1. To get it to work
under Tomcat 3.1, which uses the Servlet API 2.2, you'd need to make the following
changes:
ShoppingCart cart =
(ShoppingCart)session.getValue(session.getId());
by
ShoppingCart cart =
(ShoppingCart)session.getAttribute(session.getId());
session.putValue(session.getId(), cart);
by
session.setAttribute(session.getId(), cart);
Some of the other changes you'd need to make depend on how and where you install
the code in Tomcat3.1. For example, I have installed the code in a directory called
bookstore under C:\tomcat\webapps\. I put all the servlets and the support classes
in C:\tomcat\webapps\bookstore\WEB-INF\classes\ and the html page
bookstore.html in C:\tomcat\webapps\bookstore\servlets\. The resulting
pathnames to the servlets and the html page would need to be reflected in the code.
Is there any way to get a session object when knowing the session id?
Location: http://www.jguru.com/faq/view.jsp?EID=99348
Created: Jul 10, 2000 Modified: 2001-02-25 17:06:26.808
Author: David Garcia (http://www.jguru.com/guru/viewbio.jsp?EID=17915) Question
originally posed by Herve Devos
(http://www.jguru.com/guru/viewbio.jsp?EID=88981
There may be a way to make it work under certain servlet engines, but no
portable/standard way that I know of. -Alex]
Code sample:
// first, store the target HttpSession id, no problems about this cause the id is a
Serializable String object
HttpSession oldSesion=request.getSession(false);
String id=oldSesion.getId();
database.storeID(id);
Test conditions:
BEA Weblogic 4.5.1 (uses httpServlet Specification 2.1 ).
Windows NT 4.0
How can I explicitly unload a servlet or call the destroy method?
Location: http://www.jguru.com/faq/view.jsp?EID=99949
Created: Jul 11, 2000 Modified: 2000-07-11 14:56:23.115
Author: Oliver Springauf (http://www.jguru.com/guru/viewbio.jsp?EID=32379)
Question originally posed by Shardul Joshi
(http://www.jguru.com/guru/viewbio.jsp?EID=13401
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.
Try to add
-Dfile.encoding=UTF8
to Java arguments in JRun administrator.
[Are you sure this works? It does set a system property, but there's no a priori
guarantee JRun will be smart enough to use it to change its interpretation of UTF-8
parameters. Furthermore, as I understand it, there's a definite ambiguity or flaw in
the HTTP spec, and extended character sets are not necessarily legal as CGI
parameters. HTML-escaped values are, so you must use { format. But some
browsers do send raw non-ASCII characters, so it's a serious problem. -Alex]
How can I generate special responses for WebTV users from a servlet?
Location: http://www.jguru.com/faq/view.jsp?EID=102571
Created: Jul 14, 2000 Modified: 2000-07-15 08:39:19.212
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
I recently did this with Apache and Tomcat. Using Basic HTTP Authentication is an
Apache function, so this method should work with Apache and any servlet engine.
Different web servers will, of course, work differently.
If you haven't already done so, read the Apache FAQ about authentication (section
G) at apache.org, especially QA G.2. Also read the Apache Week article referenced
there (http://www.apacheweek.com/issues/96-10-18#userauth). These resources
will give you a good idea about how Apache can be configured to restrict access to
URL's. Neither one explicitly tells you how to use authentication with servlets, so I'll
spell it out here.
Use the <Location> directive to indicate to Apache that your specific servlet URL or
servlet URL prefix (for multiple servlets) can be accessed only by authenticated
users. The following template should be added to one of the Apache configuration
files (such as http.conf) with appropriate substitutions for your system:
You will also need to create a user file with htpasswd. See the Apache Week article
for details.
See also
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jul 16, 2001
How do I assign basic authentication on Tomcat + A...
[The following example works if the script is located behind a web server (either
remote, or running on the same machine). But if you're using a standalone Java web
server, and want to run (e.g.) a Perl CGI, is there any way to use System.exec() to
invoke the script with the correct parameters? -Alex]
Yes, you can call CGI Script from a servlet. You can write your servlet as if it is
sending data from browser. (Either using POST/ GET Method)
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try{
// Put you URL/CGI here !!!
URL url = new URL("http://localhost:8080/CgiRedir");
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
PrintStream outStream =
new PrintStream(connection.getOutputStream());
outStream.flush();
outStream.close();
It just takes a few lines of code to use this servlet. Hope this saves somebody some time . . .
and please let me know if you see ways it could be improved!
package com.ragingnet.util;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.net.*;
/** Called by another servlet or jsp page to pass post parameters - both
from the original request,
* and new ones added to it - on to another page, such as a CGI script.
* This is probably not of any use in a pure Servlet/JSP environment, but
useful for passing
* requests along to existing CGI scripts, etc.
*
* Useage: First call the following:
* setUrlForward(url) [required]
* setPassExistingParams(boolean) [optional - default is TRUE]
* setParam(paramName, paramValue) [multiple times if desired]
* setHeader(headerName, headerValue) [multiple times if desired]
*
* Then call Go(request, response)
*
* @author Roger Hand
* @date April 2, 2001
*
*/
public class PassPostRequestServlet extends HttpServlet {
private String urlForward = null;
private Vector vectParams = new Vector();
private Vector vectHeaders = new Vector();
try{
/**
* First we SEND the request to the web server
*/
PrintStream outStream =
new PrintStream(connection.getOutputStream());
while(enumPNames.hasMoreElements()) {
String paramName = (String)enumPNames.nextElement();
if (arrayParam != null) {
for(int iParam=0; iParam < arrayParam.length; iParam++) {
paramString += paramName + "=" + arrayParam[iParam] + "&";
}
}
}
} //if (passExistingParams) {
outStream.flush();
outStream.close();
/**
* Now we RECEIVE response from web server and pass it back to
browser client
*/
String inputLine;
BufferedReader inStream =
new BufferedReader(
new InputStreamReader(connection.getInputStream()));
/**Clean up resources*/
public void destroy() {
}
public void setUrlForward(String newUrlForward) {
urlForward = newUrlForward;
}
public void setPassExistingParams(boolean newPassExistingParams) {
passExistingParams = newPassExistingParams;
}
}
[The below example leaves out a cruicial step: where to put the .properties files.
Fortunately, Java looks for properties files using the same method with which it looks
for class files. So just put the .properties files in the appropriate package directory,
either under WEB-INF/classes or in a JAR file in WEB-INF/lib/ -Alex]
Please try with following code. Compile and deploy servlet files in resp. directories.
Create 3 different resource files.
Start Servlet engine and access servlet using following url
1. For franch message
http://172.22.67.23:8080/examples/servlet/ResourceServlet?MyLanguage=0
2. For german message
http://172.22.67.23:8080/examples/servlet/ResourceServlet?MyLanguage=1
3. For english message
http://172.22.67.23:8080/examples/servlet/ResourceServlet?MyLanguage=2
-------------------- ResourceServlet ------------------------------------
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
int localeSelected = 2;
String strTemp = request.getParameter("MyLanguage");
if (null != strTemp)
localeSelected = (new BigDecimal(strTemp)).intValue();
switch (localeSelected){
case 0 :
System.out.println("User Requested French Page");
rb = ResourceBundle.getBundle("LocaleStrings", Locale.FRENCH);
System.out.println(rb.toString());
break;
case 1 :
System.out.println("User Requested German Page");
rb = ResourceBundle.getBundle("LocaleStrings", Locale.GERMAN);
break;
case 2 :
default:
System.out.println("User Requested Default/English Page");
rb = ResourceBundle.getBundle("LocaleStrings", Locale.ENGLISH);
}
out.println("<html>");
out.println("<body>");
out.println("<head>");
String title = rb.getString("title");
out.println("<title>" + title + "</title>");
out.println("</head>");
out.println("<body>");
out.println(rb.getString("Question"));
out.println("</body>");
out.println("</html>");
out.println("</body>");
out.println("</html>");
}
Shirish
([email protected])
Stefano
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.
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).
Can I pass the value of variable from a servlet to ASP? Or vice versa?
Location: http://www.jguru.com/faq/view.jsp?EID=109106
Created: Jul 23, 2000 Modified: 2000-09-17 21:55:35.809
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Deepak Kalra
(http://www.jguru.com/guru/viewbio.jsp?EID=99188
You can also pass data via HTTP GET using a browser...
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Sep 17, 2000
You can also pass data via HTTP GET using a browser redirect. E.g.
response.sendRedirect("http://evil.satan.org/damnation.asp?home=hell&parent=beelzebub
How can I use JUnit to ensure that my servlets/JSP are producing valid
HTML?
Location: http://www.jguru.com/faq/view.jsp?EID=110644
Created: Jul 25, 2000 Modified: 2000-07-26 15:34:48.697
Author: Tom Copeland (http://www.jguru.com/guru/viewbio.jsp?EID=1396)
There's the traditional, brute force way - write a JUnit test case that opens a
HttpURLConnection to your servlet, reads the content, and does various
String.indexOf() and String.subString() operations until you're satisfied that all is
well (or you're tired of hacking together String operations).
A slightly more elegant method is to use an XML parser. You can open the
connection, read the contents, feed it into your XML parser, get back a document,
and walk the DOM tree checking for elements which should be there. Better, but still
clunky.
A better way is to use HttpUnit. HttpUnit allows the test case to be written using the
same "words" as used in web pages - forms, tables, etc. You can write test cases like
this (this is from the example code):
XPath
Author: Johannes Brodwall (http://www.jguru.com/guru/viewbio.jsp?EID=87292),
May 4, 2001
HttpUnit is indeed powerful. An easy way of checking the structure without mocking
too much around with text strings is to combine it with XPath.
import org.apache.xpath.XPathAPI;
import org.w3.dom.*;
This will test if the table in the response with the id attribute 'mytable' contains 10
rows.
For more detail, see What are all the different kinds of servers? in this FAQ.
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?
Location: http://www.jguru.com/faq/view.jsp?EID=112424
Created: Jul 27, 2000 Modified: 2000-08-14 11:24:54.884
Author: Alfonso Garcia-Patiño
(http://www.jguru.com/guru/viewbio.jsp?EID=111459) Question originally posed by
Kaia Cornell (http://www.jguru.com/guru/viewbio.jsp?EID=72359
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.
How can I change the port of my Java Web Server from 8080 to something
else?
Location: http://www.jguru.com/faq/view.jsp?EID=112570
Created: Jul 27, 2000 Modified: 2000-07-29 05:23:10.902
Author: Shirish Bathe (http://www.jguru.com/guru/viewbio.jsp?EID=88588)
Question originally posed by Raviraj D
(http://www.jguru.com/guru/viewbio.jsp?EID=57509
Hi Raviraj,
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:
Hope this is solution for the problem. In case If you want more info please contact
me on [email protected]
Thanks
Shirish
Yes.
The EJB client (in this case your servlet) acquires a remote reference to an EJB from
the Home Interface; that reference is serializable and can be passed from servlet to
servlet.
If it is a session bean, then the EJB server will consider your web client's servlet
session to correspond to a single EJB session, which is usually (but not always) what
you want.
How can I set a cookie that is persisted only for the duration of the client's
session?
Location: http://www.jguru.com/faq/view.jsp?EID=114132
Created: Jul 29, 2000 Modified: 2000-07-29 12:15:32.021
Author: Govind Seshadri (http://www.jguru.com/guru/viewbio.jsp?EID=14) Question
originally posed by Basawaraj Pagade
(http://www.jguru.com/guru/viewbio.jsp?EID=105646
You can create and set a cookie in the usual way. For example, if you are using a
scriptlet, you can specify:
<%
Cookie aCookie = new Cookie("aName","aValue");
aCookie.addCookie();
%>
If you do not explicitly set a lifetime for the cookie using cookie.setMaxAge(), the
cookie is automatically deleted when the user closes his browser.
You can, however, send a "redirect", which tells the user's browser to send another
request, possibly to the same servlet with different parameters. Search this FAQ on
"redirect" to learn more.
What is FORM based login and how do I use it? Also, what servlet containers
support it?
Location: http://www.jguru.com/faq/view.jsp?EID=115231
Created: Jul 31, 2000 Modified: 2001-01-19 14:41:27.417
Author: Dieter Wimberger (http://www.jguru.com/guru/viewbio.jsp?EID=25708)
Question originally posed by Alex Chaffee PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=3
Form based login is one of the four known web based login mechanisms. For
completeness I list all of them with a description of their nature:
This security mechanism provides end user authentication using HTTPS (HTTP
over SSL). It performs mutual (client & server) certificate based
authentication with a set of different cipher suites.
You can also see section 3.3.11.1 of the J2EE Specs. (User Authentication, Web
Client) for more detailed descriptions of the mechanisms.
Thus any Servlet container that conforms to the J2EE Platform specification should
support form based login.
To be more specific, the Servlet 2.2 Specification describes/specifies the same
mechanisms in 11.5 including form based login in 11.5.3.
This section (11.5.3) describes in depth the nature, the requirements and the
naming conventions of form based login and I suggest to take a look at it.
URL Pointers:
This feature is also supported in WebLogic 5.1 (I tested with sp8) and 6.0
Let's say that a webapp for which automatic reload has been enabled consists of a
group of mutually referencing servlets. Let's also say that you have modified and
recompiled all the servlets. When you hit the reload button on the browser, only one
servlet -- the servlet that the browser is pointing to -- will be automatically reloaded
by the container. Hitting the reload button on the browser for the other servlets will
not cause their reload into the container and you will only see their older versions. If
you want the newer versions of the other servlets to be reloaded into the container,
in general you'd need to shutdown and restart the servlet container.
This behavior of Tomcat 3.1 is in keeping with the following statement that appears
in Tomcat 3.1 release notes:
"...... changes to classes other than the servlet you are requesting do not trigger
class reloads -- you will need to restart Tomcat to reflect changes in those classes."
In the rest of this posting, I will explain this property of Tomcat 3.1 with the help an
example. The reader is also referred to a posting by Costin Manolache on this aspect
of automatic class reloading in Tomcat 3.1.
Let's say that after starting the servlet container, you point your browser to the
following URL:
http://localhost:8080/test-suite/servlet/TestServlet_1
the servlet container will load TestServlet_1 into the container, which will cause the
browser to display a "Hello..." message. If you click inside this message where
indicated, the browser will make a request for TestServlet_2 and it will be loaded
into the container.
Now suppose you make changes to both the servlets by altering, say, the value of
"Revision number: ". If your browser is pointing to TestServlet_1 and you hit reload
button, the servlet container will automatically reload TestServlet_1. But the
container will NOT reload TestServlet_2 even if you hit the reload button on the
browser when the browser is pointing to TestServlet_2.
To see the newer version of TestServlet_2, you have two choices: 1) Recompile the
classes and this time start out by pointing your browser to TestServlet_2. Or, 2)
Shutdown and restart the servlet container.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
out.println( "<html>" +
"<head><title> TestServlet_1
</title></head>" +
"Hello there from TestServlet_1 ------- "
+
"To see the hello message from
TestServlet_2," +
" click <a href=\"/test-
suite/servlet/TestServlet_2\">here</a> ------ " +
"Revision number: 17" +
"</body></html>" );
}
}
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
out.println( "<html>" +
"<head><title> TestServlet_2
</title></head>" +
"TestServlet_2 saying hello ------- " +
"To see the hello message from
TestServlet_1," +
" click <a href=\"/test-
suite/servlet/TestServlet_1\">here</a> ------ " +
"Revision number: 17" +
"</body></html>" );
}
}
How do I capture a request and dispatch the exact request (with all the
parameters received) to another URL?
Location: http://www.jguru.com/faq/view.jsp?EID=116711
Created: Aug 2, 2000 Modified: 2000-08-04 04:57:49.317
Author: David Garcia (http://www.jguru.com/guru/viewbio.jsp?EID=17915) Question
originally posed by lakshmi prabha
(http://www.jguru.com/guru/viewbio.jsp?EID=49600
• If the next servlet url is in the same host, then you can use the forward
method.
Here is an example code about using forward:
• RequestDispatcher rd = null;
• String targetURL = "target_servlet_name";
• ServletContext ctx = this.getServletContext();
• rd = ctx.getRequestDispatcher(targetURL);
• rd.forward(request, response);
• The other possibility is that the target servlet location is in a different host.
Then you will need to use Streams,Sockets... and the code could be
something like this:
• URL url=null;
• URLConnection conn=null;
• try{
• url = new URL
• (protocol,host,port,"/"+servlet+"?"+requestParams);
• // the requestParam contains all the attributes (name=value
pairs) you want to send taken from the incomming request
•
• conn = url.openConnection();
• conn.setUseCaches(false);
• conn.setDoOutput(false);
• } catch(MalformedURLException e) {
• // whatever you want
• }
• BufferedReader inStream=new BufferedReader(new
InputStreamReader(conn.getInputStream()));
• String respuesta=inStream.readLine();
• inStream.close();
You can read more about the first approach in the Java Developer Journal (Number
of May 2000 page 102).
Test Conditions
I have test this approach over webLogic 451 with the Service Pack 8 or higher. I can
asure you that with Service Pack 7 or lower, the forward approach doesn't work.
[That's all well and good, but you've dodged an important part of the answer: How
do we grab the values of the parameters? I have source code that does this, but
unfortunately my hard drive just crashed -- can someone else fill this in? -Alex]
import java.io.*;
import java.util.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
PrintStream outStream =
new PrintStream(connection.getOutputStream());
while(enumPNames.hasMoreElements()) {
String paramName = (String)enumPNames.nextElement();
String[] arrayParam =
request.getParameterValues(paramName);
if (arrayParam != null) {
for(int iParam=0; iParam < arrayParam.length;
iParam++) {
paramString += paramName + "=" +
arrayParam[iParam] + "&";
}
}
}
} //if (passExistingParams) {
outStream.flush();
outStream.close();
String inputLine;
BufferedReader inStream =
new BufferedReader( new
InputStreamReader(connection.getInputStream()));
} // class
RequestDispatcher rd = null;
String targetURL = "/examples/servlet/teststartpage3";
ServletContext ctx = this.getServletContext();
rd = ctx.getRequestDispatcher(targetURL);
rd.forward(request,response);
Is there any way to tell Tomcat (or any servlet engine) never to use cookies
for session management?
Location: http://www.jguru.com/faq/view.jsp?EID=116712
Created: Aug 2, 2000 Modified: 2000-08-03 21:18:39.455
Author: David Garcia (http://www.jguru.com/guru/viewbio.jsp?EID=17915) Question
originally posed by Graham Lea
(http://www.jguru.com/guru/viewbio.jsp?EID=101834
I'm not sure about Tomcat but in WebLogic (from 4.0.2 to 5.1 versions) there is
parameter in the weblogic.properties file which can enable (or disable) cookies.
The parameter line is:
weblogic.httpd.session.cookies.enable=true
or
weblogic.httpd.session.cookies.enable=false
Is there a way to include jsessionid in a hidden field (in a form) rather than in
the URL (by the URL rewriting mechanism ) ?
I saw that HttpSessionContext class was deprecated for security reason, but for
security reasons too i would like to know if there is a way to prevent the
jessionid from being logged in the HTTP server log files (of course without
using cookies) ?
Thanks in advance.
Assuming you really want to disable the security checks for ALL your servlets, you
need to edit the server.properties file and set server.security=false.
We are using Apache/Tomcat for our site. Our servlets stream data rather
than send it in one big chunk, but unfortunately it seems that Apache is
buffering the servlet output stream, so results get to the user's browser
only when the servlet closes the stream. Is there any way to control this?
Location: http://www.jguru.com/faq/view.jsp?EID=118608
Created: Aug 3, 2000 Modified: 2000-08-04 04:18:58.516
Author: joe w (http://www.jguru.com/guru/viewbio.jsp?EID=112713) Question
originally posed by Ofer Shaked
(http://www.jguru.com/guru/viewbio.jsp?EID=62619
Re: We've tried things like setting the buffer size in...
Author: Neil Smyth (http://www.jguru.com/guru/viewbio.jsp?EID=392931), Apr
2, 2001
I've the same problem: I am trying to keep open a connection to the client and
periodically write some data to it. I am using Apache with Tomcat 3.2 and mod_jk
for the connector, and running on NT. Any thoughts? What I'm doing works fine
under PWS/JRun combination, so I think it is a problem with the apache/tomcat
combination. The sympton of the problem is that we are getting some strange
buffering effects: it seems to buffer up to 256 bytes initially for the first
connectionand thereafter pass along the data immediately. However for the second
and subsequent connections it always buffers... Any thoughts appreciated!!
Regards, Neil
Re: Re: We've tried things like setting the buffer size in...
Author: Howard Meadows
(http://www.jguru.com/guru/viewbio.jsp?EID=411680), Apr 28, 2001
I think the buffering problem originates in the apache source code rather than
anything in Tomcat. If you look at request handlers in http_request.c you'll find
there is no support for chunk data. JRun probably contains its own buffering
because it was not designed specifically to run on Apache.
Re: Re: Re: We've tried things like setting the buffer size in...
Author: Timothy Bendfelt
(http://www.jguru.com/guru/viewbio.jsp?EID=454480), Jul 13, 2001
From the jdk1.3.1 release notes:
How do I upload a file from an applet to a servlet, i.e. emulate the browser's
'multipart/form' ability to upload files?
Location: http://www.jguru.com/faq/view.jsp?EID=119521
Created: Aug 4, 2000 Modified: 2002-03-31 15:20:15.035
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by alex black (http://www.jguru.com/guru/viewbio.jsp?EID=51517
The HTTPClient offering makes this possible from its mpFormDataEncode method.
Keep in mind the security restrictions of an applet accessing the local client's file
system. Basically, untrusted applets can't.
Comments and alternative answers
In WebSphere Application Server, you specify the command line arguments for the
JVM in which the Servlet Engine resides using the command line arguments property
of the Application Server. This can be set from the Administrative Console.
[OK, one down, a dozen to go... Who wants to answer for a different engine? -Alex]
How do I get the "Posting and Processing HTML Forms" example at the Java
Developer Connection to work under Servlet API version 2.2 (and Tomcat
3.1)?
Location: http://www.jguru.com/faq/view.jsp?EID=119718
Created: Aug 4, 2000 Modified: 2000-08-08 00:46:57.202
Author: Avi Kak (http://www.jguru.com/guru/viewbio.jsp?EID=26410)
To get this example to work with Tomcat 3.1, which uses the Servlets 2.2 API, you
need to make the following changes:
The most significant change you have to make concerns the use of
DataInputStream.readLine() method. The readLine() method of the
DataInputStream class has been deprecated because, as mentioned in the Java 2
SDK API, it "does not properly convert bytes to characters." Java 2 SDK API further
states that "as of JDK 1.1, the preferred way to read lines of text is via the
BufferedReader.readLine() method." Therefore, in the servlet class files
FormDisplayServlet.java and FormProcessingServlet.java, replace the
invocation
by
BufferedReader disStructure = new BufferedReader( new
InputStreamReader( fisStructure ));
by
Changing over to BufferedReader for reading the structure and the data files also
makes it necessary to change the test condition in the while loop for reading the
files. For illustration, the test condition in the while loop for reading the structure file
struct.dat needs to be changed from
while ( 0 != disStructure.available() ) {
//....
}
to
The other changes you need to make depend on where you store the the files for this
example in the Tomcat 3.1 directory structure. In my case, in the
TOMCAT_HOME/webapps directory, I created a new webapp for this example and called
it form-processing. I deposited the servlet files in the
TOMCAT_HOME/webapps/form-processing/WEB-INF/classes
directory, and I deposited the files struct.dat and data.dat in the directory
TOMCAT_HOME/webapps/form-processing/servlets/
This placement of the files dictated the following additional changes to the example
code:
to
fisData = new FileInputStream( "C:/tomcat/webapps/form-
processing/servlets/" + paramDataFile );
to
to
JSP is intended for dynamically generating pages. The generated pages can include
wml, html, dhtml or whatever you want...
When you have a generated page, JSP has already made its work. From this moment
you have a page.
If you want automatic refreshing, then this should be acomplished by the technology
included in the generated page (JSP will tell only what to include in the page).
The browser can not be loaded by extern factors. The browser is the one who fetches
url's since the http protocol is request-response based. If a server can reload a
browser without its allow, it implies that we could be receiving pages which we
haven't asked for from servers.
May you could use applets and a ServerSocket for receiving incoming signals from
the server for changed data in the DB. This way you can load new information inside
the applet or try to force a page reload.
[That's a nice idea -- it could use the showDocument() call to reload the current
page. It could also use HTTP polling instead of maintaining an expensive socket
connection. -Alex]
[Search the FAQ on "redirect" for more information on this technique. -Alex]
Is there any way to generate offscreen images without relying on the native
graphics support? I'd like to create an image without an X server running,
or create an image with more colors than the current video mode.
Location: http://www.jguru.com/faq/view.jsp?EID=121936
Created: Aug 8, 2000 Modified: 2000-09-18 09:31:11.489
Author: Scott Stanchfield (http://www.jguru.com/guru/viewbio.jsp?EID=11)
Question originally posed by David Noel
(http://www.jguru.com/guru/viewbio.jsp?EID=119574
You must have a graphical environment installed on your server to work with Java
image routines in AWT, even though the image will only be displayed on the client's
machine.
The AWT image manipulation routines use the native platform's graphics primitives
and "grab" the resulting image to send to the client.
There is a better package than XVFB that has better results. It's called PJA and it can
be found at www.eteks.com. I've started using it about 6 months ago and it works
great.
See also
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jul 2, 2001
See also What causes the error "Can't connect to X11 w...
Here's a thread
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Sep 26, 2001
Here's a thread that took place on a different question. I've moved it here for
organization's sake. J.P. Jarolim, Apr 18, 2001
You'll find a very usefull replacement of the awt-classes for non x-win enviroments under
http://www.eteks.com/pja/en
I have downloaded xvfb from ftp.xfree86.org but it won't install! I have downloaded the wright version
4.1 for solaris. but when I run the "sh xinstall.sh -check" script I'll get a "No SunOS/Solaris binaries
available for this architecture" message.
If you hit the reload button on the browser repeatedly, when the server successfully
retrieves the cookie the client browser will show the following information output by
the servlet:
Cookie Information
status retrieved
and, when the server is not able to retrieve the cookie, you'll see just
Cookie Information
Also, you'll see the following messages in the Tomcat window on the server side as
you hit the reload button repeatedly on the client browser. Whether you see a 0 or a
1 for the number of cookies returned depends on whether or not the cookie is
retrieved by the server.
This output on the server side is a sampling from a particular run. The number of
times 0's and 1's show up would vary from run to run.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
cookie.setMaxAge( 0 );
response.setContentType("text/html");
response.addCookie( cookie );
Does anyone get this behavior with Internet Explorer or other browsers?
A cookie whose age is left unspecified has the same storage property as a cookie for
which setMaxAge is invoked with a negative argument. In both cases, the cookie is
available only for the duration of the current session with the server. In both cases,
the cookie is deleted by the client when the current session expires.
I have shown below the code for a simple servlet, TestCookieLifetime, that can be
used to verify my answer to the question. The servlet creates five cookies, with the
first four being given different maximum ages, and the last with the age left
unspecified.
Of the first two cookies, cookie1 is given a maximum age of 1000 secs; and
cookie2 of 10 secs. The third cookie, cookie3, is given a maximum age of 0 secs.
This cookie will be deleted almost immediately after it is created. The fourth cookie,
cookie4, is given a negative value for its age; this cookie will be deleted when the
client browser exits. Finally, by not invoking setMaxAge on cookie5, we leave its age
unspecified.
If you point a client browser to this servlet and hit the reload button on the browser
repeatedly, you will notice that the browser will display the following pattern initially
name1 value1
name2 value2
name4 value4
name5 value5
If you wait for more than 10 seconds between reloads, the browser will display
name1 value1
name4 value4
name5 value5
and eventually
name1 value1
name4 value4
name5 value5
name2 value2
If you reload in very quick succession, occasionally you will also see the following
displayed by the browser:
name1 value1
name4 value4
name5 value5
name2 value2
name3 value3
The reason for why you may also see the line name3 value3, which corresponds to
cookie3 whose age was set to zero, is explained in another posting.
The bottom line is that the lines name4 value4 and name5 value5, the former
corresponding to a negative number for the age and the latter to age left
unspecified, will alway appear together. If you shut down the browser and restart it
again, both these lines will fail to appear in the client browser.
Here is the code for the servlet:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
cookie1.setMaxAge( 10000 );
cookie2.setMaxAge( 10 );
cookie3.setMaxAge( 0 );
cookie4.setMaxAge( -10 );
response.setContentType("text/html");
response.addCookie( cookie1 );
response.addCookie( cookie2 );
response.addCookie( cookie3 );
response.addCookie( cookie4 );
response.addCookie( cookie5 );
Websphere (at least version 1.x-2.x) works as a plug-in for a webserver such as
Apache or IIS. You will have an installation directory for both WebSphere and the
HTTP server. The location and names of these directories depends on the server
platform.
Your HTML and JSP pages will be placed in the root folder of the web server (or
virtual server), or one of its subdirectories:
Apache:
<apache install path>/htdocs
IIS:
<some path>\wwwroot
(If you are using virtual servers under IIS, you should realize that each virtual server
must be configured to use WebSphere individually)
The alternative is to place your classes in the "classes" subdirectory, or within the
system classpath. In this case, your classes are not subject to dynamic reloading,
and the servlet engine must be restarted for any changes to take effect.
How can I specify the age of the cookie (single-session or persistent) set by
the Servlets session tracking APIs?
Location: http://www.jguru.com/faq/view.jsp?EID=125053
Created: Aug 11, 2000 Modified: 2000-08-11 14:29:32.18
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by sharad gupta
(http://www.jguru.com/guru/viewbio.jsp?EID=100198
The current specs (2.2 and 2.3) allow the app developer to set the "session timeout"
in minutes in the <session-config><session-timeout> element.
However, as far as I can tell, there is no standard way to specify the age of the
cookie the servlet container uses to drop the session ID on the browser.
One reason this could be useful is to set the cookie age to -1, guaranteeing that a
session never lasts longer than the current browser session, regardless of its
longevity inside the server.
This is okay for most part but let's say that you want to modify the JSESSIONID (or
whatever cookie name) cookie set by the servlet engine. Most people will try
retrieving the cookie set by the servlet engine, setMaxAge to 0 (to delete it) and create
a new cookie with same cookie name/value and modified behavior. However, this
doesn't seem to work!! Now you have two cookies with same name -- that's not what
you want right? You want to REMOVE the previous cookie but it does not get
removed!
Until now, you have been trying cookie.setMaxAge(0) to remove a cookie but it does
not work because while removing a JSESSIONID cookie, you are also trying to create
a new cookie with same name. Now, try 'response.setHeader("Set-
Cookie","name=JSESSIONID; expires=date");' to remove the cookie set by the
servlet engine?
Per my understanding, servlet engine uses a Hashtable for storing all cookies you
provide (either for remove or add new) and uses cookie name as a key in the
hashtable entry. So, the moment you create a new cookie, it will overwrite your
previous instruction of removing a cookie with the same name (because hashtable
caanot accomodate two records with same key).
Disclaimer: I haven't tried this myself, but almost sure that it will solve your problem.
Good luck!
No, you can't. It doesn't make sense, since the server has to generate the entire
page, and can't tell the browser to jump to a specific anchor inside the page. Send a
redirect instead, using Response.sendRedirect().
Comments and alternative answers
Another way of thinking of it is, everything after the "#" gets stripped by the browser
before it makes a request; it has literally no meaning inside the web server.
Applied to web applications and distributed programming, the three logical tiers
usually correspond to the physical separation between three types of devices or
hosts:
However, inside of the application server, there is a further division of program code
into three logical tiers. This is kind of fractal: the part (app server object design)
resembles the whole (physical system architecture). In a classic JSP/Servlet system,
these objects are usually implemented as:
1. JSPs or Servlets responsible for creating HTML or WML user interface pages
2. Servlets or JavaBeans responsible for business logic
3. Servlets, JavaBeans, or Java classes responsible for data access. These
objects usually use JDBC to query the database.
In an EJB system, the three logical tiers are usually implemented somewhat
differently:
If the architecture contains more than three logical tiers -- for instance, multiple data
feeds, multiple transactional data sources, multiple client applications -- then it is
typically called an "N-tier" or "Distributed" architecture.
See also:
Why would you want to do this? Is there a reason for you needing to run 2 servlet-
enabled webservers together.
Just run with one or the other. They will both do the same job!
We have just moved from tomcat to iPlanet 4.1 for our prod environment and now do
not use TC at all.
Roger Sergeant.
BAE SYSTEMS.
[Well, one reason might be that Tomcat may support a more recent version of the
spec, or that iPlanet may have bugs that Tomcat does not... But at the moment, they
both allegedly support version 2.2 of the Servlet spec. See What version of the
Servlets or JSP specification is supported by my favorite servlet product? -Alex]
So, running Tomcat within iPlanet resolves the cert upgrade problem.
Ultimately,
I would like to see JBOSS and Tomcat 4.03 integrated with iPlanet on both Linux
and Solaris. I was able to integrate Tomcat 4.04 with Apache on Linux using
mod_jk. Unfortunately, I have been unsuccessful integrating iplanet. However, I
am making progress.
In a nutshell, you have to download the tomcat connectors source and run a make
on the nsapi_redirector.so for iplanet to use a connector called apj13. There are
some changes, of course, to tomcat's server.xml, and iplanet's obj.conf.
I've been playing with this quite a bit and have yet to make it work. I am able to
create the redirector and validate that it at least is being loaded and does not crash.
I am also able to validate that the Java classes involved for the connector are being
invoked.
If this is possible, I'm going to do it, but I'm going to need some help.
What is the difference between JServ and Tomcat? And what's up with
mod_jserv and mod_jk?
Location: http://www.jguru.com/faq/view.jsp?EID=125676
Created: Aug 13, 2000 Modified: 2000-11-07 08:21:41.353
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Mark Evertz
(http://www.jguru.com/guru/viewbio.jsp?EID=117316
JServ was one of the very first servlet engines. It is now an open source project,
consisting of two parts: a pure-java servlet engine, compliant with the Servlet spec
version 2.0, and an Apache module written in C called mod_jserv that allows Apache
to send servlet requests to the JServ JVM.
Tomcat is a completely separate product, originally written by Sun, that is now also
open-source and administered by Apache. It supports the Servlet spec version 2.2,
and the JSP spec version 1.1. It also contains a pure Java servlet engine, and a
number of connectors for several commercial web servers.
Here's the confusing part: originally, when it was time to write a connector from
Apache to Tomcat, they started with the code base of mod_jserv. Although it has
been rewritten and revised to the point where it is no longer compatible with the
mod_jserv that comes with JServ, unfortunately, it is still called mod_jserv. This
means that if you have the JServ mod_jserv installed, it will not work with Tomcat,
and vice versa.
Fortunately, the latest version of Tomcat comes with a new connector for Apache,
called mod_jk. This connector supports Tomcat but not JServ. It is also more
advanced, in that it supports Tomcat-style load balancing, and also supports SSL
authentication (though this latter functionality is still a bit rough and may have bugs
in actually *reporting* that the connection is secure).
So if you just use mod_jk and Tomcat, you should have no problems (at least as far
as this connector issue is concerned).
REALLY?
Author: Ravi Luthra (http://www.jguru.com/guru/viewbio.jsp?EID=463147), Jul 26,
2001
Where can I find information about bugs in mod_jk while using mod_ssl? Should I
use mod_jserv instead when using Apache+mod_ssl?
NOW WHAT?
Author: matt scholz (http://www.jguru.com/guru/viewbio.jsp?EID=994323), Sep 4,
2002
I'm not patient enough to try banging my head against this wall any more, if I can
avoid it... I have a perfectly functional (more or less) install of Tomcat-4.0.4 on
Redhat 7.3. (YAY). I followed the steps I found at
http://www.johnturner.com/howto/apache-tomcat-howto.html which got a compiled
mod_jk.so installed in libexec/(along with several edits of configuration files, which
obviously didn't work). According to the documentation, I should be able to see the
same things from http://localhost:8080/examples and http://localhost/examples -but I
can't The question, I suppose is now that I have mod_jk.so in the apache/libexec
folder, what do I do to convince apache to use it? Thanks in advance, Matt
See also
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
}
}
Invalidating a session could be done on an explicit logout of a user from the Web Site
or after a period of inactivity that you have defined in the application.
Comments and alternative answers
Cookies can be accessed from a servlet usingthe HttpRequest class and the method
getCookies. Sample code is included below:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
out.println("<HTML><HEAD><TITLE>COOKIE
Values<TITLE></HEAD>");
out.println("<BODY><H1>Cookies in
Session</H1>");
// Process the cookies
for (int i = 0; i <cookies.length; i++)
{
String name = cookies[i].getName();
String value = cookies[i].getValue();
out.println("Cookie Name ="+name);
out.println("Cookie Value ="+value );
}
out.println("</BODY></HTML>");
}
[So, to be clear, if you want to access cookie "foo", replace the "out.println"
statements with
if (name.equals("foo")) {
out.println(name + " = " + value); // or whatever
}
Unfortunately, there's no "getCookieByName()" method. -Alex]
First, a definition. "redirect" means sending a response from your servlet to the
browser that tells the browser to go to (make a brand new request for) another URL
or page. This should not be confused with "forward" which operates inside the servlet
engine, without informing the browser of the "new" content. For this function, you
can use the RequestDispatcher and/or the JSP <jsp:forward> tag.
If you want more control -- for instance, to display a custom page to the user for a
few seconds before going to the new page -- you can use META HTTP-EQUIV, e.g.:
<html>
<head>
<title>Page Has Moved</title>
<meta http-equiv="Refresh" content="1;
url=http://foo.com/index.html">
</head>
</body>
</html>
The "1" in the "content" section is the number of seconds the browser should wait.
"0" here should produce an almost instantaneous jump, but in that case, you might
as well use sendRedirect().
You invoke an EJB from a servlet or JSP the same way you invoke one from any
other Java code. Just read the EJB docs and FAQ and have fun!
Comments and alternative answers
See also
It turns out that when I installed Tomcat, either I inadvertently elected to have Tomcat
run as a service (in my case Win2000) or Tomcat decided for itself that it should be a
service and start itself up when my machine boots. Invoking the shutdown.bat
function did not solve the problem. Evidently, shutdown.bat is unable to stop Tomcat
running as a service--stopping a serice has to be accomplished via the service
manager.
Now, I would have thought that changing the port number in server.xml would have
allowed a 2nd instance of Tomcat to run alongside the instance that is running as a
service, each instance listening to its own port, but evidently not.
Why use EJB when we can do the same thing with servlets?
Location: http://www.jguru.com/faq/view.jsp?EID=126400
Created: Aug 14, 2000 Modified: 2001-11-09 06:08:03.377
Author: Dan Christopherson (http://www.jguru.com/guru/viewbio.jsp?EID=39644)
Question originally posed by sreenivasulu kadirimangalam
(http://www.jguru.com/guru/viewbio.jsp?EID=123964
The most significant difference between a web application using only servlets and
one using servlets with EJBs is that the EJB model mandates a separation between
display and business logic. This is generally considered a Good Thing in non-trivial
applications because it allows for internal reuse, allows flexibility by providing a
separation of concerns, gives a logical separation for work, and allows the business
logic to be tested separately from the UI (among others).
Some of the hings that servlets and JSPs can do that EJBs cannot are:
Some of the things that EJBs enable you to do that servlets/JSPs do not are:
How close is the actual session timeout period to the specified timeout
period?
Location: http://www.jguru.com/faq/view.jsp?EID=127074
Created: Aug 15, 2000 Modified: 2000-08-16 00:21:20.052
Author: Avi Kak (http://www.jguru.com/guru/viewbio.jsp?EID=26410)
During some development work recently, I became curious as to how close the actual
session timeout period was to the specified timeout period. Much to my surprise, I
discovered a wide discrepancy between the two for the case when the specified
timeout periods are short. I have not done experiments for the case when the
specified timeout periods are long. I'd expect that for the case of long timeout
periods, the two -- the specified and the actual -- would be in fairly close agreement.
I show below some empirical data obtained for four different values of the specified
timeout periods: 10, 20, 60, and 120 seconds. For each case, I ran five trials. Each
trial consisted of hitting the reload button of the client browser after the session had
already timed out from the previous reload.
These results were obtained with Tomcat 3.1 as a stand-alone web server for both
Windows NT and Solaris. The browser used was Netscape 4.73.
Shown below is a servlet, TestSessionTimeout, that I used for measuring the actual
session timeout periods. For those new to servlets, the following comments should
prove useful for understanding this servlet:
The servlet shown below uses a SessionTimer class that implements the
HttpSessionBindingListener interface. When a session times out, the
SessionTimer object, timer, is notified of that fact. It then proceeds to calculate the
time difference between the creation time instant of the session and the time when
the session becomes invalidated.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
if ( timer == null ) {
timer = new SessionTimer( session.getCreationTime() );
session.setAttribute( TIMER_KEY, timer );
}
// Generate Output
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>" +
"<head><title>Session Information</title></head>" +
"<body bgcolor=\"#FFFFFF\">" +
"<h1>Session Information</h1><table>");
out.println ("<tr><td>Identifier</td>");
out.println ("<td>" + session.getId() + "</td></tr>");
out.println ("<tr><td>Created</td>");
out.println ("<td>" + new Date(session.getCreationTime()) +
"</td></tr>");
out.println ("<tr><td>Last Accessed</td>");
out.println ("<td>" + new Date(session.getLastAccessedTime()) +
"</td></tr>");
out.println ("<tr><td>New Session?</td>");
out.println ("<td>" + session.isNew() + "</td></tr>");
Enumeration names = session.getAttributeNames();
while ( names.hasMoreElements() ) {
String name = (String) names.nextElement();
out.println ("<tr><td>" + name + "</td>");
out.println ("<td>" + session.getAttribute(name) + "</td></tr>");
}
out.println("</table></center></body></html>");
out.close();
}
}
At the time of writing Tomcat 3.2 Beta nor Tomcat 3.3 Dev have an access log
comparable to the ones you can found in Apache,IIS or IPlanet, but in a near future
this will be solved.
Comments and alternative answers
How do I "make" mod_jserv with Borland C++? (I have make but not
nmake.)
Location: http://www.jguru.com/faq/view.jsp?EID=128573
Created: Aug 16, 2000 Modified: 2000-08-16 21:18:01.374
Author: Avi Kak (http://www.jguru.com/guru/viewbio.jsp?EID=26410) Question
originally posed by Rafael Coutinho
(http://www.jguru.com/guru/viewbio.jsp?EID=115513
If nmake would do the job, it is available as a self-extracting .exe for download from
ftp.microsoft.com/Softlib/MSLFILES/nmake15.exe
Using Tomcat, how can I log each and every call to the servlet engine
(something like apache-access.log) ?
Location: http://www.jguru.com/faq/view.jsp?EID=128735
Created: Aug 16, 2000 Modified: 2001-07-19 16:09:35.37
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Ofer Shaked
(http://www.jguru.com/guru/viewbio.jsp?EID=62619
As of version 3.2, the standalone version of Tomcat does not provide an access log.
It depends on the containing web server (e.g. Apache) for that function.
If you feel like it, it would be straightforward to write an Interceptor that does this.
Subscribe to [email protected], check out the latest CVS
tree, and have fun! That's the beauty of open source. (Make sure you support the
W3C standard log format, and see the Catalina source for inspiration; there's code in
there for formatting access log entries.)
A Web Application (or "webapp") is a concept that was introduced in the Servlet
Specification version 2.2. [2.1?] You should definitely read the spec for the full story.
From the spec (chapter 9):
A web application is a collection of servlets, html pages, classes, and other resources
that can be bundled and run on multiple containers from multiple vendors. A web
application is rooted at a specific path within a web server. For example, a catalog
application could be located at http:// www.mycorp.com/catalog. All requests that
start with this prefix will be routed to the ServletContext which represents the
catalog application.
A servlet container can also establish rules for automatic generation of web
applications. For example a ~user/ mapping could be used to map to a web
application based at /home/user/ public_html/.
[...]
A special directory exists within the application hierarchy named "WEB-INF". This
directory contains all things related to the application that aren't in the document
root of the application. It is important to note that the WEB-INF node is not part of
the public document tree of the application. No file contained in the WEB-INF
directory may be served directly to a client.
/index.html
/howto.jsp
/feedback.jsp
/images/banner.gif
/images/jumping.gif
/WEB-INF/web.xml
/WEB-INF/lib/jspbean.jar
/WEB-INF/classes/com/mycorp/servlets/MyServlet.class
/WEB-INF/classes/com/mycorp/util/MyUtils.class
Comments and alternative answers
JAVABEAN
Author: SANJAY DESHPANDE
(http://www.jguru.com/guru/viewbio.jsp?EID=452552), Apr 4, 2002
In this dir structure where to store JavaBeans? i ve them in \WEB-INF\Classes but it s
not working for me
Re: JAVABEAN
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727), Apr 4, 2002
Hi,
Java is a case sensitive language. "Classes" is different from "classes".
A WAR (or "web archive") file is simply a packaged webapp directory. It is created
using the standard Java jar tool. For example:
cd /home/alex/webapps/mywebapp
jar cf ../mywebapp.war *
Note that there are two different types of web.xml files in Tomcat 3.x: There is a
web.xml that sits in the top-level configuration directory TOMCAT_HOME/conf and then
there can be a separate web.xml for each webapp in the directory WEB-INF for that
webapp. You would want to keep webapp specific deployment information, such as
initialization parameters and their values, in the web.xml specific to that webapp.
The best on-line example that illustrates servlet initialization through a webapp's
deployment descriptor is, I believe, the ServletParam servlet in the test webapp in
your Tomcat software package. This servlet can be called with two different canonical
names, as for example in
http://localhost:8080/test/servlet/servletParam1
and
http://localhost:8080/test/servlet/servletParam2
The deployment descriptor maps the canonical names servletParam1 and
servletParam2 to the actual servlet ServletParam but with different values of the
initialization parameters. When the servlet ServletParam is called with the name
servletParam1, the initialization parameter-value pairs are
param1 value1
param2 value2
and when the same servlet is called with the name servletParam2, the parameter-
value pairs are
param3 value3
param4 value4
The following constitutes a sufficient deployment descriptor for this example:
<!-- filename: web.xml in the directory
TOMCAT_HOME/webapps/<your-webapp>/WEB-INF/ -->
<?xml version="1.0"?>
<web-app>
<servlet>
<servlet-name>
servletParam1
</servlet-name>
<servlet-class>
ServletParam
</servlet-class>
<init-param>
<param-name>param1</param-name>
<param-value>value1</param-value>
</init-param>
<init-param>
<param-name>param2</param-name>
<param-value>value2</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>
servletParam2
</servlet-name>
<servlet-class>
ServletParam
</servlet-class>
<init-param>
<param-name>param3</param-name>
<param-value>value3</param-value>
</init-param>
<init-param>
<param-name>param4</param-name>
<param-value>value5000</param-value>
</init-param>
</servlet>
</web-app>
The first half of the web.xml file associates the servlet ServletParam with the name
servletParam1 and then goes on to declare its parameter-value pairs. The second
half does the same for the name servletParam2.
Comments and alternative answers
How can I call a servlet from a JSP page? How can I pass variables from the
JSP that the servlet can access?
Location: http://www.jguru.com/faq/view.jsp?EID=129506
Created: Aug 17, 2000 Modified: 2000-08-18 20:03:16.052
Author: Priya Venkatesan (http://www.jguru.com/guru/viewbio.jsp?EID=129496)
Question originally posed by prasad musunuru
(http://www.jguru.com/guru/viewbio.jsp?EID=121993
<jsp:forward page=/relativepath/YourServlet>
<jsp:param name="name1" value="value1" />
<jsp:param name="name2" value="value2" />
</jsp:forward>
See also:
• What servlet code corresponds to the various "scope" values for the
<jsp:useBean> tag?
To get the parameter(s) that are passed from JSP page, ...
Author: Shankar Narayana (http://www.jguru.com/guru/viewbio.jsp?EID=82031),
Aug 19, 2000
ridgidbliptag = true;
The answer to this question is on page 20 of the Java Servlet API Specification
Version 2.2:
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.
Example:
This example uses the above method to set "connection" property to "Keep-Alive"
and invokes the so called "RequestHeaderExample" servlet and prints the response.
part of the output is given after the code.
While the example is an application, the same works in an applet.
}
Output:
accept text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
host my.host.com
connection Keep-Alive
user-agent Java1.3.0rc3
Comments and alternative answers
You can find the RFC for HTTP 1.1, which supports ...
Author: Yasar Qureshi (http://www.jguru.com/guru/viewbio.jsp?EID=48204), Aug
24, 2000
You can find the RFC for HTTP 1.1, which supports Keep-Alive, at
http://www.faqs.org/rfcs/rfc2068.html.
Bugtraq has had reports that Tomcat has vulnerabilities that allow remote
users to get paths and to compromise root if Tomcat is run as root. Are
these true?
Location: http://www.jguru.com/faq/view.jsp?EID=131224
Created: Aug 21, 2000 Modified: 2000-08-21 19:02:58.72
Author: Ignacio J. Ortega (http://www.jguru.com/guru/viewbio.jsp?EID=98626)
Question originally posed by zeno godofnothin
(http://www.jguru.com/guru/viewbio.jsp?EID=117406
• Stop Tomcat
• delete the contents of %TOMCAT_HOME%/work
• Delete the file: admin.war from %TOMCAT_HOME%/webapps
• Delete de directory %TOMCAT_HOME%/webapps/admin
• Start tomcat
Is there any way to retrieve all of the active session ids on a server? The
HttpSessionContext interface used to provide methods to do this, but has
since been deprecated in the 2.1 API.
Location: http://www.jguru.com/faq/view.jsp?EID=131912
Created: Aug 22, 2000 Modified: 2000-08-24 16:33:53.993
Author: Rahul kumar Gupta (http://www.jguru.com/guru/viewbio.jsp?EID=4809)
Question originally posed by Anne Goyarts
(http://www.jguru.com/guru/viewbio.jsp?EID=127284
There is no way to get the all session ids apart from HttpSessionContext.
Make a class that is using hash map or hash table object which is global to the
application. Whenever a user logs in make an entry into hashmap or hash table and
remove it when he/she logs out.
At any point you can retrieves keys and their values from that class that coresponds
to user identification and session object.
...
...
<%
allsessions.put(userid,session);
String user=null;
Enumeration users= allsessions.keys();
while(users.hasMoreElements())
{
user = users.nextElement();
out.println("Userid ="+user);
out.println("session = "+allsessions.get ((String)user));
}
%>
[This code doesn't quite work -- where is "userid" acquired? How do you capture
logout? But it's a nice hack anyway... -Alex]
Comments and alternative answers
The only way out seems to be the "official" way, whereby you make an object a
session listener.
Hiding "jsessionid"
Author: M. washu (http://www.jguru.com/guru/viewbio.jsp?EID=1217388), Dec
21, 2004
Hi all,
Is there a way to include jsessionid in a hidden field (in a form) rather than in the
URL (by the URL rewriting mechanism ) ?
I saw that HttpSessionContext class was deprecated for security reason, but for
security reasons too i would like to know if there is a way to prevent the jessionid
from being logged in the HTTP server log files (of course without using cookies) ?
Thanks in advance.
We are trying to access a large volume of data from a remote database, but
the time it takes to get the data from the database is more than the
maximum timeout for the web server, so the webpage is not getting
displayed. How can we solve this problem?
Location: http://www.jguru.com/faq/view.jsp?EID=132065
Created: Aug 22, 2000 Modified: 2000-08-25 20:14:51.715
Author: Nicholas Whitehead (http://www.jguru.com/guru/viewbio.jsp?EID=1260)
Question originally posed by Geetha Santhanam
(http://www.jguru.com/guru/viewbio.jsp?EID=63150
JDBC is not usually the root cause of the delay, so I'll make the obvious suggestions
first:
jGuru received several answers to this question on the JDBC side, most of which
emphasized narrowing the query to take less time. This is excellent advice, but not
always possible. Additionally, other tasks may bring up the same issues with servlets.
During January, 2000, there was an exchange of messages on Sun's servlet mailing
list which discussed the issue and provided a more general answer. Essentially, the
advice is to start a new thread in the servlet to do the work and then, using refresh
in the header, repeatedly send a status message until the long running task is done.
See the series Timing out of response data. Interestingly, probably the one that
outlines the process best is http://archives.java.sun.com/cgi-
bin/wa?A2=ind0001&L=servlet-interest&D=0&P=80267 by one Nicholas Whitehead.
Swarraj "sk or raj" Kulkarni and Kesav Kumar Kolla also contributed to this answer.
According to the Servlet 2.2 spec, you can set a servlet alias in the WEB-
INF/web.xml deployment descriptor for your webapp.
The <servlet-name> element defines the "canonical name" for the servlet. This
name is used to refer to the servlet elsewhere in the file.
For example:
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.stinky.HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>hi</url-pattern>
</servlet-mapping>
in the webapp "examples" would map the URL http://www.stinky.com/examples/hi to
the servlet com.stinky.HelloWorld.
The url-pattern can contain the wildcard character "*". For instance, Tomcat maps all
JSPs to the JspServlet using
<servlet>
<servlet-name>jsp</servlet-name>
<servlet-
class>org.apache.jasper.runtime.JspServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>jsp</servlet-name>
<url-pattern>*.jsp</url-pattern>
</servlet-mapping>
The url-pattern can also map entire paths to a single servlet; the url-pattern
"/catalog/*" would match a URL like
"http://www.stinky.com/examples/catalog/furniture/couches/futon". The servlet can
access the extra path info (past "catalog/") via the Request object using the
getPathInfo() method.
If your server does not support the Servlet 2.2 API, then it usually provides an
alternate method. Please submit feedback to tell how your favorite servlet engine
does it!
Location: http://www.jguru.com/faq/view.jsp?EID=134657
Created: Aug 25, 2000 Modified: 2000-08-25 08:48:29.763
Author: Stuart Woodward (http://www.jguru.com/guru/viewbio.jsp?EID=129604)
Question originally posed by Richard Goh Muk Ling
(http://www.jguru.com/guru/viewbio.jsp?EID=18858
In practice, with JSDK 2.0 it doesn't seem possible to trap this Exception. It seems
like it is trapped at a lower level and a Stacktrace printed to the console which
results in lots of garbage in the server logs. (Any corrections or advice about
avoiding this is highly welcome).
As a result you really have no choice but to just process the result of a GET/POST to
your Servlet regardless of whether the client actually recieves the response.
Sometimes an apparently cancelled request is the result of the client double clicking
on a link so you may have to take precautions that this doesn't result in say two
identical transactions being made.
Example:
try{
out.println( "test\n" );
Thread.sleep( 2 );
response.flushBuffer();
} catch( Exception e ){
log( "---> Exception " + e.toString() );
}
Hitting the STOP Button in the browser results in something like this:
Thomas
Re: Right, you have no choice in JSDK 2.0 but with JSDK...
Author: Sung Hyuk Jang
(http://www.jguru.com/guru/viewbio.jsp?EID=1022540), Nov 7, 2002
Hi. I tested the problem. (Servlet can't detect browser stopped.) I tested with
tomcat 4.0.3 and tomcat 3.2. I catched ioexception in tomcat3.2. but I can't catch
any exception in tomcat4.0.3. Why did it happen? Please Guru, tell me. my code is
below. <%@ page import="java.net.*,java.util.*,java.text.*,java.io.*"
contentType="text/html"%> <% try { while ( true ) { out.println("I am in loop
" ); out.flush(); response.flushBuffer(); System.out.println("I'm alive : " + new
Date()); Thread.sleep(1000); } } catch (Exception e) { System.out.println("I'm in
Exception : " + new Date()); } %>
exception
Author: david nierop (http://www.jguru.com/guru/viewbio.jsp?EID=418198), May 9,
2001
If you don't use sockets but http, printwriter does not throw any exceptions. Instead
you should call the checkerror() routine of printwriter to check it out. But the error
flags of printwriter are only set if the webserver is configured to do so. I read this in a
book form oreilly. Does anybody know how to configure your (Apache) server?
How can I parse an HTML page to capture a URL returned from, e.g., a
search engine?
Location: http://www.jguru.com/faq/view.jsp?EID=134999
Created: Aug 25, 2000 Modified: 2001-08-18 17:59:34.98
Author: Davanum Srinivas (http://www.jguru.com/guru/viewbio.jsp?EID=2011)
Question originally posed by Sharriff Aina
(http://www.jguru.com/guru/viewbio.jsp?EID=122696
It's decoded for you. The string you get from getParameter is the actual value the
user entered, after having been encoded by the browser and decoded by the servlet
engine.
This can cause some confusion when going back and forth from servlet to HTML to
servlet again, since it means that the number of encodes does not match the number
of decodes you have to write.
See also What is the difference between URL encoding, URL rewriting, and HTML
escaping?
How can I get access to the properties of my running WebLogic server that
have been set inside the weblogic.properties file? In particular I am after
the document root of my server.
Location: http://www.jguru.com/faq/view.jsp?EID=135221
Created: Aug 25, 2000 Modified: 2000-09-16 16:45:43.949
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by Nagendra V Prasad
(http://www.jguru.com/guru/viewbio.jsp?EID=108708
In WebLogic 5.1, to gain access to the weblogic properties, you can use the
ConfigServicesDef interface which is accessible from the T3Client. The particular
property that you are after is :
• weblogic.httpd.documentRoot
You may need to pre-pend the following properties to get the full path
• weblogic.system.home
• weblogic.system.name
The following is some sample code that should get you going
import weblogic.common.*;
Question
Author: sandhya sandhya (http://www.jguru.com/guru/viewbio.jsp?EID=455310), Jul
15, 2001
How can i get access to the properties of my running weblogic server 6.0?
Re: Question
Author: Radha Krishna Guduru
(http://www.jguru.com/guru/viewbio.jsp?EID=769952), Feb 25, 2002
Weblogic 6.0 doesn't have weblogic.properties like in weblogic5.1.
There is a config.xml in the mydomain folder under
bea/wlserver6.0/cofig/mydomain.
To get the configuration details you should need to use JMX API.
Here i have given a sample program which will make uses of the JMX
API.
import javax.naming.*;
import weblogic.jndi.Environment;
import weblogic.management.MBeanHome;
import weblogic.management.configuration.DomainMBean;
import weblogic.management.configuration.ServerMBean;
public AccessMBeanForJGuru()
{
}
public static void main(String args[])
{
String s = "t3://" + args[0] + ":" + args[1];
String s1 = "system";
try
{
Object obj = new InitialContext();
Environment environment = new Environment();
environment.setProviderUrl(s);
environment.setSecurityPrincipal(s1);
environment.setSecurityCredentials(args[2]);
obj = environment.getInitialContext();
MBeanHome mbeanhome = (MBeanHome)((Context)
(obj)).lookup("weblogic.management.adminhome");
DomainMBean domainmbean = mbeanhome.getActiveDomain();
System.out.println("The root directory for
the admin home of weblogic is"+domainmbean.getRootDirectory());
//using this domain bean object you
//can get and set attributes of
//config.xml at runtime. since domainbean
extends configuarationmbean
//..........................................
//................................
ServerMBean aservermbean[] = domainmbean.getServers();
System.out.println("No of servers in the domain " +
mbeanhome.getDomainName() + " " + aservermbean.length);
for(int i = 0; i < aservermbean.length; i++) {
System.out.println("The Server
"+i+" in domain is"+aservermbean[i].getName());
}
((Context) (obj)).close();
}
catch(AuthenticationException authenticationexception)
{
System.out.println("Authentication Exception: " +
authenticationexception);
}
catch(CommunicationException communicationexception)
{
System.out.println("Communication Exception: " +
communicationexception);
}
catch(NamingException namingexception)
{
System.out.println("Naming Exception: " +
namingexception);
}
}
}
Re[2]: Question
Author: Ben Macdonald
(http://www.jguru.com/guru/viewbio.jsp?EID=895571), May 28, 2002
If I define an attribute in the weblogic.xml file like: <weblogic-web-app>
..snip..
<session-descriptor>
<session-param>
<param-name>TimeoutSecs</param-name>
<param-value>3600</param-value>
</session-param>
</session-descriptor>
..snip..
Then using the code above, how would I reference this attribute
"TimeoutSecs"?
domainmbean.getAttribute("??.??.TimeoutSecs")
Re: Question
Author: madan kawle (http://www.jguru.com/guru/viewbio.jsp?EID=978499),
Aug 7, 2002
How to access user defined property file from Weblogic 6.x ?
I want the servlet container to load one or more servlets when the
container is first fired up, as opposed to when a client issues a request for
the servlets. How do I do that under Servlet 2.2 API?
Location: http://www.jguru.com/faq/view.jsp?EID=135396
Created: Aug 26, 2000 Modified: 2000-08-30 12:52:03.497
Author: Avi Kak (http://www.jguru.com/guru/viewbio.jsp?EID=26410)
Suppose you have two servlets, TestServlet_1 and TestServlet_2, that you'd like
to get automatically loaded in when the servlet container is first fired up. And let's
say that you want TestServlet_2 to be loaded before TestServlet_1. The following
web.xml file placed in the WEB-INF directory of the relevant webapp would do the
job.
<?xml version="1.0"?>
<!DOCTYPE web-app SYSTEM
"http://java.sun.com/j2ee/dtds/web-app_2.2.dtd">
<web-app>
<servlet>
<servlet-class>
TestServlet_1
</servlet-class>
<load-on-startup>
5
</load-on-startup>
</servlet>
<servlet>
<servlet-class>
TestServlet_2
</servlet-class>
<load-on-startup>
1
</load-on-startup>
</servlet>
</web-app>
The optional content of the load-on-startup element, the positive integer 5 for
TestServlet_1 and 1 for TestServlet_2, controls the order in which such servlets
would be loaded into the container at startup. The smaller the value of the integer,
which must be positive (even 0 is not allowed) to enable automatic loading at
startup, the earlier the servlet would be loaded. If no value is specified or if the value
specified is not a positive integer, the Tomcat 3.1 container will load the servlet only
when a request is received for the servlet.
Getting a servlet container to load a servlet at startup can be very useful in certain
applications, as for example pointed out by Alex Chaffee in a servlet FAQ posting.
See also
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jul 2, 2001
How can I set a servlet to load on startup of the ...
See also
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jul 15, 2001
Startup class in TOMCAT
How do I designate a servlet to serve as a default servlet for a given
webapp under Servlet 2.2 API?
Location: http://www.jguru.com/faq/view.jsp?EID=135638
Created: Aug 26, 2000 Modified: 2000-09-06 15:31:03.151
Author: Avi Kak (http://www.jguru.com/guru/viewbio.jsp?EID=26410)
If made available, a default servlet is executed by the server whenever the client
browser points to the URL
http://foo.com/mywebapp/
or to the URL
http://foo.com/mywebapp/nonExistentServlet
For example, for a webapp named test-suite, the deployment descriptor shown
below permits my server to execute the DefaultHelloServlet for the following
URLs:
http://localhost:8080/test-suite/
http://localhost:8080/test-suite/NonExistentServlet
for any pathname substituted for NonExistentServlet provided it does not begin
with /servlet/.
Here is the deployment descriptor (web.xml) for this example that sits in the WEB-
INF directory of my test-suite webapp:
<?xml version="1.0"?>
<web-app>
<servlet>
<servlet-name>
hello
</servlet-name>
<servlet-class>
DefaultHelloServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>
hello
</servlet-name>
<url-pattern>
/
</url-pattern>
</servlet-mapping>
</web-app>
See also Alex Chaffee's Servlet FAQ entry dealing with servlet aliasing.
Comments and alternative answers
Are there any known problems with Tomcat 3.2.1 and default servlets?
Author: Carmine Greco (http://www.jguru.com/guru/viewbio.jsp?EID=414482), May
3, 2001
I have tried to make a servlet the default servlet, as described above, but it's not
working. Are there any things to be careful about? I'm using Tomcat 3.2.1 on Linux.
Re: Are there any known problems with Tomcat 3.2.1 and default servlets?
Author: Carmine Greco (http://www.jguru.com/guru/viewbio.jsp?EID=414482),
May 3, 2001
I forgot to mention that I get a directory listing instead of the output of the servlet
I want to execute.
<servlet-mapping>
<servlet-name>
start
</servlet-name>
<url-pattern>
/
</url-pattern>
</servlet-mapping>
All that the StartController servlet does is to redirect the client to the right URL.
It seems to do its job (using standalone Tomcat 3.2.1, Sun JDK 1.2.2_005, Windows
2000 Professional) but all my images are now missing.
If I understand the Servlet 2.2. spec correctly, then what happens is that Tomcat
doesn't find any servlet which matches URL paths like "images/image.gif" and so
directs the request to the default servlet.
Thanks,
--Amos
See also:
• How do I send a redirect from a servlet?
• What are the different cases for using sendRedirect() vs.
getRequestDispatcher()?
• What is the difference between response.sendRedirect(),
RequestDispatcher.forward(), and PageContext.forward()?
The difference between the two is that sendRedirect always sends a header back to the
client/browser. this header then contains the resource(page/servlet) which you wanted
to be redirected. the browser uses this header to make another fresh request. thus
sendRedirect has a overhead as to the extra remort trip being incurred. it's like any
other Http request being generated by your browser. the advantage is that you can
point to any resource(whether on the same domain or some other domain). for eg if
sendRedirect was called at www.mydomain.com then it can also be used to redirect a
call to a resource on www.theserverside.com.
In the case of forward() call, the above is not true. resources from the server, where
the fwd. call was made, can only be requested for. But the major diff between the two
is that forward just routes the request to the new resources which you specify in your
forward call. that means this route is made by the servlet engine at the server level
only. no headers are sent to the browser which makes this very efficient. also the
request and response objects remain the same both from where the forward call was
made and the resource which was called.
Thanks,
Kiran
The Tomcat architecture allows for various front-ends or "connectors" to its servlet
engine. In Tomcat 3.1, there are connectors for HTTP (to function as a stand-alone
web server), IIS, and Netscape. There is no connector for Lotus Domino (either
finished or in progress), although you're more than welcome to write one and submit
it to the repository. :)
The following thread within the Server-side discussion forum at Javaworld offers
some concrete guidelines as to when to add EJB into the mix when designing large
web-based applications.
The HttpServletRequest object from 2.0 on provides a method for retrieving the
client's character encoding. The follwing sample gets the parameter mytext and
converts it to a java Unicode string.
try{
value = new String(value.getBytes(),
request.getCharacterEncoding());
}catch(java.io.UnsupportedEncodingException ex){
System.err.println(ex);
}
return value;
}
See also
The value of a chinese character entered in the INPUT text in the Form is read by
servlet and displayed as a %uh3h2h1h0, in IE5. In Netscape 4.7, the value is reads as
%h3h2%h1h0. Whereas, IE referes to a hexadecimal number. The values obtained
using java.net.URLDecoder.decode() method are senseless in the cases of both the
browsers. Any ideas why?
Re: Re: This doesn't work, anyone know how to make it work?
Author: Hartmut Bernecker
(http://www.jguru.com/guru/viewbio.jsp?EID=424953), Jun 27, 2001
Hi,
Concretely:
Who knows if it is possible to use the web.xml in Tomcat 3.2.2 to state that
each POST Request will be UTF-8 for example?
I'd like to see a Servlet 2.2 API version of Alex Chaffee's CookieDetector
servlet.
Location: http://www.jguru.com/faq/view.jsp?EID=138297
Created: Aug 30, 2000 Modified: 2000-09-06 13:34:19.675
Author: Avi Kak (http://www.jguru.com/guru/viewbio.jsp?EID=26410)
To create a Servlet 2.2 API version of Alex Chaffee's CookieDetector servlet, replace
the statement
This change in the code is needed to reflect the directory structure for a typical
webapp for Servlet 2.2 and the fact that the URL for accessing a servlet usually
includes the name of the webapp. For illustration, I have a webapp named test-
suite. The servlets for this webapp are in the directory
TOMCAT_HOME/webapps/test-suite/WEB-INF/classes/
and the URL I'd use to access, say, a HelloServlet in this webapp would be
http://RVL2.ecn.purdue.edu:8080/test-suite/servlet/HelloServlet
All that the replacement code does is to extract the name of the webapp from the
pathname string returned by the getRealPath method.
[Thanks Avi! Now I guess I'll have to go integrate these changes... -Alex]
Apache JServ is a servlet 2.0 compliant servlet engine, so the best you can do is the
JSP 1.0 spec (you can't use JSP 1.1 as it requires servlet 2.2).
As the name says it, it is communication between servlets. Servlets talking to each
other. [There are many ways to communicate between servlets, including
• Request Dispatching
• HTTP Redirect
• Servlet Chaining
• HTTP request (using sockets or the URLConnection class)
• Shared session, request, or application objects (beans)
• Direct method invocation (deprecated)
• Shared static or instance variables (deprecated)
Search the FAQ, especially topic Message Passing (including Request Dispatching) for
information on each of these techniques. -Alex]
Basically interServlet communication is acheived through servlet chaining. Which is a
process in which you pass the output of one servlet as the input to other. These
servlets should be running in the same server.
e.g. ServletContext.getRequestDispatcher(HttpRequest,
HttpResponse).forward("NextServlet") ; You can pass in the current request and
response object from the latest form submission to the next servlet/JSP. You can
modify these objects and pass them so that the next servlet/JSP can use the results
of this servlet.
There are some Servlet engine specific configurations for servlet chaining.
Servlets can also call public functions of other servlets running in the same server.
This can be done by obtaining a handle to the desired servlet through the
ServletContext Object by passing it the servlet name ( this object can return any
servlets running in the server). And then calling the function on the returned Servlet
object.
You must be careful when you call another servlet's methods. If the servlet that you
want to call implements the SingleThreadModel interface, your call could conflict with
the servlet's single threaded nature. (The server cannot intervene and make sure
your call happens when the servlet is not interacting with another client.) In this
case, your servlet should make an HTTP request to the other servlet instead of direct
calls.
When you use Tomcat standalone as your web server, you can modify the web.xml in
$TOMCAT_HOME/webapps/myApp/WEB-INF to add a url-pattern:
<web-app>
<servlet>
<servlet-name>
myServlet
</servlet-name>
<servlet-class>
myServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>
myServlet
</servlet-name>
<url-pattern>
/jsp-bin/*
</url-pattern>
</servlet-mapping>
</web-app>
This will let you use: http://webserver:8080/myApp/jsp-bin/stuff.html instead
of: http://webserver:8080/myApp/servlet/myServlet/stuff.html But it won't
work on port 80 if you've integrated Tomcat with Apache. Graeme Wallace provided
this trick to remedy the situation. Add the following to your tomcat-apache.conf (or
to a static version of it, since tomcat re-generates the conf file every time it starts):
<LocationMatch /myApp/jsp-bin/* >
SetHandler jserv-servlet
</LocationMatch>
This lets Apache turn over handling of the url pattern to your servlet.
Using mod_jk
Author: Kyle Tippetts (http://www.jguru.com/guru/viewbio.jsp?EID=131600), Mar
28, 2001
Does this work if you are using mod_jk? I have exactly the problem described here,
but I'm using mod_jk, not mod_jserv.
Re: Using mod_jk
Author: Donna Varnell (http://www.jguru.com/guru/viewbio.jsp?EID=400951),
Apr 11, 2001
I was able to get this to work by adding the following to httpd.conf (after the
include of the mod_jk.conf_auto): JkMount /myApp/jsp-bin/* ajp12. This told
Apache to send anything that matched that url pattern to Tomcat.
Depends on whether or not your servlet container uses thread pooling. If you do not
use a thread pool, the number of concurrent connections accepted by Tomcat 3.1, for
example, is 10. This you can see for yourself by testing a servlet with the Apache
JMeter tool.
However, if your servlet container uses a thread pool, you can specify the number of
concurrent connections to be accepted by the container. For Tomcat 3.1, the
information on how to do so is supplied with the documentation in the
TOMCAT_HOME/doc/uguide directory.
I had this problem myself. I found that I had to use a full HTTP URL in the redirect.
Relative paths do not work.
[Many WAP browsers do not understand redirects. Anyone with experience with
specific clients, please post a feedback. Thanks! -Alex]
There are many products which support servlets on Linux. Most of them operate
either in a standalone mode (acting as both web server and servlet engine) or as a
back-end servlet engine plugging in to an existing web server (like Apache).
See the individual products' web sites and README files for installation instructions.
You can also think of a RequestDispatcher object as a wrapper for the resource
located at a given path that is supplied as an argument to the
getRequestDispatcher method.
To illustrate, suppose you want Servlet_A to invoke Servlet_B. If they are both in
the same directory, you could accomplish this by incorporating the following code
fragment in either the service method or the doGet method of Servlet_A:
RequestDispatcher
Author: jamal Ghaus (http://www.jguru.com/guru/viewbio.jsp?EID=499352), Sep 18,
2001
Your answer is very good, however, does the forwarded request go to the Service()
method of the second servlet? Can one specify which method to forward the request
to.
Re: RequestDispatcher
Author: Eduardo Garcia (http://www.jguru.com/guru/viewbio.jsp?EID=1145466),
Feb 11, 2004
Hello ,how you doing? After reading your question, i resolved it passing a GET
parameter in the calling of the servlet, and then, in the doGet method compare this
parameter and call the apropiate method inside the forwarded servlet, something
like this:
public class servlet_that_forward extends HttpServlet {
public void doPost (HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
RequestDispatcher RD =
getServletContext).getRequestDispatcher("forwarded_servlet?param=method1");
RD.forward();
}
}
public class forwarded_servlet extends HttpServlet {
public void doGet (HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String param;
param = request.getParameter("param");
if (param.compareTo("method1")==0) {
method1();
}
}
public void method1() {
//Do something
}
}
Hope that can be helpful, :)
Re[2]: RequestDispatcher
Author: Narciso Rodrigues
(http://www.jguru.com/guru/viewbio.jsp?EID=1155821), Mar 19, 2004
I try your code ... and i get this error...
HTTP Status 405 - HTTP method GET is not supported by this URL
}
}
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
[Running on a WinNT4.0. Looked into the event_log but it's not there.] Hi,
You have four choices to select from: [Where do you set this option? -Alex]
1. Rolling File - Rolling files enable you to remove the old logs without affecting the
running service.
A rolling file collects log data until it reaches the size set in the Rollover File Size
setting.
2. Single File - A file that collects log data until it reaches the maximum size allowed.
3. Standard Output - In most cases, the terminal screen of the machine running Java
Web Server.
4. Standard Error - The default error log for the system running Java Web Server.
You can reduce cache size to 0KB (i.e. No Cache Option) and see your messages are
written to disk.
Option 2 i.e. Single File does not uses any cache. So you can see your message
Immediately
Option 2 and 3 dumps messages on standard output/error device. for this you have
to start (Under Winnt 4.0)
Start your Web server from DOS Window (not as service).
Shirish
How to allocate a certain amount of memory to JVM when starting Sun Java
Web Server?
Location: http://www.jguru.com/faq/view.jsp?EID=206856
Created: Sep 15, 2000 Modified: 2000-09-17 14:06:58.087
Author: Davanum Srinivas (http://www.jguru.com/guru/viewbio.jsp?EID=2011)
Question originally posed by Michael Mitiaguin
(http://www.jguru.com/guru/viewbio.jsp?EID=4719
With the latest JWS 2.0, There are two options. The first one is to specify a
command line argument -vmargs. The second one is to specify the arguments in
vmargs.txt. Check the release notes for more information.
http://www.sun.com/software/jwebserver/techinfo/jws20/release_notes.html
How to write a servlet which can transfer data written in ISO8859-1 into
GB2312 or another kind of character encoding?
Location: http://www.jguru.com/faq/view.jsp?EID=207294
Created: Sep 15, 2000 Modified: 2000-10-08 13:23:39.851
Author: Jonhi Ma (http://www.jguru.com/guru/viewbio.jsp?EID=131047) Question
originally posed by Jonhi Ma (http://www.jguru.com/guru/viewbio.jsp?EID=131047
You can use this method to transfer your data from one standard encoding to
another one. I have written it out and tested it under JSDK 2.0, and it runs well. The
following is the java code I have written.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
catch(Exception e)
{
//debugging begins here
System.out.println(e);
//debugging ends here
return("null");
}
return conResult;
}//method convert ends here
You should always check and verify character encoding and Supported Encodings. In
addition, the international version of the JDK/JRE is required to have all the
encodings available.
I am using weblogic 5.1 with SP4. Can you explain why the JVM always require
Cp1252 as the source encoding? Lia
Re: I have tried the above code. But the from standard...
Author: Ivan Lee (http://www.jguru.com/guru/viewbio.jsp?EID=787737), Mar 8,
2002
It depends on your regional settings. If you were using Chinese(Traditional)
within the regional settings in Start-> Settings-> Control Panel-> Regional
Settings, then your default encoding would be GB2312. The JVM, when started
always looks at the regional settings of the PC.
How to encoding string from iso-8859-1 to GB2312 charset : data = new String(
data.getBytes("iso-8859-1"), "GB2312")
Author: seokjin seo (http://www.jguru.com/guru/viewbio.jsp?EID=817440), Feb 23,
2004
try {
String data = request.getParameter("data");
if(data != null) {
data = new String( data.getBytes("iso-8859-1"), "GB2312");
} catch(Exception e) { }
How to throw a dynamic xml page from a Servlet to Cocoon ?
Location: http://www.jguru.com/faq/view.jsp?EID=208318
Created: Sep 17, 2000 Modified: 2000-09-17 15:45:10.007
Author: Davanum Srinivas (http://www.jguru.com/guru/viewbio.jsp?EID=2011)
Question originally posed by John P James
(http://www.jguru.com/guru/viewbio.jsp?EID=125241
In Cocoon's parlance, you need to write a "Producer" servlet which can generate a
valid XML file from the HttpServletRequest parameters. An example FileProducer
bundled into Cocoon can load a requested file from disk. Another sample
DummyProducer is at:
http://xml.apache.org/cocoon/dynamic.html
According to the Servlet 2.2 spec, "The getRequestDispatcher method takes a String
argument describing a path within the scope of the ServletContext. This path must
be relative to the root of the ServletContext."
http://www.foo.com/shopping/service/support.html
is accessed with the call
context.getRequestDispatcher("/service/support.html")
response.sendRedirect("/shopping/service/support.html");
or, more generally,
response.sendRedirect(request.getContextPath() +
"/service/support.html");
Note that a path beginning with "/" is often called an "absolute URL," but this is
misleading, since
First, load the image. If you have Swing, you can use
Once you have loaded the image, you can use its getHeight() and getWidth()
methods, which work as expected.
No getWidth()
Author: Csongor Fagyal (http://www.jguru.com/guru/viewbio.jsp?EID=538458), Nov
4, 2001
Actually no getWidth() or getHeight() methods are available (at least in 1.3.1), you
can only use getHeight(ImageObserver) and getWidth(ImageObserver, or a
BufferedImage, which does have getHeight() and getWidth().
A Servlet Context is a grouping under which related servlets (and JSPs and other
web resources) run. They can share data, URL namespace, and other resources.
There can be multiple contexts in a single servlet container.
The ServletContext object is used by an individual servlet to "call back" and obtain
services from the container (such as a request dispatcher). Read the JavaDoc for
javax.servlet.ServletContext for more information.
You can maintain "application global" variables by using Servlet Context Attributes.
Servlet Context
Author: Srini Pillai (http://www.jguru.com/guru/viewbio.jsp?EID=485621), Aug 28,
2001
I am not able to digest the fact that a servlet container can have multiple Servlet
Context. If it has multiple Contexts, then how can you maintain an "application
scope" variables using the Servlet Context's setAttribute method.
Comparend to a sigleton?
Author: Fredric Palmgren (http://www.jguru.com/guru/viewbio.jsp?EID=1092794),
Mar 31, 2004
Today I am using a singleton to supply application wide parameters like different
caches. Would server context be a better alternative then the singleton?
The originally called servlet has passed the control to the current servlet, and now
current servlet is acting as controller to other resourses.
It seems that Tomcat 3.2 and ServletExec 3.0 treat relative paths in
RequestDispatcher.forward() differently.
Tomcat, as far as I've analysed it, treats the relative path to be relative to the web
application's "base", as I would expect, but ServletExec seems to require an absolute
path (not absolute URL, just path, with a "/" in front of it) in order to reach the same
relative resource.
I'm talking about a RequestDispatcher obtained via the Request, not the
ServletContext.
Thanks.
For the best explaination of this question pl. see the apache site:
The in-process Servlet containers are the containers which work inside the JVM of
Web server, these provides good performance but poor in scalibility.
The out-of-process containers are the containers which work in the JVM outside the
web server. poor in performance but better in scalibility
In the case of out-of-process containers, web server and container talks with each
other by using the some standard mechanism like IPC.
NOTE : ServletServlet does not enforce any security access over the servlets in the
weblogic server.
Anyone having access to ServletServlet can invoke any other servlet running in the
server.
You might not want to use it in a production environment.
The question mixes together two rather independent aspects of a servlet container:
"concurrency control" and "thread pooling".
Section 3.3.3.1 of the Servlet 2.2 API Specification document says that if a servlet
implements the SingleThreadModel it is guaranteed "that only one request thread at
time will be allowed in the service method." It says further that "a servlet container
may satisfy this guarantee by serializing requests on a servlet or by maintaining a
pool of servlet instances."
Obviously, for superior performance you'd want the servlet container to create
multiple instances of a SingleThreadModel type servlet should there be many
requests received in quick succession. Whether or not a servlet container does that
depends completely on the implementation. My experiments show that Tomcat 3.1
does indeed create multiple instances of a SingleThreadModel servlet, but only for
the first batch of requests received concurrently. For subsequent batches of
concurrent requests, it seems to use only one of those instances.
All servlet containers that implement the Servlet 2.2 API must provide for session
tracking through either the use of cookies or through URL rewriting. All Tomcat
servlet containers support session tracking.
See also the jGuru Servlets FAQ entries by Alex Chaffee and Simon Wong.
Are there any freeware App Servers that support this feature?
Yes, JAAS can be used as authentication technology for servlets. One important
feature of JAAS is pure Java implementation. The JAAS infrastructure is divided into
two main components: an authentication component and an authorization
component. The JAAS authentication component provides the ability to reliably and
securely determine who is currently executing Java code, regardless of whether the
code is running as an application, an applet, a bean, or a servlet.
Comments and alternative answers
How can I set a servlet to load on startup of the container, rather than on
the first request?
Location: http://www.jguru.com/faq/view.jsp?EID=218109
Created: Sep 28, 2000 Modified: 2000-09-28 21:54:41.937
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Jeremy Butler
(http://www.jguru.com/guru/viewbio.jsp?EID=141352
The Servlet 2.2 spec defines a load-on-startup element for just this purpose. Put it in
the <servlet> section of your web.xml deployment descriptor. It is either empty
(<load-on-startup/>) or contains "a positive integer indicating the order in which the
servlet should be loaded. Lower integers are loaded before higher integers. If no
value is specified, or if the value specified is not a positive integer, the container is
free to load it at any time in the startup sequence."
For example,
<servlet>
<servlet-name>foo</servlet-name>
<servlet-class>com.foo.servlets.Foo</servlet-class>
<load-on-startup>5</load-on-startup>
</servlet>
Some servlet containers also have their own techniques for configuring this; please
submit feedback with information on these.
Alternate method
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jul 2, 2001
For an alternative, see Bozidar Dangubic's post at calling init() Servlet after the
Tomcat webserver ...
See also
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jul 2, 2001
I want the servlet container to load one or more s...
Yes. It would spawn a thread that opens a ServerSocket, then listens for incoming
connections and speaks the FTP protocol.
Unfortunately I don't know of any source for FTP Server code. You may want to look
at http://www.jguru.com/jguru/faq/view.jsp?EID=107270 for more information.
How can my servlet determine the appropriate MIME type to set in the
response, based on the file extension of the file being sent?
Location: http://www.jguru.com/faq/view.jsp?EID=218913
Created: Sep 29, 2000 Modified: 2000-10-03 10:26:24.607
Author: swarraj kulkarni (http://www.jguru.com/guru/viewbio.jsp?EID=121306)
Question originally posed by Carfield Yim
(http://www.jguru.com/guru/viewbio.jsp?EID=4648
There is no automatic way for the servlet to determine the MIME type as per the
extension of the file being served to client.
In the servlet code you can have the swich kind of code where you can set the MIME
type as per the file extension type.
Here is the link which specifies all the extension types and required MIME types: File
Extensions and MIME types
getServletContext().getMimeType(File2View)
[I'm currently using Java Servlets as part of an administration program. I'm having a
problem in that the user can double click the save button (a submit image) and save
a record twice by accident.]
Give the submit image (or button) an onClick() handler. Have the handler check if a
flag is set and if not set the flag and submit the form and then clear the form.
Where can I find information about the i18n capabilities of the major
browsers?
Location: http://www.jguru.com/faq/view.jsp?EID=219545
Created: Sep 30, 2000 Modified: 2000-09-30 10:10:59.636
Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)
For Netscape see Welcome to Netscape International!. For Microsoft see International
Home Pages.
The first difference is obviously that Servlets is the technology from Sun
Microsystems and ISAPI is from Microsoft.
Other Differences are:
Yes it is.
it this true?
Author: Korey Sed (http://www.jguru.com/guru/viewbio.jsp?EID=488552), Sep 1,
2001
From what I read in the documentation, it seems to be the same, but when I tried it, it
only printed that the page that I was requesting is not in another location, where
another location was the string URL I provided to sendRedirect.
I'm a little puzzled!
Can a JavaBean access methods/implicit objects of the JSP page which
created it?
Location: http://www.jguru.com/faq/view.jsp?EID=222393
Created: Oct 4, 2000 Modified: 2000-10-05 21:51:18.598
Author: Ryan Breidenbach (http://www.jguru.com/guru/viewbio.jsp?EID=45212)
Question originally posed by Bruno Randolf
(http://www.jguru.com/guru/viewbio.jsp?EID=94633
Yes, they can, but not by virtue of the fact that they are being used in a JSP page. In
order for a JavaBean to access the methods/implicit objects of a JSP page, it has to
be initialized with a handle or reference to the page itself.
Now, your bean can access the implicit objects and methods of the calling JSP page.
You have two major options, JNI and CORBA. JNI is Java's gateway to languages that
can link with C. CORBA is OMG's Common Object Request Broker Architecture. Both
are pretty hard to use.
[See the jGuru JNI FAQ and CORBA FAQ for more information on using these
technologies. -Alex Chaffee]
JunC++ion is a product that is built on top of JNI and makes the Java/C++
interoperability problem basically a non-issue. JunC++ion generates proxy classes
for compiled Java classes, for example for a Servlet class. It also performs the task
of the javah compiler but goes one step further: it generates an implementation of
the native method that delegates to a C++ method. This allows you for example to
implement a native servlet method in C++ like this:
void _cmj_Java_MyServlet_doHandleGet( jcpp_localenv * _env,
MyServlet & _this, HttpServletRequest & _req,
HttpServletResponse & _resp )
{
ServletOutputStream os = _resp.getOutputStream();
char buffer[ 512 ];
os.println( "<!-- from native start -->" );
try
{
sprintf( buffer, "This is a message from %s\n", call_cpp_api() );
os.println( buffer );
}
catch(...)
{
throw MyException( "something bad happened" );
}
os.println( "<!-- from native end -->" );
}
JunC++ion is currently available on Wintel but is actively being ported to Solaris,
AIX, Linux and HP-UX. More information is available at http://www.codemesh.com
[Note that Alexander Krapf, the author of this answer, is the president of CodeMesh.
-Alex Chaffee]
Just treat the servlet as normal CORBA client. First , put the code which you used to
invoke CORBA object in client application's main() method to the doGet() method of
your servlet. Second, register servlet to web server. And at last you can send request
for that servlet from your browser. In this way, you have invoked CORBA from the
servlet. If you are not familiar with how to invoke CORBA from a normal CORBA
client application, you can find the code somewhere in the FAQs of CORBA.
In web.xml you can use a mime-mapping to map the type with a certain extension
and then map the servlet to that extension.
e.g.
<mime-mapping>
<extension>
zzz
</extension>
<mime-type>
text/plain
</mime-type>
</mime-mapping>
<servlet-mapping>
<url>
*.zzz
</url>
<servlet-name>
MyServlet
</servlet-name>
</servlet-mapping>
So, when a file for type zzz is requested, the servlet gets called.
Take a look on Cocoon demo apps. There's a demo for this in there.
When you want to preserve the current request/response objects and transfer them
to another resource WITHIN the context, you must use getRequestDispatcher or
getNamedDispatcher.
If you want to dispatch to resources OUTSIDE the context, then you must use
sendRedirect. In this case you won't be sending the original request/response
objects, but you will be sending a header asking to the browser to issue a request to
the new URL.
If you don't need to preserve the request/response objects, you can use either.
The simplest way is to write your JSP (or strings in your servlet) to use the HTML
entity escape characters for Unicode. For instance, the string "Ýðüö" would be
represented as
Ýðüö
or
Ýðüö
Another option is to set the character encoding for the response and output binary
(Unicode) data directly. From the Javadoc for ServletResponse:
The charset for the MIME body response can be specified with
setContentType(java.lang.String. For example, "text/html; charset=Shift_JIS".
The charset can alternately be set using setLocale(java.util.Locale). If no
charset is specified, ISO-8859-1 will be used. The setContentType or setLocale
method must be called before getWriter for the charset to affect the construction of
the writer.
See the Internet RFCs such as RFC 2045 for more information on MIME. Protocols
such as SMTP and HTTP define profiles of MIME, and those standards are still
evolving.
In addition, the international version of the JDK/JRE is required to have all the
encodings available.
See also
• http://hotwired.lycos.com/webmonkey/reference/special_characters/
• What is the difference between URL encoding, URL rewriting, and HTML
escaping?
• character encoding
• Supported Encodings
• How to write a servlet which can transfer data written in ISO8859-1 into
GB2312 or another kind of character encoding?
Comments and alternative answers
Oops
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Sep 25, 2001
Note that I just fixed a serious bug in my htmlunescape method... Sorry about that...
Download at http://www.purpletech.com/code/src/com/purpletech/util/Utils.java
Where should I place a properties file in the java web server 2.0? How will
you access the properties file using Resource Bundle?
Location: http://www.jguru.com/faq/view.jsp?EID=225511
Created: Oct 9, 2000 Modified: 2000-10-24 10:18:11.38
Author: Shirish Bathe (http://www.jguru.com/guru/viewbio.jsp?EID=88588)
Question originally posed by ganesan ganesan
(http://www.jguru.com/guru/viewbio.jsp?EID=211734
All Resources are located and loaded as normal class. The task is performed by the
ClassLoader class. The ClassLoader class uses a delegation model to search for
classes and resources.
Normally, the Java virtual machine loads classes from the local file system in a
platform-dependent manner. For example, on UNIX systems, the virtual machine
loads classes from the directory defined by the CLASSPATH environment variable.
To access properties file using Resource Bundle. Please refer to NotePad Application
Demo. It is avaliable with JSDK 2.0.
Thanks
Shirish
([email protected])
The pertinent thing here is to add the directory where your Resource Bundle
properties file is located, to the CLASSPATH on your Web Server PC.
HTH,
Fintan
You can manipulate cookies in JavaScript with the document.cookie property. You can
set a cookie by assigning this property, and retrieve one by reading its current value.
The following statement, for example, sets a new cookie with a minimum number of
attributes:
document.cookie = "cookieName=cookieValue";
alert(document.cookie);
The value of document.cookie is a string containing a list of all cookies that are
associated
with a web page. It consists, that is, of name=value pairs for each cookie that
matches the
current domain, path, and date. The value of the document.cookie property, for
instance,
might be the following string:
cookieName1=cookieValue1; cookieName2=cookieValue2;
Shirish ([email protected])
I'm not really sure how/why you would convert an applet to a servlet. Applets are
small applications that run on a client computer, typically with a GUI interface.
Servlets process request to a server. So there doesn't seem to be a clear way/reason
to convert an applet to a servlet.
CGI scripts and servlets do basically the same job - back end processing on a server.
Basically, all you have to do is alter any web pages that post to a CGI script to now
post to a corresponding servlet. Then you would simply have the servlet perform the
same processing that the CGI script did.
And, as I am sure you are aware, converting from CGI scripts to servlets is a good
idea. This should not only increase the performance of your web application, but give
all the benedits of programming in Java.
How do I write to a log file using JSP under Tomcat? Can I make use of the
log() method for this?
Location: http://www.jguru.com/faq/view.jsp?EID=228620
Created: Oct 14, 2000 Modified: 2001-07-19 15:42:34.817
Author: Serge Knystautas (http://www.jguru.com/guru/viewbio.jsp?EID=100012)
Question originally posed by Peter Gelderbloem
(http://www.jguru.com/guru/viewbio.jsp?EID=91670
Yes, you can use the Servlet API's log method in Tomcat from within JSPs or servlets.
These messages are stored in the server's log directory in a file called servlet.log.
The problem is that you need to dump all the order details that you now have in the
hidden fields into a database and MCK doesn't do this for you. So what i did was use
some javascript in the success.tem file that does the following :
<body onload="document.successForm.submit()">
<FORM name="successForm" action="/context/jsp/success.jsp">
So the user receives the success response from Cybercash into a success.tem page
which doesn't stay for long because it autosubmitts to a success.jsp page which can
retrieve all the order/customer data from the hidden fields of success.tem and dump
them into a database, send confirmation email , etc.
It works but the main problem is that if the user presses the browser's "Back" button
from the success.jsp he will go to the success.tem which will autosubmit again and
try to redump all the same order data to the database.
Unfortunately you cannot tell MCK to send the order response directly to a .jsp page
and do it the right way.
You are supposed to know CGI programming and customize directly the
directpaycradit.cgi script and dump all the transaction details from within that script
before it forwards to the success.tem file.
Unfortunately, the servlet spec does not allow you to change the HTTP method of a
dispatched request (from GET to POST or vice versa).
This is a problem if you want to call a servlet that only responds to a POST request,
or that has different implementations for doGet and doPost. (This is poor servlet
design, but using someone else's servlet, you may not have a choice.)
You can work around this by using a URLConnection as in
http://www.jguru.com/jguru/faq/view.jsp?EID=62798
How can I use a servlet to print a file on a printer attached to the client?
Location: http://www.jguru.com/faq/view.jsp?EID=232366
Created: Oct 19, 2000 Modified: 2001-06-24 11:04:49.495
Author: Serge Knystautas (http://www.jguru.com/guru/viewbio.jsp?EID=100012)
Question originally posed by sonali khanolkar
(http://www.jguru.com/guru/viewbio.jsp?EID=213541
The security in a browser is designed to restrict you from automating things like this.
However, you can use JavaScript in the HTML your servlet returns to print a frame.
The browser will still confirm the print job with the user, so you can't completely
automate this. Also, you'll be printing whatever the browser is displaying (it will not
reliably print plug-ins or applets), so normally you are restricted to HTML and
images.
First you should consider how you want to run your command-line Java interpreter.
Do you want this to happen within the same Java Virtual Machine (JVM), i.e., the
same memory space, that the servlet is running or do you want it to be a separate
process?
If you want to run it within the JVM, you can call the static main() method on the
class you were going to run on the command-line. You would create a String array
with whatever command-line arguments you were going to pass, and pass this to the
main() method.
If you want to run this in a separate JVM, you would use the
java.lang.Runtime.exec() method. You would use the exec() method to run the new
command-line and more than likely, wait for the command-line program to finish
executing. Here is some sample code:
Runtime rt = Runtime.getRuntime();
Process process = rt.exec("java MyClass arg1 arg2");
try {
process.waitFor();
} catch (InterruptedException ie) {
ie.printStackTrace();
}
[ See also http://www.jguru.com/jguru/faq/view.jsp?EID=209356 ]
[ You can also bypass servlets altogether using the JavaCGI package. -Alex]
Michael Wu
How can I use a servlet to print a file on a printer attached to the server?
Location: http://www.jguru.com/faq/view.jsp?EID=232378
Created: Oct 19, 2000 Modified: 2000-10-24 10:19:16.647
Author: Serge Knystautas (http://www.jguru.com/guru/viewbio.jsp?EID=100012)
Question originally posed by sonali khanolkar
(http://www.jguru.com/guru/viewbio.jsp?EID=213541
This depends on how your printers are attached to your computer. I can think of two
basic ways you can print to a printer attached to the server.
The second approach is more OS specific. You could create a temporary file and copy
that file to the printer device. This would allow you more flexibility and ease in terms
of what you could print, but would tie you into how your OS provided printer devices.
First off, if www.foo.com is going to be the only hostname served off your machine,
then it's not technically a virtual host. Virtual hosting is when you want multiple
hostnames to be served off the same machine. If there's only one hostname, then
it's an "actual" host :-)
In any case, you need to contact your ISP and ask them to set up a DNS mapping
from www.foo.com to your machine's static IP address, and configure your machine
and/or web server so it thinks "www.foo.com" is its own name. Technical details of
this process are outside the scope of this FAQ (though if someone wants to submit a
feedback with a pointer to instructions, please do).
There are two techniques for true virtual hosting. (Both require the involvement of
your DNS ISP, as above.)
See the references below for more information on enabling IP aliasing for your OS.
From this point, configuration details vary widely based on your operating system,
your web server, and your servlet engine. We will defer answering them here;
instead, we request specific FAQ questions on each combination of web server and
servlet engine.
If your servlet engine supports the Servlet spec 2.2 or greater, you will probably
need to re-map the "default context", so "/" maps to "/mywebapp/". See this FAQ for
doing this on Tomcat.
See also:
In order to make the document appear to load more quickly, the Acrobat Reader
relies on two features. First, you must of course make sure the PDF file is in the
linearized format which the author of the PDF should be able to do. Second, since
you are serving the file from a servlet, you must support the HTTP protocol features
that Acrobat is depending on.
In short summary, when Acrobat receives the first part of file it can determine that it
is in linearized form. This enables it to cache the tables that are present at the
beginning of the file and then close the connection, preventing the entire document
from downloading all at once. From then on Acrobat fetches each page or object as it
is needed from the web server. It does this by using the HTTP byte range headers in
requests, and your servlet needs to support these for it to work properly.
The byte range headers are described in the HTTP/1.1 RFC #2616 section 14.35, but
a brief description is that in any HTTP request there may be extra headers that
indicate the client is requesting only part of the entity, rather than the full entity.
These headers indicate a byte range, or offest and length, that the client is asking
for. An example is:
The key to making this work in HTTP 1.1 is in the way the server responds to such
requests. If the server does not understand the byte range headers, it will reply in
ignorance with the usual "200 OK" and send the entire file. But if it does understand
the byte range headers, it replies with a "206 Partial Content" and sends only the
requested portion of the file. Looking at the response code is how different client
programs are able to display whether a server supports "resumable downloads." If
you can program your servlet to support these requests for partial content, I think
you'll get the result you want.
[Short answer: no modern browser uses HTTP PUT for anything meaningful, so
doPut() is never used, except for a custom protocol. If you want to upload a file,
see How do I upload a file to my servlet? -Alex]
POST means to apply the content accompanying the request to the entity in the
request URI, usually in the sense that the entity processes the content and returns
some data as the result. Servlets and CGI scripts fit this description.
PUT means very simply that the accompanying content *is* the entity described by
the request URI, and the server is being asked to store it as such. So the following
conversation makes sense when PUT is used:
Hello!
<-HTTP/1.1 200 OK
<-HTTP/1.1 200 OK
Content-Length: 6
Content-Type: text/plain
Hello!
Is there only one ServletContext instance associated with all the servlets
running in a 2.1 (or prior) compliant servlet engine?
Location: http://www.jguru.com/faq/view.jsp?EID=236603
Created: Oct 25, 2000 Modified: 2000-10-26 09:44:27.876
Author: Garth Somerville (http://www.jguru.com/guru/viewbio.jsp?EID=225821)
Question originally posed by sharad gupta
(http://www.jguru.com/guru/viewbio.jsp?EID=100198
Essentially the answer is yes, although even in the 2.1 specification it would have
been permissible for a container to define multiple contexts either based on virtual
hosts or based on part of the request URL, the same way it is done in 2.2. But I think
the practical answer is yes, there is one context.
Re: But why does it happen only when I use Netscape as...
Author: John Scudder (http://www.jguru.com/guru/viewbio.jsp?EID=252439),
Apr 26, 2001
open up <TOMCAT_HOME>/conf/server.xml change your Logger "tc_log" tag's
verbosityLevel to "WARNING" rather than "INFORMATION". There are five
different options, and "WARNING" won't place any garbage on our standard
output. See the comments in server.xml for more details. <Logger name="tc_log"
verbosityLevel = "WARNING" />
Re: Re: But why does it happen only when I use Netscape as...
Author: Dinu Jose Varghese
(http://www.jguru.com/guru/viewbio.jsp?EID=440122), Jun 16, 2001
Thank u very much. i was very much worried about this socket error coming
on the console. When the verbosity level is set to warning in the server.xml
,these error messages are gone from the console.
Craig says
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jul 19, 2001
Craig McClanahan says, on the tomcat-dev mailing list:
The server is reporting "connection reset by peer" in the middle of a request. That
means one of the following things:
The problem was a submit button in a form which had its onClick attribute set to
"location=URL". Upon clicking the button, javascript wants to go to URL while
the form wants to go to its own url as specified by its action attribute The
problem is solved by adding "return false" to the onClick attribute to prevent
the onClick event from being passed on to the form:
This only worked for me because I did not need to know the response of the
servlet, I just needed it to go and do something. But this stops the connection reset
by peer problem because the servlet responds straight away.
Re[2]: Another question on this....
Author: Suresh Addagalla
(http://www.jguru.com/guru/viewbio.jsp?EID=449405), Feb 7, 2002
Hi,
I can understand if 'Connection reset by peer' is reported by web server when
the user presses stop or reload. I am facing a problem where JRun is reading a
request from iPlanet, and JRun thows this exception. Any ideas as to what
could be wrong?
Thanks in Advance,
Suresh
thanks:)
I use a servlet to export WML on the Nokia Toolkit. Why can't I output a
Chinese String (GB2313 or UNICODE)?
Location: http://www.jguru.com/faq/view.jsp?EID=238455
Created: Oct 27, 2000 Modified: 2000-11-02 15:32:26.224
Author: Brian O'Byrne (http://www.jguru.com/guru/viewbio.jsp?EID=38567)
Question originally posed by chile wang
(http://www.jguru.com/guru/viewbio.jsp?EID=138876
The WAP protocol gaurantees only 7-bit ASCII, which limits you to the most basic
character sets.
Most 'phones will support 8-bit ASCII. AFAIK none support Unicode.
Not with Servlet spec 2.2. The next version of the spec will allow you to pass in your
own response object to the request dispatcher, which can intercept header and
cookie setting calls, and record them for your later inspection.
When I'm using the getCookies() method (of HttpServletRequest) I get only
the cookie(s) I set. How can I get all the cookies on my HD?
Location: http://www.jguru.com/faq/view.jsp?EID=245303
Created: Nov 4, 2000 Modified: 2000-11-04 19:07:10.516
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Zvi Septon
(http://www.jguru.com/guru/viewbio.jsp?EID=226023
How do I share sessions between two server instances, one secure (HTTPS)
and one normal (HTTP)?
Location: http://www.jguru.com/faq/view.jsp?EID=245672
Created: Nov 5, 2000 Modified: 2000-11-30 08:57:13.73
Author: Ryan Breidenbach (http://www.jguru.com/guru/viewbio.jsp?EID=45212)
Question originally posed by ewhale ewhale
(http://www.jguru.com/guru/viewbio.jsp?EID=133291
The management of sessions is handled by your servlet container. That is, you will
never have to write any custom code so you can share sessions between servlets - it
is already handled for you. The entry point from the servlet container to your servlet
will always be the service(HttpServletRequest req, HttpServletResponse res)
method. Since this method takes an HttpServletRequest object as a parameter,
you can always call getSession() to access the HttpSession.
As far as having two servlets - one for HTTP and one for HTTPS - these should
behave basically the same. All of the HTTPS encryption/decryption is hidden from the
servlet. Unless your HTTPS servlet needs to have some code to ensure it is
processing a request whose protocol is HTTPS, these two servlets should be pretty
much the same.
See also Can I move between http and https-based resources while sharing the same
session? in the JSP FAQ.
[If the two servers are actually distinct, then you'd have to find some way of
tunneling the data across. Hidden fields are probably your best bet, although that
may not suit your security policy. -Alex]
Where and how can I define an application level variable that gets
initialized at container startup? Something like the Application_OnStart Sub
in the global.asa file of MicroSoft ASP.
Location: http://www.jguru.com/faq/view.jsp?EID=245909
Created: Nov 5, 2000 Modified: 2000-12-07 21:15:56.603
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Mattias Deny
(http://www.jguru.com/guru/viewbio.jsp?EID=227945
Make an InitServlet and initialize it in there. See I want the servlet container to load
one or more servlets when the container is first fired up, as opposed to when a client
issues a request for the servlets. How do I do that under Servlet 2.2 API?. Create it,
then put in as a ServletContext Attribute.
MyData mydata = new MyData();
getServletContext().setAttribute("some.attribute.name", mydata);
Comments and alternative answers
If you want to share the information in non servlet classes (connection pools, etc) you
can create a "Singleton" object (kind of) that holds all the data you want to share. For
flexible data sharing a map would be a good idea.
Create the instance of the Object in the described startup servlet and access it in the
hole application with a static getInstance()-method.
[statics are almost always a bad idea. Use an application (context) variable instead.
Then you won't get burned by, e.g., multiple applications using the same code. -Alex]
For downloading an image, sound, or video file (GIF, JPEG, MP3, WAV, AVI, et al.),
see How do I download a (binary, text, executable) file from a servlet or JSP? and
How do I create an image (GIF, JPEG, etc.) on the fly from a servlet? .
There is no explicit support for streaming media protocols in the Servlet API. You
would have to write, or locate, your own RealAudio or ShoutCast server (for
example).
Actually, it is possible (and not that hard) to send binary info from a servlet. You have
to call getOutputStream() on your response object, and feed it your data. Included is a
snippet from the output portion of a servlet I wrote that dynamically generates
JPEGS.
res.setContentType("image/jpeg");
ServletOutputStream sout = res.getOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sout);
encoder.encode(workingImage,JPEGparams);
[Thanks! I don't think that deserves an "Actually" though -- that technique is
documented in the above referenced FAQs. - Alex]
HTML suggestion
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jul 15, 2001
ramanujam ragavan suggests:
Hi, You can always embed vedios using the <Embed src="filename.mpg"> as part of
the HTML output specified by the PrintWriter.println() statement. ex:
PrintWriter display=response.getWriter();
response.setContentType("text/html");
display.println("<html>....</head>");
display.println("<embed src="success.mpeg">");
display.println("Any output Text");
I want to use hidden variables for session tracking. How can I get the
session object? Since the Servlet API 2.1 there is no method
request.getSession ( String sessionId )
Location: http://www.jguru.com/faq/view.jsp?EID=246613
Created: Nov 6, 2000 Modified: 2000-12-07 19:18:18.944
Author: reshma deshmukh (http://www.jguru.com/guru/viewbio.jsp?EID=132478)
Question originally posed by Thomas Hirschböck
(http://www.jguru.com/guru/viewbio.jsp?EID=225611
2)HttpSession getSession() Gets the current valid session associated with this
request, if create is false or, if necessary, creates a new session for the request.
[Yes, but that doesn't answer the question -- is there a way to get the session a
priori without the server doing it automagically for you? -Alex]
I want to hide the "jesessionid" in a hidden form field but don't know how to
recover the session from the servlet without using the deprecated class
HttpSessionContext ?
Thanks in advance.
Should the applet send a request from time to time to check if the response
has arrived? I can't wait for the response in the servlet because I will run
into the HTTP timeout. I tried to use the Keep-alive connection and from the
servlet send a "ping" message (an object) to the applet but the content is
not flushed until the response is completed even though I call flush(),
because of the HTTP mechanism.
Any idea to avoid pinging the server uselessly?
Location: http://www.jguru.com/faq/view.jsp?EID=248491
Created: Nov 8, 2000 Modified: 2000-12-07 20:43:37.099
Author: Jens Dibbern (http://www.jguru.com/guru/viewbio.jsp?EID=9896) Question
originally posed by Nicolas Cohen
(http://www.jguru.com/guru/viewbio.jsp?EID=235112
[There's no real problem with "pinging" from the applet to the servlet every 30
seconds. The load per request is still pretty low. Keep-alive / server-push is an OK
solution, but it sounds like it's more trouble than it's worth. But flush() should still
work -- maybe there's a bug in your servlet engine? -Alex]
A good solution for long running transactions in servlets is to use a Thread for it and
store the thread in the Session. After starting the Thread you can response a "wait"
message and send following requests from the applet asking for the result every 30
seconds (or whatever interval you like). The servlet should respond with wait
messages as long as the Thread is alive and after that respond with your results.
Second, you must map that url pattern to a servlet name and then to a servlet class
in your web.xml configuration file. Here is a sample exerpt:
<servlet>
<servlet-name>myservlet</servlet-name>
<servlet-class>com.mypackage.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myservlet</servlet-name>
<url-pattern>/myservlet</url-pattern>
</servlet-mapping>
Comments and alternative answers
<servlet>
<servlet-name>
FitnessApplicationServlet
</servlet-name>
<servlet-class>
com.fitness.web.FitnessApplicationServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>
FitnessApplicationServlet
</servlet-name>
<url-pattern>
/fitness
</url-pattern>
</servlet-mapping>
and this in my_tomcat_httpd.conf
ApJservMount /fitness /ROOT
but if i try going to http://server_name/fitness/login i get this error:
2001-02-11 04:37:14 - Ctx( /fitness ): 404 R( /fitness + /login +
null) null
there is nothing in the error logs. thanks for your help
Servlet Aliasing
Author: Robert Hector (http://www.jguru.com/guru/viewbio.jsp?EID=412771), Apr
30, 2001
It seems the suggested approach does NOT work under Tomcat v 3.2.1. It does work,
however, under v 3.1.1. Is there a bug in 3.2.1 or does it have to be done differently in
3.2.1? Thanks, Bob Hector
Servlet Aliasing
Author: Premjith SunTec (http://www.jguru.com/guru/viewbio.jsp?EID=739544),
Jan 30, 2002
Hi, I am Premjith working at Suntec trivandrum ,india.I have done the servlet
aliasing and is working fine. My requirement was to change the context root name
"Servlet" to OSI i.e http://localhost/online/servlet/Login to
http://localhost/online/OSI/Login when i changed the content of
Web.xml,Server.xml,and all CONF files of tomcat to incorporate it it was working
till i restart Apache server.Later i tried by copying the configured files to a
temporory directory and overwriting the conf files with these files .I included this
copy command in "startup" file of tomcat.i expectsome comments on this reply
I want my servlet page to redirect to a login page if the session has timed
out. How can I know if my session has timed out?
Location: http://www.jguru.com/faq/view.jsp?EID=251532
Created: Nov 11, 2000 Modified: 2000-12-07 20:00:51.64
Author: Dieter Wimberger (http://www.jguru.com/guru/viewbio.jsp?EID=25708)
Question originally posed by Amit Jain
(http://www.jguru.com/guru/viewbio.jsp?EID=111841
If the servlet engine does the time-out, following code should help you:
//assume you have a HttpServletRequest request
if(request.getSession(false)==null) {
//no valid session (timeouted=invalid)
//code to redirect to login page
}
[See also Servlets API Specification 2.2]
Note that the code should work under 2.0 and 2.1 as well.
Comments and alternative answers
Can I force the browser to save a downloaded file with a name I specify,
rather than the name of the URL?
Location: http://www.jguru.com/faq/view.jsp?EID=252010
Created: Nov 12, 2000 Modified: 2001-07-23 09:18:44.093
Author: Alexandros Kotsiras (http://www.jguru.com/guru/viewbio.jsp?EID=64209)
Question originally posed by sameet Joshi
(http://www.jguru.com/guru/viewbio.jsp?EID=234380
Assuming that you want to save the file as "myFile.txt" you have to set the Content-
Disposition response Header as follows :
response.setHeader("Content-Disposition",
"attachment;filename=myFile.txt");
Note that even if the file is of a type that the browser can display ( .html .txt etc.)
because you set the disposition type as "attachment", the browser will not open it
but it will instead pop up a "save as" box.
See also How do I download a (binary, text, executable) file from a servlet or JSP?
(especially the feedback)
There is a bug in IE 5.5 SP1. If the content-disposition is "attachment", then IE 5.5 SP1 will
open the referrer document (i.e. download.htm) rather than the intended document in the
URL. See Microsoft support article Q281119
(http://support.microsoft.com/support/kb/articles/Q281/1/19.ASP?LN=EN-
US&SD=gn&FR=0&qry=q281119&rnk=1&src=DHCS_MSPSS_gn_SRCH&SPR=MSALL)
Prior to IE 5.0 Microsoft didn't honor the content-disposition field, so it was never an issue.
A fix to mshtml.dll is available on request from Microsoft. The fix works, I tested it.
Can you point me in the right direction to find this simple little thing?? Thanks!
Re: Re: Re: Second posting - I didn't see the first so I am re...
Author: Brian Kreulen
(http://www.jguru.com/guru/viewbio.jsp?EID=428360), May 28, 2001
I do have an email listed in my bio... did you mean that you wanted a non-
yahoo or non-hotmail email?
Re: Re: Re: Re: Second posting - I didn't see the first so I am re...
Author: Scott Rolfson
(http://www.jguru.com/guru/viewbio.jsp?EID=341761), May 28, 2001
I can't see your email addy. You can make it visible to all users if you
go to the member page button on the top right of the page and add your
email (any address is OK) in the BIO textbox below the quotation
textbox. If you don't want to do that, then send me your email address
to [email protected] so I can reply with the files.
Re: Re: Re: Re: Re: Second posting - I didn't see the first so I
am re...
Author: Brian Kreulen
(http://www.jguru.com/guru/viewbio.jsp?EID=428360), May 29,
2001
Got it... it should be up there now...
Just in case it didn't......
yes you can do that by modifying the web.xml file. You will have to invoke the
org.apache.jasper.runtime.JspServlet for all the requests having extension
.html. You can do that by changing the Servlet mapping code:
<servlet-mapping>
<servlet-name>
jsp
</servlet-name>
<url>*.html</url>
</servlet-mapping>
<mime-mapping>
<extension>
html
</extension>
<mime-type>
text/html
</mime-type>
</mime-mapping>
Request attributes are bound to a specific request object, and they last as far as the
request is resolved or while it keep dispatched from servlet to servlet. They're used
more as comunication channel between Servlets via the RequestDispatcher Interface
(since you can't add Parameters...) and by the container. Request attributes are very
useful in web apps when you must provide setup information between information
providers and the information presentation layer (a JSP) that is bound to a specific
request and need not be available any longer, which usually happens with sessions
without a rigorous control strategy.
Thus we can say that context attributes are meant for infra-structure such as shared
connection pools, session attributes to contextual information such as user
identification, and request attributes are meant to specific request info such as query
results.
Is there any way I can assign different values of CLASSPATH to different
contexts?
Location: http://www.jguru.com/faq/view.jsp?EID=255582
Created: Nov 16, 2000 Modified: 2000-12-07 21:18:37.38
Author: Tim McNerney (http://www.jguru.com/guru/viewbio.jsp?EID=210140)
Question originally posed by Dennis Cook
(http://www.jguru.com/guru/viewbio.jsp?EID=232644
One way to get the functional equivalent is to put the files in question in either
"<app-path>/WEB-INF/classes" or "<app-path>/WEB-INF/lib", depending on
whether you are talking about a .class or .jar. The CLASSPATH for a given webapp
will include WEB-INF/classes and all the .jar files found in WEB-INF/lib. Say you had
utils.jar and form-taglib.jar in WEB-INF/lib, the resulting classpath would look like:
$CLASSPATH:<app-path>/WEB-INF/classes:<app-path>/WEB-
INF/lib/utils.jar:<app-path>/WEB-INF/lib/form-taglib.jar
[...but remember, it's built automatically by the servlet container. -Alex]
[Question continues: For example if I have two contexts on a single web server, and
each context uses a login servlet and the login servlet connects to a DB. The DB
connection is managed by a singleton object. Do both contexts have their own
instance of the DB singleton or does one instance get shared between the two?]
The classes loaded from context's WEB-INF directory are not shared by other
contexts, whereas classes loaded from CLASSPATH are shared. So if you have
exactly the same DBConnection class in WEB-INF/classes directory of two different
contexts, each context gets its own copy of the singleton (static) object.
In general, you will run into synchronization issues when you try to access any
shared resource. By shared resource, I mean anything which might be used by more
than one request.
To some degree you can find the information about the browser from HTTP request
header "User-Agent". For example if the page was called by IE5.5 the header value
would be:
request.getHeader("User-Agent");
The bad news is that event if you know the type of the browser you still do not know
about some features that user may have had customized: e.g Java may be off, or
JavaScript may be off, etc.
Good luck,
Michael
My HTML pages take too long to load. Where can I find advice on how to
optimize the rendering time?
Location: http://www.jguru.com/faq/view.jsp?EID=259570
Created: Nov 21, 2000 Modified: 2000-12-07 23:55:34.537
Author: Troy Niven (http://www.jguru.com/guru/viewbio.jsp?EID=219893) Question
originally posed by Ely Yang (http://www.jguru.com/guru/viewbio.jsp?EID=238563
TROY
You'll see "MSIE" somewhere for internet explorer. Surprisingly, on both IE (on NT)
and Netscape return "Mozilla" as part of the response.
[It's not surprising, it's just stupid. :-) The reason IE pretends to be Mozilla goes
back to the days when Netscape (aka Mozilla) was the only browser that supported
certain features, e.g. Tables. Certain CGI scripts would check the user-agent header,
and only output tables if the UA contained the string "Mozilla." Otherwise, they would
output a lame < PRE > version, or nothing at all. Naturally, the authors of IE wanted
their browser to show these tables, so they *had* to lie.
The solution would have been if the Netscape browser sent a different, capabilities-
oriented header (e.g. "Accepts: Tables") but Netscape was a hastily written, poorly-
though-out piece of junk. IMHO. :-)
Initiatives like CC/PP and UAProf are attempting to fix the problem for both Web and
WAP browsers but their acceptance remains to be seen.
-Alex]
I have a Servlet that does an extensive search which may take up to 1-2
minutes to finish. I would like to display a "Please wait ...." page while the
search is being performed and before the search results are displayed. How
can I do this?
Location: http://www.jguru.com/faq/view.jsp?EID=263573
Created: Nov 27, 2000 Modified: 2001-07-23 10:20:21.168
Author: Perry Tew (http://www.jguru.com/guru/viewbio.jsp?EID=60814) Question
originally posed by ethan c (http://www.jguru.com/guru/viewbio.jsp?EID=240218
Ethan,
I've written a servlet that does this same thing (well, it executes a long query). What
I did was to create a class that spawned a thread to do the query. I then set flags to
indicate the query was underway. Whenever a request came in, I checked the flags
and output html based on whether the query was done or not. I added some extra
bells and whistles, such as how many records had been retrieved so far.
I put it together pretty quickly, so it may not be the most professional solution, but
you're welcome to look at the code to gain an idea of how I did it. (You may have to
scrape out some query code, but it's not much.)
//LongTaskServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
HttpServletResponse response)
throws
ServletException, IOException{
/**
*/
public void doGet ( HttpServletRequest request,
HttpServletResponse response)
throws
ServletException, IOException{
PrintWriter
out;
response.setContentType("text/html");
out = response.getWriter();
if ( request.getParameter("doTask")
!= null) {
longTask.doLongTask();
out.println(
"<html><head>");
if ( longTask.isDoingTask() ) {
out.println(
"<meta http-equiv=refresh content=10>" + "\n" );
out.println(
"</head><body><center>" + "\n"
Page</h1>" + "\n"
+ " <h4>Current
Status</h4></center>" + "\n"
+ "<table border=\"0\"
width=\"50%\">" + "\n"
);
out.println( "<tr><td
width=\"30%\"><b>Last Error:</b></td><td>");
out.println( longTask.getLastError() );
out.println( "</td></tr>"
+ "\n");
out.println( "<tr><td
width=\"30%\"><b>Current Status:</b></td><td>");
out.println( longTask.getStatus() );
out.println( "</td></tr>"
+ "\n");
out.println("<tr><td
colspan=\"2\">" + "\n");
if ( longTask.isDoingTask() ) {
out.println(
"<i>This
} else {
out.println(
"<b>No
out.println(
"</td></tr></table>" + "\n");
if ( !longTask.isDoingTask() ) {
out.println(
"
<center>" + "\n"
+ "
<form name=\"form1\"
method=\"POST\">" + "\n"
+ "
<input
"value=\"yes\">"
+ "\n"
+ "
<input
+ "\n"
+ "
</form>" + "\n"
+ "
</center>" + "\n"
);
out.println(
"</body></html>");
out.close();
//===========================================
//LongTaskBean.java
public LongTaskBean(){}
return inLongTask;
inLongTask = flag;
return lastErrorMsg;
lastErrorMsg = msg;
}
public String getStatus(){
return status;
status = s;
if( !isDoingTask() ){
setTaskFlag(true);
new LongTaskThread(
return;
super( str );
lastErrorMsg = error;
inLongTask = false;
/* reset the
lastErrorMsg */
setLastError("NONE
================//
10; i++ ){
setStatus("I'm
try
setLastError("NONE:
Completed Successfully");
setTaskFlag(false);
}
IMHO, all previous answers in this page are wrong solutions. You should return a
multipart response thanks to the "multipart/x-mixed-replace" content type. This kind
of response also permits push media, webcam feed, chat, etc...
out.println("<H1>Waiting...</H1>");
out.flush();
out.println("<H1>Done</H1>");
out.print("\n\r--boundary--\n\r");
out.flush();
}
Re: IMHO, all previous answers in this page are wrong ...
Author: veljo otsason (http://www.jguru.com/guru/viewbio.jsp?EID=384089),
Mar 21, 2001
hmm.. this is really something i didn't know before. but if i called that example
with IE, i got the page like this:
--boundary
Content-Type: text/html
<H1>Waiting...</H1>
--boundary
Content-Type: text/html
<H1>Done</H1>
--boundary--
with NS i got no answer at all:( what'd be the problem?
Re: Re: IMHO, all previous answers in this page are wrong ...
Author: Roland Röder (http://www.jguru.com/guru/viewbio.jsp?EID=389526),
Apr 4, 2001
i tried your code and the page was shown in the same way as above (without
recognizing the boundary; but this seems to be a little bit browser dependant).
But i got another problem: the page was displayed after leaving the method
and not after the out.flush() call. Any suggestions what to do?
Re: Re: IMHO, all previous answers in this page are wrong ...
Author: Bjoern Schmidt
(http://www.jguru.com/guru/viewbio.jsp?EID=431451), May 31, 2001
Hi! If you just copy and paste the posted examplen, it really looks like this.
You have to tell your Browser that you're sebding HTML. Just insert
something like this:
out.println("<HTML><TITLE>this is a test</TITLE><BODY>\n");
Regards Bjorn
Re: IMHO, all previous answers in this page are wrong ...
Author: Raja kannan (http://www.jguru.com/guru/viewbio.jsp?EID=433245), Jun
3, 2001
Hi i have just executed ur program but the first "waiting" message does not hide
when the "done" message is displayed
Here is the code i have written: (which does not work right)
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class wait extends HttpServlet {
out.println("<H1>Done</H1>");
out.print("\n\r--boundary--\n\r");
out.println("</body>");
out.println("</html>");
out.flush();
}
}
If u have any new ideas pls share with me
Re: Re: IMHO, all previous answers in this page are wrong ...
Author: Pramod Vuppalapanchu
(http://www.jguru.com/guru/viewbio.jsp?EID=453652), Jul 11, 2001
Iam facing the same problem. I tried the sample code here , and the initial
"wait" message does not go after the "done" message. This is a problem. Does
anyone have an idea how to handle this ? I cannot use http-refresh technique
from the "wait" page, because my servlet gets many parameters from the
requests object and if I refresh from the wait page these parameters are null.
Any help would be greatly appreciated. Thanks.
Re: IMHO, all previous answers in this page are wrong ...
Author: Stephane Boisson (http://www.jguru.com/guru/viewbio.jsp?EID=1512),
Jun 11, 2001
Well, it appears that Microsoft Internet Explorer don't support multipart MIME
responses.. so multipart/mixed response won't work either.. ( MS Support KB
article)
An alternative is to test the UserAgent and use a different strategy with IE (for
example Refresh directive in HTTP header)
I did some research on what you were talking about, and I thought I would post some
articles and notes I found on multipart/x-mixed-replace. Netscape has a nice
introduction to using your technique here. There's also an interesting mailing list
message talking about different ways to perform client pulls and server pushes.
Anyways, thought I'd pass on what I've learned to those after me.
Perry Tew
The simplest solution for displaying "Please Wait" Page.(if you don't want
to monitor the percentage of download occured)
Author: Sanjay Panchal
(http://www.jguru.com/guru/viewbio.jsp?EID=464765), Jul 31, 2001
when a particular page is requested, show the please wait page
which contains html meta tag "<META HTTP-EQUIV=\"REFRESH\"
CONTENT=\"0\">"
and set the session variable. Due to refresh tag the page is
recalled
now remove the session variable and do the computation.
Untill the browser gets the actual computed page, it will wait
and will not refresh the Please wait page.
Meanwhile, Please wait page will be displayed.
public void doGet ( HttpServletRequest req, HttpServletResponse
res )
out.println( "<HTML>" );
out.println( "<HEAD>" );
out.println( "<TITLE>Please Wait...</TITLE>" );
out.println( "<META HTTP-EQUIV=\"REFRESH\"
CONTENT=\"0\">" );
out.println( "</HEAD>" );
out.println( "<BODY>" );
out.println( "<CENTER>" );
out.println( "<H1>Download in Progress</H1><HR>"
);
out.println( "<H2>Please wait.</H2>" );
out.println( "</CENTER>" );
out.println( "</BODY>" );
out.println( "</HTML>" );
out.close();
}
else
{
session.removeValue( "WAIT" );
out.println( "<HTML>" );
out.println( "<HEAD><TITLE>Actual
Page</TITLE></HEAD>" );
out.println( "<BODY>" );
out.println( "<CENTER><H1>Actual Page is being
displayed</H1><BR><B>" );
out.println("Started computation<BR>");
for ( int i = 1; i < 6; i++ )
//do your time consuming Process
{
out.println("Inside
computation"+i+"<BR>");
try
{
Thread.sleep( 2000 );
}
catch ( InterruptedException e )
{
}
}
out.println("Finished computation");
out.println( "</B></CENTER>" );
out.println( "</BODY>" );
out.println( "</HTML>" );
out.close();
}
}
Re: The simplest solution for displaying "Please Wait" Page.(if you
don't want to monitor the percentage of download occured)
Author: Maurizio Turatti
(http://www.jguru.com/guru/viewbio.jsp?EID=734356), Jan 25, 2002
It works! It's really a good solution, thank you. I'm using it in a jsp page,
like this:
<%
if (session.getAttribute("WAIT") != null &&
request.getParameter("event").equals("COUNT_USERS")) {
session.removeAttribute("WAIT"); <head>
<title>Communithink Administration Tool:
waiting....</title>
<meta http-equiv='Refresh' content='1'>
</head>
<body>
<h1 align=center>Waiting...</h1>
</body>
</html>
<%
} else {
session.setAttribute("WAIT", new String()); %>
<html>
...
...
</html>
<% } %>
How do I use the security manager to grant persissions for the servlet to
call the java.lang.Runtime.exec() method to run a native application on the
server?
Location: http://www.jguru.com/faq/view.jsp?EID=264256
Created: Nov 28, 2000 Modified: 2000-11-30 19:42:23.753
Author: Jeff Williams (http://www.jguru.com/guru/viewbio.jsp?EID=231946)
Question originally posed by Donghua Liu
(http://www.jguru.com/guru/viewbio.jsp?EID=13364
On most app servers, the sandbox is not enabled, so all you have to do is call
Runtime.exec().
You must be VERY careful about checking the parameters -- especially if they were
derived from the HTTP request. Remember RULE #1 for web app programming is
"NEVER trust the HTTP request." A hacker can manipulate all the headers,
parameters, form data, hidden fields, etc... Client side checking (JavaScript) is
meaningless to security.
IF you have enabled the sandbox on your server, then you simply have to have a
Policy file that grants exec permission on that file. See Security Permissions for a
great description of the permissions and their risks.
You also want to be very sure about the native app you are calling with exec. If it
hangs and you are blocked reading from the child, you're toast. I wrote a framework
that starts a separate monitoring thread and calls child.destroy() if the timeout is
reached. Good luck!
Apache is an HTTP server written in C that can be compiled and run on many
platforms. See http://www.apache.org
Java WebServer is an HTTP server from Sun written in Java that also supports
Servlets and JSP.
Tomcat is an open-source HTTP server from the Apache Foundation, written in Java,
that supports Servlets and JSP. It can also be used as a "plug-in" to native-code
HTTP servers, such as Apache Web Server and IIS, to provide support for Servlets
(while still serving normal HTTP requests from the primary, native-code web server).
See http://jakarta.apache.org/tomcat
.. therfore there is no difference in their over all purpose except the languages
used to write them. ( ? )
Author: Gene G (http://www.jguru.com/guru/viewbio.jsp?EID=1172699), May 21,
2004
... if tomcat is both an http server and a servelet container, why is apache necessary in
projects where tomcat is used ? Thx,
Re: .. therfore there is no difference in their over all purpose except the
languages used to write them. ( ? )
Author: Vijay Dogra (http://www.jguru.com/guru/viewbio.jsp?EID=1175631), Jun
2, 2004
Apache is a web server (mainly support static html). Tomcat is a servlet container
(mainly support servlets)
Re[2]: .. therfore there is no difference in their over all purpose except the
languages used to write them. ( ? )
Author: ramu vempati
(http://www.jguru.com/guru/viewbio.jsp?EID=1183164), Jul 1, 2004
Can we maintain every thing (static html , JSP and servlets) with tomcat
itself?. When do we need both Apache and Tomcat running on the server.
Thank You
Why
Author: Moe Binkerman (http://www.jguru.com/guru/viewbio.jsp?EID=1216498),
Dec 15, 2004
Why does the server need to understand servlets? Does apache "understand" html?
does apache "understand" cgi programs? How are servelets different that a cgi
program?
Web Servers
Author: Yashavantha Nagaraju
(http://www.jguru.com/guru/viewbio.jsp?EID=1242357), May 4, 2005
I think most of uses Tomcat web server. Even i need know what is the reason for
that...
Calling a servlet from a perl script is no different than getting information from any
other URL. The perl script has no clue its a servlet and doesn't need to know this.
[In other words: use HTTP, and the standard Perl HTTP libraries, but open the
connection to localhost if it's on the same box. -A]
Does Tomcat 3.1 support Java Servlet API 2.0 specifications? The
documentations refers to API 2.2, but is it downward compatible?
Location: http://www.jguru.com/faq/view.jsp?EID=266873
Created: Nov 30, 2000 Modified: 2000-12-08 00:04:07.932
Author: Stefan Tryggvason (http://www.jguru.com/guru/viewbio.jsp?EID=266869)
Question originally posed by Maureen Boyce
(http://www.jguru.com/guru/viewbio.jsp?EID=243448
Tomcat 3.1 supports the servlet API 2.2. Certain methods including the getServlet,
getServlets and getServletNames methods of ServletContext have been deprecated
since 2.0. The ServletContext methods above, while still available, no longer return
anything useful. There are a few other differences too.
Where do I install the JDBC driver ZIP files, JAR files & DLLs? How do I
ensure they're in Tomcat's CLASSPATH?
Location: http://www.jguru.com/faq/view.jsp?EID=268823
Created: Dec 4, 2000 Modified: 2000-12-20 10:15:28.017
Author: Ignacio J. Ortega (http://www.jguru.com/guru/viewbio.jsp?EID=98626)
Question originally posed by Allwyn Pinto
(http://www.jguru.com/guru/viewbio.jsp?EID=245385
Since version 3.2, all the JARS present in the %TOMCAT_HOME%/lib directory are
automatically appended to Tomcat's classpath, but only the jars are appended. To
have a ZIP automatically appended rename it to *.jar ( as a jar is only a renamed zip
) and voila....
1. Put the jar file in your webapp's WEB-INF/lib/ directory. This set of JARs is
added to the classpath for your webapp only. Be careful, however: if a
different driver for the same JDBC URL is already on the system classpath,
then it may (may!) be loaded instead of yours. (Whether it is or not depends
on whether that driver has already been loaded yet.)
2. Change the Tomcat CLASSPATH environment variable, or "-classpath"
command-line option, to contain your JAR or ZIP. This is set in the Tomcat
startup script, tomcat.bat/tomcat.sh. Read that file for details on how to edit
it.
- Alex ]
Comments and alternative answers
I want to insert a blob retrieved from a form field (with type='file') into a
database. How can I convert the data returned by request.getParameter()
to a BLOB type?
Location: http://www.jguru.com/faq/view.jsp?EID=275076
Created: Dec 11, 2000 Modified: 2000-12-24 21:47:29.092
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Jewel Chen
(http://www.jguru.com/guru/viewbio.jsp?EID=265610
Given a set of bytes, see How do I upload SQL3 BLOB & CLOB data to a database?
for how to insert it into a database that supports BLOBs.
To upload file data from a browser to a servlet, see: How do I upload a file to my
servlet?.
Jorge Jordão, Eduardo Estefano, and Trapix Smith also contributed to this answer.
conn.setAutoCommit(false);
String prepare = "insert into news_xml values(" + id + ", empty_blob())";
String cmd = "SELECT * FROM news_xml where id=" + id + " for update";
Statement stmt = conn.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
stmt.executeUpdate(prepare);
ResultSet rset = stmt.executeQuery(cmd);
rset.next();
BLOB blob = (BLOB)((OracleResultSet)rset).getBlob(2);
FileInputStream instream = new FileInputStream(f);
OutputStream outstream = blob.getBinaryOutputStream();
int size = blob.getBufferSize();
byte[] buffer = new byte[size];
int length = -1;
while ((length = instream.read(buffer)) != -1) outstream.write(buffer, 0, length);
instream.close();
outstream.close();
conn.commit();
Should I use HTML Java libraries (eg. BEA's konaHTML) or raw HTML to
generate my pages? What are the pros and cons?
Location: http://www.jguru.com/faq/view.jsp?EID=277048
Created: Dec 13, 2000 Modified: 2000-12-13 10:50:41.948
Author: Jeff Williams (http://www.jguru.com/guru/viewbio.jsp?EID=231946)
Question originally posed by andrew boddy
(http://www.jguru.com/guru/viewbio.jsp?EID=242163
I don't see many 'pros' to using print statements with raw HTML. I've used kona and
the Java apache project's ECS with great results. The major pro is that you can build
reusable components so that you don't have to repeat stuff. That said, I can
definitely understand those folks who like the MVC pattern and want to separate the
GUI (view) from the logic. I think the best approach for this is to use a master
servlet that handles security and parameters, then loads and sends the appropriate
JSP (the view). --Jeff
A Web Server understands and supports only HTTP protocol whereas an Application
Server supports HTTP,TCP/IP and many more protocols. Also many more features
such as Caches,Clusters,Load Balancing are there in Application Servers which are
not available in Web Servers. We can also Configure Application Servers to work as
Web Server. In short, Applicaion Server is a super set of which Web Server is a sub
set.
[See also What are all the different kinds of servers? (Such as Web Servers,
Application Servers, etc) ]
Your final summary is fairly good, but I think the best description is that Web servers
are HTTP servers, whereas an application server runs application code in the context
of some higher level API (servlets, EJB, ASP, Enhydra's compiled HTML thingy)
Even if we take it literally, a web server serves web pages so an application server
should serve with application (logic).
The application logic (here, the business logic) is embedded in some form, let that
be an EJB or CORBA component, and the application server allows us to get the
services provided by those components.
IMHO, the qualities such as load balancing, fail-over support, caching are all non-
funtional requirements that are applicabale to any distributed application (web
server, db server, app server etc.)
Application vs Webserver
Author: siraj ahmed (http://www.jguru.com/guru/viewbio.jsp?EID=405469), Apr 18,
2001
If application server has inbuilt jvm and servlet engine then why we call
javawebserver2.0 as "webserver" it can handle the servlet request then its also an
application server. Please comment....
You don't have to do anything special to include JavaScript in servlets or JSP pages.
Just have the servlet/JSP page generate the necessary JavaScript code, just like you
would include it in a raw HTML page.
The key thing to remember is it won't run in the server. It will run back on the client
when the browser loads the generate HTML, with the included JavaScript.
--jsp code--
</script>
Re: You can include JavaScript inside JSP code in two ...
Author: erni meded (http://www.jguru.com/guru/viewbio.jsp?EID=1232501), Mar
14, 2005
How did you include JavaScript in the servlet?? I am having problem with that for
couple days. I can include everything,but the line <SCRIPT
LANGUAGE="JavaScript"> is giving me so many problems. Whatever I try it
does not work.
You can't. It's a fundamental limitation of the HTTP protocol. You'll have to figure out
some other way to pass the data, such as
No it is not at all a bug. but it is a good practice if you write the destroy() method
and destroy your servlet because if many servlets running on the same webserver
are not destroyed explicitly, then the performance of the web server falls down.
[In other words, destroy() is not guaranteed to be called... but if it is, you should
make sure it works right. -Alex]
Any thoughts on how either of them will effect performance in case of heavy
loads?
Location: http://www.jguru.com/faq/view.jsp?EID=286913
Created: Dec 27, 2000 Modified: 2001-01-04 05:38:13.174
Author: Badri Kuppa (http://www.jguru.com/guru/viewbio.jsp?EID=98194) Question
originally posed by Modha Kumar
(http://www.jguru.com/guru/viewbio.jsp?EID=253506
1. By using the first one, you will have lots of if..else..conditions and even the code
won't be easily readable!
2. Performance increases by 2nd option as the load on one single servlet is less.
[This is not necessarily so, since any servlet is just code being executed in a JVM
thread; unless it's synchronized, then you can have as many requests as you want
inside a single servlet. -Alex]
3. IBM states "Do one thing at a time, Do it well" which suggests the 2nd option.
Especially when coupled with a file/jdbc based state-machine and external processor
classes, it makes a neat system. The processor classes might even be servlet-
independent, giving them a chance to be reused.
If you can use JSDK 2.2 and JSP 1.1 in your project, you should check out jakarta's
Struts-project (which also uses the 1-servlet approach). Their concept rocks (and
knowing the people behind their software will do the same).
first one
Author: anish malanthara (http://www.jguru.com/guru/viewbio.jsp?EID=1105417),
Jul 31, 2003
IBM's recommendation is not meant to be taken literally. The spirit of it is that 'one
thing' means one functionality/area etc. In this case, login/logout is one functionality,
and one servlet can handle that. And as any experienced developer can tell you, if/else
is not a bad thing. It can be the elegant solution when used properly. just imagine if
every possible action had a servlet to handle that in a Web-UI environment. The same
solution can be applied to data access/editing etc. However, these exist much better
ways of handlign those scenarios than just servlets.
The problem seems to be the server takes longer than 10 minutes to release a
servlet instance.
This can probably be configured, but what you should do instead is open the
connection, execute the statements and close the connection all in the service
(doGet or doPost) method, instead of keeping it opened. You can still load the
driver class in init, since that needs to be done only once.
Example: (notice I'm using String constants for DB access for simplicity, I should be
reading that information from an outside source):
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
If you find this approach too slow, consider using a connection pool.
Or, you could implement a timer task that releases and reestablishes the connection
every 9 minutes. See java.util.Timer. This would have to be carefully synchronized, in
case a servlet asks for the connection while it is in the process of being reupped.
Can I generate Microsoft Excel documents using JSP or servlets?
Location: http://www.jguru.com/faq/view.jsp?EID=288029
Created: Dec 28, 2000 Modified: 2002-03-01 14:15:23.141
Author: Jorge Jordão (http://www.jguru.com/guru/viewbio.jsp?EID=275762)
Question originally posed by Saravanan Shankaran
(http://www.jguru.com/guru/viewbio.jsp?EID=232649
Apart from using C++ and JNI directly, there are (at least) two ways to read/write an
MS Excel file in Java.
1. Using a Java-COM bridge (Please view my previous answer to How can I get
email addresses out of an MS Outlook database, and add new ones?).
2. Using Formula One, which is a Reporting Engine API for Java that allows you
to manipulate MS Excel 95/97/2000 files (including charts, formulas and
functions).
<START OF FILE>
<%@page contentType="text/html"%>
<%response.setContentType("application/vnd.ms-excel");%>
<table>
<tr>
<td>cell1</td><td>cell2</td>
</tr><br>
</table>
<END OF FILE>
So based on the above conditions, the use of COM Excel object or any of the
Windows stuff are out of the question.
See also
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jun 27, 2001
Check out Access Microsoft Excel data through serv... and Generation of excel file.
see also
Author: Laurent Mihalkovic (http://www.jguru.com/guru/viewbio.jsp?EID=407112),
Apr 10, 2002
You can also have a look at the HSSF project from the apache group. It is a pure Java
implementation of the Excel '97(-2002) file format.
cheers
1. Schedule a servlet to load on server startup. See How can I set a servlet to load
on startup of the container, rather than on the first request?
3. In this thread's run() method, calculate the number of milliseconds to wait until
the task should be performed. Then call Thread.sleep(msec). Then do the task, and
loop (infinitely).
See also How can I automatically invoke a servlet at regular time intervals using
Resin?
Comments and alternative answers
Since submitting this I have found out the solution myself - or at least one solution,
there are probably others. The answer lies in "accept" part of the header. Basically, if
it contains the directive for WAP and WML then the content type of the response can
be set for WML.
i.e.
/** Content type string for HTML */
public static final String CONTENT_TYPE_HTML = "text/html";
if (null != request) {
String mimeTypes = request.getHeader( HEADER_ACCEPT );
if ( null != mimeTypes ) {
if ( 0 != mimeTypes.trim().length() ) {
if ( -1 != mimeTypes.toLowerCase().indexOf(CONTENT_TYPE_WML) ) {
retval = CONTENT_TYPE_WML;
}
// Put any other content type conversions in here.
}
}
}
return retval;
}
This will set the content type to HTML by default, unless the user agent accepts
WML.
Comments and alternative answers
Such a database exists in several places; one is in the Morphis open-source project, in
a file called device.xml. I expect that as new browsers are released, they will update
this list on an ongoing basis. [As of this writing, this site is still in beta, so be gentle
:-) ]
good question!
Author: Ali Khurram Abbas (http://www.jguru.com/guru/viewbio.jsp?EID=295141),
Jan 6, 2001
good question!
I call a servlet as the action in a form, from a jsp. How can I redirect the
response from the servlet, back to the JSP? (RequestDispatcher.forward will
not help in this case, as I do not know which resource has made the
request. request.getRequestURI will return the uri as contained in the
action tag of the form, which is not what is needed.)
Location: http://www.jguru.com/faq/view.jsp?EID=295190
Created: Jan 6, 2001 Modified: 2001-01-08 17:12:23.721
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Vinod Amladi
(http://www.jguru.com/guru/viewbio.jsp?EID=280439
You'll have to pass the JSP's URI in to the servlet, and have the servlet call
sendRedirect to go back to the JSP. For example:
<FORM ACTION="/foo/myservlet">
<INPUT TYPE="HIDDEN" NAME="redirect"
VALUE="/foo/thisjsp.jsp">
Shoe size: <INPUT NAME="shoesize">
<INPUT TYPE="SUBMIT">
</FORM>
Then in the servlet...
response.sendRedirect(request.getParameter("redirect"));
Comments and alternative answers
Sorry to ask this trivial question here, I am answering my own query here.
I had recently tried in a few servlet engines and sendRedirect works for HTTPS. I had
initially got this problem with a certain brand of servlet engine that seems to be
incomplete.
[That's OK! It's a valid question (though easy to check for yourself). What servlet
engine was broken? -Alex]
Yes it does.
Author: Shailesh Dangi (http://www.jguru.com/guru/viewbio.jsp?EID=97397), Jan
12, 2001
Yes it does.
How can I get system environment variables from a servlet?
Location: http://www.jguru.com/faq/view.jsp?EID=296467
Created: Jan 8, 2001 Modified: 2001-01-08 08:13:41.598
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Marek Koniew
(http://www.jguru.com/guru/viewbio.jsp?EID=280673
However, you can read the equivalent of most of the CGI environment variables from
the ServletRequest object. See
http://www.jguru.com/jguru/faq/view.jsp?EID=11699
There's a user session handling tutorial on the developerWorks Java Zone that
teaches techniques using servlet and JSP technology. A key point is to enable session
handling, so the servlet knows which user is doing what. The tutorial shows a URL
bookmarking system in which multiple users access a system to add, remove, and
update an HTML listing of bookmarks. The servlet uses JSP technology to handle the
user interaction.
Yes, like any Java method call, RequestDispatcher.forward() returns to the caller.
Hence we should ensure that, the caller should not be using PrintWriter() or
getOutputStream() object, as it results in IllegalStateException. Neither should the
call be followed by another call of RequestDispatcher.forward() or
RequestDispather.include().
[The idea of RequestDispatcher.forward is that the first servlet sets things up, and
the second one prints. Unfortunately, that architecture is somewhat limited. If you
want both to print, you must use RequestDispatcher.include instead. -Alex]
[More Q: (I know how to set the content-type from a servlet, but I require formatted
bordered table oriented output in the word doc.) ]
The simplest way, since the Word format is messily binary, is to write out an RTF file,
which is mostly ASCII-oriented. This technique works just well--check out the RTF
output from an SEC filing at www.FreeEDGAR.com to see some nice examples of
programmatically-generated RTF.
Also, you could just write an HTML file, and set its...
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jan 15, 2001
Also, you could just write an HTML file, and set its Content-Type header to
"application/ms-word". This will cause Windows to open it using Word. (Not sure
what will happen on other platforms, but you sound fairly Windows-centric.) See also
http://www.jguru.com/jguru/faq/view.jsp?EID=3696
Re: Also, you could just write an HTML file, and set its...
Author: Christophe MOUSTIER
(http://www.jguru.com/guru/viewbio.jsp?EID=1074991), Apr 9, 2003
Hmmm...HTML loses many information that WORD & RTF format have.
I've tried to handle the RTF file which is a somehow good idea, but I have a file
which weights 8MB in WORD and 120MB in RTF !!!
So far, I cannot afford handling so huge data (not the computer, but rather the time
of load/save action spent for the user)
Any other Idea ?
Tomcat 3.x supports load balancing through Apache (mod_jserv). Tomcat 4.x
supports it natively.
Comments and alternative answers
According to my view,
A load balancing is useful when one
server(say Tomcat1) which is serving all jsp/servlets
is shutdown then the serving automatically
taken care of by another server(say tomcat2) in the
cluster WITHOUT LOOSING THE "SESSION" between the
pages that we are navigating.
I'm not sure about this thing in Resin server but in other servers it's a setting for the
servlet request, means whatever value you set to this property, your client will wait
for a response for that period of time from a servlet after that time expires it breaks
the connection to your servlet.
I make simple servlet which do Thread.sleep(), but client does not breaks connection
...
Thanx anyway
How can we make tree widgets, like in Swing, in an HTML page?
Location: http://www.jguru.com/faq/view.jsp?EID=299847
Created: Jan 11, 2001 Modified: 2001-01-15 08:12:07.349
Author: Michael Szlapa (http://www.jguru.com/guru/viewbio.jsp?EID=241392)
Question originally posed by hatinder vohra
(http://www.jguru.com/guru/viewbio.jsp?EID=216890
Applets tend to be less browser dependent. Large applets may be slow to load over
low-bandwidth connections and they are also slow to start on older computers. Also
applets may be disabled in the browser or not be available inside the firewall.
3. Build your tree logic on the server side using JSP or servlet technology. Avery
node is the hyperlink, when clicked the server side generates new page where given
node is expanded/colapsed.
This is potentially the slowest but the most robust solution - works always. This
solution will not allow you to use drag and drop functionality.
Regards,
Michael
Would an AWT implementation of a tree remove the need for plug-ins? Is such an
implementation available somewhere?
See also
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Oct 30, 2001
How can I display content in the form of a Tree using JSP?
I have a global variable in a servlet class. What will happen to this global
variable if two requests hit on the same time?
Location: http://www.jguru.com/faq/view.jsp?EID=300129
Created: Jan 11, 2001 Modified: 2001-01-15 08:10:23.982
Author: Renato Michielin (http://www.jguru.com/guru/viewbio.jsp?EID=255654)
Question originally posed by guan ho
(http://www.jguru.com/guru/viewbio.jsp?EID=126860
[See How do I ensure that my servlet is thread-safe? for more information. Note also
that using SingleThreadModel may not work, if other servlets/classes access the
global (static) variable as well. -Alex]
Unforseen Events
Author: David Tomlinson (http://www.jguru.com/guru/viewbio.jsp?EID=423613),
May 17, 2001
In the old days, they would say that "results are undefined"! David
How can you select multiple files for upload to a servlet? The browse button
on my form only allows me to choose one file at a time.
Location: http://www.jguru.com/faq/view.jsp?EID=303625
Created: Jan 16, 2001 Modified: 2001-07-23 10:18:08.076
Author: Jorge Jordão (http://www.jguru.com/guru/viewbio.jsp?EID=275762)
Question originally posed by Vai Patel
(http://www.jguru.com/guru/viewbio.jsp?EID=270553
You'll have to put as many file components in your page as the number of files you
want to upload. Remember to assign a different NAME attribute value to each.
I've found only one other (non-applet) solution: upload the files one at a time. You
generally want to reload the page after each upload and display a list of files that have
already been uploaded.
The advantage to this method is that it allows an arbitrary number of files and doesn't
clutter up your interface with lots of unwieldy file input controls.
The down side is that you have to store the files as they're uploaded. If you're writing
a Web mail application, for instance, you might prefer to get all the attachments at
once and send them straight through to the mailer. Also, storing the files means you
need to clean them up if the user aborts halfway through.
I'm doing the exact opposite right now. We've got PDFs stored in an Oracle database,
I pull out multiple PDFs, create a new ZipOutputStream around the
ServletOutputStream, and then put each PDF as a new ZipEntry. You can specify the
filename as you create the new ZipEntry. It works great, and the user can choose
which PDFs he wants and then receives an archive of all of them.
The Java Servlets O'Reilly book is very good, but it is a bit outdated (it covers API
2.0). An update will be coming though, check it out at the author's web site.
See also
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Dec 28, 2002
Can you recommend some good books on servlets?
Instead of a good book, i have a cheaper solution. After reading this, even a newbie
can code servlets. An excellent web tutorial :
http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/
Comments and alternative answers
According to the Servlet 2.2 Specification, "Session tracking through HTTP cookies
is the most used session tracking mechanism and is required to be supported by all
servlet containers", so it should be the default on all servers.
Suppose I have 2 servers, server1 and server2. How can I take data in a
cookie from server1, and send it to server2?
Location: http://www.jguru.com/faq/view.jsp?EID=304637
Created: Jan 17, 2001 Modified: 2001-01-19 14:17:51.598
Author: Jorge Jordão (http://www.jguru.com/guru/viewbio.jsp?EID=275762)
Question originally posed by Soumendu Das
(http://www.jguru.com/guru/viewbio.jsp?EID=264142
• Reads the cookie name, value and expiration date request parameters, using
request.getParameter().
• Creates a similar cookie, using response.addCookie().
If the two servers are in the same domain you can set...
Author: Fabio Moratti (http://www.jguru.com/guru/viewbio.jsp?EID=63024), Jan 23,
2001
If the two servers are in the same domain you can set the "domain" attribute for the
cookie, in this way it is sent to both servers.
Version 3.5.2 of WebSphere supports WAR files and the Servlet 2.2 specification -
see section 8.7 of this Red Book for details.
This sounds like the servlet you have may be implementing the SingelThreaded
interface. Is this true? Also, you really need to watch your use of class-level
variables. Any variables you display to your user should probably be declared and
assigned from within the scope of the doPost, doGet, or service methods.
Are you able to post your servlet code here? That might be instructive.
How can I pass data from a servlet running in one context (webapp) to a
servlet running in another context?
Location: http://www.jguru.com/faq/view.jsp?EID=311485
Created: Jan 24, 2001 Modified: 2001-01-27 04:31:51.328
Author: Ryan Breidenbach (http://www.jguru.com/guru/viewbio.jsp?EID=45212)
Question originally posed by nagaraj thota
(http://www.jguru.com/guru/viewbio.jsp?EID=34847
There are three ways I can think of off the top of my head:
Also
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Oct 25, 2001
This question is also answered at:
How can I join a session with a given sessionId without using cookies?
Assume I get the session from the HttpSessionContext passing the session
Id.
Location: http://www.jguru.com/faq/view.jsp?EID=314666
Created: Jan 28, 2001 Modified: 2001-01-29 07:39:30.678
Author: Ravindra Babu katiki (http://www.jguru.com/guru/viewbio.jsp?EID=313843)
Question originally posed by Jayaprakash A
(http://www.jguru.com/guru/viewbio.jsp?EID=284375
It is better to use URL Rewriting. Generate a session id by your self and append that
session id to the URL at the end.
For more details, see this site's FAQs for URL Rewriting in Servlet OR JSP section.
URL rewritng is better option for your case because Session uses cookies and without
cookies you can not use sessionid.
[Still doesn't quite answer the question: is there a way to get the session a priori (if
you know the session ID)? -Alex]
How can I write an "error page" -- that is, a servlet or JSP to report errors
of other servlets?
Location: http://www.jguru.com/faq/view.jsp?EID=318806
Created: Feb 1, 2001 Modified: 2001-07-16 15:14:03.037
Author: Subrahmanyam Allamaraju
(http://www.jguru.com/guru/viewbio.jsp?EID=265492) Question originally posed by
Junming Zhu (http://www.jguru.com/guru/viewbio.jsp?EID=280800
The Servlet 2.2 specification allows you to specify an error page (a servlet or a JSP)
for different kinds of HTTP errors or ServletExceptions. You can specify this in
deployment descriptor of the web application as:
<error-page>
<exception-type>FooException</exception-type>
<location>/error.jsp</location>
</error-page>
The web container invokes this servlet in case of errors, and you can access the
following information from the request object of error servlet/JSP: error code,
exception type, and a message. Refer to section 9.8 of Servlet 2.2 spec.
You should check the dtd of the Web Application Descriptor (web.xml). There is an
element that it's just for that:
<error-page>
<error-code>404</error-code>
<location>/test.html</location>
</error-page>
Note: it wouldn't work without the '/' preceding test.html and the parser is
real picky about where in the file you place the definitions. This is after the
<servlet-mapping> element.
<web-app>
<error-page>
<error-code>404</error-code>
<location>/error404.jsp</location>
</error-page>
</web-app>
Make changes one at a time, so you can tell where you went
wrong and what works and what doesn't. It's not like HTML. If
you have a mistake, it will cause problems with tomcat and you
won't even be able to start it!
<error-page>
<error-code>500</error-code>
<location>/error500.html</location>
</error-page>
A context error...
http://www-106.ibm.com/developerworks/java/library/j-
tomcat/?open&l=101,t=grj,p=TomcatTricks
Note that these changes will not take be applied until you
restart Tomcat. The same is true with web.xml.
Fabio
Spoon
<error-page>
<error-code>404</error-code>
<location>/errorpages/html404.html</location>
</error-page>
is fine but nobody can tell where in the web.xml file it goes. Sure, we can then go
look it up in the DTD and maybe figure out that cryptic syntax to determine where it
goes, but since YOU know the answer, YOU already know where it goes, so tell us.
<web-app>
...
<servlet>
...
</servlet>
...
<welcome-file-list>
...
</welcome-file-list>
<error-page>
<error-code>404</error-code>
<location>/errorpages/html404.html</location>
</error-page>
<taglib>
...
</taglib>
...
</web-app>
so that we know the error-page stuff goes between the welcome-file-list and the taglib
stuff.
While learning J2EE, I have found hundreds of partial answers like these which cause
more confusion than help. In the future, I wish more people would take the time to
provide a complete answer that simply removes doubt instead of creating more.
Please always include enough context in one's Deployment Descriptor answers so that
people know where the excerpt goes. If the above answer had been done this way, the
ensuing pile of questions others had about where it goes and why it wasn't working
could have been avoided.
It's not just you, almost everybody makes these types of mistakes when answering
questions and it simply drives me insane.
Spoon
If you are using a Java server side solution, like the JSDK (which I suppose) then you
can store/retrieve the references in/from the HTTPSession object which you can get
from the incoming HttpRequest object.
I've written a servlet that was using JServ and now I upgrade to use
Tomcat. What would I need to change?
Location: http://www.jguru.com/faq/view.jsp?EID=321264
Created: Feb 5, 2001 Modified: 2001-02-06 07:44:37.919
Author: Tim Pierce (http://www.jguru.com/guru/viewbio.jsp?EID=19457) Question
originally posed by Bapu Patil (http://www.jguru.com/guru/viewbio.jsp?EID=49941
The only thing you should have to change code-wise is whatever has been changed
in the Servlet API between the API used in JServ and the api used it Tomcat... just a
couple that come to mind are
I've written a servlet that was using JServ and now I upgrade to use
Tomcat. What would I need to change?
Location: http://www.jguru.com/faq/view.jsp?EID=322048
Created: Feb 6, 2001 Modified: 2001-02-11 11:10:11.75
Author: Ryan Breidenbach (http://www.jguru.com/guru/viewbio.jsp?EID=45212)
Question originally posed by Bapu Patil
(http://www.jguru.com/guru/viewbio.jsp?EID=49941
Well, there isn't any reason that your servlet itself would have any specific code in it
that would not allow it to be deployed on Tomcat. By this, I mean the code in the
init, service, deGet, etc. methods should be servlet-container independent.
That being said, all you should have to do it register the new servlet with Tomcat.
This requires modifing two files, server.xml and web.xml.
The server.xml file is where you will register your web application (the context in
which your servlet will operate). This would look something like this:
<Server>
<!-- other stuff here -->
<ContextManager debug="0" workDir="workDir" >
<!-- other stuff here -->
<!-- your context -->
<Context path="/myApp" docBase="webapps/myApp" debug="0"
reloadable="true" / >
</ContextManager>
</Server>
The web.xml file is where you will configure your web application. This includes
configuring your servlet's alias and initial parameters. This would look something
like:
<servlet>
<servlet-name>myServlet</servlet-name>
<servlet-class>com.mypackage.MyServlet</servlet-class>
<init-param>
<param-name>param1</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>myServler</servlet-name>
<url-pattern>/useMyServlet</url-pattern>
</servlet-mapping>
See the Tomcat Users Guide for more details.
ColdFusion is a Proprietary system with its own markup tags for doing the server side
processing. Servlets again have a completely different architecture and they have
their own way of processing the server side logic. You may have to re-write the code
entirely when you migrate to Servlets. I would suggest ColdFusion to JSP is more
appropriate migration if your application has more presentation content rather than
heavy application logic.
Regards,
Radhakrishnan
The only real way to react is not to buy or use any of such products, however, we all
know that this is hardly possible.
Apparently this happens very sporadically...it doesn't happen all the time and after this
happens if you click Refresh, sometimes the proper page comes up.!!!!! And mine is
not even a secure web server(I mean I'm still trying it with http and not https.) on
JRun.
Typically, assuming you have a login page, the session should be created in the login
validation servlet, and all other servlets just need to do request.getSession(false),
and if this returns a null, they should serve the login page.
regards,
- Vikram
rgds, satish
For me, using IE6 as I am, it was to do with the Internet Options - Privacy -
Advanced tab having the 'Always allow session cookies' checkbox checked.
I simply un-checked the box, saved it, and lo and behold the session now persists!
Cheers,
Marcus.
If you refer to the API documentation you will see that the getSession(boolean
create) method will only create a new session if no session is available. When a
session aready exists this session will be used.
Check if your browser is using cookies or if the session is properly appended to the
link URL. To make it possible for the container to identify the session you can use
cookies or append the session-id via response.encodeURL(String url). If neither
cookies nor URL rewriting is used the servlet container cannot determine the session
and will a new one every time.
regards
Niclas
Session
Author: Navaljit Bhasin (http://www.jguru.com/guru/viewbio.jsp?EID=404310), Apr
17, 2001
The answer given by you is misleading and totally wrong As per your answer
request.getSession(true) always return new session. Sorry sir, go back to school and
clear the concepts.No wrong advices. As per j2ee docs this is answer Parameter: true -
to create a new session for this request if necessary; Parameter : false- to return null if
there's no current session Please note the if necessary in case the parameter is true.
Why the hell you give wrong suggestions. Naval
Re: Session
Author: rahul gagrani (http://www.jguru.com/guru/viewbio.jsp?EID=1167271),
Apr 29, 2004
Hello can u please tell me what is the difference between request.getSession(true)
and request.getSession() . After referring to the api docs i just dont find any
difference as they both returns the session (if available) and if it is not available
yet, creates one.
[More info: I.e. if servlet not gives answers for 1 min. (it freezes, it makes too long
SQL query etc), browser will receive some error message.
I work with resin servlet engine, but if it is impossible in resin, solutions for other
engines also are welcome.
Of course, I can do this manualy (Timer, or just Thread with sleep()) but solution at
config level is preferable.
Thanx]
For HTTP1.1 you can set status codes for response. (some browsers support for 1.0
also) You can call response.setStatus before sending any content via the PrintWriter.
For setting timeout , status code is "SC_GATEWAY_TIMEOUT" with value 504. You
can call response.setStatus(504)for that. You call call response.sendError also. The
advantage of sendError over setStatus is that, with sendError, the server
automatically generates an error page showing the error message. In your case it
will be :
response.sendError(response.SC_GATEWAY_TIMEOUT,
"Timeout");
[That doesn't answer the question directly; you still need to implement your own
timeout in your servlet code before sending the 504 response. Is there a standard
way to configure this irrespective of servlet code? -Alex]
It could be that the servlet does not have sufficient permissions to write to the file-
system (which itself depends on what permissions the servlet container process has).
Try explicitly specifying the full path to a directory that you know has full 'global'
read/write access permissions.
FileNotFoundException
Author: rajiv k (http://www.jguru.com/guru/viewbio.jsp?EID=386332), Mar 24, 2001
your class shuld impliment Serializable interface .So add-- implements Serializable--
to your class .It will work All built in classes have no problem Isn't. Try that also...
The current servlet spec (2.2) doesn't mention specifically where to store
configuration files. The new version (2.3) will have a more explicit way of accessing
them.
In the meantime, a good technique is to put them in the *root* level of your WEB-
INF/classes directory. (e.g. "mywebapp/WEB-INF/classes/config.txt".) Since this
directory is automatically on your classpath, you can load the files using
InputStream in = this.getClass().getResourceAsStream("/" +
filename);
if (in == null)
throw new IOException("Resource " + filename + " not
found");
Comments and alternative answers
How can I develop a servlet or JSP which can comunicate with an applet
showing the list of all the other users? This applet should also allow the
user to send messages to specific users in the list (More or less like the
applet in myYahoo when a Yahoo messenger is not installed)
Location: http://www.jguru.com/faq/view.jsp?EID=338370
Created: Feb 25, 2001 Modified: 2001-02-25 17:30:54.792
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Abey Mullassery
(http://www.jguru.com/guru/viewbio.jsp?EID=268841
Oddly enough, I've developed such an applet/servlet combo :-) I'm calling it
"Combadge."
It's still not ready for release, but I'll be releasing it soon. Please bug me via email.
See also Jabber and the Jabber Applet for inspiration and source code.
This notion of a web application became very significant upon the Servlet 2.1 API,
where you could deploy an entire web application in a WAR file. For more specifics on
web application, please see this FAQ.
Notice that I always said "servlet instance", not servlet. That is because the same
servlet can be used in several web applications at one time. In fact, this may be
common if there is a generic controller servlet that can be configured at run time for
a specific application. Then, you would have several instances of the same servlet
running, each possibly having different configurations.
This is where the ServletConfig comes in. This object defines how a servlet is to be
configured is passed to a servlet in its init method. Most servlet containers provide
a way to configure a servlet at run-time (usually through flat file) and set up its
initial parameters. The container, in turn, passes these parameters to the servlet via
the ServetConfig.
Many WAP browsers and/or proxies do not understand cookies and/or redirects. This
means you will have to use URL rewriting for your session management. Feel free to
complain to the WAP product vendors -- these are basic HTTP features that really
should be implemented.
How many cookies can one set in the response object of the servlet? Also,
are there any restrictions on the size of cookies?
Location: http://www.jguru.com/faq/view.jsp?EID=340982
Created: Feb 28, 2001 Modified: 2001-03-02 07:18:07.991
Author: Jorge Jordão (http://www.jguru.com/guru/viewbio.jsp?EID=275762)
Question originally posed by mpavanu muni
(http://www.jguru.com/guru/viewbio.jsp?EID=253970
If the client is using Netscape, according to the Client-Side JavaScript Reference, the
browser can receive and store
Which classes implement the interfaces from the standard servlet API such
as HttpSession, HttpServletRequest, etc.?
Location: http://www.jguru.com/faq/view.jsp?EID=342634
Created: Mar 2, 2001 Modified: 2001-03-02 07:07:04.753
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Artyom Malyshkov
(http://www.jguru.com/guru/viewbio.jsp?EID=284237
The server vendors must write those classes, and pass them in to your servlets. The
beauty of interfaces is that each server vendor can implement their own version of
the same interface, and your code need not change.
Most of the Servlet containers reload the servlet only it detects the code change in
the Servlet, not in the referenced classes.
<Context path="/myApp"
docBase="D:/myApp/webDev"
crossContext="true"
debug="0"
reloadable="true"
trusted="false" >
</Context>
The reloadable = true makes the magic. Every time the Servlet container detects
that the Servlet code is changed, it will call the destroy on the currently loaded
Servlet and reload the new code.
But if the class that is referenced by the Servlet changes, then the Servlet will not
get loaded. You will have to change the timestamp of the servlet or stop-start the
server to have the new class in the container memory.
There are many good answers here at jGuru related to this question. You may find
them useful:
Servlet reload problem
[That's great, but a little brief -- anyone want to elaborate with more details, code
samples, etc.? -Alex]
<BODY>
<IMG src="img/pic.gif">
</BODY>
That should take care of the problem.
Comments and alternative answers
Another solution:
Author: Juergen Staebler (http://www.jguru.com/guru/viewbio.jsp?EID=424068),
May 23, 2001
Well, I tried it and got NO gif's at all. (Problem is the request.getContextPath, its
null.) So I handle it on a similar way:
Inside the servlet set-up a session attribute,
e.g.:
request.setAttribute("mySourceDir", "/src/package/").
regards
J.Staebler
[It works fine when I use Tomcat as standalone. However, when passing the query
string through Apache 1.3.12 and mod_jserv.so the query string gets cut where the
language specific characters start. I can see that Apache writes the language specific
characters in the access log. So I guess something is happening with the query string
on the way from Apache to Tomcat. I'm using Red Hat Linux 6.2. Is there a way to
put these language specific characters all the way through? The characters in
question are swedish (åäöÅÄÖ). Or do I have to do some gismo with mod_rewrite?]
Try using %nn (where nn is the hex ASCII key code) in the GET request.
[Also, make sure you're using the latest version of mod_jk (not mod_jserv) -Alex]
Use encoding
Author: amit singi (http://www.jguru.com/guru/viewbio.jsp?EID=380857), Apr 27,
2001
When u r passing a query string don't pass it directly just convert it into following
format. %xx (where xx is the hex ASCII key code) You can do this by using function
encode of java class URLEncoder in net package. But for this you need to get the
bytes in the specific encoding from the string and then construct string. If u want to
pass s(String) in query then use this URLEncode.encode(new
String(s.getBytes("Shift_JIS"))) where shift_jis is the encoding for that language and
while retrieving the request parameter use shift_jis to get the string value.
Are there any editors for developing servlets?
Location: http://www.jguru.com/faq/view.jsp?EID=348070
Created: Mar 9, 2001 Modified: 2001-03-12 11:41:39.731
Author: JP Moresmau (http://www.jguru.com/guru/viewbio.jsp?EID=127279)
Question originally posed by Surendra Kumar
(http://www.jguru.com/guru/viewbio.jsp?EID=300649
Most commercial Java IDEs now have servlet support and debugging build in (at
least in their "enterprise" versions...). I know that Inprise JBuilder and Oracle
JDevelopper do for example... Try Allaire JRun studio if you are using JRun.
Comments and alternative answers
visual cafe and visual age for java also support s...
Author: sree mam (http://www.jguru.com/guru/viewbio.jsp?EID=31208), Mar 14,
2001
visual cafe and visual age for java also support servlets.
Most Servlet Engines should support HTTPS (SSL) Connections if they are used as a
plug-in to common HTTP servers such as Netscape, IIS and Apache. The reason for
this is that the Web Server will provide the HTTPS connection between the client and
the Web Server.
However, one draw back of this mechanism is that the communication from the Web
Server to the Servlet engine may not be HTTPS but either a proprietory protocol
(such as OSE for WebSphere for remote installs) or a TCP/IP connection to the
Servlet engine or via the plug-in protocol (if local). In most cases this may not be an
issue but if data is still required to be encrypted between the Web Server and Servlet
Engine an IPSec or SOCKS solution can be provided to handle comms to the Servlet
Engine.
answer
Author: John Smith (http://www.jguru.com/guru/viewbio.jsp?EID=431592), May 31,
2001
Think and read documentation
Re: What is the maximum length of a URL, including... It's very server-dependant.
Check Server documentation. Please see 3.2.1 General Syntax section of
ftp://ftp.isi.edu/in-notes/rfc2616.txt.
The HTTP protocol does not place any a priori limit on the length of a URI. Servers
MUST be able to handle the URI of any resource they serve, and SHOULD be able to
handle URIs of unbounded length if they provide GET-based forms that could
generate such URIs. A server SHOULD return 414 (Request-URI Too Long) status if a
URI is longer than the server can handle (see section 10.4.15).
Note: Servers ought to be cautious about depending on URI lengths above 255
bytes, because some older client or proxy implementations might not properly
support these lengths.
Manish
Test
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Mar 22, 2001
Test
Why do I get the compiler error "package javax.servlet does not exist" or
"package javax.servlet not found in import"?
Location: http://www.jguru.com/faq/view.jsp?EID=413601
Created: May 2, 2001 Modified: 2001-05-05 14:17:16.683
Author: Kursat Demirezen (http://www.jguru.com/guru/viewbio.jsp?EID=412558)
Question originally posed by Kevin Fonner
(http://www.jguru.com/guru/viewbio.jsp?EID=412162
Why do I get the compiler error "Package javax.servlet not found in import"?
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), May 5, 2001
You need the servlet API libraries in your classpath. These are usually found in
servlet.jar (although some servlet engines, IDEs, and earlier versions of the servlet
package called them jsdk.jar or something else). Make sure servlet.jar is in your
classpath and you should be all set.
If javap can find it, then your config file or script isn't setting the classpath correctly.
Perhaps it's a syntax error or you're just confused about which script/config
file/setting is really getting used. Or perhaps you're using a different install of Java --
different JDKs can have different classpaths.
Re: Why do I get the compiler error "Package javax.servlet not found in
import"?
Author: Monty Fury (http://www.jguru.com/guru/viewbio.jsp?EID=463799), Jul
27, 2001
I too have spent hours and hours trying to work out why, despite setting my
CLASSPATH correctly to point to the servlet.jar archive in the Tomcat
installation, the javac compiler refuses to find it and thus gives such messages as
"package javax.servlet does not exist".
By searching on Sun's java sites, the Tomcat site, and many mailing lists, I saw
that tons of people were having the same problem, and the only replies offered
were of the form "are you *sure* you've set the CLASSPATH properly?!"
Naturally, I was sure I had, but as it turns out, I hadn't: There was a problem with
case-sensitivity, at least on my system (Windows ME). The servlet.jar file was
located as follows:
C:\Program Files\Tomcat-3.2.3\lib\servlet.jar
CLASSPATH=.;C:\PROGRA~1\TOMCAT~1.3\LIB\SERVLET.JAR
CLASSPATH=.;C:\PROGRA~1\TOMCAT~1.3\lib\servlet.jar
My knowledge of computing has been entirely self-taught over the last year, and
there are some serious gaps - can anyone tell me why a DOS pathname should
suddenly be case sensitive like that?
Re: Re: Why do I get the compiler error "Package javax.servlet not found
in import"?
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jul
27, 2001
Because DOS is stupid. Next question? :-)
Re: Re: Why do I get the compiler error "Package javax.servlet not found
in import"?
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jul
27, 2001
By the way, a good way to be sure you've set the class path is by using javap.
In the above, typing "javap javax.servlet.Servlet" would have failed until you
got the right class path.
Re: Re: Why do I get the compiler error "Package javax.servlet not found
in import"?
Author: Amit Jain (http://www.jguru.com/guru/viewbio.jsp?EID=520788), Oct
15, 2001
Hi, I am facing same type of problem. Environment is : Windows ME, JRUN
and Tomcat(tried on both), Apache web server. From last 2 days I have tried
each possible combination for class path to servlet.jar but nothing is working. I
am getting sick of restarting my computer each time I change my classpath ;(.
Help will be really appriciated. Thanks, Amit Jain
Re: Why do I get the compiler error Package javax.servlet not found in
import?
Author: devender bejju (http://www.jguru.com/guru/viewbio.jsp?EID=1204161),
Oct 8, 2004
seems like the CLASSPATH itself is a biggest hurdle for newbies. anyways I too
have the same problem, some where in the document
( http://www.coreservlets.com/Apache-Tomcat-Tutorial/#Set-CLASSPATH ) i
found that we need to give the path in double quotes if tomcat is install dir has any
spaces eg "C:\Program Files\Apache Software Foundation\Tomcat
5.0\common\lib\servlet-api.jar";"C:\Program Files\Apache Software
Foundation\Tomcat 5.0\common\lib\jsp-api.jar" normally in dos envi, every thing
after the first space is treated as parameters (importantly unlike the prior versions
of tomcat (<5),for tomcat 5 its both the servlet-api.jar and jsp-api.jar) like in the
above ex , without the double quotes dos treats c:\program as one and rest of the
things as parameters in the same doc author said to put . and .. and ..\.. i
understood it why its required but need to continue research , dont know how long
it takes i will post when I solved
Re: Why do I get the compiler error Package javax.servlet not found in
import?
Author: Thanh Le Ngo (http://www.jguru.com/guru/viewbio.jsp?EID=1215714),
Dec 10, 2004
you can set classpath .;C:\j2sdk1.4.2_04\lib;c:\j2ee\lib\j2ee.jar j2ee is j2ee home
directory, in j2ee.jar has package javax.servlet (the default is
c:\Sun\AppServer\lib\j2ee.jar) it's ok for me when i compile servlet
Someone else posted the following command and I've had much better results using
it:
javap javax.servlet.Servlet
I found the winning classpath command for my configuration...it looks like this:
set classpath=.;C:\Java\Tomcat\common\lib\servlet-
api.jar;C:\Java\Tomcat\common\lib\jsp-api.jar;C:\Java\
No.
Tomcat (talking about version 3.x.x) is the reference implementation of the webapp
part of J2EE (ie, no EJB). In this spec connection pooling is not contemplated.
You can however use pooling by using the JDBC 2.0 optional package instead of
JDBC 2.0 directly.
For additional info see the JGuru JDBC FAQ Forum and see How do I access a
database from my servlet? in the Servlets FAQ.
-Mike
Dear Mike
After several attempts, I'm unable to setup and make distributed transactions to
work in Tomcat. I am using Tomcat 4.0.4, Tyrex .97 and struts-1.1-b2.
Can you please give me a running sample application which uses transcation
mgmt?
Many many thanks in advance
Denny Dedhiya
How can I return a readily available (static) HTML page to the user instead
of generating it in the servlet?
Location: http://www.jguru.com/faq/view.jsp?EID=415883
Created: May 5, 2001
Author: André Wolf (http://www.jguru.com/guru/viewbio.jsp?EID=310274) Question
originally posed by Anthony Lew
(http://www.jguru.com/guru/viewbio.jsp?EID=415782
To solve your problem, you can either send a "Redirect" back to the client or use a
RequestDispatcher and forward your request to another page:
1. Redirect:
A redirection is made using the HttpServletResponse object:
2. if(condition) {
3. response.sendRedirect("page1.html");
4. } else {
5. response.sendRedirect("page2.html");
6. }
7. RequestDispatcher:
A request dispatcher can be obtained through the ServletContext. It can be
used to include another page or to forward to it.
8. if(condition) {
9. this.getServletContext()
10. .getRequestDispatcher("page1.html").forward();
11.} else {
12. this.getServletContext()
13. .getRequestDispatcher("page2.html").forward();
14.}
Both solutions require, that the pages are available in you document root. If they are
located somewhere else on your filesystem, you have to open the file manually and
copy their content to the output writer.
If your application server is set up in combination with a normal web server like
Apache, you should use solution (1), because the the web server usually serves
static files much faster than the application server.
Is there a way to detect when the session has expired, so that we can send
a redirect to a login page?
Location: http://www.jguru.com/faq/view.jsp?EID=415912
Created: May 5, 2001 Modified: 2003-01-08 14:08:04.407
Author: Michael Wax (http://www.jguru.com/guru/viewbio.jsp?EID=242559)
Question originally posed by rbkadam raju
(http://www.jguru.com/guru/viewbio.jsp?EID=405242
[In our Servlet framework, session timeout happens after 1hr. Currently if user tires
to access the pages after 1hr, he gets null-pointer exception. Is there any way we
can detect that session has been expired, so that we can show standard HTML Page
to User, indicating that his session has expired, he has to LOGIN again.]
-----------------
if (session != null)
{
session.invalidate();
}
session = request.getSession(true);
Then in other servlets where the session is used, the following code should be
included.
HttpSession session = request.getSession(false);
if (session == null)
{
//redirect to login page
}
//other code
And when the user logs out, session can be invalidated.
You could add an attribute in the HttpSession object storing the time, the user
made last request. This value is updated as and when the user makes request.
A thread would be monitoring the user inactivity time by comparing the "Last
Request" time in session object with that of the "Current time".
The thread's "sleep" time should be less than the "countdown" time.
As of Servlet spec 2.2, it's impossible to add or remove parameters from a request
object. Servlet spec 2.3 will have some mechanism to allow this functionality. (How
difficult it will be in practice is not clear. It will definitely not be as easy as
'request.removeParameter("foo")', unfortunately.)
In the meantime, using a wrapper class will work in some servlet engines but fail in
others.
A tad misleading....
Author: Lukas Bradley (http://www.jguru.com/guru/viewbio.jsp?EID=35930), Dec 2,
2002
The 2.3 spec still does not allow access to the "innards" of the Servlet Container
vendor specific implementation. Therefore, unless you are writing your own Servlet
Engine, it still remains impossible to add or remove parameters from a request object.
Workaround
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jan 9, 2003
http://www.jguru.com/forums/view.jsp?EID=1016603
[Textbook descriptions (many) that I have seen so far really don't go very far in this
regard- they either are too vague (use servlets/JSP between the GUI and EJB) or too
low level (connect two with getRequestDispatcher())... I am interested in "proper"
organization and functional decompositon of a multiservlet application, and am sure
that many people are dealing with this same issue- thanks for your kindness! Barry]
Barry,
You can consider the "MVC Design Pattern", a.k.a. "Model 2 Architecture".
There is an interesting article on Javaworld: Understanding JavaServer Pages
Model 2 architecture. In addition, you can take a look at Struts, one of the many
projects of the Apache foundation regarding Java. [ Ross Keatinge adds:
Also check out Webwork which is an MVC framework similar to Struts. For me as a
Java newbie it was a lot easier to understand and get started with than Struts. ]
According to the Java Language definition, a static variable is shared among all
instances of a class, where a non-static variable -- also called an instance variable --
is specific to a single instance of that class.
The big difference between instance variables and static variables comes when you
have configured your servlet engine to instantiate two instances of the same servlet
class, but with different init parameters. In this case, there will be two instances of
the same servlet class, which means two sets of instance variables, but only one set
of static variables.
Remember that you can store data in lots of different places in a servlet. To wit:
(In the case of SingleThreadModel, there may be many instances of the same servlet
class even with the same init parameters. SingleThreadModel is confusing and
usually unnecessary.)
Where can I find a description of the tags (elements and attributes) used in
web.xml?
Location: http://www.jguru.com/faq/view.jsp?EID=416037
Created: May 5, 2001
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
Francois-Yanick Bourassa (http://www.jguru.com/guru/viewbio.jsp?EID=389655
Francois,
The web.xml is the Servlet Web-Application descriptor. It's a standard XML file and
the description and the full description (including the list of all the available tags) can
be found in the Servlets 2.2 final specifications.
I don't think you can do that. The cookie specification defines only one domain per
cookie, so I don't think there is a way to read the same cookie from more than one
domain.
Different servlets may share data within one application via ServletContext. If you
have a compelling to put the servlets in different applications, you may wanna
consider using EJBs.
[You can also use a database, or use the file system, but it's difficult to share the
data inside the JVM. Even using statics may not work, since the two web applications
may be using different classloaders. -Alex]
Also
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Oct 25, 2001
This question is also answered at:
E.g.:
log("Servlet called with name " + request.getParameter("name"));
If this is insufficient, you can use java.io classes to write your own files.
See also:
If the cookies at client side are disabled then session don't work, in this
case how can we proceed?
Location: http://www.jguru.com/faq/view.jsp?EID=416057
Created: May 5, 2001
Author: Wayne Xin (http://www.jguru.com/guru/viewbio.jsp?EID=49940) Question
originally posed by girish kumar
(http://www.jguru.com/guru/viewbio.jsp?EID=322626
you may:
1. (from servlet) write the next page with a hidden field containing a unique ID that
serves as "session ID". So next time when the user clicks submit, you can retrieve
the hidden field.
2. If you use applet, you may avoid "view source" (so that people can't see the
hidden field). Your applet reads back an ID from the servlet and use that from then
on to make further requests.
[Also, search the topic Servlets:Cookies, Sessions, and State Management for more
information about sessions and cookies. -Alex]
res.setHeader("refresh","10; URL=http://"
+req.getServerName()+"/Openingpage.html");
out.println(e.getMessage());
out.close();
How to read a file from the WAR or webapp? If I have a configuration file,
say an XML file, stored inside the WAR, how do I open it from a servlet? I.e.,
Location: http://www.jguru.com/faq/view.jsp?EID=416061
Created: May 5, 2001
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
Alex Chaffee PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=3
The WAR file is automatically opened by the servlet container during the startup... at
least this is what the servlet specs are saying (and it is happening with both Resin
and Tomcat). Once you reach the servlet just use ServletContext.getRealPath() to
get the file.
For example if the file is in a 'template' dir under the root of the context, use
getRealPath("/template/file.xml");
Comments and alternative answers
getRealPathgetServletContext().getRealPath("/WEB-
INF/myconfig.xml")
(may not work on some servlet containers, but it's supposed to).
If I use the same directory path my server/ application is not able to find the file.
And I do not know what to do. Where and how should I tell my application to safe
my edited file properly?
Thank you,
Nick
URL myURL=application.getResource("/test.properties");
InputStream in = myURL.openStream();
Properties p = new Properties();
p.load( in );
out.println( p.getProperty("message") );
using getResource()
Author: Richa Sharma
(http://www.jguru.com/guru/viewbio.jsp?EID=1223623), Jan 27, 2005
While using URL myURL=application.getResource("/test.properties"); Where
should I place the test.properties file. I placed it, where I have my jsp files, but
I am getting myURL=null. Also should I make any changes in web.xml
How to read a file from war or webapp using servlet from weblogic
Author: bodapati koteswararao
(http://www.jguru.com/guru/viewbio.jsp?EID=1248895), Jun 16, 2005
Hi everybody, I know code of how to read the file from war or webapp using the
servlet from weblogic. Thanks and regards, Kotewararao
Re: How to read a file from war or webapp using servlet from weblogic
Author: sun lee (http://www.jguru.com/guru/viewbio.jsp?EID=1253509), Jul 15,
2005
Hi Bodapati, I have this problem with WebLogic. Can you share your solution?
By the way, I don't have the problem with Tomcat. Thankd, Sun
How can I set the number of concurrent connections in Java Web Server
2.0?
Location: http://www.jguru.com/faq/view.jsp?EID=416163
Created: May 6, 2001
Author: JIA Java Italian Association
(http://www.jguru.com/guru/viewbio.jsp?EID=414973) Question originally posed by
Chi Pong Lau (http://www.jguru.com/guru/viewbio.jsp?EID=415694
I don't have Java Web Server installed, but I've downloaded the manual and I've got
the answer to all your question. Maybe you can do the same for future reference
(aka: RTFM):
Administration Tool: Service Tuning
The Service Tuning page enables you to set or adjust properties that affect service
performance
[...]
Handler Threads
These settings affect the performance of threads within the service. Minimum: Sets
the minimum number of threads the service maintains in its handler pool to service
incoming requests. Because thread creation adds overhead to the service's response
time, set this property to a non-zero value. The default is 10 threads.
Maximum: Sets the maximum number of threads the service maintains in its handler
pool to service incoming requests. The default is 50 threads.
Timeout: Sets the expiration timeout for an idle handler thread. The default is 300
seconds.
On another page of the same manual, I've also found this note regarding Threads
and explaining how they affect performance and concurrency connection:
Tuning server performance
Threads
One thread is required per connection. Adding threads consumes more memory, but
can yield better response time for your clients on a server that concurrently serves
multiple connections that are either high latency or involve access to some high-
latency resource (like a servlet accessing a database on the other side of the
country).
You see how useful a manual is?
Regards.
Check out this answer. The logic is the same, but it's reversed.
You insert the object you need in the request scope with request.setAttribute() and
then you use the RequestDispatcher to forward or include the jsp page.
In the JSP page you use request.getAttribute() to get the object(s) back.
If you need to read the form parameters, you just use the RequestDispatcher,
because it passes the request object.
See also:
• How can I pass data retrieved from a database by a servlet to a JSP page?
• How can I call a servlet from a JSP page? .
For beginning jsp coders it is probably confusing that there is a specific mechanism
for passing an http parameter from a jsp to a servlet, but not the other way around.
Instead, rather than passing a parameter (limited to being a mere text string), you can
pass an attribute, which can be any object you'd like. Very handy!
On the other hand, there are times when you do actually need to send an http
parameter, as when you want to forward (to use the term loosely) a request to a
legacy cgi script that's expecting POST style parameters to be passed. It can be done,
but involves opening up streams, etc., and is rather messy . . . an ideal candidate for
encapsulation in a utility class. (I'll upload mine if there's any interest.)
As simple as that.
foo means... nothing. Literally. It's the name you give something to mean "this thing
has no name." It means "fill in your own variable name here."
Used very generally as a sample name for absolutely anything, esp. programs and
files (esp. scratch files). ...
When `foo' is used in connection with `bar' it has generally traced to the WWII-era
Army slang acronym FUBAR (`F**ked Up Beyond All Repair'), later modified to
foobar. Early versions of the Jargon File interpreted this change as a post-war
bowdlerization, but it it now seems more likely that FUBAR was itself a derivative of
`foo' perhaps influenced by German `furchtbar' (terrible) - `foobar' may actually
have been the original form.
Near the end of WWII, the U.S. Air Force patrolling German airspace encountered
highly maneuverable balls of light in the area between Hagenau in Alsace-Lorraine
and Neustadt an der Weinstrasse in the Rhine Valley. These unidentified flying
objects came to be referred to as "Foo Fighters", or "Kraut Balls" by those who
believed the objects were a secret German weapon.
See also:
• http://www.pla-net.net/~alucard/archives/humour/foo.html
• http://www.cs.oberlin.edu/students/jmankoff/FOO/FAQ
[I have I servlet that generates a HTML page and I want to use a CSS file (named
senior.css), so I wrote a statement like that:
out.print(" <link rel='stylesheet' type='text/css' href='senior.css'>")
]
The statement is perfect, but remember that it is parsed by the browser so the file
should reside in a directory that is accessible to the browser.
I suggest you to put the CSS file in the rood of your context and have that statement
point there. That's what I normally do.
[That way, no matter where your page is located, it can find it at the root level if it's
called "/senior.css" or "/foowebapp/senior.css". -Alex]
<LINK REL="StyleSheet"
HREF="<%=request.getContextPath()%>/util/CSS/Style.css"
TYPE="text/css">
However, you must make sure that the entire path is accurately typed (i.e. is
case sensitive).
If I've understood correctly, the Application Event of Servlet 2.3 is Sun's answer to
one of the most request festures to servlets, which is an easy way to monitor, and
reacts to, specific events that happen during the lifecycle of an application.
The idea is very similar to a Swing event. A developer can set up listeners on the
objects that needs to be monitored and receive an event object, so can react
appropriately.
For example a programmer can create a listener on a session object inplementing the
HttpSessionListener interface, that has two methods:
void sessionCreated(HttpSessionEvent evt) that is fired when a new session
object is created;
void sessionDestroyed(HttpSessionEvent evt) that is fired when a new session
object is destroyed or invalidated;
How do I change the default sessionID identifier name in Tomcat 3.2.1? The
default identifier name is jsessionid.
Location: http://www.jguru.com/faq/view.jsp?EID=416225
Created: May 6, 2001
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
Henky Wibowo (http://www.jguru.com/guru/viewbio.jsp?EID=388711
Hi.
I don't think you can change that identifier, because the name 'jsessionid' it's
specified in Chapter 7 of the Servlet 2.2 specifications, that you can download here
I don't really know what you would like to do, but I'm afraid that the only way to
change it it's to manage your own session cookie with your own identifier and,
eventually, using that cookie to map map your identifier with the jessionid.
[How does Tomcat distribute servlet/JSP processing to the 20+ Java processes it
creates? Is each client request serviced by a different Java process? If Tomcat
received 100 simultaneous servlet requests, would it need to create 100 Java
processes to handle them?]
Theoretically yes, Tomcat will try to optimize the requests to handle as much
simultaneous requests it can.
[N.B.: Under Linux, each Java Thread appears in the process list (ps) as a separate
process. This is because native Linux threads are implemented as lightweight
processes. However, there is still only one Java process space -- the memory/CPU
reported by each thread is actually shared among all threads. -A]
Yes, the number of threads can be controlled for each connector in the server
configuration file (normally server.xml). This is an extract from the Tomcat User
Guide:
The default configuration is suitable for medium load sites with an average of 10-40
concurrent requests. If your site differs you should modify this configuration (for
example reduce the upper limit). Configuring the pool can be done through the
<Connector> element in server.xml as demonstrated in the next fragment:
<Connector
className="org.apache.tomcat.service.PoolTcpConnector">
<Parameter
name="handler"
value="org.apache.tomcat.service.connector.Ajp12Connect
ionHandler"/>
<Parameter
name="port"
value="8007"/>
<Parameter
name="max_threads"
value="30"/>
<Parameter
name="max_spare_threads"
value="20"/>
<Parameter
name="min_spare_threads"
value="5" />
</Connector>
As can be seen the pool has 3 configuration parameters:
max_threads - defines the upper bound to the for the concurrency, the pool will not
create more then this number of threads.
max_spare_threads - defines the maximum number of threads that the pool will
keep idle. If the number of idle threads passes the value of max_spare_threads the
pool will kill these threads.
min_spare_threads - the pool will try to make sure that at any time there is at least
this number of idle threads waiting for new requests to arrive. min_spare_threads
must be bigger then 0.
You should use the above parameters to adjust the pool behavior to your needs.[...]
If you want something general (for the entire context, you should use something like
this:
...
<context-param>
<param-name> NAME </param-name>
<param-value> VALUE </param-value>
</context-param>
...
If you need to set parameters for a single servlet, then use the <init-param> tag
inside the servlet tag:
<servlet>
<servlet-name>...</servlet-name>
<servlet-class>...</servlet-class>
<init-param>
<param-name> NAME </param-name>
<param-value> VALUE </param-value>
</init-param>
</servlet>
[These are accessible from Java by calling getInitParameter("NAME") -A]
-----------------
ERROR reading java.io.fileinputStream@39240e At Line 14 /web-app/servlet/
ERROR reading java.io.fileinputStream@246701 At Line 14 /web-app/servlet/
Starting service Tomcat-Apache Apatch Tomcat/4.0
------------------
sa wa
How can I distinguish between text file and binary file after I read a file
onto my servlet?
Location: http://www.jguru.com/faq/view.jsp?EID=416280
Created: May 6, 2001
Author: Luigi Viggiano (http://www.jguru.com/guru/viewbio.jsp?EID=101985)
Question originally posed by Shoukatali Sayyad
(http://www.jguru.com/guru/viewbio.jsp?EID=412603
Reading it and checking the file's content: if it contains only chars in [a..z, A..Z, 0..9]
and punctuation marks, it's a text file; viceversa, if it contains extended chars it isn't.
To recognize binary data format check also How do I know that a particular file is in
binary or text format without relying on the extention of a file?.
How can I get the path to the currently running servlet's .class file? For
example, the function will return "C:\Test\Servlets\" when I locate the
ABC.class in C:\Test\Servlets\ ?
Location: http://www.jguru.com/faq/view.jsp?EID=416303
Created: May 6, 2001
Author: Luigi Viggiano (http://www.jguru.com/guru/viewbio.jsp?EID=101985)
Question originally posed by [missing] virtualsnack
(http://www.jguru.com/guru/viewbio.jsp?EID=400551
Try this piece of code, it does work even for standard Java objects:
String className = servlet.getClass().getName();
ClassLoader servletClassLoader =
servlet.getClass().getClassLoader();
URL classFileURL = servletClassLoader.getResource(className +
".class");
System.out.println("classFileURL = " + classFileURL);
Where servlet is an instance of your servlet. [Note: from inside a running servlet,
use this.getClass() -Alex]
If you don't have ready any instance of your servlet, you should replace
Servlet.class where servlet.getClass() is used. [Note: this will return the path
to Servlet.class, not to MyServlet.class -- Servlet.class may be stored in a totally
separate directory, based on the Servlet engine. -Alex]
Check this
Author: Prathap Guptha (http://www.jguru.com/guru/viewbio.jsp?EID=344441), May
7, 2001
Have you tried with this , if not Can you please try with this it may be helpful for you.
servletContext.getRealPath(request.getServletPath());
I still have a problem to get the location of a loaded class. I tried the three examples
below and get always null ! What's wrong ??? I use Tomcat 4.0.1 and no Jar-files. My
classes are in Tomcat\webapps\InfoNet\WEB-INF\classes, InfoNet is the name of the
application. Help is very welcome.
Boerries
..............................
className = this.getClass().getName();
servletClassLoader = this.getClass().getClassLoader();
System.out.println("test 1: " + servletClassLoader.getResource(className +
".class"));
servletClassLoader = Servlet.class.getClassLoader();
System.out.println("test 2: " + servletClassLoader.getResource(className +
".class"));
servletClassLoader = Thread.currentThread().getContextClassLoader();
System.out.println("test 3: " + servletClassLoader.getResource(className +
".class"));
Wow, it's incredible, but I've just opened the javadoc of Servlet 2.2 and I've found
these two incredible methods of the javax.servlet.ServletRequest:
getRemoteAddr() Returns the Internet Protocol (IP) address of the client that sent
the request.
getRemoteHost() Returns the fully qualified name of the client that sent the
request, or the IP address of the client if the name cannot be determinated.
It's incredible how many strange things you can find when you decide to RTFM.
Regards.
[See also What are the Servlet equivalents to all the CGI environment variables? ]
Hi,
It is possible that the loss of quality it's done in the conversion to a GIF. Remember
that that format only allows 256 colors and I don't know how the color reduction it's
done.
I've used that encoder few times for generating charts, where the number of color
was limited. But I prefer to generate jpeg images using the jpeg encoder that it's
now part of the Java 2 distribution, and it's way fater than the GIF Encder:
import com.sun.image.codec.jpeg.*;
...
...
BufferedImage image = ... your image ...;
BufferedOutputStream bos = new
BufferedOutputStream(response.getOutputStream());
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
encoder.encode(image);
...
You can even control the jpeg quality with the JPEGEncodeParam, just altering a little
the above example:
JPEGEncodeParam eP = JPEGCodec.getDefaultJPEGEncodeParam(image);
eP.setQuality(1.0f, true);
BufferedOutputStream bos = new
BufferedOutputStream(response.getOutputStream());
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
encoder.encode(image, eP);
If the result satisfy you, then probably the problem it's really in the reduction of the
number of colors.
What are all the enhancements/changes in the Servlet 2.3 spec (currently in
Public Draft release)?
Location: http://www.jguru.com/faq/view.jsp?EID=417543
Created: May 8, 2001
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
Saravanan Jayachandran (http://www.jguru.com/guru/viewbio.jsp?EID=91462
JavaWorld has an interesting article Servlet 2.3: New features exposed that can give
you a very good response to your question.
Comments and alternative answers
Also
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Mar 1, 2002
See also http://jcp.org/aboutJava/communityprocess/first/jsr053/index.html
To specify arguments, type the name of the servlet followed by a ? then the
arguments. Server redirects can be performed by providing arguments in this
fashion to RedirectServlet. For example, you could alias /oldlocation to
/RedirectServlet?http://www.newcompanyname.com/newinformation.)
In addition, many container have specific solution, some of them already covered by
FAQs:
Tomcat with a comment regarding Oracle or JRun.
Comments and alternative answers
How do I pass a variable into a thread that can be accessed from the run()
method?
Location: http://www.jguru.com/faq/view.jsp?EID=425562
Created: May 21, 2001
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Namrata Rai
(http://www.jguru.com/guru/viewbio.jsp?EID=418726
Create a subclass of Thread with a custom instance variable and initialize it in the
constructor. (This is basic object-oriented programming design, BTW.)
Hi Alex..I have a situation where i need to run the bean as a seperate thread. The bean
method requires 6 parameters. And the above solution you gave can be applied there?
I don't need any PrintWriter or i don't need to deal with any request or response
objects. I have all the 6 parameters ready with me.
I just need how to call the bean method using the above method you gave.. I have
written in the following way. May be you can check on this and pour in your
suggestions..
*** code
public class MyThread extends Thread{
} // end of run()
} // end of MyThread()
- Venu
Great Help
Author: abhay sahai (http://www.jguru.com/guru/viewbio.jsp?EID=940140), Jul 18,
2002
Really I was looking to such help where I can start a new bean context with each
thread and this gives me enough guidence. Thanks again
In a protected connection (SSL), everything is encrypted, cookies too. Yes you can
implement an algorithm to encrypt cookies value, why not... but you have to
encrypt/decrypt handly with your own code.
Comments and alternative answers
Marking the cookies this way ensures they cannot be delivered over an unencrypted
session such as http.
Joy,
The order of the objects that are unbound when the session exires is, theoretically,
unknown.
Mainly it depends how the servlet comntainer stores the attributes. Normally, the
selection is a Hashtable or an unsorted collections, so the 'order' of the Enumeration
that they use for removing them it's not guaranteed or defined.
I've checked Tomcat sources and they use an Hashtable, so when the expire()
method is called, they get the Enumeration using getAttributeNames() and the
remove the objects one by one.
HttpSessionBindingEvent
Author: Bill Fox (http://www.jguru.com/guru/viewbio.jsp?EID=501381), Nov 30,
2001
I have a similar need/question. But I am approaching the question from a diferent
angle.
When the Session sends signals to the Bound objects, does the session send signals to
all objects before the first is unbound?
Or
Does the first object recieve the unbinding event message, get unbound, and then the
next object recieves its message.
In this second scenario, we cannot be sure which object leaves the session first. (Elvis
object has just left the session)
Re: HttpSessionBindingEvent
Author: Bill Fox (http://www.jguru.com/guru/viewbio.jsp?EID=501381), Dec 4,
2001
Answering my own question...
After reviewing the Apache Tomcat implementation, the unbound object gets the
HttpSessionBindingEvent message AFTER the object is removed from the
HashMap in the session. Therefore, no guarantees about what order the objects are
unbound, and no guarantee that one object will be in the session when another
recieves the unbound event signal.
When must I use clustering -- that is, a pool of web servers instead of a
single web server?
Location: http://www.jguru.com/faq/view.jsp?EID=425615
Created: May 21, 2001
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
Federico Crivellaro (http://www.jguru.com/guru/viewbio.jsp?EID=418395
Federico,
It really depends on the load of your system, and the hardware that you are using
(or plan to use).
A pool of web servers will definitely serve a higher number of pages and it will be
more safe in a case of a crash of a system but, obviously, it's more expensive. In
addition you need to have a good solution for making sure that once a session on a
system it's started, that user will be always redirected to the same system, otherwise
you have to handle your own session with a database or (bad!) with a networked file
system.
A single web server is normally the "starting solution" and if the system it's good and
powerful enough, it could handle a really good amount of traffic.
[See What servlet engines support clustering -- that is, sharing of session data
across multiple load-balanced web servers? for more information. -Alex]
If the page that contains the server side includes is a servlet or a JSP page, the only
reasonable way is to use a package like SSI for Java (http://www.areane.com/java/).
Comments and alternative answers
I'm not sure if this is the intent of your question, but I had a conflict with SSIs and
Apache/Tomcat.
I already had a documentRoot that was serving *.shtml files. Then I installed Tomcat
(3.2.1) (I have Apache 1.3.12). I mapped the webapp root onto my existing
documentRoot.
The *.shtml files suddenly weren't working any more. The reason is that the tomcat-
apache.conf file that Tomcat automatically generates was including an Apache
Options directive that didn't include the "Includes" argument.
Although my httpd.conf file (for Apache) DID have the Options Includes..., because
httpd.conf was Including the tomcat-apache.conf file as the very last line in the
httpd.conf file, tomcat-apache.conf's Options line was overwriting the httpd.conf's
line.
SSIs worked. But the disadvantage now is that I have to manually modify the
tomcat.conf file now after any changes to Contexts in server.xml and after
shutdown.sh/startup.sh sequence. Not only this, but also have to *remember* to do it.
Both of which lead to errors.
Not sure this answers *YOUR* question, but it may help someone else having similar
problem with SSIs, Apache (1.3.12), and Tomcat (3.2.1)
in web.xml I added:
<servlet>
<servlet-name>ssi</servlet-name>
<servlet-class>org.apache.catalina.servlets.SsiInvokerServlet</servlet-class>
<init-param> <param-name>isVirtualWebappRelative</param-name> <param-
value>1</param-value> </init-param>
<!-- <load-on-startup>3</load-on-startup> -->
</servlet>
This allowed the above servlet code to not crash with a CLASS_NOT_FOUND
error. But I still can't get SSI to work. Here's what I have done. Would someone
please let me know what I'm doing wrong?
--Steve Morad
<servlet-mapping>
<servlet-name>ssi</servlet-name>
<url-pattern>*.shtml</url-pattern>
</servlet-mapping>
Holger
Does anyone know if Tomcat can parse both JSP and SSI within the same
document? For example:
test.jsp
<%= "Hello World" %>
<!-- inlcude virutal="test2.jsp"-->
I know that this is a terrible coding practice (since one should use JSP
includes instead of SSI when coding a JSP file) but ServletExec with
iPlanet allows this type of thing and we have legacy code with this
requirement.
Basically it looks like Tomcat would need to be told to parse every file of
this type twice, once for JSP content, and once for SSI.
Thoughts?
Stephen
Re: How can I enable SSI (server-side includes) under Tomcat/Apache?
Author: Sanket Taur (http://www.jguru.com/guru/viewbio.jsp?EID=1178189),
Aug 26, 2004
Remove the XML comments from around the SSI servlet and servlet-mapping
configuration in Apache Tomcat-installation-directory/conf/web.xml.
In JavaScript, do
var image1 = new Image();
image1.src = "xyz.gif";
And then use image1.src wherever you were using the xyz.gif
[Note: there seems to be a bug in IE 5.5 preventing this from working. See the
forum thread for details. -A]
Are there any good code examples demonstrating the use of Servlet 2.3
Filter API?
Location: http://www.jguru.com/faq/view.jsp?EID=430553
Created: May 29, 2001
Author: surya mp (http://www.jguru.com/guru/viewbio.jsp?EID=425333) Question
originally posed by Romin Irani
(http://www.jguru.com/guru/viewbio.jsp?EID=73205
SiteMesh
Author: Mathias Bogaert (http://www.jguru.com/guru/viewbio.jsp?EID=202039),
May 30, 2001
SiteMesh uses Servlet 2.3 filters, and is open source. Check it out at
http://www.opensymphony.com/sitemesh/.
Where can I learn (more) about Java's I/O (input/output, IO) capabilities?
Location: http://www.jguru.com/faq/view.jsp?EID=431192
Created: May 30, 2001
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)
JSP Tutorial
Author: Steve Erbert (http://www.jguru.com/guru/viewbio.jsp?EID=291279), Jun 26,
2001
www.jsptut.com has a very good beginners introduction to JSP.
Where can I learn (more) about Java's support for developing multi-
threaded programs?
Location: http://www.jguru.com/faq/view.jsp?EID=431248
Created: May 30, 2001
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)
jakarta.apache.org
Author: Norman Hanson (http://www.jguru.com/guru/viewbio.jsp?EID=462048), Dec
26, 2001
jakarta.apache.org is really the absolute source for info on tomcat.
Re: jakarta.apache.org
Author: Norman Hanson (http://www.jguru.com/guru/viewbio.jsp?EID=462048),
Dec 26, 2001
bum link...
jakarta.apache.org
Where can I learn (more) about using various XML (eXtensible Markup
Language) technologies (such as DTDs, Schemas, SOAP, DOMs, etc.) with
Java?
Location: http://www.jguru.com/faq/view.jsp?EID=431956
Created: May 31, 2001
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)
Check out the jGuru XML FAQ.
Where can I learn (more) about Sun's peer to peer, "Project JXTA"?
Location: http://www.jguru.com/faq/view.jsp?EID=431963
Created: May 31, 2001
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)
There is no need for any special configuration for JAAS to be used with the Tomcat
server. Make the settings as we do to execute an application program, i.e., changing
the java.security,java.policy file in the jre/lib/security of the jdk1.3.
Comments and alternative answers
Configurtion is needed
Author: tippu sultan (http://www.jguru.com/guru/viewbio.jsp?EID=417083), Jun 2,
2001
The configuration will differ from server to server , and most of the server till today
doesnot support jaas authorisation for ex., Websphere and weblogic . and the
authentication is concerned weblogic supports jaas authentication . i don't have idea
whether which other servers support jaas authentication ., Upto configure of jaas with
servlets , configuration should be made with webserver not with servlets particularly
for ex., for making jaas authentication in weblogic6.0 we should set the system
property of weblogic.server.policy to the policy file (not a config file as we work in
command prompt) to the policy file where we have mentioned about which login
module it should use. finally, let me make it very clear configuration will differ from
webserver to webserver till today
JAAS
Author: erdkal erdkal (http://www.jguru.com/guru/viewbio.jsp?EID=560642), Dec 4,
2001
Hi Sultan, you write, that is no need for any special configuration for JAAS to be used
with the Tomcat server. That wondered me, because I don't found any example,
tutorial, which describes the using of JAAS with Tomcat. So can you describe more
details, what for example you make. Erdal
I don't know anything about JRun, but I think that you can use any external profiler
tools like the one mentioned in this answer:
http://www.jguru.com/faq/viewquestion.jsp?EID=407939.
How can I get a list of all the session objects in an application scope?
Location: http://www.jguru.com/faq/view.jsp?EID=433242
Created: Jun 3, 2001
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
Jose Compadre Junior (http://www.jguru.com/guru/viewbio.jsp?EID=260394
As many other guru have already told you, there is no way to do that with Servlets
2.2. Previously there were two methods, but they both have been deprecated and
they return null.
The new Servlets (2.3), even if they are not going to provide any direct method to
do solve your problem, will provide additional tools for helping you building your own
solution.
I'm talking about the Application Events. You will be able to create a listener to a
session object that will insert, the session id into, for example, an HashMap, and
authomatically will remove it when the session is destroyed or invalidated.
The problem is not come out as improper META tag of html. becasuse java is
providing the ISO-8859-1 encoding standard. the problem source is com.oreilly
package. i look inside the source and i realize that the econding type is written
wrong. it is written as "ISO-8859-1". but it must be "ISO8859_1". i corrected it. i
could do it because the source code is available.
The same problem appears in Java Mail API. but i cant see the source and cant
modify.
JavaMail source
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Jun 3,
2001
You can always get the JavaMail source directly from Sun. It just doesn't come with
the implementation.
Oreilly Package
Author: Rajanish Nagwekar (http://www.jguru.com/guru/viewbio.jsp?EID=285484),
Jun 4, 2001
I am also using the code given in oreilly servlet book to upload files and it is working
w/o any errors. And the encoding standard, which is hard coded, is ISO-8859-1. So I
feel that the problem might not be with the encoding standard or at least not the one
pointed out. Please correct me if I am wrong.
Upload problem
Author: Alex Skrypnik (http://www.jguru.com/guru/viewbio.jsp?EID=388047),
Jul 31, 2001
When I put enctype="multipart/form-data" in the form description, after submit I
got the following error:
the same for jsp and servlets (in case of servlets using, I have doGet and doPost
methods implemented). I use Tomcat 3.2.1, JBuilder5. html code (jsp handler) is
the following:
Normally web servers have their own protection system already in place. If you are
running Apache, for example, or anothe NCSA compliant web server, you can rely on
the standard basic authentication. You can take a look ath this interesting article
for Apache, and eventually check the documentation of your web server to see if
they have something similar.
In addition, on the Servlet-Container side, I'll suggest you to take a look at the
Servlet 2.2 Specification. Chapter 11 is entirely dedicated to the "Security" topic
and can give you a clear understanding of what you can achieve with a Servlet
Container. In addition, take a look at the DTD of web.xml, the Web Application
Descriptor, Paragraph 3.12 and a security example at Paragraph 13.3.2.
There is no need to set the attribute ,you have to just the set the Content type in
each and every page(JSP/ Servlets) and rest is atuomatically being taken care of.
As I wrote in my first message the apache web server does not perform the
authentication in this case but the servlet does. So the web-server could not send his
error- page because the browser does not send any information about pressing the
cancel-button.
The solution is, that you not only have to send an HttpServletResponse with
res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
but in addition you have to send content through the response's PrintWriter
which is shown by the browser if the user cancels authentication.
Can I use a java servlet to check if a browser is using 128 bit encryption?
Location: http://www.jguru.com/faq/view.jsp?EID=444019
Created: Jun 23, 2001
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
james lee (http://www.jguru.com/guru/viewbio.jsp?EID=297098
[I know that for Netscape, the user agent in the request header has a "U;" that
indicate that the browser is using 128 bit encryption. What about IE?]
Unfortunately there is no standard way to get that piece of information. The one
you've mentioned, as you probably know, it's not a standard solution and there is no
way to guarantee that it will be maintained in the future.
browser encryption
Author: Orest Guran (http://www.jguru.com/guru/viewbio.jsp?EID=445770), Jun 26,
2001
I used the following bit of code to determine the browser encryption: String
cipherSuite = (String)req.getAttribute("javax.net.ssl.cipher_suite"); This returns a
string that looks something like: Netscape 4.73: RC4-Export_40 Netscape 6.0:
RC4_128 IE5.01: RC4_128 From there you can see the Cyryptographic Suite and key
length see:
http://java.sun.com/products/servlet/2.1/api/javax.servlet.ServletRequest.html and
http://java.sun.com/j2se/1.4/docs/guide/security/jsse/JSSERefGuide.html#CipherSuite
and http://java.sun.com/security/ssl/API_users_guide.html for more details.
How can we hide the html source code when the user tries to view the
source code from the browser's "view source" file menu option?
Location: http://www.jguru.com/faq/view.jsp?EID=444156
Created: Jun 23, 2001 Modified: 2001-06-24 18:44:02.929
Author: Luigi Viggiano (http://www.jguru.com/guru/viewbio.jsp?EID=101985)
Question originally posed by ramesh babu
(http://www.jguru.com/guru/viewbio.jsp?EID=411199
[Short answer: no, it's not possible, since the source code *is* the response. If the
user wants to see your source, he can. However, here's a clever hack... -A]
Yes it's possible, I've done it sometimes ago. You can make a JavaScript decoding
algorithm executing it at runtime... But, it's very simple to reverse it for people
knowing JavaScript...
The following code will hide everything in most JavaScript enabled browsers: I've
tried it with IE5 and Opera5 and it works perfectly, but Netscape decodes it when
showing the source.
<HTML>
<SCRIPT LANGUAGE="JavaScript1.2">
<!--
function decode(s,k) {
var sl=s.length;
var kl=k.length;
for(decoded='',i=0, j=0; i<sl; i+=2, j++) {
decoded += String.fromCharCode(((s.charCodeAt(i) - 97) +
((s.charCodeAt(i+1) - 97) << 4))^k.charCodeAt(j%kl));
}
return decoded;
}
document.write(decode("gfpcabdbbbeflhbalbbagacclekdbchclaffhblbja" +
"icbbhbbbkeccnadbibkblcabcfifkefcmacfjdpboccblbffmdoccbfbmblajckb" +
"oekfobocbaobabeflhkfkbabladcleoehbfadcmamejecaghffdbjbdaaclbpehf" +
"jacclbgaabibfglegcnbdaedfflbgakegclbcfabcbgcibcajbpahgkbebffacgc" +
"dadbgcjafdmbcabakecclbbbkboaccbbcfndodkajdcfgbfajcbahblboblhkfkb" +
"eeeflhfamejemaiclbgaffjaicjbnbhahffggfcefedfohddedhfkebcebbbabhf" +
"fgdchbhaoagclbdbjflcfdmbdbjbgepaabobdapaddmbbbebgeedebmbgaheedab" +
"aambmafgffbambabcciebelegfedbaaakbeaacleafmdnebdabcfgapacclbcfba" +
"caoclbfbgakeddnbdbbakeodkbhaffkbcckbcajbpahgcanbaagadclbffbakefc" +
"abobmbpabdabmffflcddbadbgbbahggakbmbkbedffnblbkebcmbaaabkeicdbeb" +
"ffobpcabcfgacaicaaobbbpafdffnbdbkeiahalbkbeajgffldcfmbccfffaebob" +
"ecnbhbbbkeeaifabablakcgacfcbgaocbagaabibhgmbmbffobpcabcfbblafdob" +
"cflbpagchacfbclajclbkbebpbedabaaffnagcbahblfkegajbobffobpckbbaab" +
"kekckbpbabeaddgacfcadalcjbcfhbpahgjbnbgaobhgmbmbffobocibhbjfkelc" +
"mbjbabkeddabdbhajbhgmbmbffobpcabcfhalaoclbmfhfgfiggagahafajccbme" +
"jefebckbmbbaeflhhbaalegffchamejemaiclbgaffmagcgbhbieiebbabaabbla" +
"jcebofedibocebobjfccccjbeaabobocgbdbjfjbgclbbaifjbcchalbdbiehgga" +
"lbpapakhhemejemaiclbgaffjaicjbnbhahffggfcefedfohddedhfkebcebbbab" +
"hffgdchbhaoagclbdbjflcfdmbdbjbgepaabobdapaddmbbbebgeedebmbgaheed" +
"abaambmafgffbambabcciebelegfedbaaakbeaaclekfhcfaodffadebobddmacf" +
"ifkefajbdbbbpahghchalbeacchalfjefeedbaaakbeaacleoekfmaiclbgalegf" +
"ighbnbbbdbjh", "jGuru"));
//-->
</SCRIPT>
</HTML>
Comments and alternative answers
See also...
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jun 25, 2001
See also How can I disable the user viewing the source code...
This is how you hide the code for your Internet explorer browser:
Author: andreas strauman (http://www.jguru.com/guru/viewbio.jsp?EID=1255912),
Jul 31, 2005
Maby this works on other explorers to, but iæve only tryed this in
explorer.
<script>
//<!--
//-->
</script>
you can of course write more code under the </script> tag.
A special directory exists within the application hierarchy named “WEB-INF”. This
directory contains all things related to the application that aren’t in the document
root of the application. It is important to note that the WEB-INF node is not part of
the public document tree of the application. No file contained in the WEB-INF
directory may be served directly to a client.
Re: Make sure the jar file has the correct path
Author: Aris Javier (http://www.jguru.com/guru/viewbio.jsp?EID=445452), Jun
26, 2001
There was a bug in tomcat 3.1 that did not permitted to perform this cool feature.
Try to use tomcat 3.2.x or later and it will work, i'm using tomcat 3.2.2 and it is
ok. Aris
Re: Make sure the jar file has the correct path
Author: Jan Viaccava (http://www.jguru.com/guru/viewbio.jsp?EID=505214), Oct
2, 2001
Hi,
I have the same problem. What do you mean with wrong path???
And how can I fix the problem ???
Jan
Re: Make sure the jar file has the correct path
Author: Tim Cooke (http://www.jguru.com/guru/viewbio.jsp?EID=756423), Mar
14, 2002
Dear Newman
I'm using Tomcat 4.0.1, and I have the same problem as logged by Taruvai, so I'm
both interested and confused to hear that your JAR contained the "wrong" path for
your classes.
Please could you give an example of a wrong path and a right path?
Kind regards
Tim Cooke
Re[2]: Make sure the jar file has the correct path
Author: Newman Shee
(http://www.jguru.com/guru/viewbio.jsp?EID=445216), Mar 14, 2002
The problem I ran into was an error on my part. The jar file that I used has the
wrong path. By that I meant the class file should be under a directory called
com/avid/mmserver/util, but when I jar the class files, I put them under the
wrong directory.
1. 1. do a jar tvf on the jar file and look at the directory where the class
files live.
2. 2. take a look at the .class files in your build environment(when
running outside of Tomcat0.
3. 3. make sure they are the same.
Newman
Re[3]: Make sure the jar file has the correct path
Author: Tim Cooke
(http://www.jguru.com/guru/viewbio.jsp?EID=756423), Mar 14, 2002
Newman
Thanks for your very fast response and help.
I've discovered something about the location of JAR files that makes it all
work for me, and posted the information on another thread.
Regards
Tim Cooke
Re[4]: Make sure the jar file has the correct path
Author: Alan Lukens
(http://www.jguru.com/guru/viewbio.jsp?EID=948053), Jul 12, 2002
I have had similar problems. The manifest.mf file in the META-INF
folder stores the jar file information. See
"java.sun.com/j2se/1.3/docs/guide/jar/jar.html" for details.
Re[5]: Make sure the jar file has the correct path
Author: Michael Civello
(http://www.jguru.com/guru/viewbio.jsp?EID=935119), Jul 30,
2002
I'm seeing something even more odd... My app was running fine in
tomcat 3.2.3 and as I developed I saved full copies of good working
points. One day after a reboot, tomcat decided to stop seeing my
jars in the webapp lib dir. I didn't change any of the tomcat libs or
settings and I even restored to a previously working version of my
app but it just doesn't find them anymore. If I dump the jar into the
TOMCAT_HOME/lib, then it finds it. Anyone ever see such a
change? I reinstalled tomcat and it continues...
Solved!
Author: Michael Civello
(http://www.jguru.com/guru/viewbio.jsp?EID=935119), Jul 31,
2002
My lib problem went away when I nuked the CLASSPATH that I
had in my environment. It essentially was making TOMCAT have
two classes111.zip files in the path once it included it's
$TOMCAT_HOME/lib files. I don't know why that made a
difference but it did. Thought you should know... MJC
Re: Make sure the jar file has the correct path
Author: Karl Stahmer (http://www.jguru.com/guru/viewbio.jsp?EID=1205657),
Oct 15, 2004
Had the same problem with Tomcat 5.0.28.
Say you're creating class files from a DOS (Windows) command window in the
directory (folder) C:\Java and your class files are in the package:
com.mycompany.mypackage
C:\Java\com\mycompany\mypackage
How do I get the content (not the name) of an option in a choice box?
Location: http://www.jguru.com/faq/view.jsp?EID=444351
Created: Jun 24, 2001 Modified: 2001-06-24 19:31:14.516
Author: thomas dietrich (http://www.jguru.com/guru/viewbio.jsp?EID=413665)
Question originally posed by J Allen
(http://www.jguru.com/guru/viewbio.jsp?EID=437322
[ The cleanest solution is to build the HTML yourself, and make the "value" attribute
something you know, like the database id, or even the content itself. From
getParameter() returns a value of a choice box, I ...:
Alessandro A. Garbagnati, Jun 19, 2001
Hi, If I've understood your problem, you have somthing like this:
<select name=whatever>
<option value=value_1>text_1</option>
<option value=value_2>text_1</option>
<option value=value_3>text_3</option>
</select>
The request.getParameter("whatever") it's returning you the first value selected (or
the only one in a case of a single selection), and there is no way, from the request
object, to get the text. The reason it's simple. That information it's not part of the
request when you submit the form. The only information passed it's the value.
There are two solutions. One is to maintain the array (or map or whatever you use
for generating the dropdown box) between responses so, when you get the request
you read the value and you get back your text from the array (or map or etc.). The
secon solution is to change the value of the option to include the text, maybe with
some kind of separator (could use |), and when you get the value, you just split in
the value and the text.
Hello J Allen,
<form>
<select name="dd" onChange="document.forms[0].ddtext.value
=
document.forms[0].dd[document.forms[0].dd.selectedIndex].te
xt;">
<option value="1">One</option>
<option value="2">Two</option>
</select>
This is a working example of cheesiness at it's finest. :) the fields are fully qualified
so that you can see what they look like before you start taking short cuts.
Sincerely,
Thomas Dietrich
Another Alternative
Author: Michael Rimov (http://www.jguru.com/guru/viewbio.jsp?EID=295251), Jul
17, 2001
JCorporporate's eForum provides another servlet-implemented online forum
JRun is a J2EE compatible container. For this reason it supports (besides JSPs and
Servlet) EJB as well. JRun is actually a plugin on a web server in order to redirect JSP
and servlet calls from the web server (propably non java enable i.e IIS) into is's WEB
container.
Tomcat is a plugin itself but implements only the WEB container (i.e it can run only
JSPs and Servlets -no EJB o JTS or other APIs of J2EE)
Allaire JRun
Author: Sergi Arrufat (http://www.jguru.com/guru/viewbio.jsp?EID=405615), Jun 25,
2001
Meanwhile Tomcat is open source, Jrun is proprietary software. If you are interested
on a open source J2EE container, I recommend you Jboss. You can get it for free in
http://www.jboss.org.
Thanks in advance
Thanks in advance
Can Tomcat produce extensive web logs like IIS (If I use the JRun connector to IIS)
and in what format does the Tomcat logs are generated: W3C Log format? I need the
logs because I need the webtrends log analyzer to parse to give me/everybody
extensive web statistics reports.
See How do I add a search engine to my web site? (though this covers searching
your site, not the whole Internet).
Running a Web Crawler is a pretty big job. Do you have a couple of terabytes of free
disk space?
[I wrote a servlet, and I want to convert it to a JSP file. Usually it is very simple - all
of the code of the "doGet" method directly goes into the JSP. But now I have a
private method in that servlet, that the “doGet” method calls with various
arguments. How do I put that in a jsp? ]
<%!
private void foo() {
System.out.println("foo");
}
%>
<%
foo();
%>
How can I submit an HTTP POST request when the user clicks a normal
HREF link?
Location: http://www.jguru.com/faq/view.jsp?EID=445910
Created: Jun 26, 2001
Author: Sonu TheKool (http://www.jguru.com/guru/viewbio.jsp?EID=3468) Question
originally posed by puneet jain
(http://www.jguru.com/guru/viewbio.jsp?EID=423518
You can post to a servlet using JavaScript through HREF in the following way. Any
parameters you need to send can be sent using the "hidden" parameters.
<form name="submitForm" method="POST" action="/servlet/ServletName">
<input type="hidden" name="param1" value="param1Value">
<A HREF="javascript:document.submitForm.submit()">Click Me</A>
</form>
Comments and alternative answers
JS:
function submitMe()
{
document.MyForm.action="http://www.ugs.com/";
document.MyForm.target="targetName";
document.MyForm.submit();
return;
}
Victor,
Chapter 11 of the Servlet 2.2 specification is entirely related to Security. Basically the
concept is that you can use the standard http authentication schemes (i.e.: basic,
digest). This means that you can authenticate a user among a database (or, for
example, another source) without developing html login forms.
-Alex]
Tomcat communicates with the Apache server using localhost. When tomcat gets the
request it's from the Apache on localhost, so it also redirects the response to
localhost.
response.sendRedirect(
"http://" + request.getHeader("host") + "/" + yourFileName
);
Comments and alternative answers
Redirect
Author: Lee Evans (http://www.jguru.com/guru/viewbio.jsp?EID=454053), Jul 12,
2001
don't know if this applies to you but if authentication is required for a servlet before
authentication for apache then the redirect does not work. if apache authentication has
been gained first then the redirect works fine. the only way we have got it to work at
the moment is using the HTML META tag with type refresh content 0 and the url of the
redirection, this goes through apache again so works fine hope this helps you
Re: Redirect
Author: Michael Smith (http://www.jguru.com/guru/viewbio.jsp?EID=970016),
Jul 31, 2002
My test app will redirect but it takes at least minute to redirect..... I can open a
new browser, paste in the URL and get to the page I want to go to before this
command redirects me the page.
Possible solution
Author: Jermaine Stewart (http://www.jguru.com/guru/viewbio.jsp?EID=1176573),
Jun 6, 2004
I too noticed this. However, I used javascript to over come this. Since my conditions
to relocate were in an if statement, I changed...
response.sendRedirect(url);
to
Is there a way I can get the context name and the servlet path from the init
method of a servlet?
Location: http://www.jguru.com/faq/view.jsp?EID=445946
Created: Jun 26, 2001
Author: Uwe Hanisch (http://www.jguru.com/guru/viewbio.jsp?EID=438858)
Question originally posed by Jayaprakash A
(http://www.jguru.com/guru/viewbio.jsp?EID=284375
Well, up to now the only way to get your context path is to call getContextPath()
on a HttpServletRequest object. But this object you receive only with a HTTP
request to your HttpServlet. E.g.:
protected void doGet(HttpServletRequest req, HttpServletResponse
resp)
throws ServletException,IOException {
}
I think it would be usefull, if you can obtain the context path also from the
ServletContext. But at the moment I see no chance to get the context path in the
HttpServlet init() method.
Comments and alternative answers
I'm sorry, i know that this is far from optimal, but ...
Niko
WebAppServletContext beaWebApp =
(WebAppServletContext)servletContext;
String contextPath = beaWebApp.getContextPath();
For other implementations, one should consult the web/app server documentation.
How do i know from which page the request has come from?
Location: http://www.jguru.com/faq/view.jsp?EID=446592
Created: Jun 27, 2001
Author: cedric chin (http://www.jguru.com/guru/viewbio.jsp?EID=383299) Question
originally posed by Gopal Saha
(http://www.jguru.com/guru/viewbio.jsp?EID=10163
[I have a JSP which can be called from multiple pages . On exiting from the page it
must go back to the particular page from where it was requested.How do i know the
URL of the calling page?]
Try this:
I won't regard alternatives like integration to CORBA via IIOP, because this would
lead too far here.
How can I recognise which submit button (as images using the
type="image" attribute) is pressed in a form containing multible (image)
submit buttons?
Location: http://www.jguru.com/faq/view.jsp?EID=446673
Created: Jun 27, 2001
Author: Nick Furiak (http://www.jguru.com/guru/viewbio.jsp?EID=431833) Question
originally posed by Chris Woolmer
(http://www.jguru.com/guru/viewbio.jsp?EID=418786
In your servlet you would put your code in conditional block headed by:
if (request.getParameter("your name")!=null)
I have submit buttons on several different html pages that are responding nicely to
this technique.
I also want to set the tool i want to use once clicking on hte image button that is i
either zoom in or zoom out but i cant figure out how to keep track of these .. so
basically i have to first selcet zoom in and zoom out and then in some way pass
them to the servlet Could i keep some session for these and then i could access the
session directly from the servlet by any chance However if so how can this be
done cos im getting lost :(
Another problem i have is that i have some links in the jsp that once i click them
they cakll the same servlet i am using before yet this time the servlet redners an
image and saves it to disk .. this image is in turn displayed on the JSP the links are
on however, everytime i click on the link it redirects me to an empty page first and
then if i go back and refresh , the image on the jsp chganges Any ideas pls"?
Well, supposedly, you can add the following meta tag to your pages and the XP
versions of e.g., Microsoft Internet Explorer won't hack up your pages with their
filth...
<meta name="MSSmartTagsPreventParsing" content="TRUE">
I'm not holding my breath. :-(
Comments and alternative answers
self.close()!!
Author: Sriram Narasimhan (http://www.jguru.com/guru/viewbio.jsp?EID=105242),
Jun 28, 2001
Hi, even if i use <meta name="MSSmartTagsPreventParsing" content="TRUE"> tag,
the dialog box pops up(in IE5.0) asking me whether i need to close it !! This is a
smart tag provided by IE and doesn' happen the same way with netscape !! here's the
snippet i'm using !!
<html>
<head>
</head>
<body>
<form>
<meta name="MSSmartTagsPreventParsing" content="TRUE"> <input type=button
value= closeWindow onclick=self.close()>
</form>
</body>
</html>
Re: self.close()!!
Author: Charles Martin (http://www.jguru.com/guru/viewbio.jsp?EID=399771), Jun 28, 2001
Well, you may not have to worry now. According to the following article on Yahoo News, Microsoft h
SmartTags from the upcoming release of Windows XP.
http://dailynews.yahoo.com/h/is/20010628/bs/microsoft_drops_controversial_tagging_feature_from_w
Re: self.close()!!
Author: philippe morel (http://www.jguru.com/guru/viewbio.jsp?EID=323839),
Jul 2, 2001
I'm not completly sure of what I'm saying but as it is written on webdeveloper site
:
"Placement of META tags should always be placed in the head of the HTML
document between the actual <HEAD> tags, before the BODY tag."
A servlet's life-cycle is determined by the servlet container. Therefore, when the life-
cycle methods(init, service and destroy) are called is determined by the
container. So, unless your container - in this case JRun - provides specific hooks to
do this, you can't.
One question you may want to ask yourself is why you want to do this. Why do you
want to restart a servlet? If you are restarting a servlet in order to refresh a cache or
reload the state of something, you may want to move this functionality into another
the class. That way, you can restart/refresh what ever class you need without
depending upon a servlet's life-cycle.
How do I get the IP address of the real client, not the IP address of a proxy
server?
Location: http://www.jguru.com/faq/view.jsp?EID=448703
Created: Jul 2, 2001
Author: JIA Java Italian Association
(http://www.jguru.com/guru/viewbio.jsp?EID=414973) Question originally posed by
Andy Sun (http://www.jguru.com/guru/viewbio.jsp?EID=139266
If the client is using a proxy server, the real request to your servlets arrives fromt
the proxy, and so you get the proxy's IP address.
Some proxies will complete the request with an header like "X-Forwarded" or "X-
Forward-IP", or something similar. That header will contain the 'real' IP address.
Be aware that fortunately there are a lot of anonymous proxy servers and they do
not pass any additional header (and sometimes they do not appear as proxy).
["Fortunately" for an anonymous user, but unfortunately for a server admin. Ah, the
constant struggle between privacy and features... :-) -Alex]
If you don't have a doGet method in your servlet, then that explains it. Someone's
calling your servlet with a GET request, and your servlet (via the superclass
implementation of doGet) is saying it can't do that.
Have your doGet call doPost and it should work fine.
thanks...
[
Message:Application is currently unavailable for service
Target Servlet: null
]
The error message 503 means that the service is unavailable and the server can't
respond.
Did you test your servlet in the WebSphere Test Environment? Try to test the servlet
and test it in a browser.
WTE/Servlet Engine
Author: Miriam Heffernan (http://www.jguru.com/guru/viewbio.jsp?EID=426294),
Jul 3, 2001
I've got this error before too - it was resolved by adding/importing some
features/projects to my workspace which were required in order for the code to
compile properly
It is also posible that you load some init Parameters in the servlet config, but you
haven't called the super.init method in the servlet initilization. Check this if you
use init parameters in your config.
What content type do I use when writing an object from an applet to a servlet?
Author: nick varey (http://www.jguru.com/guru/viewbio.jsp?EID=454082), Jul 12,
2001
I believe you can also use a more general:
conn.setRequestProperty("Content-type", "application/octet-stream");
nick varey
Re: What content type do I use when writing an object from an applet to a
servlet?
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Jul 27,
2001
The receiving end needs to know the class type. At least one version of Tomcat
requires the internal content type with class name.
Re: Re: What content type do I use when writing an object from an applet
to a servlet?
Author: sam pitroda (http://www.jguru.com/guru/viewbio.jsp?EID=476938),
Aug 14, 2001
setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
How are multiple servlet contexts defined or configured on Sun's Java Web
Server?
Location: http://www.jguru.com/faq/view.jsp?EID=454625
Created: Jul 13, 2001
Author: Sachin Patil (http://www.jguru.com/guru/viewbio.jsp?EID=280417)
Question originally posed by Neal Criscuolo
(http://www.jguru.com/guru/viewbio.jsp?EID=98107
In the Admin tool provided by Java Web Server-2 you have the option called
manage/servlet, in which you can add (load), modify(Configure) servlets. while
adding new or modifying existing servlet you have to give the path (java package)
and Aliases you set in servlet aliases. This automatically sets the context path for
servlets.
To update/complete or recover data from a FDF you need adobe java classes which
are JNI for Adobe DLLs.
There are some caveats at the site. Read it first before jumping in.
And as for running it in VisualAge, you need FDFtk.jar file and the JfdfTk.DLL in the
VAJ's classpath.
OS Binding
Author: Don Kitchen (http://www.jguru.com/guru/viewbio.jsp?EID=585512), Dec 14,
2001
You are also tied into a Windows environment. This does limit you from being
platform independent.
1)SUN has reported that this Function Sequence error is a bug in JDK 1.2 Check out
Sun's BUG List for more info on this.
2) If you are using JDK 1.2 try switching to JDK 1.3. It helped us.
Cheers, Pramod.
myStatement.close();
myStatement = myConnection.createStatement();
This is ugly and incurs a performance hit (though not as bad as recycling the
connection object) but it does work (at least in our case). Hope this helps.
Darrell Teague
Architect
Canopy International
Thanks,
Rahul
Hi,
Thanks for the prompt reply.
The code snippet follows:
JavaBean code
//get connection obj into mxConn var
cs = mxConn.prepareCall("{call xt_someStoredProc(?)}");
cs.setInt(1,pk_activity);
rs = cs.executeQuery();
while (rs.next())
{ //do something; }
rs.close();
cs.close();
//close connection in the finally block
The error occurs even for a simple select query when the functionality is
used simultaneously by many users.
Declaring the cs & rs obj at class or function level made no difference
My mail adddress is [email protected]. Pls mail if you require more
info.
Thanks
How to allow the client to download and execute a .bat or .exe file?
Location: http://www.jguru.com/faq/view.jsp?EID=455202
Created: Jul 15, 2001 Modified: 2001-07-23 09:57:16.236
Author: Luigi Viggiano (http://www.jguru.com/guru/viewbio.jsp?EID=101985)
Question originally posed by Vimaladhithan Palraj
(http://www.jguru.com/guru/viewbio.jsp?EID=451132
[But see How to copy the file from Server side into Client ... for words of warning
about security... -A]
HTTP is a connectionless protocol -- meaning that after the request is served the
connection between the client and the server is closed. A session allows you to
overcome this limitation by storing client activities. It has many, many uses but one
example could be shopping cart type application. You can use the session to track
items clients have selected.
CSV stands for "Comma Separated Values", so just keep any record and separe each
field with a comma and each record with a newline ('\n'). You'll have a perfect CSV
file, easy readable by any program supporting this simple format.
You are allowed to spawn a thread from a Servlet. Sounds like you want to make a
thread object and store it as an attribute in your application context. See the FAQ I
want the servlet container to load one or more servlets when the container is first
fired up, as opposed to when a client issues a request for the servlets for how to
start it. Basically, you make a thread object, call mythread.start(), then call
context.setAttribute("mythread", mythread).
You can give your daemon object methods to activate and deactivate, but it will be
accessible (almost a global) from any servlet at any time.
This can be used to run, e.g., a chat server that accepts socket connections from an
applet, independently of the Web server (and on a different port than 80 or 8080).
Or a status-checker that performs some action periodically, like updating a cache or
monitoring a database connection.
Here's some simple (untested) code that spawns a daemon thread that keeps track
of the number of seconds since it's been launched.
Note that this can be dangerous in a load-balanced application, as when using the
"distributed" flag in your web.xml. You must be aware if your background thread will
be running in multiple VMs, and if that will cause any sychronization problems.
See Servlet Thread Topic for more information.
Synchronization missing!
Author: Boris Folgmann (http://www.jguru.com/guru/viewbio.jsp?EID=953582),
May 12, 2005
As PrintSecs is running in parallel to MyDaemon, you have to synchronize the access
on the variable secs. Note that getSecs() is called in the context of PrintSecs.
public class MyDaemon extends Thread {
long secs = 0;
public void run() {
while (true) {
Thread.sleep(1000);
synchronized (secs) {
secs++;
}
}
}
public long getSecs() {
synchronized (secs) {
return secs;
}
}
}
1) First, when the servlet it called it should be the final action for that JSP. (I.E. the
action of a form).
2) Second, redirection should be the final action of that servlet, like don't call the
redirection, and then have the servlet try write to the response.
3) Third, and I'm not sure about this, I believe that you can't be already writing to
the response page, before you call the redirection.
Check these out, these were some of my probs trying to work with redirection in the
past, and might be a little fuzzy too.
Solution
Author: Avi Sharma (http://www.jguru.com/guru/viewbio.jsp?EID=455502), Jul 16,
2001
This is additional point apart from the mentioned Dont use response object or
out.println statement after RequestDispatcher statement.
RequestDispatcher Forwarding....
Author: Srivathsan Santhanam
(http://www.jguru.com/guru/viewbio.jsp?EID=480213), Aug 21, 2001
Hi
Thomas Dietrich is correct.While forwarding a request to another page using
RequestDisatcher te servlet expects that no ServletOutputStream is opened and no
output stream is sent.Since a request is being forwarded to another page you cannot
have an servlet output stream opened to write out another object.But this is not the
case with ReuestDispatcher includes. Hope you got my point!!!
Currently, I have found in most servlet engines that the error is reported but an
exception is not thrown so processing can continue normally.
Typically this is not a problem because for a particular request usually html is being
sent back via the use of getWriter() or a dataStream is being sent back via the use of
getOutputStream(). Problems occur when code is sloppy and switches back and forth
between these methods or in portal style applications where some of the portal has to
be output to the stream before the portlet content is known. In these cases, you have to
set your response buffer large enough so that the response is not committed before you
have a chance to clear it out. In order to clear your response out you have to look at
individual servers because it is implementation specific ... This is how I do it in
WebLogic 6.0
ServletResponseImpl servletresponseimpl =
(ServletResponseImpl)response;
if(response.isCommitted())
throw new IllegalStateException("Cannot process a data download
on a response that is already committed");
ServletOutputStreamImpl servletoutputstreamimpl =
(ServletOutputStreamImpl)servletresponseimpl.getOutputStreamNoCheck();
servletoutputstreamimpl.clearBuffer();
servletresponseimpl.reset();
Servlet Engines (e.g. Resin or Tomcat) should not allow directory browsing of WEB-
INF. Tomcat 3.2, for example, had that same issue and they have fixed it in Tomcat
3.2.1. This was happening when Tomcat was used standalone (not just as a
container, but even as a web server).
If this problem happens with a specific version of a standalone Resin, you should
consider to try the latest version (I'm running 1.2.5) and, eventually, send a bug to
Caucho.
Consider that this issue should happen when using the container in standalone mode.
When the container (Resin, Tomcat or abother one) is used just for serving servlet &
jsp behind a more reliable and complete web server, like Apache, the problem is on
Apache, that is serving everything else. When you ask for WEB-INF, in fact, Apache
doesn't even connect to Tomcat, there is no reason.
So, if this is your scenario, you should add lines like these:
<Directory /WEB-INF>
AllowOverride None
Deny From All
</Directory>
Inside the virtual host or whatever you think is appropriate and, obviously, changing
"/WEB-INF" with the appropriate context.
[Original Question:
<context-param>
<param-name>server</param-name>
<param-value>xxxxxxx</param-value>
</context-param>
But when I am calling getInitParameter("server") in init method it is returning null
value. How to resolve this? ]
The <context-param> tag is used to set an init parameter for the whole application
context, it is accessible by all Servlets and JSPs. You have to use getInitParameter()
of javax.servlet.ServletContext, not the similar method found in HttpServlet. Just try
the following method call in your servlet, it should return the correct parameter:
getServletContext().getInitParameter("server")
Alternatively, you can set an init parameter for a specific Servlet, it will only be
accessible by this Servlet:
<web-app>
<servlet>
<servlet-name>myservlet</servlet-name>
<servlet-class>org.myorg.MyServlet</servlet-class>
<init-parameter>
<param-name>server</param-name>
<param-value>xxxxxxx</param-value>
</init-parameter>
</servlet>
...
</web-app>
See also
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Sep 18, 2001
See also this forum thread: passing parameters through web.xml always returns ...
NoClassDefFound
Author: Emroz Habib (http://www.jguru.com/guru/viewbio.jsp?EID=467026), Aug 2,
2001
Make sure you have tools.jar in your runtime envoiurment.If you have j2ee.jar in your
classpath, you should take it out cause tomcat will look into it to tools/javac/main
Tomcat-NoClassDefFoundError:.....
Author: Srivathsan Santhanam
(http://www.jguru.com/guru/viewbio.jsp?EID=480213), Aug 21, 2001
Hello
When installing Tomcat you should ensure the following things..
1.your JAVA_HOME path oints to your jdk directory.
i.e add the following line to your autoexec.bat file
set JAVA_HOME=<jdk path> say for eg c:\jdk1.3 (as may be the case).This
ensures that the tools.jar in the jdk1.3 folder is mapped to JAVA_HOME for running
and also the claaspath should include the pointer to the bin directory where the java
executable file is located.
Re: Tomcat-NoClassDefFoundError:.....
Author: Oleg Beregovich (http://www.jguru.com/guru/viewbio.jsp?EID=487671),
Aug 30, 2001
Hello Srivathsan.
I get this problem when I accessing jsp. I have tomcat 3.2.3 on win 2000 and jdk
1.3. I set JAVE_HOME and TOMCAT_HOME. When I run tomcat run or tomcat
start it shows me CLASSPATH its setting and it has all the libraries including
tools.jar in c:\jdk1.3\lib. I was trying reinstalling things and moving them around
but I am getting this error for all examples and my jsps. My main surprise is that
when I installed tomcat couple of weeks ago I didn't have any problems running
jsp. Please advise what else can I try. Thank you Oleg
I then noticed that the JAVA_HOME env var was pointing to a directory
(/usr/bin) which contained a link to both java as well as javac, nothing more.
When I changed JAVA_HOME to point to the real thing (i.e. the java
development kit) in /usr/java/jdk1.3.1/) and I restarte Tomcat, I could fiddle
around with servlets as well as JSP.
Re[2]: Tomcat-NoClassDefFoundError:.....
Author: Ale Kalyna (http://www.jguru.com/guru/viewbio.jsp?EID=1203697),
Oct 6, 2004
I've got the same problem too! Well, now i'm updating Symantec Antivirus,
couse it is the last hope. Even reinstalling JDE won't help (i tried this couple of
times). I've even tried to reinstall Windows (just in case) and still it remains
unsolved. I tried to ask more experienced people, and they said: 'Ëèáî õóåâà
âèíäà, ëèáî áëÿäñêèå âèðóñû' which can be translated something like: 'I don't
know either' :-)
my solution
Author: Yun Liu (http://www.jguru.com/guru/viewbio.jsp?EID=578122), Dec 9, 2001
Under Unix, includes the /usr/java/lib/tools.jar into your classpath. It should work...
Re: my solution
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727), Jan 11, 2002
Hi,
You should say:
include <location of your java dir>/lib/tools.jar, because you cannot be sure that
java resides under /usr on all system. Many system, and many administrator, in
fact, can put java under /usr/local or even under /opt.
java.lang.NoClassDefFoundError
Author: Girish Kshirsagar (http://www.jguru.com/guru/viewbio.jsp?EID=704336),
Dec 28, 2001
In general if classpath has been setup correctly the error should not occur. However, make sure that
your classpath includes .; i.e. path to your current folder where the program is located. If not, the above
error will show up and this may be all you need to fix your problem.
Re: java.lang.NoClassDefFoundError
Author: Indranil Poddar (http://www.jguru.com/guru/viewbio.jsp?EID=1242172),
May 3, 2005
Thanks Girish..i tried a lot of other stuffs in vain before your advice solved my
problem
java.lang.NoClassDefFoundError
Author: Gurvinder Singh Sethi
(http://www.jguru.com/guru/viewbio.jsp?EID=1214917), Dec 7, 2004
Include the lib path of java directory which contains tools.jar in the classpath
environment variable. This will solve the problem
There are many free web-based hit counters out there that take care of a lot
of the hassles for you. Most seem to serve up a GIF so you can embed it in
your page as an IMG or JavaScript. See:
The most common thing to count is individual hits to your site's home page,
via an IMG reference (see below). You may instead want to count unique new
user sessions (see the API for HttpSession for information on setting up a
listener that listens for new sessions), or some other factor.
Servlets are transient. If you want your hit count to last past a server restart,
you need to save it somewhere. This means using either a file system or a
database. See
You can either display the results as an image, or as embedded text or HTML.
See below for information on image-based hit counters. To use embedded
text, the easiest way is to write your hit counter as a JavaBean, with separate
methods for incrementing the count and returning the current count. Then
you can instantiate the bean, place it in the application context, and access it
from any servlet using code like:
HitCounter h =
(HitCounter)getServletContext().getAttribute("hitcounter");
h.incrementCount();
out.print(h.getCount());
Returning an image simplifies some aspects of the system but means you
have to deal with creating an offscreen image and rendering the text inside it.
You may also want to make your hit counter be an applet. See How can I add
a counter applet to my web page? and How can I pass an object from an
applet to a servlet? for help there.
<IMG SRC="/myapp/counter">
and each client request will increment the count and display the image in a single
shot.
(This simple architecture would have been possible for text too, if only Marc
Andreesen had simply implemented client-side include in Netscape, instead of
wasting all his time on tables and frames, which totally suck. Oh well, maybe next
life.)
However, this technique is not always accurate, since it can count reloads, if the
same user goes back to the home page. Also, you may end up counting hits to sub-
pages too. Adding a parameter, as in IMG SRC="/myapp/counter?page=home" may
help distinguish these case.
Bean Example
Author: Tim Bardzil (http://www.jguru.com/guru/viewbio.jsp?EID=457044), Jul 18,
2001
Will a hit counter that is place in a bean with "application" scope be reset when the
server is restarted? If so, is there any way to get around this?
[See How can I write an "error page" -- that is, a serv... for the canonical FAQ on
error pages. -A]
In Tomcat, like in all the fully compliant servlet containers, you have the equivalent
of the 'ErrorDocument' using the web application descriptor (web.xml).
This is useful because you can handle either error codes (like the 404) or even
exception.
<!-- The error-page element contains a mapping between an error code or exception
type to the path of a resource in the web application -->
<!ELEMENT error-page ((error-code | exception-type), location)>
<!-- The error-code contains an HTTP error code, ex: 404 -->
<!ELEMENT error-code (#PCDATA)> <!--
The exception type contains a fully qualified class name of a Java exception type. -->
<!ELEMENT exception-type (#PCDATA)>
<!-- The location element contains the location of the resource in the web application
-->
<!ELEMENT location (#PCDATA)>
<error-page>
<error-code>404</error-code>
<location>/ErrorPage.jsp</location>
</error-page>
<error-page>
<exception-type> java.lang.Exception </exception-type>
<location>/ErrorPage.jsp</location>
</error-page>
Note :- "ErrorPage.jsp" will not receive the actual exception occured unlike the error
page that you specify using the JSP page directive with "errorPage" attribute which
receives the actual exception through an implicit "exception" object.
JSP:Include
Author: vinay thakkar (http://www.jguru.com/guru/viewbio.jsp?EID=1193667), Aug
17, 2004
does this error handling holds true when the page mentioned in the jsp:include tag
shows 404 error?
How can I automatically invoke a servlet at regular time intervals using
Resin?
Location: http://www.jguru.com/faq/view.jsp?EID=458416
Created: Jul 19, 2001
Author: Michael Strasser (http://www.jguru.com/guru/viewbio.jsp?EID=455820)
Question originally posed by Harsh Sugandhi
(http://www.jguru.com/guru/viewbio.jsp?EID=401509
I think that if you want every five minutes you need to use:
<run-at>:00 :05 :10 :15 :20 :25 :30 :35 :40 :45 :50 :55</run-at>
It's tough to get HTTP to return more than one file at a time. You could
1. just return a page listing all the files, and ask the user to click each link
2. package all the files into a Zip archive using the java.util.zip package classes,
and download that file
3. write a JavaScript function that downloads each of the files in turn
Not sure how well any of these will work. I'm pretty sure there's no easy way to just
download several files in a row, waiting for one to finish before serving the next.
[Keywords: file download multiple files several files many files at once]
Multidownload by Javascript
Author: Donatello Parigino (http://www.jguru.com/guru/viewbio.jsp?EID=451493),
Aug 31, 2001
How I can perform point 3 of proposed solution ?
When downloading a file to a client, how can I inform the client of the file
size, so it can predict how long it will take?
Location: http://www.jguru.com/faq/view.jsp?EID=460092
Created: Jul 23, 2001
Author: Donatello Parigino (http://www.jguru.com/guru/viewbio.jsp?EID=451493)
Question originally posed by Jonas Lindgård
(http://www.jguru.com/guru/viewbio.jsp?EID=447485
response.setHeader("Content-disposition", "attachment;filename=name");
response.setIntHeader("Content-length", filelength);
ServletOutputStream sos = response.getOutputStream();
...
Comments and alternative answers
Jakob Nielsen's article Why Frames Suck (Most of the Time) summarizes the issue
pretty nicely.
In general, if you are tempted to use frames, you should use tables instead. JSP's
<jsp:include> tag allows you to share common code like nav bars.
Arguments please
Author: Patrick Willart (http://www.jguru.com/guru/viewbio.jsp?EID=460888), Jul
24, 2001
I think you are right. Most of the times frames suck. Using tables and <jsp:include> is
a very good way to use common elements in you pages.
Reasons not to use frames:
Of course there are ways to work around most of these issues by using javaScript. My
opinion is there are some cases where frames offer a nice solution under the condition
that the designer knows what he is doing.
Do they?
Author: das Megabyte (http://www.jguru.com/guru/viewbio.jsp?EID=460934), Jul 24,
2001
I agree...frames cause havoc with bookmarking...but only for Netscape users.
Netscape is a dead project comprising less than 14% of the browser market (less than
7% of traffic on OUR sites). Printing with frames has been a cinch since 1997, and
since frames allow you to print just what you want (and not a lot of ugly header or
navbar stuff that is useless on paper anyway) they are actually better for the user
making a record of a sale or printing content to read later. If people are stealing your
content, read the http referrer and if it's a common thief, stop display (you're in
JSP...this is a CINCH). As for search engines...proper use of your robots.txt and a
small snippet of JavaScript to check for your frameset fix those issues.
While jsp:includes help make frames less necessary, they also create a lot of
inefficiencies. If you're building a dynamic nav bar every time you load a page, you're
beating on your servers needlessly, adding to your page download times what's usally
a large amount of table code and generally increasing your bandwidth for code that
isn't necesary to reload every time the page is.
Frames are more efficient and allow you so many liberties -- one of my favorite tricks
is to roll up a frame after a form submission that has a "Please Wait..." graphic, that
the content page rolls back down when it's completed download.
Re: Do they?
Author: Anand Jayaraman
(http://www.jguru.com/guru/viewbio.jsp?EID=449084), Jul 30, 2001
das Megabyte, Could you please show with the code how you show "Please
Wait..." graphic, if it's okay with you ? Thanks. Anand.
IDAutomation has a set of commercial beans, applets, and servlets for dynamic bar
code generation.
Comments and alternative answers
[I am using:
reqDisp =
servletContext.getRequestDispatcher("/applicationsecurity/RedirectLogin
.jsp")
reqDisp.forward(req,res);
]
reqDisp =
request.getRequestDispatcher("/applicationsecurity/RedirectLogin.jsp"
);
reqDisp.forward(req,res);
Comments and alternative answers
Fails on WL6.1
Author: Michael Westbay (http://www.jguru.com/guru/viewbio.jsp?EID=572920),
Dec 4, 2001
I'm using Struts for a web appliation, and it does just that:
RequestDispatcher rd =
getServletContext().getRequestDispatcher(path);
if (rd == null) {
...
return;
}
rd.forward(request, response);
This works fine with Tomcat, JRun, WebLogic 6.0, and others. However, WebLogic
6.1 (on WinNT, Linux, Solaris, and FreeBSD) does not appear to forward the request
parameters.
Google searches have not shown up anything unusual, leaving me wondering if I'm
the only one experiencing these problems.
Well, Struts does this deep within its framework, so I guess the only way to find out is
to write something a bit more contained to test it. If anyone else has experienced such
strange behavior on WL61, though, I'd like to hear about it, and what you did as a
work around.
What is the difference between a RequestDispatcher object obtained from
the Request object and the RequestDispatcher object obtained from the
ServletContext ?
Location: http://www.jguru.com/faq/view.jsp?EID=473812
Created: Aug 10, 2001
Author: Raji Chawla (http://www.jguru.com/guru/viewbio.jsp?EID=467765)
Question originally posed by Aejaz Sheriff
(http://www.jguru.com/guru/viewbio.jsp?EID=18227
request.getRequestDispatcher("url").forward(request,response);
and
getServletConfig().getServletContext().getRequestDispatcher("url").forw
ard(request,response);
One : you can pass relative URL address when using request.getRequestdispather,
and absolute URL address when using ServletConfig.getRequestDispatcher.
[When you show a form (POST or GET) to a user you can check for some required
fields in javascript, but you should double check it again on the servlet. I mean,
some fields are required, other need to be in a range (too many characters, too little
number, NaN, and so on), and other simple checks.
I'm using an XML config file where I say every argument that every servlet receives,
if it's required or not, its type and limits, and so on. I was wondering if there was
another way more appropiate to do this.]
No. You could create a monstrously complex method using reflection and a list of
data types and expected values, but that gets unworkable really quickly. The
problem is, you'll have your own types of valid data values, and any library that tries
to solve the whole thing will become something like XSchema, which is really
complicated and *still* doesn't handle certain common cases.
I always find that when a "config" file format gets too complicated, you may as well
throw it away and just use Java as your rules language.
My advice is to just make a method called "validate(HttpRequest)" for each servlet.
It can return a null if they're OK and a String with an error message if they're not.
The calling doGet() method can print the error message in whatever form is
appropriate for your UI (divide and conquer).
Then, once you've written a few of these, you will see repeated types of checks --
like "make sure it's really a number" and "make sure it's between a given range."
Factor these out into static utility methods, put them into a class (say,
FormValidator). Then rewrite your old validate() methods to use these utility
methods, and writing new validate() methods will become a little easier next time.
Also, check Jakarta Regexp package if you're going to be validating string contents.
Following is an example for WebLogic 6.x that protects all URLs that begin with
/secure:
<web-app>
<security-constraint>
<web-resource-collection>
<web-resource-name>SecurePages</web-resource-
name>
<description>Security constraint for resources in
the secure directory</description>
<url-pattern>/secure/*</url-pattern>
<http-method>POST</http-method>
<http-method>GET</http-method>
</web-resource-collection>
<auth-constraint>
<description>only let the admin role access the
pages </description>
<role-name>admin</role-name>
</auth-constraint>
<user-data-constraint>
<description>SSL not required</description>
<transport-guarantee>NONE</transport-guarantee>
</user-data-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<security-role>
<description>A role to access the secured
pages</description>
<role-name>admin</role-name>
</security-role>
</web-app>
<weblogic-web-app>
<security-role-assignment>
<role-name>admin</role-name>
<principal-name>system</principal-name>
</security-role-assignment>
</weblogic-web-app>
Hi, sounds like you're trying to set a header after you've written something to the
response output stream.
This allows a server to send the headers to the client before sending the response
contents. This way the client can determine some meta data about the repsonse (for
example what the type of the content is).
This means that as soon as the first byte of repsonse contents is written the reponse
goes into a state where headers can't be set. Trying to do so, results in an
IllegalStateException.
OutputStream out =
response.getOutputStream();
out.writeln("Hello...");
out.flush();
response.setContentType("text/html");
response.setContentType("text/html");
OutputStream out =
response.getOutputStream();
out.writeln("Hello...");
out.flush();
Comments and alternative answers
Are there any restrictions placed on applets loaded from HTML pages
generated from servlets / JSP pages?
Location: http://www.jguru.com/faq/view.jsp?EID=485955
Created: Aug 28, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
It is good practice to include the CODEBASE attribute in the APPLET tag and specify a
directory other then the servlet directory for storing the applet-related classes. For
example:
out.println(<"APPLET CODE=Foo.class CODEBASE=/applets WIDTH=400
HEIGHT=400">);
Some Web servers think that all classes loaded from the servlets directory are
automatically servlets, thus causing the applet not to load.
Use Java.net.Authenticator
Author: Bhiku Mhatre (http://www.jguru.com/guru/viewbio.jsp?EID=494523), Sep
10, 2001
I suggest you install a default Authenticator to achieve this. You could save your
username/password in a file or read it in a Properties object (authProp). The code
could look similar to this:
import java.net.*;
{.. ..
** add this before opening a URL connection> ***
Authenticator.setDefault(new MyAuthenticator(authProp));
.. .. }
// Add this class to your app class MyAuthenticator extends Authenticator{
MyAuthenticator(Properties myProp)
{
this.myProp = myProp;
}
protected PasswordAuthentication getPasswordAuthentication()
{
String username = myProp.getProperty("username");
String password = myProp.getProperty("password");
if (username==null || password==null)
{
System.err.println("MyAuthenticator: username or password is null.Returning null");
return null;
}
else
return new PasswordAuthentication(username,password.toCharArray());
}
}
Note that you cannot use a full qualified URL in getRequestDispatcher(). This must
be the path of the servlet relative to the servlet context. For example: If your servlet
context is called "/Select" and your servlet (which you want to dispatch to) is
mapped to "/Select" within this context, you have to call
getRequestDispatcher("/Select?TABLA="+param).
You should also verify if the returned dispatcher object is not null before you call
either include(request, response) or forward(request, response). As you can see in
the API documentation both methods require two parameters request and response,
which are the same one you have defined in doGet().
I recommend you to read the API documentation, everything is very well explained in
there. And I can recommend the Servlet Tutorial you can find at the SUN-Java
webpage, especially the section "Invoking Other Web Resources".
DoPost to DoGet???
Author: Irene Espadas (http://www.jguru.com/guru/viewbio.jsp?EID=481137), Dec
21, 2001
Thank for your answer. But...if I do this in a DoPost method it goes to the DoPost
method of the other server. How can I do to go from DoPost to DoGet
method????????? Thanks
Why do I get the error Http Method POST is not Supported by this URL?
Location: http://www.jguru.com/faq/view.jsp?EID=492829
Created: Sep 7, 2001
Author: Jatinder Thind (http://www.jguru.com/guru/viewbio.jsp?EID=488511)
Question originally posed by Gopala Pulipaka
(http://www.jguru.com/guru/viewbio.jsp?EID=487958
Most probably you have put only the doGet() method in your servlet. If the form
you used to submit data has POST in its method tag, the above exception will be
thrown. Change this tag to GET or add a doPost() method into your servlet.
int
colorvalue=Integer.parseInt(req.getParameterValue("ColorParameter"));
Could anyone kindly tell me how to process this value of the parameter into an
integer value so I may pass it to the Color(int) constructor. Thanks. ]
colorParameter = reqest.getParameterValue("ColorParameter");
if(colorParameter != null && ! "".equals(colorParameter)
&& colorParameter.length == 8){
colorParameter = colorParameter.substring(2);
r = Integer.parseInt(colorParameter.substring(0,2), 16);
You'd be much better off writing a class for handling this. It will be cleaner and more
easily reusable. You can call a constructor, which can either throw an exception or
have a private method for isValidHex. Also, you can call methods to set brightness,
adjust the hue, find other related colors --basically apply all the color theory you
know!
How do I use Visual Cafe to debug my servlets running inside the WebLogic
Web server?
Location: http://www.jguru.com/faq/view.jsp?EID=492844
Created: Sep 7, 2001
Author: Irene Espadas (http://www.jguru.com/guru/viewbio.jsp?EID=481137)
Question originally posed by srini k
(http://www.jguru.com/guru/viewbio.jsp?EID=485364
Should I use one servlet supporting GET to show pages and POST to process
forms, or two separate servlets?
Location: http://www.jguru.com/faq/view.jsp?EID=497265
Created: Sep 14, 2001 Modified: 2001-09-15 12:33:34.676
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Raji Chawla
(http://www.jguru.com/guru/viewbio.jsp?EID=467765
I prefer keeping my servlets as simple as possible. That means one servlet per page,
and one per function. In this case, that would mean one servlet to show pages and
another servlet to process forms. The trick is, all the servlets can communicate with
the common data model, which is stored using session or application attributes.
For example, I have one servlet (actually a JSP) that displays a form. The ACTION
for that form is another servlet which processes the parameters. That servlet sends a
redirect to the resulting page -- either the original form with an error message, or
the "Thanks for filling out the form" page servlet (actually a JSP). This allows me to
keep my UI design very flexible. For instance, I can have two different pages call the
same "process form" logic servlet, allowing (e.g.) a "Search" box on every page and
a separate Search page to use the same behind-the-scenes logic.
It's definitely a style choice; I like my way because it's more flexible; lumping
everything together can lead to brittle spaghetti code.
And as for GET and POST in the same servlet, I think that's kind of messy. I actually
like it when POST servlets can still respond to GET requests with the same semantics
-- it makes it a lot easier to debug! (I can just type in my test case in the address
bar.) Note that this requires that doGet() and doPost() have the same
implementation, which is trivial in the Servlet API:
You should also read the Forum Thread on this subject for many other good
comments.
Having said this, for the sake of simplicity, I suggest that all such methods
perform related functions.
• The second point is about browser redirect vs. request dispatcher's forward
mechanism. Browser redirects involve extra roundtrip between the server and
the browser. One should be careful about this choice.
[getClass().getResource() is the wrong approach, since the WAR file is not in the
current classloader's path. getServletContext().getResource() should work, but
apparently fails under WebLogic. Fortunately... -A]
What is the best way to store a large object, such as a result set, across
requests, but only for a short term, say for using the result set for printing
for instance?
Location: http://www.jguru.com/faq/view.jsp?EID=497495
Created: Sep 15, 2001 Modified: 2001-09-27 09:11:15.513
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Scott MacLellan
(http://www.jguru.com/guru/viewbio.jsp?EID=51832
[ I am assuming to store it in the session object would not be the best option. Also I
don't want to have to re-issue the query just to print it or do something else with
it. ]
First, as another poster pointed out, you should slurp the data from a ResultSet into
an object (probably a JavaBean) immediately upon retrieval. That frees up database
resources.
Then, what do do with the bean? You could store it in the session. Despite your
skepticism, that's probably the best plan. The session will be around the next time
the user makes a request.
If memory fills up, some servlet containers have the ability to swap the session data
to disk; then, when the user needs it again, it will be automatically (and
transparently to you) loaded back into memory. To assure this will work, make sure
your bean implements the Serializable interface.
If the user gives up and goes away before using the data, then you needn't worry
about memory leaks, since the session data will be released when the session
expires.
Once you're done with the data, however, you should remove it from the session
immediately, allowing normal garbage collection to take effect.
If the data set is too large to efficiently store into memory, then you can either
serialize it to disk, or store it back into a database. However, those options require
you to take responsibility for garbage collection -- you will need to have some
algorithm for deleting old files or records -- and that can be a real pain in the neck.
Check out
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Sep 27, 2001
Dmitry Namiot, Aug 20, 2001 writes:
How can I implement returning part of a large (1000+ rows) result set to
the client?
Location: http://www.jguru.com/faq/view.jsp?EID=497499
Created: Sep 15, 2001
Author: Bozidar Dangubic (http://www.jguru.com/guru/viewbio.jsp?EID=433955)
Question originally posed by Bryan James
(http://www.jguru.com/guru/viewbio.jsp?EID=497040
Try RowSet.
However, you will never be able to return first n rows "while result set is being
loaded." although that is a nice functionality, it would be tremendously hard to
implement it in the JDBC driver. you have no control of how data is obtained from the
database unless you wrote the JDBC driver yourself. therefore, no luck there. you
can try to combine some logic to access first n number of rows from the database,
but request for n+1, n+2... records would require additional queries to the database
which can get overly complex. so try RowSets. I am sure that you will be satisfied
with the performance and functionality.
Realistically, the support issues with Tomcat and JServ aren't really a problem. If you
write good code, you'll never trip up these servers.
My choice would be Tomcat, since it's an Open Source project (making it free and
giving you access to the source code if necessary), stays on top of the servlet API
developments, and works very well (I've never had any problems).
I would personally stay away from JRun for the counterpoint reasons listed above,
but have no technical reasons to poo-poo JRun. Allaire has good products, and I've
heard that JRun 3.0 and above is a lot easier to work with in terms of configuration,
etc.
Hope that helps,
-chris
Comments and alternative answers
c) It's expensive in an Production environment ($500 per server, $4500 for a pack
of 10)
JRun
Author: K Makinen (http://www.jguru.com/guru/viewbio.jsp?EID=516487), Oct 10,
2001
In my understanding, JRun uses pretty weak session ID generation algorithms. So if
security is an issue to be considered, JRun may not be the best choice.
jrun == booty
Author: Phillip Morelock (http://www.jguru.com/guru/viewbio.jsp?EID=523143), Oct
17, 2001
I must say, i used the developer version of JRun (the free-as-in-beer version) -- and it
was the absolute biggest nightmare in terms of configuration and setup i have ever
used in my entire life. Allaire products i've used: Homesite (excellent HTML and JSP
dev tool), Cold Fusion (don't get me started -- nasty and slow), and JRun
(configuration nightmare).
Overall, i gotta say -- with Tomcat, I was up and running and focusing on my code in
literally 10 minutes. Jrun -- i gave up after spending several hours over a couple of
days. In fact, I tried JRun first, and it completely turned me off to servlet containers
for a period of about three months. At that point, I tried Tomcat, and fell in love. The
rest is history.
An applet is executed on the client side (browser), not on the server side (servlet
container). You need to place the applet class files in a location accessible from the
browser, which means you have to treat them like normal files (like HTML or GIF files
that you want the browser to load). Thus they need to go in the webapp directory
tree, but not in the WEB-INF subdirectory.
It is best to think of the set of applet class files as entirely different from the set of
servlet class files. They will be loaded by different Virtual Machines, and may even
have different versions of classes. It is a simple matter to configure your build
environment (Ant or make) to create copies of common class files in the two
different classpath directories.
Since the concept of "current directory" is kind of fuzzy in the Servlet API, it is
usually easiest to make a separate directory just for your applet class files, and use
the optional CODEBASE parameter to the APPLET tag. Here is an architecture that
works well:
myapp/WEB-INF/classes/MyServlet.class
myapp/WEB-INF/classes/Util.class
myapp/index.html
myapp/applets/MyApplet.class
myapp/applets/Util.class
Then if your servlet generates a line like:
out.println("&lt;APPLET CODE='MyApplet.class' WIDTH=50 HEIGHT=50
CODEBASE='/applets'&gt;"&gt;;
The browser will be able to load MyApplet.class and Util.class from your /applets web
directory. It will not be able to load anything from WEB-INF/classes, since those files
are accessible only by the servlet engine.
Note that loading an applet from a page generated by a servlet is much the same as
loading an image. It is also easier to use a common "images" directory in that case,
so that images can be loaded from any page regardless of "current" directory.
See also:
• What is the Java Plug-In? (and the topics Applets:Plug-in and Browsers: Plug-
in)
• How do I set my CLASSPATH for servlets?
• Where do I store image files so my servlet's HTML pages can display them?
ok, so what if your applet class and your servlet class need to access common
utility classes?
Author: George Francis (http://www.jguru.com/guru/viewbio.jsp?EID=894160), Jun
27, 2002
If my web-app has utility classes that need to be accessed by both the applet and the
servlets - where should they be deployed?
Re: ok, so what if your applet class and your servlet class need to access
common utility classes?
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jan 5,
2003
Unfortunately, you need to put common classes/jars in both places: both inside
WEB-INF -- so the servlet can find them -- and inside the normal htdocs
directories -- so the applet can find them.
(As the original answer said, "It is a simple matter to configure your build
environment (Ant or make) to create copies of common class files in the two
different classpath directories.")
[I want to pass this parameters to JVM that runs my servlet. E.g. -Djava.
naming.factory.initial = com.sun.jndi.cosnaming.CNCtxFactory]
You should take a look at iText. It's an open source PDF library for java, hosted over
at sourceforge. They have an example of using servlets to return dynamic PDF
documents.
http://www.lowagie.com/iText/
[See also the forum thread for this topic: How do I use servlets to return dynamically
genera... ]
Comments and alternative answers
Try XSL-FO
Author: Shai Almog (http://www.jguru.com/guru/viewbio.jsp?EID=501707), Sep 22,
2001
xml.apache.org has most of the things you need (an XSLT processor and an early yet
functional XSL-FO implementation). One warning though, XSLT is a REALLY ugly
language, but it is rappidly gaining popularity and it does have some nice features.
Try xml.apache.org/fop
Author: hotjaffa jaycee (http://www.jguru.com/guru/viewbio.jsp?EID=390693), Sep
22, 2001
Hi, We've had a simialr requirement recently and used fop from the apache project.
Wihin 2 days we had solved our problem and had a serv;et + jsp dynamically
generating XML/XSL -> FO file -> PDF. Nice 'n' easy and robust and open source
Hi Tony,
Two methods must be added to your object when you implement this interface:
These methods are called when the object is put in session (valueBound) and when
the object is removed from the session (valueUnbound).
To answer to your question: you have to put your code in the valueUnbound
method to do some actions just before the object is removed (or replaced!) from the
session.
If the session expired or is invalidated, all objects are unbound from the session, and
the method valueUnbound is called.
Regards,
Denis Navarre
Comments and alternative answers
Re
Author: Massimiliano Ragazzi
(http://www.jguru.com/guru/viewbio.jsp?EID=945577), Jul 25, 2002
The valueUnbound doesn't function because when it's called the object is jaust
removed
See also
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Dec 9, 2002
Session Management - Clean up after session time out.
When a servlet is first called, the response object is fresh and new: its headers have
not been set, its buffers are empty, and no data has been written to the client.
However, as soon as either the status code or any of the headers have been written
-- or potentially written -- to the client, or when data has been -- or may have been
-- written to the body stream, then you may be susceptible to the
IllegalStateException error. The problem that this exception is signalling is the new
data that you are (or may be) writing is inconsistent with the data that's already
been set and then irretrivably sent ("committed") to the client.
"Header already sent" means that one or more headers have been committed to
the client, so you can't set that header again.
"Output Stream or Writer has already been obtained" means that since the
calling servlet has already called response.getWriter() or
response.getOutputStream(), that contaminates the data stream, since the response
has been (or may have been) written to already, making it unsuitable for forwarding.
(Some would argue that the exception is overkill; that the Servlet API should just
silently log the problem, then continue as best it can, e.g. by simply not writing the
new headers or status code or body text. However, the API as it stands is less
forgiving, and it throws a hard exception.)
A further complication is "side effects", where methods set the "committed" flag
unnecessarily, or at least unexpectedly. For instance, calling response.flushBuffer()
sets the "committed" flag (even if the buffer is empty). Furthermore, calling
RequestDispatcher.include() calls response.flushBuffer() (even if the "included"
servlet doesn't actually write any data to the response). That means that you
shouldn't ever call include() before calling forward().
What this all means is that the Servlet API is inadequate as a general framework for
sending messages among active objects to form a data pipeline. Fortunately, you
have an API that is perfectly adequate for that task: Java itself. Structure your
application to use JavaBeans and Java method calls. Restrict your Servlets to two
types: one type is all data-processing, and the other type is all response-writing.
If you want your response-writers to be modular (one object to build the nav bar,
one object to build the banner ad, one object to build the body, one object to build
the page footer, etc.), you have two choices:
1. use JavaBeans or Java method calls to build up the HTML in the response, or
2. use RequestDispatcher.include() to bring in content from many little servlets
from inside a master response-builder servlet.
You may also look into Servlet 2.3 Filters as an alternative way to string page
content together from multiple resources (though it too is quite complicated and
ambiguous at times).
See also:
I find Tags to be the easiest way to modularize a response. But of course i defer to the
author of this answer as someone with obviously more experience. It's just -- well,
check out custom tagging and jsp's for your responses. They're pretty neat.
Can I print the dynamic content output to my browser from a JSP page
without showing the address URL?
Location: http://www.jguru.com/faq/view.jsp?EID=502936
Created: Sep 24, 2001 Modified: 2001-09-26 08:39:43.115
Author: Matt Goodall (http://www.jguru.com/guru/viewbio.jsp?EID=450000)
Question originally posed by king hw
(http://www.jguru.com/guru/viewbio.jsp?EID=132496
If layout matters that much then I would recommend writing a servlet to populate a
PDF file with the data you have on your JSP. The servlet sends the PDF to the
browser and the browser loads Adobe Acrobat to view the page.
If you choose to do that take a look at FDF - PDF's form API. It's pretty easy to use,
there are Java packages to help with the task and I'm sure FDF will have been
mentioned on jguru before.
Note that using PDF does mean that the client needs to have an Acrobat viewer
installed.
FDF Merge
Author: Ranjan Banerjee (http://www.jguru.com/guru/viewbio.jsp?EID=505211), Sep
27, 2001
I have seen the results of FDF Merge and have been quite impressed by it.
Virtual directories
Author: Nitin Baligar (http://www.jguru.com/guru/viewbio.jsp?EID=207743), Oct 17,
2001
To the best of my knowledge, you can show the output without showing the URL in
the browser. In the web server admin, you can create the virtual directories which will
point to particular JSP page and if u just load like www.yourdomain.com/virtualDir it
will load the particular JSp page which is linked in the web server admin.
When you say getSession(true), this method will check whether already a session is
existing for the user. If a session is existing, it will return that session object,
OTHERWISE WILL CREATE A SESSION OBJECT EXPLICITLY AND RETURN TO THE
CLIENT.
When you say getSession(false), this method will check whether a session is
existing. If yes, then it returns the reference of that session object, OTHERWISE IT
WILL RETURN 'null'.
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. However, many EJB-enabled servlet engines do.
Even if your engine does support persistent sessions, it is usually possible to disable
this feature. Read the documentation for your servlet engine.
Note that this means that a JDBC Connection should not be stored in a session,
however convenient that would be. You can put it in an application scope variable, or
in a "transient" field of a private class. Read the docs for the Serializable interface to
learn more.
I've written some code (two servlets: a Source and a Target) to test this scenario:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.net.*;
import java.util.*;
URL url;
URLConnection urlConn;
DataOutputStream cgiInput;
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setUseCaches(false);
urlConn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
cgiInput.writeBytes(content);
cgiInput.flush();
cgiInput.close();
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
Did you try using the exists() method of the File object? e.g.:
Download manually
Author: Zeljko Trogrlic (http://www.jguru.com/guru/viewbio.jsp?EID=4607), Sep 28,
2001
There was a way to manually download a file. You can give any name to the file, so
you should probably use automatically generated temp name. Procedure is described
in documentation. This doesn't exist in old versions of the COS.
We use a number of properties files, both from the classes directory and from sub
directories without any problem.
I am working with JServ which does not provides a WEB-INF directory. But still i
want to load a properties file. Is It possible? If Yes then How?
Regards
Saurabh
Re: Can I load a property file even if don't have WEB-INF dir?
Author: brian ally (http://www.jguru.com/guru/viewbio.jsp?EID=530592), Oct 25,
2001
saurabh,
with jserv, i use pretty much the same code - getResourceAsStream()
just leave the properties file at the top of your classes directory. you'll want to be
sure it's readable by jserv, which should be the same user apache is running as.
regards,
Re: Re: Can I load a property file even if don't have WEB-INF dir?
Author: brian ally (http://www.jguru.com/guru/viewbio.jsp?EID=530592), Oct
25, 2001
not working
Author: ram k (http://www.jguru.com/guru/viewbio.jsp?EID=865733), May 3, 2002
I tried to do classloader stuff in my java class which is not a servlet and it did not
work.
[Note: the following is not a full-featured HTTP proxy. Other true HTTP proxies, like
Squid, accept the CONNECT request, and can interpret the HTTP headers
intelligently. This is a simple tunneling proxy, so it may not work correctly if you set it
as your browser's proxy setting. Also, a more full-featured proxy has other features,
like caching media. -Alex]
Recently I wrote a little Proxy in java and it works fine tunneling the requests with
any ports to tomcat, but I didn't use apache (That's not the reason anyway) and NT
instead of WIN98. I think it's either the configuration of the Proxy or the network
configuration in your System
try this:
import java.net.*;
import java.io.*;
import java.util.*;
Socket fromClient;
String host;
int port;
long timeout;
public static final String usageArgs =" <localport> <host> <port> <timeout_ms>";
if(argv.length>=3) {
int localport = Integer.parseInt(argv[0]);
String url = argv[1];
int port = Integer.parseInt(argv[2]);
int timeout = 30000;
try {
timeout=Integer.parseInt(argv[3]);
} catch(Exception e) {}
self.run(localport,url,port,timeout);
} else {
System.err.println("usage: java " + self.getClass().getName() + usageArgs);
}
}
}//class
correction
Author: Martin Erren (http://www.jguru.com/guru/viewbio.jsp?EID=446238), Sep 29,
2001
This Proxy won't accept more than one client. To start the ProxyConnection as a real
Thread (Line 127):
instead of
directly.
Re: correction
Author: Hartmut Trüe (http://www.jguru.com/guru/viewbio.jsp?EID=547171),
Nov 14, 2001
Hmm,
r.start()
works fine, but
r.run()
throws an IOException with JDK 1.3.1_1. Maybe, it's a security exception for
AccessController.doPrivileged()?
Re[2]: correction
Author: Troy Kinsella (http://www.jguru.com/guru/viewbio.jsp?EID=779766),
Mar 3, 2002
Aren't you not supposted to call run() directly anyways?
Multiple Clients
Author: Rishath Rias (http://www.jguru.com/guru/viewbio.jsp?EID=1164187), Apr
19, 2004
I tried changing c.run() at line 127 to c.start() as mentioned in the comment section.
But, I'm getting java.net.SocketException and java.lang.NullPointerException. How
can I make this proxy to accept multiple clients? Plz Help!
How can I get quotes in my servlet output so the string will be quoted for
JavaScript?
Location: http://www.jguru.com/faq/view.jsp?EID=507420
Created: Sep 30, 2001
Author: Marin Velikov (http://www.jguru.com/guru/viewbio.jsp?EID=36886)
Question originally posed by Paul Reh
(http://www.jguru.com/guru/viewbio.jsp?EID=483132
Use request.getQueryString() and parse the list in order yourself. You can use a
StringTokenizer, something like this (untested code):
StringTokenizer st = new StringTokenizer( request.getQueryString(), "&"
);
while (st.hasMoreElements()) {
String token = st.nextToken();
String name = token.substring(0, token.indexOf("="));
}
See also
By the way, the parameters are not guaranteed to be sent over in the order they
were on the page, but I think most browsers do that anyway.
No. You can't do it for extracting parameters from the post request.
Re: Re: Re: Re: getting parameter names from query string
Author: Alan Johnson
(http://www.jguru.com/guru/viewbio.jsp?EID=241283), Oct 7, 2001
Feel free to use it but don't think there is any warrentee, expressed or
implied, etc. Notice the FMCFormat Parameter.
Re: Re: Re: Re: Re: getting parameter names from query string
How to get parameters in order using servlets, for a SendMail program using
post, the working answer.
Author: Renato Moscoso (http://www.jguru.com/guru/viewbio.jsp?EID=548467),
Nov 15, 2001
Well all information about this, is wrong (for POST), and no code works, plz don't
write scratch without warning about it because it really makes waste time by the way
I needed a whole day to figure out how to do it, there no way using standar methods,
because : - The applet server always get the data before one can get it, so its almost
impossible o use HttpUtils libs, this lib sucks, I think is deprecated. - The main
problem is about HashTables, they are always in disorder, why I don't know, some
people said to Override the Hash table with a kind of OrderedHashTable, but I've tried
3 classes 2 downloaded and one modified and it doesn't work. The answer is really
easy, and is in apache jserv page, we need to change the encoding type for the form,
so the web server will not parse it, here the html : <FORM
ACTION="/servlet/SendMail" METHOD="POST" enctype="text/plain"> Ok
now we have enctype=text/plain, so what next, so we simply use a Reader and do
parsing by hand here is the code :
String mailData = "";
BufferedReader r=req.getReader();
String ssx;
int t = 0;
while ((ssx=r.readLine()) != null) {
int i = ssx.indexOf("=")+1;
if (ssx.startsWith("mailFrom="))
mailFrom = ssx.substring(i);
else if (ssx.startsWith("mailTo="))
mailTo = ssx.substring(i);
else if (ssx.startsWith("returnPage="))
returnPage = ssx.substring(i);
else if (ssx.startsWith("subject="))
subject = ssx.substring(i);
else if (ssx.startsWith("mailText="))
mailText = ssx.substring(i);
else if ((!ssx.startsWith("Submit=")) &&
(!ssx.startsWith("Reset="))) {
mailData += ssx+"\n";
}
t ++;
if (t > 1000) break;
}
// Validate Data //
if (mailFrom == null) throw new ServletException("Se requiere
el campo mailFrom.");
if (mailTo == null) throw new ServletException("Se requiere
el campo mailTo.");
if (returnPage == null) throw new ServletException("Se
requiere el campo returnPage.");
if (subject == null) throw new ServletException("Se requiere
el campo subject.");
if (mailText == null) mailText = "";
mailText = mailText.replace('~','\n');
mailData = mailText + mailData;
sendMail(mailFrom, mailTo, subject, mailData);
Simple and so easy, I don't know why we have to lead with this things having a
programming languaje so powerfull like Java, writing this servlet is very even using a
bach script. This is an awfull message, but I haved a really bad day, may english is
really bad I speak spanish. Enjoy Coding :)
Re: How to get parameters in order using servlets, for a SendMail program
using post, the working answer.
Author: John Westbury (http://www.jguru.com/guru/viewbio.jsp?EID=757563),
Feb 13, 2002
look like cobol
Can two web applications (servlet contexts) share the same session object?
Location: http://www.jguru.com/faq/view.jsp?EID=511752
Created: Oct 4, 2001 Modified: 2003-01-12 07:42:10.003
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
Phuong Nguyen (http://www.jguru.com/guru/viewbio.jsp?EID=489857
[For example:
Also
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Oct 25, 2001
This question is also answered at:
I don't get it ... why can't two web applications share a session?
Author: Gary Bisaga (http://www.jguru.com/guru/viewbio.jsp?EID=580782), Dec 11,
2001
Ok, I officially don't get it. There seem to be two problems here:
We're trying to set up a group of related but somewhat independent applications that
all want to be able to share the same user session information (user id, language
choice, etc.) and don't really want to put them all in the same WAR file. And I don't
see why I should have to. If anybody has an answer to these questions I'd be grateful.
Re: I don't get it ... why can't two web applications share a session?
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jan 11,
2003
> What's insecure about two web applications on my own server, both of
> which I wrote, accessing the same user session information?
Nothing! But some people run other people's webapps on their server (think ISPs,
or commercial/third-party webapps). The crossContext attribute is there for you to
tell Tomcat, "Yes, it's OK, I know what I'm doing."
Re: I don't get it ... why can't two web applications share a session?
Author: Vijay Arunkumar
(http://www.jguru.com/guru/viewbio.jsp?EID=1055450), Feb 10, 2003
SECURITY, isnt just related to hackers... Also implies the issue of ISOLATION.
Lets say your WEBAPP-ONE uses session variables to track logical steps or
whatever. And one of the variables is called FOO. Now if there is a WEBAPP-
TWO using a session variable FOO also, both will overwrite each other, if the
same client is accessing both applications at same time... which we all do.
SAMPLE SCENARIO:
The most common scenario where session conflict will introduce security
problems is when access rights are stored in session variables. Lets say user 1 has
access level 5 for WA1, and access level 10 for WA2. (Access Levels are arbitrary
numbers i am using and not part of the JSP or Servlet spec). User logs into WA1
which creates a session variable SV_ACC_LEVEL and stores 5. now all pages
hide CLASSIFIED info based on this level. Now, user logs into WA2, (hmmmm...
using SV_ACC_LEVEL again, i suppose), now user goes back to WA1. Aahaah!
Now the user has level 10 access to both WA1 and WA2.
Many huge corporations groups all there "Supposed to be Isolated" Apps under
the same WEB-APP context. Including the place where i am working at... and it
took a lot of effort for me to explain to my managers the problems of not using
seperate web-apps. And when I demoed this point by simply writing a jsp page
that set up certain session vars for logiging into classified apps, and obviously
demoed a log in when i am supposed to be denied access, it hit em.
So, .... before i go too deep into hacking and lose my mind over this matter, let me
just state my point. SHARED SESSIONS is a HUUUGE SECURITY RISK.
Can i setup Tomcat to run inside the web server process itself (on
Netscape/IIS?), instead of running it as a separate process. Do there
something available i can use or do i have to write my own JNI code for
this?
Location: http://www.jguru.com/faq/view.jsp?EID=520057
Created: Oct 14, 2001 Modified: 2001-10-18 12:10:28.738
Author: Davanum Srinivas (http://www.jguru.com/guru/viewbio.jsp?EID=2011)
Yes. The dirty work has already been done for you. More information can be found at
TOMCAT - In-Process HowTo.
Comments and alternative answers
It has features:
1) eliminate 8080 port from urls
2) redunce load on tomcat as images and other resources are handled by IIS
3) support http keep alive for jsp and servlets
4) easy setup for SSL by IIS, no hassle for setting up SSL for tomcat
- Akash Kava
1. You can put the information you like in a HTTPSession object. This object is
created for you and stays with the user during the time they are in the site.
This is done like this:
2. HttpSession s = request.getSession(true);
3. s.setAttribute("returnVal", callMethod());
The first row creates the session if there are no sessions. Next row sets the
value you like in to the session object. Remember that in the JSP page you
have to cast this object back to whatever object it is. All "things" in a session
object are stored as java.lang.Objects.
here is how that is done inside the JSP page:
myObject = (myObject)
session.getAttribute("returnVal");
4. The other way of doing this is to put the value in the request object. It is
similar to the previous example, only it is the request object.
Here is how that is done:
5. RequestDispatcher rd =
getServletContext().getRequestDispatcher("/yourjsppage.jsp");
6. request.setAttribute("myObject", getMyObject());
rd.forward(request, response);
The first row gets the requestDispatcher, the second line adds your object to
the request object and the last line forwards the request. In the JSP page you
use the "request" object like this:
myObject = (myObject)request.getAttribute("myObject");
Comments and alternative answers
outputToServlet.writeObject("asdfa");
outputToServlet.flush();
outputToServlet.close();
InputStream in = servletConnection.getInputStream();
I believe that the new session will be generated on next request by the client, not
immediately after the invalidate.
Comments and alternative answers
New session
Author: Subrahmanyam Allamaraju
(http://www.jguru.com/guru/viewbio.jsp?EID=265492), Oct 18, 2001
That's true. In case you want to establish a new session within the same request, try
using send-redirect to the same servlet. This way, the container gets a chance to
establish a new session.
When downloading a PDF document that is less than 8000 bytes long, the
document is downloaded but is not displayed. How can I fix this?
Location: http://www.jguru.com/faq/view.jsp?EID=524472
Created: Oct 18, 2001
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
Alan Taylor (http://www.jguru.com/guru/viewbio.jsp?EID=447303
I've had a similar problem before when I'm sending a PDF that I'm generate. The
problem seems to happen when the PDF file is smaller than the buffer size of the
response object (8K by default).
We've solved the problem with a little help from the buglist of Microsoft IE knowledge
base. Setting the Content-Length in the response object, shoud do the trick.
Working code:
byte[] data = ...;
response.setContentType("application/pdf");
response.setContentLength(data.length);
BufferedWriter out = new BufferedWriter(new
OutputStreamWriter(response.getOutputStream()));
out.write(data);
out.flush();
out.close();
For more discussion, see these two threads in the Servlets FAQ and the JSP FAQ.
HTTP/1.1 200 OK
Content-Type: application/pdf
Content-Length: 91853
Date: Wed, 10 Apr 2002 20:23:00 GMT
Server: Apache Tomcat/4.0.3 (HTTP/1.1 Connector)
Last-Modified: Tue, 05 Sep 2000 10:51:39 GMT
ETag: "91853-968151099000"
That seems to be o.k, but as a matter of fact it isn't. What do you suggest?????
How do I play a sound on the server from inside a servlet? The Java Sound
API doesn't seem to work.
Location: http://www.jguru.com/faq/view.jsp?EID=524475
Created: Oct 18, 2001
Author: Jitendra Mehta (http://www.jguru.com/guru/viewbio.jsp?EID=64025)
Question originally posed by Jitendra Mehta
(http://www.jguru.com/guru/viewbio.jsp?EID=64025
[More Q: I am trying to use java sound API in my servlet based application. One of
the subclass in my 'playSound.class' extends thread. I am loading audioClip inside
this thread, which is not working. It doesn't raise any error. If I skip the thread and
load clip directly, it works fine.]
I changed my servlet to implement 'SingleThreadModel' and my code worked! Now I
don't know if implementing 'SingleThreadModel' will hamper performance of my
application. I am using only one servlet which is mounted when web server starts.
package moore.mifc.system;
import java.applet.AudioClip;
import java.applet.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.URL;
import java.net.MalformedURLException;
import java.awt.GridBagLayout;
import moore.mifc.system.*;
public class playSound {
SoundList soundList;
String login = "login.wav";
String logout = "logout.wav";
String menu = "menu.wav";
String ready = "systemReady.wav";
String unknown = "unknown.wav";
String chosenFile;
String status;
public playSound() {
startLoadingSounds();
}
void startLoadingSounds() {
//Start asynchronous sound loading.
try {
codeBase = new URL("file:\\mifc\\res\\") ;
} catch (MalformedURLException e) {
logSound.out(e.getMessage());
}
}
public void stop() {
onceClip.stop(); //Cut short the one-time sound.
if (looping) {
loopClip.stop(); //Stop the sound loop.
}
}
if (what.equalsIgnoreCase("login") )
{
//based on time play greetings..
onceClip = soundList.getClip("login.wav");
if (onceClip == null) {
logSound.out("Sound " + "login" + " not loaded yet.");
return;
}
stop();
onceClip.play(); //Play it once.
return;
if (onceClip == null) {
logSound.out("Sound " + "ready" + " not loaded yet.");
}
stop();
//Play it once.
onceClip.play();
return;
}
else if( what.equalsIgnoreCase("unknown") )
{
onceClip = soundList.getClip("unknown.wav");
if (onceClip == null) {
logSound.out("Sound " + "logout" + " not loaded yet.");
}
stop();
onceClip.play(); //Play it once.
return;
}
return;
this.baseURL = baseURL;
}
return (AudioClip)get(relativeURL);
}
To capture clickstreams generally you need a browser-side plugin like Alexa. That's
*way* out of the realm of servlets.
To track click streams inside your site, check the Referer HTTP field (to see where
people came from before hitting your site). Once they're in your site, you can make
every servlet-generated page log its name and the username to your database. But
there's no simple way to "turn clickstream recording on" or whatever.
Comments and alternative answers
The new servlet 2.3 specification allows you to easily write a click-stream filter.
Author: mindaugas idzelis (http://www.jguru.com/guru/viewbio.jsp?EID=128502),
Nov 1, 2001
With the new servlet 2.3 specification, it IS possible to see the clickstreams of people
on your site. This is implemented using a filter. There are "ready-made" filters that
you can just plug in and they will work. For a detailed overview please go to
http://www.javaworld.com/javaworld/jw-06-2001/jw-0622-filters.html
Also, http://www.orionsupport.com/clickstream/
http://www.opensymphony.com/clickstream/
While this works fine for small time values, for large values the session dies out well
before the given time value. Is there a way around this?? The documentation talks of
HttpSession.getMaxInactiveInterval() using which the session timeout can be set.
Has anyone tinkered with this?? Appreciate some help very much.
Answer:
session.setMaxInactiveInterval(600);
session timeouts
Author: Nick Furiak (http://www.jguru.com/guru/viewbio.jsp?EID=431833), Feb 26,
2002
I think the session.setMaxInactiveInterval(time) requires that you enter the interval in
milliseconds.
hai friends,
iam using
1. tomcat4.0.4
2. Javamail api
3. servlets
session.setMaxInactiveInterval(14400);
<session-config>
<session-timeout>240</session-timeout>
</session-config>
thanks.
2.3 Servlets, doFilter(), and Request Headers If you've ever done NSAPI, you know
that it gives you full access to the web server's processing of a request. One of the
neat things it lets you do is modify/insert request headers. For example, you could
look for a specific cookie in the request, and if it's there, insert an authorization
header into the request, and then pass this modified request on to the rest of the
web-server's normal processing (most importantly for this particular example, the
authentication phase).
Are there any classes out there that let you do this sort of thing? It doesn't appear to
me that the standard 2.3 doFilter() chaining scenario will work, as I can only
manipulate the response headers. I'm thinking of developing something myself using
lwj (libwww-java: http://lwj.sourceforge.net/.). Any advice/ideas about going down
this road? Thanks!
[See the topic Servlets: Sessions and the question How do I use Session Tracking?
-Alex]
A session is an object associated with a client connection to the server. it has the
ability to carry information related to the client. since http is a connectionless
protocol, developers need an ability to "remember" what the client of the application
did during the visit to the page. a great example of the need and use of session is a
infamous shopping cart. as users browse through products they are interested in,
they add products they want to buy to the 'shopping cart' this information needs to
be stored somewhere so that when users decides to check-out and purchase the
products, the system knows all the products client wants to purchase. so 'shopping
cart' is stored in the session which drags along on each client invocation to the server
until session expires.
the way server handles session is server-specific. the specification does not specify
exact implementation of the session. some web servers may use cookies, some may
use something else. but overall, it is up to the implementer to decide how this is
done.
I am Sorry
Author: Rotti Sowmindra (http://www.jguru.com/guru/viewbio.jsp?EID=487648),
Dec 30, 2001
I am sorry to say that if we diable cookies in the client browsers we cant user sessions
too.Because the basic funda with sessions is they use cookies to store the reference to
the value of the session.It means a session creates a cookie on the client side which
has reference to its value in the server where as a cookie directly stores the value in
the client's side. I would like to be proven wrong Regards Sowmindra
Re: I am Sorry
Author: Kumar KMK (http://www.jguru.com/guru/viewbio.jsp?EID=716239), Jan
10, 2002
If you disable cookies servlet container may use urlrewriting for session
management in effect you cant disable sessions by disabling cokies.
Re[2]: I am Sorry
Author: Tuan Sau-Wern
(http://www.jguru.com/guru/viewbio.jsp?EID=437561), Oct 14, 2002
What Rotti says is correct. You still need to enable cookies at the client side to
have sessions working.
Re[3]: I am Sorry
Author: neal ravindran
(http://www.jguru.com/guru/viewbio.jsp?EID=17737), Dec 23, 2003
Hmmm..I thought it could still be(ie with cookies disabled at client)
encapsulated in the header part and the browser could read it. Wrong?
My servlet reads the contents of a text file which I access using a File object.
What issues are involved when this file is read concurrently by several different
threads? Do I have to synchronize access to the file, or does it not matter when
access is read-only?
Should not matter if the file is only for reading. Make sure that you close the file
when you are done using it.
Comments and alternative answers
Sun's specifications for Servlet define only the WEB-INF/classes and WEB-INF/lib
directories in order to make the web application portable.
If you are not interested in portability, you can still put all your classes into the
CLASSPATH environment variable.
The startup script for Tomcat 3.2.x should automatically add that classpath to the
one used by Tomcat, while, with version 4.0.x and 3.3.x, you definitely need to make
a small change in the startup script to add the CLASSPATH environment to the one
that is generated by the script to esecute Tomcat.
The only issue is that the classes/jars you've added will be available to all the web
applications running under that instance.
[Also, they may conflict with other library JARs. XML parsers are notorious for this
problem. -Alex C]
Portability may not be a concern. In addition to the fact that such classes will be
available to all applications running under that container (since such classes will be
loaded by the classloader loading the the container runtime itself), you will not have
the ability to undeploy and deploy such classes dynamically.
Most contaienrs let you specify the interval for checking changes. I think you
may even turn off this. I'm not sure how much overhead it involves, but this
does not outweigh the advantages of scoping classes under /WEB-INF/classes
and /WEB-INF/lib directories.
EAR files?
Author: Pete Halverson (http://www.jguru.com/guru/viewbio.jsp?EID=537495), Nov
2, 2001
a J2EE Enterprise Application Archive (an .ear file) allows a web app (.war file) to be
packaged with any dependent libraries (.jars), including third-party class libraries as
well as EJB client stub jars, e.g. something like
webapps/webapp.war
ejbs/ejb-client.jar
xerces.jar
xalan.jar
If you declare all your .jar dependencies in the .war's JAR manifest (*not* web.xml),
the container is supposed to make those classes available in addition to /WEB-INF/lib
and /WEB-INF/classes. But support for EARs is still limited. JBoss handles them
(and if you're running tomcat inside of JBoss, it seems to work as expected), but I
don't know who else does. pch
small change
Author: bill weaver (http://www.jguru.com/guru/viewbio.jsp?EID=575360), Dec 12,
2001
you say "while, with version 4.0, you definitely need to make a small change in the
startup script to add the CLASSPATH environment to the one that is generated by the
script to esecute Tomcat."
what is the "small change" you mention and to what file (i'm a newbie to
apache/tomcat and all things java and am having lots of problems locating servlets)
many thanks
bye
See How do I access a database from my servlet or JSP?... and the topic
Servlets:Databases
Disagree
Author: Bozidar Dangubic (http://www.jguru.com/guru/viewbio.jsp?EID=433955),
Nov 5, 2001
This solution leaves connections open for the life of the JSP page. If you have 200-
300 JSP pages (not unusual at all for medium-size projects) you would have to have
200-300 connections open just to serve JSPs. and although you will save some time if
you keep the connections in JSPs open, it is a pretty bad design and wastes a lot of
resource. connection pooling is the way to go. create a pool of connections for the
JSPs to use and get the connection from the pool. resources can be used optimally
with this approach and performance will be about the same (with some tweaking
based on load).
Re: Disagree
Author: brett haas (http://www.jguru.com/guru/viewbio.jsp?EID=538610), Nov 5,
2001
What if the portion of the site (or project) only has about 20-30 pages which
actually make an connection to a database.
Would it be better than just to leave open the connection and allow them to be
shared for all threads?
Connection handling
Author: Subrahmanyam Allamaraju
(http://www.jguru.com/guru/viewbio.jsp?EID=265492), Nov 5, 2001
• Get the connection when required and close it immediately after use. Do this
within the doXXX() methods.
• Configure your J2EE container for connection pooling.
Firstly, you **should** not keep connections as instance variables - this would not
work under multiple threads (which happens all the time with servlets/JSPs). There is
an example about this in one of my papers published in JDJ Mar 2000 issue.
Most J2EE containers provide connection pooling (i.e, implement the JDBC2
connection handling SPI). This takes care of the connection overhead, and
transperantly pools connection objects.
The second one was declaring the connection object globalling and intializing it
once in init(). The avg load of each page was: 7337 ms (global connection)
Neither of these test used connection pooling. And I called System.gc in the
finally block after getting the load time for the current thread.
By these results, I would have to assume that global connection is your better
option, if you are not going to use connection pooling.
As
SELECT
id, // int
cat, // varchar(25)
title, // varchar(100)
byline, //varchar(20)
left(convert(varchar(1000), body),
charindex('. ', convert(varchar(1000), body), 500)
// text
as body
FROM
article
ORDER BY
cat,
title
ASC
Assuming that you're getting connections in the init() method, and that your
servlet does not implement the SingleThreadModel interface, here is how can
things can go wrong.
Let's say there are two hits T1 and T2 (almost concurrently) to this servlet, and
that there are three database related tasks (D1, D2 and D3). Here is one
hypothetical scenario:
How many transactions do you see? You will see two, with the first rolled
back. The second transaction starts after the first rolls back. So, the second
transaction includes D3 only. As you see, this is incomplete.
The poing is that, transactions get mixed up since both the threads are
operating on a single connection object.
I hope this explains why multiple threads should not share the same
connection. This is precisely what happens in the case of servlets.
I have a quick question for you, which is not directly related to this topic.
}
private boolean getConnectionInfo()
{
debug = Boolean.valueOf(getInitParameter(DEBUG)).booleanValue();
dbAlias = getInitParameter(ALIAS);
boolean connection = (dbAlias != null)?true:false;
if (connection)
{
dbDriver = getInitParameter(DRIVER);
dbUrl = getInitParameter(URL);
dbUsername = getInitParameter(USERNAME);
dbPassword = getInitParameter(PASSWORD);
dbMaxConnections =
Integer.parseInt(getInitParameter(MAXCONN));
dbIdleTimeout = Integer.parseInt(getInitParameter(IDLE));
dbCheckoutTimeout =
Integer.parseInt(getInitParameter(CHECKOUT));
if (debug)
{
System.out.println("******
StartupConnectionPoolServlet - debug true ******");
System.out.println("get attributes for pool - " +
dbAlias);
System.out.println( dbDriver);
System.out.println( dbUrl);
System.out.println( dbUsername);
System.out.println( dbPassword);
System.out.println( dbMaxConnections);
System.out.println( dbIdleTimeout);
System.out.println( dbCheckoutTimeout);
}
}
return connection;
}
}
then in jsp...
/* get a connection from the pool with the given alias */
ConnectionPool pool=
(ConnectionPool)getServletContext().getAttribute("myConnection");
Connection conn = pool.getConnection();
...
/* for completeness */
/* return the connection to the pool */
pool.returnConnection((PooledConnection)conn);
you need to define the servlet in your web.xml, define the paramters for your connection and set load-
on-startup
also to support multiple pools, just have multiple entries in your web.xml, but using the same servlet-
class
--norm
I'm in the prosses of setting up a pool, and used your advice. But I don't
understand the following part of the StartupConnectionPoolServlet.
if (getConnectionInfo() )
{
//DriverManager.registerDriver((Dr
iver)(Class.forName(dbDriver)));
if( debug)
System.out.println("adding alias to mgr - " + dbAlias);
poolMgr.addAlias(dbAlias,
dbDriver, dbUrl, dbUsername, dbPassword,
dbMaxConnections,
dbIdleTimeout, dbCheckoutTimeout);
if( debug)
System.out.println("setting pool on session - " + dbAlias);
pool = poolMgr.getPool( dbAlias );
getServletContext().setAttribute(
dbAlias, pool);
}
I don't understand why the addAlias() and getPool() methods are both used within
a debug block. These methods seem pretty essencial to me. Esspecially with the
registerDriver commented. I'm not an expert yet, and cannot figure out how I
should reconfigure this servlet to make it work for me. Can you shine your light
on the matter?
Thanks, Joost
Joost
Thanks,
Joost
why create a new bean? you can put any Object in the servlet context.
Cheers,
Joost
I'm not quite sure what you are asking for. what do you have
working so far, and what is not working? Also I'm not familiar
with COBRA.
maybe it's a good idea to also reply to one of the guys above,
since they have way more experiance than I do. But I'll see what
I can mean for you.
cheers,
Joost.
Is there any way to change/set owner of a file that is uploaded, before it's
saved to the filesystem?
Location: http://www.jguru.com/faq/view.jsp?EID=543979
Created: Nov 9, 2001
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Henrik Bengtsson
(http://www.jguru.com/guru/viewbio.jsp?EID=536810
No, but once it's written you can spawn a "chown" using Runtime.exec. It's up to
your OS whether it will let you do that, however. Search the Servlets and Tomcat
FAQs on "user permissions" and the like for more help.
Short answer: you can't, at least not directly. However, you can share data across
sessions on your own by using the "application context."
See also
• Is there any way to retrieve all of the active session ids on a server? The
HttpSessionContext interface used to provide methods to do this, but has
since been deprecated in the 2.1 API.
• How can I find out the number of live sessions within my servlet engine using
either JSP or servlets?
• How can I join a session with a given sessionId without using cookies?
Assume I get the session from the HttpSessionContext passing the session Id.
• What is the difference between request attributes, session attributes, and
ServletContext attributes?
----------------------------------------
Since both ServletContext and HttpSession are interfaces, how thread-safe they
are depends on their implementations.
That said, I wouldn't think that you would have to worry about this issue much.
Since HttpSession objects are unique to each user, you probably won't be accessing
any of these with more than one thread at the same time. As for ServletContext
objects - nearly all the methods are read methods. And since the only objects you
will be putting in the ServletContext are application wide in scope, you will
probably want to put these in at the apps startup anyway and read them from that
point on.
--------------------------------
If you're using a Servlet 2.3 container, create a HttpSessionListener that puts each
new Session object in a Collection on sessionCreated() and takes it out on
sessionDestroyed(). Your administrator user can retrieve that Collection (you would
probably want store it in the Application Context), and do things with the Sessions
like list them, invalidate them, etc.
I have got this error when I tried to access the Tomcat welcome page at
http://localhost:8080 using Tomcat 4.0.
The server starts up fine. The error comes up when I access the welcome
page. All my other JSP codes residing in Tomcat cannot be access as a result
of this problem.
I have tried to reinstall the entire Tomcat Server and JDK 1.3 to ensure that
everything is the default setting but the problem still persists. This problem
came all of a sudden. There was no problem at all in the first place.
Location: http://www.jguru.com/faq/view.jsp?EID=568095
Created: Nov 30, 2001
Author: Perry Tew (http://www.jguru.com/guru/viewbio.jsp?EID=60814) Question
originally posed by Sad Guy (http://www.jguru.com/guru/viewbio.jsp?EID=547265
This is caused by mismatched versions of jars used by Tomcat. I've encountered this
error before when I've done upgraded tomcat and failed to remove old jars from my
classpath ( like servlet.jar, etc). It happens when tomcat attempts to call a new
method that is not found in older jars. If you download a fresh version of tomcat and
copy over your existing jars, you should sync up your system. A better idea would be
to download a fresh version of tomcat and just use that version completely.
How can I suppress the parameters from displaying in the URL? For
instance, if I pass in a password, I don't want it to show up in the address
bar.
Location: http://www.jguru.com/faq/view.jsp?EID=586493
Created: Dec 16, 2001
Author: Mathias Neuhaus (http://www.jguru.com/guru/viewbio.jsp?EID=131203)
Question originally posed by Radhe Yanamandra
(http://www.jguru.com/guru/viewbio.jsp?EID=579307
Simply use POST method for submitting the form instead of GET.
Note there's no way to suppress parameters when using GET; that's the way the
parameters are passed - as part of the URL, which the browser displays.
Oh, may be there is a way... Use a REDIRECT to tell the browser to fetch another
page (you'll have to "remember" the parameters from the first request though!).
Alex
Author: Alexandros Kotsiras (http://www.jguru.com/guru/viewbio.jsp?EID=397266),
Dec 21, 2001
You can always use a dummy frame, this is a frame with zero size and include all
your pages in a frameset. This way there is no query string in the url, but a savvy user
can easily find the url that hits the data page without the frameset
In subsequent pages:
(In fact direct access to pages can be prevented if the user is not logged in by
verifying if the session value is null or not)
HttpSession session = request.getSession(false);
String passwd = (String)session.getValue("PASWD");
You could store these on the session, of course, but there may be reasons you don't
want to do that. For example, sometimes you want to pass forward a parameter that is
specific to the page being displayed. These kinds of parameters you don't want to put
on the HTTP session, and for this reason: if the user goes past this page into another
page that sets the parameter to something else, then backs up using his browser
"back" button and refreshes the page, you will have the later value, not the correct
page-specific value.
For these cases, you can use a URL encryption algorithm. Take a look at many
financial sites and you'll see a URL that looks something like:
http://foo.com?876sdf=SDS987987SDF
They are encrypting the URL parameters to pass some "secret" information. It's a little
more work of course, since you have to decrypt them on the way out. But it can be a
handy mechanism.
What are the steps that I need to follow to deploy my servlet in WebLogic
6.1?
Location: http://www.jguru.com/faq/view.jsp?EID=586701
Created: Dec 17, 2001
Author: Samiul Karim (http://www.jguru.com/guru/viewbio.jsp?EID=523694)
Question originally posed by Saravanan Devaji Rao
(http://www.jguru.com/guru/viewbio.jsp?EID=383486
2. Create inside this the structure reqd. as per Servlet 2.2 API viz.
MyAssignment
|
--WEB-INF
|
--classes
3. Place ur HTML,JSP files in MyAssignment folder(or any folder inside it but outside
WEB-INF folder).
4. Place your compiled servlet class file inside classes folder (or any folder inside it.
Just use packages in that case).
<servlet-mapping>
<servlet-name>CounterServlet</servlet-name>
<url-pattern>/CounterServlet/*</url-pattern>
</servlet-mapping>
</web-app>
7. Copy the entire structure and place it inside the applications folder of Weblogic.
[You can also cd to your project directory ("MyAssignment") and use jar, as
jar cf ../myassignment.war *
Then use the WebLogic deploy tool inside the console to deploy the WAR (the console
is available in http://localhost:7001/console/ -A]
Comments and alternative answers
I believe that web-app_2.2.dtd is misspelled and you can verify it at this page:
J2EETM — DTDs.
• http://java.sun.com/j2ee/dtds/web-app_2_2.dtd
• http://java.sun.com/j2ee/dtds/web-app_2.2.dtd
Maybe this is to prevent errors for misspelled web.xml like the one that you found.
I've made a diff between them and contents are identical, so no problem may occur,
but it's better to make things right.
seems wrong
Author: shan fu (http://www.jguru.com/guru/viewbio.jsp?EID=241378), Apr 9, 2002
show refer to HttpServletRequestWrapper
To answer the original question, you can use a standard way to notify servlets
further-down the 'forward-chain' that they have been forwarded-to by placing an
object in the request 'attributes'. Each action can check this attribute against, say,
null, and if it is non-null, then it can assume that it was a forward from another
servlet, not an original request from a client's browser.
-chris
When two or more people are using my servlet, why does everyone see the
data for the person who has logged in latest?
Location: http://www.jguru.com/faq/view.jsp?EID=594540
Created: Dec 23, 2001
Author: Norman Hanson (http://www.jguru.com/guru/viewbio.jsp?EID=462048)
Question originally posed by Gajanan Koparde
(http://www.jguru.com/guru/viewbio.jsp?EID=592587
[It's probably because you're using instance variables to store data. Instance
variables are dangerous in a servlet. Use session attributes instead. -Alex]
If you still want your servlet multithreaded, try creating the data Object in one
request (doGet), add the data Object to the users session, then forward to the
second servlet where you pick up the object.
There are probably two questions here: Can you put all your code in the doXXX
method(s) and Should you put all you code in the doXXX method(s).
As for the first part - yes, you can put all the code in your servlets. However, you
need to be aware of a couple of things. First, this obviously limits your servlet to a
specific task. This is fine if this is what you are wanting. Also, know that servlets are
not thread-safe unless it explicity implements SingleThreadModel, so you don't
want any unsychronized access to a class-scoped attribute. In fact, you are probably
best not using any "non-constant" class-scoped attribute. You are safer creating
attributes at the method level and passing them as parameters. As for your question
of how you return a ResultSet from a public void doXXX method - you can't.
Instead, you would probably place this object in the request/session as so:
...
ResultSet rs = loadData();
req.getSession().setAttribute("resultSet", rs);
...
Now the object can be retrieved from the request/session by another servlet of JSP.
Now, for the second part - should you do all the work in the servlet class. Well, this
depends. If you application is fairly simple, you can get away with this because you
won't have that much code to maintain. However, once your application becomes
somewhat complex, you probably want to employ the Front Controller Pattern.
Basically, this is a single servlet that intercepts all application requests and forwards
them to other classes to be processed. This pattern has several advantages:
For more on this pattern and other J2EE patterns, go to Sun's J2EE Patterns Catalog.
[Make sure to also read the forum thread where this question was posed for more
advice. -Alex]
Is it better to have lots of methods to my servlet, or to keep the code inside the
doGet or doPost method?
Author: shivangi gupta (http://www.jguru.com/guru/viewbio.jsp?EID=762763), Feb
18, 2002
According to me keeping a code inside doGet() /doPost() is best idea . Because in this
way we can follow the oops concepts by encapsulating things without showing what's
going on. if we define whole methods outside it will lead to low cohesion which is
bad practice
Now the purpose of this approach is to make your code portable across different
vendor for parsers.
How can i specify a system property out side the servlet so that createXMLReader()
can get it on its own...thus true vendor independence can be obtained???
---------------------------------
Answer: Most servlet engines allows you to pass parameters to the VM when its
starting. Find out how your servlet engine does this and pass:
-Djavax.
xml.parsers.SAXParserFactory=qualified.name.of.parserfactory
[This will probably be in the servlet container's startup script. E.g. for Tomcat this will
be either tomcat.sh, tomcat.bat, catalina.sh, or catalina.bat. For WebLogic it is
startWebLogic.bat. Etc... -Alex]
Alternative solution
Author: Giles Paterson (http://www.jguru.com/guru/viewbio.jsp?EID=806029), Mar
21, 2002
JAXP looks in the following places when trying to locate a factory:
For a truly neutral configuration method, option 3 is your best bet. It is the method I
use, and it works flawlessly.
As I make use of SAX, DOM and Transformers, I have three files in the META-
INF/services directory:
javax.xml.parsers.SAXParserFactory
javax.xml.parsers.DocumentBuilderFactory
javax.xml.transform.TransformerFactory
each of these files contain a single line, specifying the appropriate implementation
class to use.
I read the section on Filters and the spec seems to be silent on some
issues... Can you clarify?
Location: http://www.jguru.com/faq/view.jsp?EID=594562
Created: Dec 23, 2001
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
Taruvai Subramaniam (http://www.jguru.com/guru/viewbio.jsp?EID=23676
1. Can a filter attach new objects to the request without having to create a request
wrapper. I have no need to override any methods in request just make available
some objects downstream to other filters and the servlet.
4. Is there any way to create a filter chain on the fly? I have to string together a
number of reusable components. But which ones I use will depend on some
parameters in the URL.
--------------------------------------------
Answer:
Let me try to give you some answers or, better, the way I interpret the specs.
1) Yes, I definitely think so. You have both the request and response objects and so
you should be able to attach objects in the request scope with setAttribute(String,
Object).
2) I think that the better way to discover that is to try. Personally I think that for the
scenario you have described, the servlet container will get the exception halting the
process.
3-4) Yes, you should be able to achieve what you need, maybe trying to create some
kind of filter factory and chain the created filter to the one you need.
It looks like an interesting thing to try... As soon I have some free time, I'm going to
try it myself.
Our servlet program needs to read an image file (*.jpg or gif) and create
thumnail files. Is there any program available I can use ?
Location: http://www.jguru.com/faq/view.jsp?EID=594565
Created: Dec 23, 2001
Author: Denis Navarre (http://www.jguru.com/guru/viewbio.jsp?EID=495283)
Question originally posed by Jason Peng
(http://www.jguru.com/guru/viewbio.jsp?EID=533294
You'll find how to read and write some image formats. How to apply some effects.
And if I remember well, you can save the image with different sizes.
JPEG thumbnails
Author: Mathias Neuhaus (http://www.jguru.com/guru/viewbio.jsp?EID=131203),
Jan 8, 2002
I used the Independend JPEG group's JPEG-library via JNI for this.
The decompress-function has a parameter to extract every 2nd, 4th or 8th pixel. Just
compress the resulting bitmap to a new JPEG and return that as a byte [] to the
Java-program.
Pretty fast, no fiddling with Images and the IJGs implementation can easily be
replaced by Intel's JPEG-library.
ImageMagick
Author: Fredric Palmgren (http://www.jguru.com/guru/viewbio.jsp?EID=1092794),
Mar 31, 2004
What about imageMagick (http://www.imagemagick.org/) do anyone has any
experiances with it?
How to check for the validation of a Unix login username and password from
Java?
Location: http://www.jguru.com/faq/view.jsp?EID=594578
Created: Dec 23, 2001
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Kady Ny (http://www.jguru.com/guru/viewbio.jsp?EID=512473
How to check for the validation of a Unix login username and password from
Java?
Author: Omindra Rana (http://www.jguru.com/guru/viewbio.jsp?EID=1164665), Jun
6, 2005
just open the password file from the root directory and fetch data(login and password)
from that file. But u must have root permission for that.
Omindra Rana
Yes, but you have to use JNI. See the JNI FAQ for help on using JNI. Also, see your
servlet engine's documentation for help on how to set up the environment
(environment variables, where to place the library files, etc.) so JNI will be able to
work inside the servlet container.
Comments and alternative answers
out.println("<scriptlanguage=\"JavaScript\" >");
out.println("<!-- hide from old browser...");
I have an array in servlet that need to be copied to a new array in the javascript,
how do I do that?
-----------------
Normally, the result of servlet is an HTML page, which might contain JavaScript.
So you can not copy contents of servlet variable to javascript variable directly like in
following code
The following code is actually creating javascript code which is then executed at
client browser.
How can I access one servlet method from some other servlet in same
context?
Location: http://www.jguru.com/faq/view.jsp?EID=722714
Created: Jan 16, 2002
Author: Bozidar Dangubic (http://www.jguru.com/guru/viewbio.jsp?EID=433955)
Question originally posed by yasin yasin
(http://www.jguru.com/guru/viewbio.jsp?EID=403197
You do not call methods on the servlet from other servlets. If you need to perform
some functionality in many servlets, put that functionality in some other object that
you can create from both servlets. Servlets are request-response mechanism and not
just regular java classes that you call methods on it.
Comments and alternative answers
SOAP as a remedy
Author: Oliver Lau (http://www.jguru.com/guru/viewbio.jsp?EID=729942), Jan 22,
2002
Well, you *can* use other servlets' functionalities from some servlet. Enter SOAP.
For a broad overview please go to
http://developer.java.sun.com/developer/technicalArticles/xml/webservices/
Example:
I would like to put this String: "até" The problem is when I get the cookie value I
receive "at".
----------------------
URLEnocder.encoder(str);
In a request object you can store, on the server side, some object that can be useful
during the processing of your pages. This uses request.setAttribute() and
request.getAttribute().
Remember that the life of the request object lasts through all the include and
forwards, and ends when the page has been sent back to the browser.
The getParameter() method, instead, will return you the specific parameter that has
been passed to the page through GET or POST.
Location: http://www.jguru.com/faq/view.jsp?EID=738277
Created: Jan 29, 2002
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
SMPS SMPS (http://www.jguru.com/guru/viewbio.jsp?EID=738243
Hi,
You can change the "timeout" value in two ways.
The XML DOCTYPE headers are missing from your web.xml file.
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
Or...Is WEB-INF all capital case (sorry if I ask you this question, but this could be one
cause of the problem).
[Note that this error would not cause a problem in some older servlet engines.
Specifically, I'm pretty sure Tomcat 3 was not so strict. This is a "gotcha" when
upgrading from Tomcat 3 to Tomcat 4. -Alex C]
web-app declaration
Author: L B (http://www.jguru.com/guru/viewbio.jsp?EID=743001), Feb 1, 2002
I got the same sort of error message, but that was because of the fact that the DTD is
more strict in the sequence of elements. I had a <taglib> directive declared before
<servlet> and that will do for Tomcat 3.* but not for 4.0! I had to move it after the
<servlet> directive.
</web-app>
and here is the error I get when I run Tomcat,
PARSE error at line 23 column -1 org.xml.sax.SAXParseException:
Element "servlet-mapping" allows no further input; "url-pattern"
is not allowed.
Using JSP I can use implicit object exception when my JSP page is declared
with <%@ page isErrorPage="true" %> directive. But how to get this
reference programmatically, for example with a servlet ?
Location: http://www.jguru.com/faq/view.jsp?EID=740991
Created: Jan 30, 2002
Author: Luigi Viggiano (http://www.jguru.com/guru/viewbio.jsp?EID=101985)
Question originally posed by Luigi Viggiano PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=101985
It is possible to get a reference to the exception even if our page is not declared with
isErrorPage="true" attribute, or inside a servlet.
The Java Servlet Specification Version 2.3 / JSP 1.2 (paragraph SRV.9.9.1
"Request Attributes"), introduced a new request attribute to get the exception
object. So you can write following code with any Servlet container implementing
Servlet specifications 2.3 / JSP 1.2 (i.e. Tomcat 4):
Throwable exception =
(Throwable)request.getAttribute("javax.servlet.error.exception");
If you are using Servlet specifications 2.2 / JSP 1.1 (i.e. Tomcat 3.x) you can
explore JSP generated code to discover that it does a similar thing to get the
exception object within a JSP error page:
Throwable exception = (Throwable)
request.getAttribute("javax.servlet.jsp.jspException");
as specified in the JavaServer Pages™ Specification (paragraph 2.2.2 "Client Request
Time Processing Errors" page 38, see also pag. 47).
This should work in all JSP 1.1. engines, and Servlet 2.2 containers.
You need to be notified by the web server when the session expires. To do that you
need to implement the HttpSessionListener (Servlet 2.3 spec) interface and configure
it in the deployment descriptor of the web application. If you have an older Servlet
container (implementing Servlet 2.2 spec) you can implement
HttpSessionBindingListener and put it in session, so when the object is unbound.
Example:
}
Note: I've not included exception handling, but you'll need to do.
So in your JSP you'll put the object in session to create the connection (this is just an
example):
<%
session.setAttribute("connHolder", connHolder);
%>
Then to use it:
<%
MyConnectionHolder connHolder =
(MyConnectionHolder)session.getAttribute("connHolder");
Connection conn = connHolder.getConnection();
%>
When the session expires, the connection will be closed automatically.
[That is, if you use a ConnectionPool, then you don't have to worry about when the
session ends. You just release it when the *query* ends (or the Request). - Alex]
Session Expiration
Author: Bharadwaj Iyer (http://www.jguru.com/guru/viewbio.jsp?EID=1067952), Apr
8, 2003
I ve been facing the same problem. Will the class in which the HttpsessionListener
has been implemented called automatically or should we have to invoke it explicitly.
If we have to invoke explicitly then how to go about it?
Try
String getFullURL(HttpRequest request) {
StringBuffer url = request.getRequestURL();
if (request.getQueryString() != null) {
url.append('?');
url.append(request.getQueryString());
}
return url.toString();
}
How can I unit test my servlets?
Location: http://www.jguru.com/faq/view.jsp?EID=744086
Created: Feb 2, 2002
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Alex Chaffee PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=3
You may want to look into HttpUnit for doing unit testing, esp. the ServletUnit
section. It's integrated with JUnit and allows you to do programmatic testing of
servlets in-process or remotely -- i.e. check response text or response codes or
whatever you like.
Comments and alternative answers
It's probably a server bug. Make sure you are using the latest version of your servlet
container, and check the bug reports. Also, try running your code on a different
server (e.g. standalone Tomcat 4.0.1 (not running behind Apache -- see below)) to
see if the error still happens.
See the forum thread for more information: Why can't I upload image files using
com.oreilly.servlet.multipart.FilePart in my servlet (running with Tomcat) ?
What's the initial user name and password for Jakarta Tomcat 4's admin
tool?
Location: http://www.jguru.com/faq/view.jsp?EID=757542
Created: Feb 13, 2002 Modified: 2002-09-03 00:50:24.848
Author: gunther van roey (http://www.jguru.com/guru/viewbio.jsp?EID=710858)
Question originally posed by Jason Peng
(http://www.jguru.com/guru/viewbio.jsp?EID=533294
As far as I know, there is no user that is assigned the 'admin' role after an
installation of tomcat. (For security reasons I assume).
You can assign this role to a username/password combination of your choice in the
/conf/tomcat-users.xml file.
Regards,
Günther.
What's the initial user name and password for Jakarta Tomcat 4's admin tool?
Author: Chuck Heinle (http://www.jguru.com/guru/viewbio.jsp?EID=20906), Feb 21,
2002
Actually, I have the same question. As I was skimming the docs on the Jakarta site, it
mentions a "manager" for deploying/undeploying, that prompts for a user/password.
Leaving them blank does not permit entry. http://localhost:8080/manager I assume
this is what the first posting was referring too.
Re: What's the initial user name and password for Jakarta Tomcat 4's admin
tool?
Author: Han Steenwijk (http://www.jguru.com/guru/viewbio.jsp?EID=763110),
Feb 21, 2002
Yes, that is what the web.xml for the "manager" application says.
But after I entered a user with the role "manager" in tomcat-users.xml I got the
message: "Failed unknown command".
Re[2]: What's the initial user name and password for Jakarta Tomcat 4's
admin tool?
Author: Chuck Heinle (http://www.jguru.com/guru/viewbio.jsp?EID=20906),
Feb 21, 2002
I have just started to use this...but I have found that you have to enter a
command after the base URL...such as list, install, remove, etc...
http://localhost:8080/manager/list I found this link to be helpful...
http://localhost:8080/tomcat-docs/manager-howto.html
Re: What's the initial user name and password for Jakarta Tomcat 4's admin
tool?
Author: Han Steenwijk (http://www.jguru.com/guru/viewbio.jsp?EID=763110),
Feb 22, 2002
You're absolutely right. Thanks for helping me out.
Like the introduction on the Tomcat documentation states "There's nothing like
scouring the web only to find out that the answer was right in front of you all
along!"
Re[2]: What's the initial user name and password for Jakarta Tomcat 4's
admin tool?
Author: hitesh shah (http://www.jguru.com/guru/viewbio.jsp?EID=768705),
Feb 23, 2002
Hi, i just entered following line in tomcat/conf/tomcat-users.xml file
Re[3]: What's the initial user name and password for Jakarta Tomcat
4's admin tool?
Author: Paul Brinkley
(http://www.jguru.com/guru/viewbio.jsp?EID=461720), Jul 25, 2002
For REALLY low security, this line seemed to work too:
<user name="" password="" roles="standard,manager"/>
Re[4]: What's the initial user name and password for Jakarta
Tomcat 4's admin tool?
Author: Jp Encausse
(http://www.jguru.com/guru/viewbio.jsp?EID=971400), Jul 31, 2002
Is there a way to have a silent / quiet login ? I want to do a reload of my
webapp On tomcat 3.x you just have to touch web.xml On tomcat 4.x
you have to call the manager with reload command Like you say it
popup a dialog, I don't want it, I want an automatic login. Any Idea ?
Best Regards, Jp
Re[3]: What's the initial user name and password for Jakarta Tomcat
4's admin tool?
Author: Marian Skalsky
(http://www.jguru.com/guru/viewbio.jsp?EID=927231), Sep 3, 2002
Helped!
Thanx!
Re[4]: What's the initial user name and password for Jakarta
Tomcat 4's admin tool?
Author: Mark Doe
(http://www.jguru.com/guru/viewbio.jsp?EID=1037812), Dec 13, 2002
Once I restarted Tomcat, changes to the tomcat-users.xml mentioned
above worked.
<role rolename="admin"/>
<user username="system" password="password" roles="admin"/>
Re: I tried this and am still being prompted for logon credentials
Author: Chris Radabaugh
(http://www.jguru.com/guru/viewbio.jsp?EID=1153447), Mar 11, 2004
This worked for me, found at UCL computing site.
Enabling the Administration and Manager services
Tomcat can be configured in detail by directly working with the files in your
tomcat directory and sub-directories. However, there are also web-based
applications that run within the server to make managing tomcat easier.
These are: The Administration application for managing the server and users. The
Manager application for managing applications running on the server. These
applications can be accessed by setting up a tomcat user with the correct access
priviliges. Do this by locating the file tomcat/conf/tomcat-users.xml in your local
tomcat installation. By default the file contains:
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="tomcat"/>
<role rolename="role1"/>
<user username="tomcat" password="tomcat" roles="tomcat"/>
<user username="both" password="tomcat" roles="tomcat,role1"/>
<user username="role1" password="tomcat" roles="role1"/>
</tomcat-users>
Each line starting <user ... is specifying a tomcat user, their password and their
roles (what services they can access). Add the following line just before the last
line:
<user username="admin" password="tomcat" roles="admin,manager"/>
This will set your tomcat username to admin and the password to tomcat. You can
replace these with any username/password you like but do not use your Computer
Science login/password.
Then save the file and restart the web server (./shutdown followed by startup). On
the main index page you can then click the Administration links (Tomcat
Administration and Tomcat Manager), login and access the services. When
logging in you will be prompted for the username and password set in the user
configuration above - don't use your CS login.
The tomcat Manager service is most likely to be useful as you can load, start, stop
and remove web applications without having to continually stop and start the
server."
Re[2]: I tried this and am still being prompted for logon credentials
Author: Jorge Bittencourt
(http://www.jguru.com/guru/viewbio.jsp?EID=1182143), Jun 28, 2004
Hi there: I´ve tried everything mentioned above, but no matter what passwords
I enter in the tomcat-users.xml, I can´t get authenticated when I access
http://localhost:8080/manager (or manager/list, etc) or
http://localhost:8080/admin. I´ve tried restarting Tomcat many times after
changing the file, but still no authentication. Does anybody have any ideas on
what could go wrong? Thanks in advance. Jorge
Re[3]: I tried this and am still being prompted for logon credentials
Author: r ruedeberger
(http://www.jguru.com/guru/viewbio.jsp?EID=1192902), Aug 13, 2004
Hi, I just followed the example of Chris Radabaugh, from Mar 11, 2004 (is
the arcticle before yours) - and it was successful. What really has to be kept
in mind, is to shutdown.sh and startup.sh tomcat again, after the file:
"tomcat-users.xml" has been changed. It looks tomcat reads this file only
once during startup. Hope for success, JR
Re[4]: I tried this and am still being prompted for logon credentials
Author: r ruedeberger
(http://www.jguru.com/guru/viewbio.jsp?EID=1192902), Aug 13, 2004
I would like to add: to get into "Administration Tomcat Manager", I had
to make a "tomcat-users.xml" w/o the lines defining the "admin" - like
this:
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="tomcat"/>
<role rolename="role1"/>
<role rolename="manager"/>
<user username="tomcat" password="tomcat" ;roles="tomcat"/>
<user username="role1" password="tomcat" roles="role1"/>
<user username="manager" password="manager" roles="manager"/>
</tomcat-users>
... and then start tomcat by "startup.sh", "http://127.0.0.1:8080" on
browser and went into "Administration" | "Tomcat Manager"
assigning the appropriate user/ passwd for manager.
So I was able to get into that function, but to use "Administration" |
"Tomcat Administration",
I stopped tomcat by "shutdown.sh" and changed the file "tomcat-
users.xml" to (includes now "admin"):
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="tomcat"/>
<role rolename="role1"/>
<role rolename="manager"/>
<role rolename="admin"/>
<user username="tomcat" password="tomcat" roles="tomcat"/>
<user username="role1" password="tomcat" roles="role1"/>
<user username="manager" password="manager" roles="manager"/>
<user username="admin" password="tomcat" roles="admin"/>
</tomcat-users>
... started tomact again by "startup.sh", "http://127.0.0.1:8080" on
browser and went into "Administration" | "Tomcat Administration" to
input the appropriate user/ passwd.
From now on I could use both the menues/ functions "Tomcat
Administration" and "Tomcat Manager" -
but was never asked again for a password for "Tomcat Manager". I
reproduced this way a few times - very, very strange, but it works.
Maybe it helps others too, JR.
P.S.:I'm using tomcat from the SuSe 9.0 distribution.
Using WebLogic 6.1, why can't I load a servlet from a JAR file in my /WEB-
INF/lib directory?
Location: http://www.jguru.com/faq/view.jsp?EID=759427
Created: Feb 14, 2002
Author: JIA Java Italian Association
(http://www.jguru.com/guru/viewbio.jsp?EID=414973) Question originally posed by
Gary Bisaga (http://www.jguru.com/guru/viewbio.jsp?EID=757704
He said: "Jar files in the WEB-INF/lib directory must only contain one period (full-
stop) in their filenames, so opencms-db-1_4_0.jar works but opencms-db-1.4.0.jar
doesn't."
Can I have some simple code for my own connection pooling class?
Location: http://www.jguru.com/faq/view.jsp?EID=759672
Created: Feb 14, 2002
Author: Christopher Schultz (http://www.jguru.com/guru/viewbio.jsp?EID=138382)
Question originally posed by nimit shah
(http://www.jguru.com/guru/viewbio.jsp?EID=459796
_connection = connection;
notify();
}
}
This will get you by in a pinch. Code to this interface and then expand the class to
include more connections, probably in a "real" data structure like a queue.
If you change your implementation but not your interface (except maybe your
constructor), you should not have to change any of your servlet code.
-chris
How can a servlet refresh automatically if some new data has entered the
database?
Location: http://www.jguru.com/faq/view.jsp?EID=759758
Created: Feb 14, 2002 Modified: 2002-02-15 16:15:16.173
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by R Mahadevan
(http://www.jguru.com/guru/viewbio.jsp?EID=750208
No easy way.
You can use a client-side Refresh or Server Push -- see What is server push? How do
I use it from a servlet?
You also have to figure out how to ask the database if something changed, on the
servlet-side. You're on your own for that :-) See the JDBC FAQ for help. You probably
have to spawn a thread that periodically does an SQL query.
When I describe the servlet mapping in the web.xml file the url-pattern
"/*" means "match all requests". Can I specify the url-pattern like "match
all except *.jsp" ?
Location: http://www.jguru.com/faq/view.jsp?EID=768872
Created: Feb 22, 2002 Modified: 2002-02-24 20:33:18.055
Author: JIA Java Italian Association
(http://www.jguru.com/guru/viewbio.jsp?EID=414973) Question originally posed by
Denis Morozov (http://www.jguru.com/guru/viewbio.jsp?EID=733306
1) first, does the url-mapping of "/" catch all requests or should it be "/*"?
2) second, without declaring them explicitly, are the 'default' and 'jsp' servlets
(from Tomcat's web.xml) known to the web application deployment descriptor?
Or do I have to re-declare them in the web.xml for each web app?
3) According to the spec, order doesn't matter (most specific wins instead). Please
confirm.
4) I'm trying to serve requests from a given servlet, except for those within certain
folders. E.g.
\myapp
\images
\private
\WEB-INF
with the following mappings:
<!-- Catches all requests -->
<servlet-mapping>
<servlet-name>MyApp</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Per
You have:
<url-pattern>/images</url-pattern>
You need:
<url-pattern>/images/*</url-pattern>
2. JSP mapping
When Tomcat matches a url-pattern it seems to eat up all the paths that match
so that given your url-pattern of "/private/*.jsp", the following would happen:
Now that JSP servlet will match _any file_ ending in .jsp and pass in the
appropriate full path.
So "http://example.org/private/foo.jsp" gets handed to the JSP servlet as
"/private/foo.jsp"
<!-- Make sure HTML, JS, and CSS files get handled
by the default servlet, no matter where they are
-->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<!-- Make sure all JSP files are handled by the JSP
servlet no matter where they are -->
<servlet-mapping>
<servlet-name>jsp</servlet-name>
<url-pattern>*.jsp</url-pattern>
</servlet-mapping>
In order to run Struts, do I need to install a servlet container such as
Tomcat?
Location: http://www.jguru.com/faq/view.jsp?EID=771298
Created: Feb 25, 2002
Author: Aron Tunzi (http://www.jguru.com/guru/viewbio.jsp?EID=446077) Question
originally posed by Nguyen van Tin
(http://www.jguru.com/guru/viewbio.jsp?EID=761500
Code comment..
Author: Fredric Palmgren (http://www.jguru.com/guru/viewbio.jsp?EID=1092794),
Mar 31, 2004
It seems like the right code would be:
boolean containsKey = request.getParameterMap().containsKey(param);
It would also be possible to ask for a value of the supplied key(param) using
boolean containsKey = request.getParameterMap().containsValue(param);
How do i get the name of the file from a file upload form?
Location: http://www.jguru.com/faq/view.jsp?EID=771302
Created: Feb 25, 2002
Author: sachin thukral (http://www.jguru.com/guru/viewbio.jsp?EID=573922)
Question originally posed by ken lo
(http://www.jguru.com/guru/viewbio.jsp?EID=589625
Using Jason Hunter's O'reilly Servlet package, if you pass some parameter as query
String or hidden variable,then only by using Vectors I was getting parameters which
was passed from the previous page. Since in multipart forms Request.getPararmeter
does not work.
But it is possible to get filename of the file which is uploded (I suppose this is your
requirement).
Using iws.getWorkingDirectory will give you the current working directory. Now using
the following you can get the filename,just try the last one as well to get the
requested parameter(I'm not sure for the last line)
I put my JAR file inside WEB-INF/lib, but my classes are not getting found.
However, when i unzipped classes into WEB-INF/classes/, it works. What's
up?
Location: http://www.jguru.com/faq/view.jsp?EID=771307
Created: Feb 25, 2002
Author: Luigi Viggiano (http://www.jguru.com/guru/viewbio.jsp?EID=101985)
Question originally posed by ko ko
(http://www.jguru.com/guru/viewbio.jsp?EID=764398
Similar Problem
Author: Brendan Richards (http://www.jguru.com/guru/viewbio.jsp?EID=773717),
Feb 27, 2002
I'm getting a similar problem attempting to run cocoon2 on Tomcat 4.0.2.
(Impossibile trovare il percorso specificato -> Could not find specified path)
Where do I go wrong ?
David
http://www.mail-archive.com/[email protected]/msg24405.html
thanks,
I'm a beginer at JSP, but I have a good background in ASP what makes things a little
easier for me and I'm a Java programmer ( up to now, for hobby - PLEASE HIRE ME
IF YOU HAVE AN OFFICE IN BRAZIL - ;) and I have made some interesting things
with Java2, for example a Visual Program to build Applications in Java Swing -
Inspired in VB and Delphi, but much simpler... Let's go for the solution:
"This hint is for Windows users, under Linux I haven't tested it, so there's no
warranty. At least it can serve as a guideline..."
%CATALINA_HOME%\work\Catalina\localhost\_
Every JSP that you run is exported to this package as a java file, then it's compiled.
Add as the first line of the java source codes that you want to use the following
string:
package org.apache.jsp;
Now, when you call JSP pages, Tom kitty (I find Tomcat's logo very nice!) has the
class files in an accessible area to link to the new compilations.
I love open source and I knew a say that I liked very much:"The future is open".
I have a free upload component that I made for ASP programmers at
http://www.amorpositivo.com/download/index.asp
Sergio Almeida
You have to modify the build.xml file for your web application to put the lib
folder on the compilation classpath. You can do this by addding these:
<fileset dir="${basedir}/web/web-inf/lib">
<include name="*.jar"/>
</fileset>
lines in the build.xml file for your web application. This XML element should be
added in <path id="compile.classpath"> element.
I have been trying to find a way not only to get the user certificate info - i.e.
Authentication via DigitalID, but also to have a digest of the request, signed
by the client (Web Browser Only - not the Applet/Application case) or
something like that, so I can proove to a 3rd party that the user with the
specific certificate has issued the specific request. Is it at all possible?
Location: http://www.jguru.com/faq/view.jsp?EID=776825
Created: Feb 28, 2002
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Alexander Radev
(http://www.jguru.com/guru/viewbio.jsp?EID=769532
That's an interesting question. I'm pretty sure the answer is "no," at least not
without hacking the server. The request *is* signed by the client, effectively, but (a)
since it's SSL, what's signed is not the request itself, but the symmetric key used to
encrypt the request before it's sent, and (b) the Servlet spec doesn't expose any of
the mechanics of the SSL transaction anyway -- it just hands you an already-
authorized Principal.
No you can't. It's the container who manages the lifecycle of the sevlet not you. Also,
you must call super.init() for init() to work properly.
Comments and alternative answers
java
Author: kojma fer (http://www.jguru.com/guru/viewbio.jsp?EID=1032159), Nov 29,
2002
whats the difference between webserver and application server? why ejb programes
run in application server only why not in web server? how will u handle multiple
resultset objects?
Re: java
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Nov 30,
2002
See What are all the different kinds of servers? (Such as Web Servers, Application
Servers, etc)
no constructor in servlet
Author: shaik kalesha (http://www.jguru.com/guru/viewbio.jsp?EID=1102933), Sep
10, 2003
the reason for not using constrctor in servlet is we can't write constructors in
interfaces
Does Jserv support the following methods from Servlet spec 2.2?
Location: http://www.jguru.com/faq/view.jsp?EID=777589
Created: Feb 28, 2002
Author: Chandra Patni (http://www.jguru.com/guru/viewbio.jsp?EID=33585)
Question originally posed by Nigel Smith
(http://www.jguru.com/guru/viewbio.jsp?EID=458605
[or are these methods new to the servlet API since 2.0, as this appears to be the
latest version that JServ supports? My problem is that I have developed in using
Tomcat 4.0.1 (and hence servlet 2.3), and now have been given an Oracle server
which seems to use Jserv as the servlet engine. The above methods cannot be
found. Any ideas on how to get around this?. Please!]
For JServ, you can ues the following methods.
Once you install your servlet inside a servlet container like Tomcat, you can fetch the
results of the servlet by using a command-line tool like wget or curl (or write your
own HTTP client -- it's not very difficult).
You can also use a tool like ServletUnit (part of HTTPUnit) that's a "bare-bones" on-
the-spot servlet runner. Be warned, though; it doesn't implement all the features.
Do you submit the form from the javascript? This can happen if you are calling the
javascript function which does document.formName.submit() but the form itself also
has an action attribute. Therefore, the form actually gets submitted twice. If you are
submitting the page from the javascript, remove the action attribute from the form
tag.
Comments and alternative answers
<script language="JavaScript">
function submitRequest() {
document.runReport.submit();
}
</script>
sir u have mentioned that Action attribute should not be used . Then, how i will
map my destination URLfrom the Javascript funtion.
function checkb4send()
{
if (...document.form1.fields are well filled...)
{return true;}
return false;
}
Additional info:
I'd like to organize my webapps in subdirectories of the tomcat/webapps/ directory. I
have right now a setup like:
/tomcat/webapps/<client>/application
The problem that I have is that those applications are not started automatically upon
tomcat startup. I do have the <load-on-startup> tags in my individual web.xml files
but it doesn't seem to do anything.
Unfortunately, this structure can't really work.
Tomcat, in fact, consider all the subdirectories under the webapps directory as
default contexts. In this case it considers all the <client> directories as contexts and
looks for the WEB-INF/web.xml for each of them.
So, in your design, Tomcat considers the client's directories (and not their
subdirectories) as web applications.
You can organize all your applications using that structure, but do not use the
webapps directory (use any other location) and you have to define all the context
manually in the server.xml, or just put all the applications in the webapps directory.
As specified by the documentation, this method returns the login of the user making
this request, if the user has been authenticated, or null if the user has not been
authenticated.
The authentication, in this case, is the http authentication.
Comments and alternative answers
How does one go about authenticating so that getRemoteUser() does not return
null?
Author: John Corro (http://www.jguru.com/guru/viewbio.jsp?EID=271751), Apr 23,
2002
How does one go about authenticating so that getRemoteUser() does not return null?
Re: How does one go about authenticating so that getRemoteUser() does not
return null?
Author: Gerard Fernandes
(http://www.jguru.com/guru/viewbio.jsp?EID=903300), Jun 4, 2002
You set up a Realm - See the Tomcat documentation for Realms and use that for
authentication. The default Realm in Tomcat is the Memory Realm where users
and administrators can be configured. Only a User with "manager" role assigned
can access the Tomcat Management application.
Re: How does one go about authenticating so that getRemoteUser() does not
return null?
Author: Joachim Aschoff (http://www.jguru.com/guru/viewbio.jsp?EID=904224),
Jun 5, 2002
If you use Tomcat with IIS as web server, it is possible to get the login name of the
client by using getRemoteUser, if the client is running windows. In the IIS
management console, go to the properties of the virtual directory "jakarta", select
the security tab and press edit. Uncheck anonymous access and check integrated
windows authentification. (How to configure IIS with tomcat is described
somewhere else ...). Calling getRemoteUser now returns the clients windows login
name. Joachim
<IfModule mod_webapp.c>
WebAppConnection conn warp localhost:8008
WebAppDeploy webappName conn /someOtherName/
WebAppInfo info
</IfModule>
- the trick is to make sure that your servlet URL has restrictions defined in
the httpd.conf file. Something like this:
<Location /someOtherName/>
AuthName "MainRealm"
AuthType Basic
AuthUserFile /opt/apache/users
require valid-user
</Location>
- now go to your servlet URL .http://localhost/someOtherName/...... you
will get a native browesr login popup and getRemoteUser() will return the
proper user on every request that is below that URL
Re: How does one go about authenticating so that getRemoteUser() does not
return null for websphere and weblogic?
Author: vivek kamble (http://www.jguru.com/guru/viewbio.jsp?EID=1138420),
Jan 12, 2004
Re: How does one go about authenticating so that getRemoteUser() does not
return null for websphere and weblogic?
request.getRemoteUser() = null
Author: Ar Ja (http://www.jguru.com/guru/viewbio.jsp?EID=1158024), Mar
27, 2004
I am using Tomcat Server3.3, even though I configured server.xml file like
<Ajp13Connector port="8009" tomcatAuthentication="false" I am getting
request.getRemoteUser() as null? Any help is highly appreciable Thanks Jac
Is this when the user aborts the process by clicking the browser's stop button, or
navigating to another link? At what point in the process is this exception thrown,
when the servlet attempts to send the response back to the browser?
<hr> Yes, it happens when the user clicks stop, or logs off, or otherwise prematurely
aborts the connection. It's nothing to worry about. It's a normal part of life on the
Web.
It can't.
The request-response nature of the HTTP protocol prevents us from sending "push"
data to the browser.
In a servlet, are the method variables are shared between several threads
or not?
Location: http://www.jguru.com/faq/view.jsp?EID=994203
Created: Sep 4, 2002
Author: Luc-André Essiambre
(http://www.jguru.com/guru/viewbio.jsp?EID=430486) Question originally posed by
Harry Angel (http://www.jguru.com/guru/viewbio.jsp?EID=993284
Variables declared in methods are never shared, whether these methods are static or
not...
[However, session variables are shared, and instance variables *may* be shared (or
may not, which means you shouldn't use them) - Alex]
confusion!!
Author: Harry Angel (http://www.jguru.com/guru/viewbio.jsp?EID=993284), Sep 5,
2002
"Variables declared in methods are never shared" "session variables are shared"
"instance variables *may* be shared (or may not, which means you shouldn't use
them)" There is much confusion! Who really knows java & servlet??
Re: confusion!!
Author: Jegadisan Sankar Kumar
(http://www.jguru.com/guru/viewbio.jsp?EID=992176), Sep 5, 2002
I am not sure why you find this confusing. It is quite simple actually.
public final class SomeServlet extends HttpServlet
{
private int instanceVariable;
The localVariable is created for each and every single thread. This is the same
for pretty much all the programming languages I have ever encountered (If anyone
has seen something else, please do correct me). Each thread usually has it's own
memory space, and they will allocate memory for the variable and store it within
their own memory space.
As for the sessionVariable, this variable is available to any servlet to which the
User visits. So, if the User were to visit another servlet, regardless of the thread
coz each request will spawn it's own thread, the session variable will be available
to the servlet.
Regards
Jega
Re[2]: confusion!!
Author: Jegadisan Sankar Kumar
(http://www.jguru.com/guru/viewbio.jsp?EID=992176), Sep 5, 2002
Oh yeah, just to make sure I provide you with the complete picture. When i
said the instanceVariable is available to any thread executing within the
doGet method, I was assuming that the Serlvet Engine only had one instance
of the SomeServlet in it's context.
If you want the instanceVariable to be shared among any and all possible
instances of the SomeServlet, you should declare it as static. If for example
you declared a variable like private static int staticVariable above or
below the instance variable declaration, then this staticVariable will be the
same for all the instances of SomeServlet that exists within the Servlet
Engine.
Just wanted to make sure I gave you all the info, and didn't leave you with a
misconception.
Regards
Jega
Re[3]: confusion!!
Author: Christopher Koenigsberg
(http://www.jguru.com/guru/viewbio.jsp?EID=722897), Sep 5, 2002
Re: confusion!!
Author: vikram shahi (http://www.jguru.com/guru/viewbio.jsp?EID=1020223),
Oct 31, 2002
Hey ... only the service method is used as a part of multi threads accross users.
Any variables created inside that, will have multiple copies, with values specific
to the users using it. Instance variables are not shared. And yes, set the variables
and their values as attributes in the HttpSession. And share it with as many
servlets u want, in the SAME session. Anybody correct me if i am wrong...
Clarficiations
Author: Samer Naser (http://www.jguru.com/guru/viewbio.jsp?EID=1022799), Nov
7, 2002
1- Static objects are always shared, there is one instance per application (i.e. process).
All threads within the process access the same instance. 2- Member variables within a
servlet are available to multiple threads, but only one thread at a time. This is because
threads reuse a servlet, but do not use it at the same time!
Re: Clarficiations
Author: Rasmus Pedersen
(http://www.jguru.com/guru/viewbio.jsp?EID=1007915), Nov 12, 2002
Does that mean that each thread in a sense creates its own "copy" of the doPost
method found in the single servlet instance? This "copy" has the effect that each
thread does not have to worry about simultanious access to variables only in the
scope of the doPost method?
Re: Clarficiations
Author: Steven Zacharias
(http://www.jguru.com/guru/viewbio.jsp?EID=1020313), Nov 12, 2002
This is because threads reuse a servlet, but do not use it at the same time!
That's not true, is it? In general, isn't there one instantiated object of a particular
servlet, and isn't it quite possible (even likely under any kind of load) that the
server's threads concurrently use that object?
In other words, wouldn't the following servlet pseudo-code frequently print out
differences under load?
class Silly {
java.util.ArrayList al_ = new java.util.ArrayList() ;
Re: Clarficiations
Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537),
Nov 19, 2002
Well, in case of Java, ClassLoaders can make the static fields non-shared.
There is no standard way for this. If you've studied the infrastructure for SMS (or
MMS) messaging, you would've noticed that there needs to be a gateway for sending
the SMS (or MMS). The API with which you ask the gateway to send a message
depends on the gateway vendor.
I'm not aware of an open-source SMS gateway, but you'll find some commercial
products with Google.
For example:
http://smsj.sourceforge.net/
http://www.sourceforge.net/projects/smsj
[You could store the Connection object somewhere, but that's] not a very good
approach anyway.
You better show a confirmation dialog before sending anything to server. You may
also put everything within a session (or hidden fields if you hate sessions) and do the
real update only on real confirmation.
Usually the word "distributed" refers to the system being composed of physically
separate parts where different logic is performed in different places.
A typical distributed web application is such that there is one "web server", which
hosts the View and Controller parts of the MVC pattern and a separate (or several)
"app server", which hosts the EJBs acting as the Model of the MVC pattern.
The advantage of this approach is the flexibility of the infrastructure. You can scale
the hardware only for the EJB layer if you want, you can locate the web server closer
to your enterprise network's edge while leaving the app server behind more firewalls.
[See the discussion forum thread for some interesting further discussion. -A]
The package javax.servlet is not in the standard J2SE libraries. It's included in
j2ee.jar or servlet.jar. You can find these by downloading J2EE or Tomcat
respectively.
Then add the JAR to your classpath and you're all set.
e.g <jsp-file>/index.jsp</jsp-file>
Now when you want to forward to a servlet that doesn't have a url-mapping in the
web.xml, you use getNamedDispathcer(servlet-name) else it should be the url-
pattern when you are using getRequestDispatcher(path).
This is what I have understood of it. The more hazy part is that even JSPs are
compiled into servlets at runtime. But these servlets are accessible without
specifying any url-pattern.
You must get the init-param from servlet and load it into the bean, either defining a
set method or passing it into the constructor. The init-param tag is for init
parameters for the servlets and JSP and not for JavaBeans. They have other ways to
load parameters (such as properties files and things like that).
[While the below works, for Tomcat 4 another answer is simply to add the attribute
reloadable="true" to the Context element for that webapp. Sometimes you don't
want all contexts to be reloadable. -Alex]
<!-- Define properties for each web application. This is only needed if you want to
set non-default properties, or have web application document roots in places other
than the virtual host's appBase directory. -->
and insert the following line just below it: <DefaultContext reloadable="true"/>
Be sure to make a backup copy of server.xml before making the above change.
See also
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jan 12, 2003
Restarting Tomcat after rebuilding a servlet
<Loader className="org.apache.catalina.loader.WebappLoader"
loaderClass="org.apache.catalina.loader.WebappClassLoader" checkInterval="3"
/>
By default reload takes place every 15 seconds. The above object should be placed
withing the Context element of your web-application.
Rommel Sharma
<form action="<%=pageContext.getServletContext()%>/doThis"
method="post">
But this seems like a round about way to go for something so simple. Am I
missing something here?
Location: http://www.jguru.com/faq/view.jsp?EID=1027662
Created: Nov 19, 2002
Author: Roger Hand (http://www.jguru.com/guru/viewbio.jsp?EID=292314)
Question originally posed by Taylor Sabine
(http://www.jguru.com/guru/viewbio.jsp?EID=1026487
[Short answer: No, unfortunately you need to actively make your URLs "context-
aware". Some frameworks make this easier for you, but I end up doing something
like you described. -Alex]
You can avoid a lot of the base path problems by having your forms submit to a jsp
page, and having that jsp page forward to the servlet. So your form submission
avoids all path problems:
<form action="MySubmitPage.jsp">
I started by making a dummy jsp page that did nothing but forwarded, but now I put
the forwarding action at the top of the jsp page with the form ... there's a small bit
of code that checks to see if the query includes the form variables from a form
submission. It the query vars (or, actually, a single "marker" var - see example
below) are there we forward to the servlet for processing. If not we display the page
with the form, ready to be filled in.
Since the browser sees the return url as being in the same dir as the original form
jsp page, all image links, etc., work correctly even though it's the servlet that's doing
all the work and then forwarding to the result page. (Of course if you do a redirect
you avoid the path problems too but you burn an extra trip to the browser.)
Of course this really just offloads the problem you bring up of the path to the servlet
... instead of the problem being in the action tag in the jsp code that forwards to the
servlet. To make my code portable I use something similar to the method you
suggest:
if ("true".equals(request.getParameter("_saveNew"))) {
String urlForward = pageContext.getServletContext()
+ "com.mycompany.editinfo.BeanSaveServlet";
%>
<jsp:forward page="<%= urlForward %>"/>
<%
return;
} //if saving data
/* We have no data to save; show the form. */
<html>
...
Note, however, that in many cases, you will receive null references--even if you
specify a valid context path. In most servlet containers, a context (web application)
must explicitly allow other contexts access to its ServletContext. For example, in
Tomcat, the crossContext attribute of the Context element of server.xml must be
set to true to allow other contexts to access this context. The Servlet specification
recommends this behavior for "security conscious" environments.
See also:
• Can two web applications (servlet contexts) share the same session object?
(which also has links to many other places it's answered)
response.sendRedirect(String)
Author: Andrew Postoyanets (http://www.jguru.com/guru/viewbio.jsp?EID=343575),
Nov 22, 2002
response.sendRedirect(String) works fine with relative URLs as of Servlet API
2.2
See J2EE 1.2.1 API Specification for
HttpServletResponse.sendRedirect(java.lang.String)
This method can accept relative URLs; the servlet container will convert the relative
URL to an absolute URL before sending the response to the client.
Re: response.sendRedirect(String)
Author: Michael Dean (http://www.jguru.com/guru/viewbio.jsp?EID=805382),
Dec 4, 2002
I thought the shorter version presented the information more clearly, but the longer
version is technically more correct. :)
The answer to your question is "Yes". You can call destroy() from within the
service(). It will do whatever logic you have in destroy() (cleanup, remove attributes,
etc.) but it won't "unload" the servlet instance itself.
You do not manage the life cycle of servlets in the program; the servlet engine does.
[Alex adds:]
"Is it possible that the servlet container will call destroy() while the servlet is still
processing a request inside service() on a different thread?"
then the answer is also yes, but it's a degenerate case. The servlet container is
required to wait a reasonable amount of time for current requests to finish
processing. So if your request is not totally lagging, it should work out fine. If you're
spending more than a few seconds processing a request, that's a UI problem that
you should try to work out first.
Check the servlet spec for more details.
BTW, destroy() does not imply garbage collection. The instance may live on in
memory long after destroy() is called.
How can I call the get method of a servlet automatically, when a *different*
HTML page is loaded?
Location: http://www.jguru.com/faq/view.jsp?EID=1030392
Created: Nov 25, 2002
Author: Michael Dean (http://www.jguru.com/guru/viewbio.jsp?EID=805382)
Question originally posed by sriram rangaraj
(http://www.jguru.com/guru/viewbio.jsp?EID=1020819
[I thought of using a image on the html page and sending the request to the servlet
for the image.]
The image will work if the user enables images in his/her browser. Other solutions
(JavaScript, link pre-fetching, servlet receiving requests for Cascading Style Sheets,
etc.) all have similar "failure modes."
And return a tiny image (i.e. a 0-pixel image). (P.S. The spyware thing is a joke. :)
The only way to ensure that the servlet gets called, though, is to make all clients
request the servlet directly (and have the servlet serve the appropriate HTML page).
This will work if you don't have external pages (i.e. not yours) pointing directly to the
HTML page...
However, the Servlets 2.3 specification (i.e. the current one) has added a new
feature which you could use. It allows you to define Servlet Filters--which provide a
"controller-like" functionality to your web application. With a filter, you can intercept
and pre-process requests and/or intercept and post-process responses to any web
content on your server (i.e. Servlets, JSP's, HTML, images, CGI's, SSI's, etc.). You
can even refuse requests and responses. Since it's all done on the web server, client-
side configuration cannot be used to defeat this mechanism. This is the functionality
you want.
Incase your html page is generated from a servlet u could as well use the below
statement
What is the best way to generate a universally unique object ID? Do I need
to use an external resource like a file or database, or can I do it all in
memory?
Location: http://www.jguru.com/faq/view.jsp?EID=1030397
Created: Nov 25, 2002 Modified: 2003-02-28 08:01:34.258
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
Andy Brown (http://www.jguru.com/guru/viewbio.jsp?EID=1027054
[I need to generate unique id's that will be used for node 'ID' attribute values within
XML documents. This id must be unique system-wide. The generator must be
available to a number of servlets that add various node structures to my XML docs as
a service. What is the best way to tackle this? The 'possible' ways I can see:
• Keep the maximum ID value in a flat-file where the service would read it upon
start-up and increment it. Upon shutdown or failure, it would write the latest
max id to the file.
• Calculate the max id by searching the XML itself. This will be tougher since
XML requires an alpha-numeric value (not strictly numeric).
• Use a database (MySQL) with a two-field table where one field is the
incremental counter.
I just have this feeling that none of the above are the most efficient ways of doing
this.
Regards, -Andy]
There is an additional way to do that that doesn't rely on an external file (or
database) like the one you have presentred. If has been presented in the EJB Design
Patterns book, written by Floyd Marinescu, and available in a pdf format for free from
the given link.
The suggested solution is based on the UUID for EJB pattern, that comes out from
this question:
How can universally unique primary keys can be generated in menory without
requiring a database or a singleton?
Without enetring in the specifics (you can fully check out the pattern by reading the
appropriate chapter), the solution is to generate a 32 digit key, encoded in
hexadecimal composed as follows:
1: Unique down to the millisecond. Digits 1-8 are are the hex encoded lower 32 bits
of the System.currentTimeMillis() call.
2: Unique across a cluster. Digits 9-16 are the encoded representation of the 32 bit
integer of the underlying IP address.
3: Unique down to the object in a JVM. Digits 17-24 are the hex representation of
the call to System.identityHashCode(), which is guaranteed to return distinct
integers for distinct objects within a JVM.
• I need to generate a GUID and have seen suggestions about using an RMI
server but nothing about how to actually generate the GUID itself.
• What is the best way to provide a unique identifier as a primary key that will
work in a database independent manner? I'm looking for functionality similar
to Oracle's proprietary MY_SEQ.NEXTVAL.
• How do I automatically generate primary keys?
• and the original thread: What is the best way to implement a system-wide
object ID generator?
- Alex Chaffee]
Comments and alternative answers
Random class
Author: P Manchanda (http://www.jguru.com/guru/viewbio.jsp?EID=344357), Feb
28, 2003
Hi,
Try using the java.util.Random class to generate random numbers that can be used as
IDs.
(BTW,you don't need to use rmi nor know anything about rmi to use these classes)
-Nathan
Making it Faster
Author: Kimbo Mundy (http://www.jguru.com/guru/viewbio.jsp?EID=1120338), Oct
8, 2003
It seems to me that you could speed up the algorithm above by modifying step #4.
Instead of computing the random number every time, just compute it the first time,
and then increment it after that. 2 different JVMs should still just have a 1 in 4 billion
chance of overlap.
Millisecond overlap
Author: Thomas Paré (http://www.jguru.com/guru/viewbio.jsp?EID=1238395), Apr
14, 2005
Thanks for the very interesting pointer on 'Ejb design patterns'. I've read the
implementation details and found something troublesome.
In step 1 : "Unique down to the millisecond. Digits 1-8 are are the hex encoded lower
32 bits of the System.currentTimeMillis() call". Only the lower 32 bits of time are
considered, which makes the uniqueness of that part only valuable for a period of 50
days. Looks like a serious issue.
I am also setting the locale and content type on the HttpServletResponse to "ja" and
"text/html; charset=Shift_JIS" respectively.
Does anyone have a sample on how to get international unicode characters from a a
form input field/servlet parameter into a string and from a java string into a form
input or text field? ]
Answer:
See at :
http://w6.metronet.com/~wjm/tomcat/2001/May/msg00433.html
So if you want to get an Unicode String (UTF-8) you have to do something like that:
I found that all of the big 3 browsers(IE,NS/M,O) have very poor support of sending
encoding information of their request. So you will not get the encoding anyway from
the request.
I took the approach of setting the uniform encoding, such as utf-8, to all pages in your
app (and hope the users do not change the browser's encoding between pages,
fortunately most of user do not know what it is and won't change it), or page before
submit. So, the request's encoding will be as you specified (utf-8). AND, most
important is to set the request char encoding (setCharacterEncoding()) to 'your'
encoding (utf-8) before you get the parameter (getParameter). This will interpret the
submitted request in utf-8. Otherwise, the getParameter will split the double byte
chars into some string cannot interpret again.
This work for any langauages, mixed language on the same page, or even mixed
language on a form field (as long as the user can type it in).
I'm uneasy using it however, because sooner or later a version of Tomcat or some
other servlet engine is going to fix the problem and do the stream to string conversion
based on the character set specified in the headers of the message from the browser.
When that happens existing applications with this code are going to screw up a treat.
[ For example I want to load some settings when the application starts and i keep
that object in the application scope so that any part of the application can use that
information. Now if the environment is clusterd will this Object available across the
clustered application?]
No, an object saved with 'application scope' (Saved in the ServletContext) is not
truly global.
If the data is doesnt change often (like a city-zipcode table) there is no problem
using application scope.
Just initialize it when your Container starts up!
The fun starts when your servlet begins to update the Object. An update to a
Context done by a Servlet in Container A is not propagated to the Context in
Container B!
Personally I wouldnt use the the ServletContext as a parking place for global
variables - I see it as a place for holding information relevant for the application
infrastructure (paths, datasource names etc) - not for the application logic.
try this..
java.net.URL url;
try {
url = new java.net.URL(new java.net.URL(req.getRequestURL
().toString()),"../");
} catch (java.net.MalformedURLException e) {
// catch the exception ....
}
You should set the maximum age with setMaxAge(int seconds) with a positive
number to set your own expiry right after creating the cookie. Use getMaxAge() right
after setting the expiry, because once the cookie itself is set to the client browser,
the getMaxAge() doesn't perform like the way you are intending.
Not just maxAge, Domain and path also returns default value
Author: Avani Shah (http://www.jguru.com/guru/viewbio.jsp?EID=28330), Jul 23,
2003
Not just maxAge, Domain and path also returns default value for a cookie irrespective
of they being set when they were created in the previous request on the server... so
once they return from the client browser (netscape or IE) only name value pair
returns... is it webserver dependent?
See How do I implement a hit counter in Servlets or JSP? for a definitive answer.
Your servlet must know how to speak NNTP, or call a library that does.
You may also find the NNTP specifications enlightening. See RFC 977 and RFC 2980.
I'd like to dynamically generate a PHP file from a servlet, then have Apache
execute it. Is this possible? Setting the Content-type does not seem to help.
Location: http://www.jguru.com/faq/view.jsp?EID=1035740
Created: Dec 9, 2002
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Dima Gutzeit
(http://www.jguru.com/guru/viewbio.jsp?EID=1011859
[I am working with Apache 2 with Tomcat 4.1. I am integrating some system that
was built with servlets, with some PHP project. What I need to do is generate PHP
files from servlets. Problem is that after generating the files , Apache does not parse
it as PHP files , which is not good :-). I;ve tryed to change the pageContent of
HTTPResponse to "text/plain" - Nope. "text/html" - presents the
files as HTML without the PHP part , it simpoy ignores it. I've even tryed setting it to
"application/x-httpd-php" , in this case after clicking on link it saves me the file on
my computer (Apache does not understand the file type. ]
Answer:
You need to write the PHP files to your server's disk drive, in the htdocs directory.
Then send a browser redirect to the URL corresponding to the file you just wrote.
The client will then ask the server for that file; Apache will notice the PHP file on its
disk and execute the PHP interpreter on it.
There's no way to get Apache to invoke the PHP interpreter directly on pages output
by Tomcat. It happens too late in the dispatching game.
How to suppress the URL shown in the address bar? No matter what page
the customer is on, I want to just show http://sitename.com and no JSP
page name.
Location: http://www.jguru.com/faq/view.jsp?EID=1035749
Created: Dec 9, 2002
Author: Brian Glodde (http://www.jguru.com/guru/viewbio.jsp?EID=313271)
Question originally posed by Edison T
(http://www.jguru.com/guru/viewbio.jsp?EID=1004270
And the user cannot bookmark any pages. And the browser's history list will contain
a bunch of identical names (meaning it's extremely difficult to find a specific page
from the list under the Back button--browse a few pages in the frames version of the
API javadoc to see). And a user opening a link in a new window (i.e. right-click,
"Open Link in New Window") or bookmarking a link (i.e. right-click, "Bookmark This
Link") will get only part of the page--possibly losing a navigation bar or a title frame
(or, if all content is in the "content" frame, will see the page and its location in the
location bar--thereby getting around your desired behavior). And when a new
window is opened or a link accessed directly via a bookmark, the user may get
strange behavior due to target attributes of the a (anchor) element. And ...
But if you really want to create a difficult to use web application (or, more likely, your
boss is telling you to do so), go ahead--you won't be the only one. :)
Remember, the reason that the web is so popular is because the user controls the
experience. Therefore, any time you ask, "How do I remove some capability provided
by HTTP and/or HTML?" Abraham Lincoln answered the question best, "You can fool
some of the people all of the time, and all of the people some of the time, but you
can not fool all of the people all of the time."
Being able to display one address in the location bar while displaying a page from
another "anonymous" location without any way for the user to identify the
"misdirection" would be a huge security problem. HTTP/HTML make the location
available to the user so he/she can potentially make informed decisions about
whether to submit information.
[See also:
• How can I suppress the parameters from displaying in the URL? For instance,
if I pass in a password, I don't want it to show up in the address bar.
• Why do Frames suck?
- Alex]
Comments and alternative answers
How to notify the user to save data before the session expires? Then if the
user does not respond, then save the data.
Location: http://www.jguru.com/faq/view.jsp?EID=1035755
Created: Dec 9, 2002
Author: raj subramani (http://www.jguru.com/guru/viewbio.jsp?EID=576334)
Question originally posed by Subbareddy Kalakota
(http://www.jguru.com/guru/viewbio.jsp?EID=1017528
If you are going to save the data even if the user does not repond, then why not
save it right at the beginning anyway?
Cheers
-raj
[See also
Is there a way to detect when the session has expired, so that we can send a
redirect to a login page?
Why do I get the error: SAX parser fatal error: External entity not found:
"http://java.sun.com/dtd/web-app_2_3.dtd"?
Location: http://www.jguru.com/faq/view.jsp?EID=1037581
Created: Dec 13, 2002
Author: Benoit Quintin (http://www.jguru.com/guru/viewbio.jsp?EID=394478)
Question originally posed by Manos Batsis
(http://www.jguru.com/guru/viewbio.jsp?EID=984102
[This happens because Sun's Web site is down, so the servlet engine can't find the
remote copy of the web.xml DTD at that URL.]
Well, you can download the dtd and point the document reference inside web.xml to
the local copy, I suppose.
[You can also "inline" the DTD by replacing the reference with the literal text of the
DTD. See this web.xml file for an example.
Finally, you could attempt to turn off DTD validation in the XML parser, but not all
servlet engines allow you to configure the XML parser they use to parse web.xml.
-Alex]
When a first request is made to a servlets the init() method is called for the
first time and after that the threads will serve the subsequent requests.
What will happen when 2 requests are made to a servlet at the same time
immediately after the server has restarted?
Location: http://www.jguru.com/faq/view.jsp?EID=1041360
Created: Dec 27, 2002
Author: Stephen McConnell (http://www.jguru.com/guru/viewbio.jsp?EID=248618)
Question originally posed by anil reddy
(http://www.jguru.com/guru/viewbio.jsp?EID=505941
The App server will queue up the requests. Then, they will be processed with the first
one (the App server decides) calling the init method and the second waiting until it's
finished to throw the processing thread.
Stephen McConnell
init method()
Author: bitap kalita (http://www.jguru.com/guru/viewbio.jsp?EID=1222505), Jan 21,
2005
The init() method is called when the server start if you specify that servlet should be
loaded on start up(which is the normal practice).So,when the request arrives the
servlet is already ready waiting for you.
What is the maximum length of the data we can send through the get()
method?
Location: http://www.jguru.com/faq/view.jsp?EID=1041361
Created: Dec 27, 2002
Author: Stephen McConnell (http://www.jguru.com/guru/viewbio.jsp?EID=248618)
Question originally posed by Augustine Dsilva
(http://www.jguru.com/guru/viewbio.jsp?EID=1032362
It is dependent upon the browser and server, however in RFC 2068 it states
Servers should be cautious about depending on URI lengths
above 255 bytes, because some older client or proxy
implementations may not properly support these lengths.
Since the GET method packs all it's information into the URI, yo shouldn't work with
a URI (that is internet address plus data) of > 255 bytes.
Read the RFC (Request for Comment). It's dry, but has a lot of info in it and helps
you learn the history of the Internet. The RFCs are a compilation of all the
documents and communications which helped set the standards and lay the
foundation for the internet. They also contain information on upcoming standards.
Hope this Helps
Stephen McConnell
Question
Author: Ugo Posada Zabala (http://www.jguru.com/guru/viewbio.jsp?EID=1040388), Dec
30, 2002
Does that mean that the full resource must not excede 255 bytes, for instance, if a file we
want to read is stored in
http://www.hellobeautifuljavaworld.com.wa/publications/tutorials/beginners/march/2002/...
or whatever, the full address lenght must be less than 255 or otherwise it wont be possible
to access it?
That means that the website admins must be careful in where do they store the data.
[Full question: When we implement singlethreadmodel it means that only one thread
can access the service method at a time.now my question is ,why can't we achieve
the same thing my making the service() method synchronized. theory says that we
shouldn't synchronize the service method. but what will happen if we do so,except
from the performance problem?]
Assume that you write a servlet and synchronize the service(...) (or any of the
doXXX(...) methods or any method you call from any of these methods). Once you
deploy the servlet, the servlet container receives ten "near-simultaneous" requests
for the servlet. Upon receipt of the first request, the servlet container kicks off a
thread and sends it on its way (i.e. starts it executing the service(...) method).
With this approach each thread has an "equal" probability of being the next allowed
to execute the service(...) method. It's complete anarchy--every thread for itself.
About this time, the person who sent the second request is calling you to say that
your application is down. :) And, if you really want things to get complex, try
synchronizing the service(...) method and the doXXX(...) methods...
So what does the servlet container do? It provides queueing and prioritization
(generally first-in-first-out) of requests.
Some servlet containers instantiate multiple servlet objects (and maintain a servlet
pool--remember that synchronizing a method locks the object (or instance), not the
method, so multiple threads can execute the same method in different instances) to
handle multiple simultaneous requests. (Note that this means that you may need to
synchronize access of static members.)
Others (like Tomcat, IIRC) provide as little support for SingleThreadModel servlets
as is required by the servlet specification (they don't waste time creating object
pools) since using SingleThreadModel is a "cop out." Keep reading, I'll explain
why... :) Implementing the interface often gives developers a false sense of security
when it comes to multi-threaded programming. For example, regardless of whether
your servlet implements SingleThreadModel or not, you still need to consider
synchronization problems with static members, HttpSession attributes,
ServletContext attributes, and any other classes outside the scope of the servlet
(i.e. JavaBeans, support classes, etc.).
So, what do you do if you're not sure whether your servlet is thread-safe? Your best
bet is to talk with other developers who have more experience in multi-threaded
programming (someone who's been doing it for 30 years is a good beginner ;). Also,
do all you can to learn about the topic. IBM's DeveloperWorks website has a lot of
articles on multi-threaded programming, including Understand that for instance
methods, synchronized locks obj..., Threading lightly, Part 1: Synchronization is not
the enemy (and parts 2 and 3), and many, many more. Also, check out some of their
tutorials, like Introduction to Java threads.
[Full question:
I have an application that I am migrating to a clustered environment with multiple
Tomcat 4.1.x servers. I am in the process of changing the persistent session data to
another format.
I am inclined to persist the limited data we have in a cookie rather than use a
session server and persisting the data in a central database.
What I need to know is how to make Tomcat not persist the session object between
requests and not send back the jsessionid cookie.
Set up a filter to run incoming requests past a JSP that with page directive
<%@ page session="false" %>.
There are probably other ways. Or you can dig through Tomcat's source code to
figure out the mechanism by which this page directive deactivates sessions.
Good luck!
I do pretty much the same thing to get my appconfig.xml file read in and parsed. I
simply convert the URL into a string format and use that to parse the XML.
The RequestDispatcher will call the servlet's service method. If your servlet
extends javax.servlet.http.HttpServlet the same 'do' method will be called
automatically by the service method, depending on the method used the original
request.
Comments and alternative answers
Re: When using a dispatcher and calling .forward(), will doGet() or doPost()
be called in the target servlet?
Author: Satish Rapalli (http://www.jguru.com/guru/viewbio.jsp?EID=1233969),
Mar 21, 2005
No, We can not enter directly into the doPost() of any servlet class,except through
a form which uses method = post. When calling .forwarding or .include the target
servlet class must have doGet() method to accept this request.
Re[2]: When using a dispatcher and calling .forward(), will doGet() or doPost() be
called in the target servlet?
Author: Eelco Cramer (http://www.jguru.com/guru/viewbio.jsp?EID=200853), Apr 14,
2005
No. Just to be sure I tested this with Tomcat 5.5. If I foward the request like this:
getServletContext().getRequestDispatcher("/printing").forward(request,
response);
The forward will use the request method from the orginal request.
It's one of the last sub-elements of <webapp>. Check the DTD if you're unsure.
See also:
• How close is the actual session timeout period to the specified timeout period?
• How can you set the session timeout in tomcat higher?
• How can an HttpSessionListener comunicate directly to an user web browser
that his session has been destroyed by server web.xml "timeout" parameter?
• Is there a way to detect when the session has expired, so that we can send a
redirect to a login page?
• How can I prevent the expiration of a Session?
using invalidate()
Author: sridhar Tirumala (http://www.jguru.com/guru/viewbio.jsp?EID=1139770),
Jan 18, 2004
I hope u can timeout the session with help of invalidate()method .But if u want
timeout specific session id then simply use removeAttribute(java.lang.String name)
based on getLastAccessedTime() ("Returns the last time the client sent a request
associated with this session ")
If you are new to websphere, it seems to be strange at least initially,to deploy the
simple servlet. One way you can do is you need to generate a war file. For this you
can use Application Assembly Tool that ships with websphere, it is simple if you use
this tool, it walks you throwgh the steps to create a war file, and you can start a
websphere console from "first steps" and you can deploy the file you created . And
you can access your servlet by
http://localhost:8090/your_web_application_context/servlet_url_mapping
This is very high level to get started, you can find more info in "infocenter" at
ibm.com. You really need to do some research.
Not complex
Author: Manjunatha Prasad (http://www.jguru.com/guru/viewbio.jsp?EID=1220641),
Jan 11, 2005
This task is not at all complex. Just open web.xml and change the Servlet and Servlet
mapping configuration. Keep you servlet in the WEB-INF/classes followed by your
package name. Restart your system. Thanks, Manju
Although that's a very elegant solution, it may be overkill. There are a couple of
simple solutions available. The more elegant approach using Filters, however, could
make for a much more reuasable, maintainable, and robust architecture.
I couldn't tell exactly what you are trying to do, but here are some options. My guess
is that you want Case 1, but just in case...
Case 1: An HTTP request is submitted to a servlet. From this servlet, you are
dispatching a request to another (third-party) servlet that needs a parameter that is
not included in the request. You can add a parameter to the request by "appending"
it to the URL. For example:
RequestDispatcher dispatcher =
request.getRequestDispatcher("/servlet/some.ThirdPartyServlet" +
"?" +
"param_name=" + "somevalue");
dispatcher.forward(request, response);
Just be careful to run the parameters through the
java.net.URLEncoder.encode(String, String) method if there's a possibility that
the values contain "illegal" characters.
Note that the value of the value attribute may be a request time expression (i.e.
<jsp:param name="param_name" value="<%=
request.getAttribute("someAttributeWithAValidToString") %>" />. Here the
JSP translator should take care of encoding "illegal" characters in the value.
Case 3: You have an HTML form that submits directly to a (third-party) servlet, but
you do not want the user to see some fields (i.e. you want to keep the form simple).
Use "hidden" form fields:
If you want a dynamic value, you can create the HTML form with a JSP. Here, the
browser "packages up" the form values, so you don't want to run the values through
java.net.URLEncoder.encode(String, String).
Case 4: You want call the third-party servlet directly from HTML without using a
form. Append the required parameters to the URL:
<a
href="/servlet/some.ThirdPartyServlet?param_name=somevalue">Clickable
Text</a>
Here again, if using a JSP to create "dynamic" links, make sure you properly encode
the characters in the URL with java.net.URLEncoder.encode(String, String).
I have the same issue, but the answers provided do not address the question, as I
understand it.
I have a JSP page which contains a form that is "self submitting", meaning the action
on the form calls the same JSP page again. After a submit, I want the JSP to process
the parameters and change their values. Just like there is a request.getParameter, I'm
looking for a setParameter method. When the page reloads, I want the a new value set
for the parameter.
Lets say I have a form field called preditor_id, with a value of "Gator". When the
form is submitted to my "preditor.jsp" code, I want to get the preditor_id parameter,
use the value that was submitted, say "Gator", and reload the form with a new value
set for the preditor_id parameter, say "shark".
I know I can simply write out the new value "shark" as an input type: <input
type="text" name="preditor_id" value="shark"> - but that's not what I'm talking
about.
What I want to know is - how do I change the value of the parameter sent back in the
request header?
How do I do that?
Also, you apparently have to do it during each doPost call??? Not sure what that
means, since you can't call sendError during each doPost... Maybe you just have to
set the WWW-Authenticate header each time.
The easy way is to use Apache and mod_ntlm. Then req.getRemoteUser() returns
the logged in user's name. You can use Apache <Location> directives to limit access
to servlet urls. I have used this with JServ and Tomcat.
-Alex]
out.println("Username:"+username+"<BR>");
out.println("RemoteHost:"+remoteHost+"<BR>");
out.println("Domain:"+domain+"<BR>");
}
}
Comments and alternative answers
We made one product which we used for some other purpose but fortunately it
also gave solution of your problem as well.
By using JspISAPI you can enable NTLM authentication for tomcat applications.
http://jspisapi.neurospeech.com
- Akash Kava
It wont work with Windows 95, no matter what I did. But in my firm we still have
some WS that uses it, hmmmm.
Thirdly, i tried to pack the code in a FilterChain, but couldnt make the forward,import
etc stuff work.
So i gave up, and made a simple Ms IIS server, with one asp page witch redirects the
username & domain back to me. A very sad,bad hack, but it works.
Tech specs:
J2EE = Weblogic Server 6.1 sp1
OS = Unix TRU64
If you trim the encoded string it should take care of the 40 sec. delay.
There are a lot of garbage bytes at the end of that string.
Since HTTP sees two carriage returns as the end of the headers,
the rest of the headers after WWW-Authenticate are put
in the body of the message and the browser gets confused.
This includes content-length, encoding, type, etc. Modified code line below.
<html>
<body>
This is login asp file
<%
dim UserName
dim authlogin
UserName = request.ServerVariables("LOGON_USER")
authlogin = request.ServerVariables("AUTH_LOGIN")
response.write("
Logged in user is " & UserName)
response.write("
Login in auth is " & authlogin)
response.write("
")
%>
Finished executing the asp file.
</body>
</html>
Thanks
Joan
This is incorrect...
Author: Eric Glass (http://www.jguru.com/guru/viewbio.jsp?EID=1088764), May 28,
2003
The above code performs IDENTIFICATION, not AUTHENTICATION. A user can
easily set their IE preferences to prompt for a password, enter ANY username and
password, and enter the system.
Also, NTLM is a negotiated authentication protocol; any hard-coded values are bound
to fail, as the client and server use flags to negotiate supported capabilities. The
posted code, for example, specifies the following flags:
This will fail on Windows 95/98 clients, since they don't support Unicode (should
send Negotiate OEM (0x00000002)).
The open-source jCIFS library provides exactly the functionality mentioned (namely,
HTTP NTLM authentication against a domain for servlets):
http://jcifs.samba.org
The newest versions can be found at:
http://users.erols.com/mballen/jcifs
Eric
Well, once you have authenticated via NTLM you can get the users logon
name and query the domain's active directory to get more information about
that person. I use the jfcis package to enable the NTLM.
You can do the querying of active directory with JNDI API. The following
code does what you need, but the down side is that you have to pass in security
credintials to the active directory to create a connection before you can search
against it. (Microsoft's site has documented the steps to take to allow
anonymous access to the active directory.)
try {
// retrieve the authenticated user's logon name
String userName = request.getRemoteUser();
env.put(Context.SECURITY_AUTHENTICATION,"simple");
env.put(Context.SECURITY_PRINCIPAL, activeDirUser);
env.put(Context.SECURITY_CREDENTIALS,
activeDirPassword);
String host = DOMAIN_CONTROLER; // A Domain
Controller Server
String port = "389"; // Active Dir Port
DirContext ctx;
ctx = new InitialDirContext(env);
ctx.close();
} catch (Exception e) {
System.out.println("Exception = "+ e);
}
You will see that the users active directory information is spit out to the
console. It will be up to you to retrieve the relevant information.
My code
try { env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://ukhqits002/dc=sews-
e,dc=com");
} catch(Exception ex)
{
out.print("erroe in first para-----"+ex);
}
try {
// Create the initial directory context DirContext ctx = new
InitialDirContext(env); //String userLogon =
userName.substring(DOMAIN_NAME.length() +1);
//System.out.println(userLogon); // Ask for all attributes of the object
Attributes attrs = ctx.getAttributes("cn=francir, ou=Silverdale, ou=sews-
e"); // Find the surname ("sn") and print it out.println("sn: " +
attrs.get("sn").get()); // Close the context when we're done ctx.close(); }
catch (NamingException e) { out.println("Problem getting attribute: " +
e); }
Your advice is highly appreciated.
Rajesh
Thanks
Joan
Well, it is that simple, this is java basics, and is based on the simple exanple that is
provided in the Java API Documentation, for java.util.Enumeration. I strongly
suggestion to read it when you have some time.
The role of controller is to dictate what to do behind the scenes and what to display
in the view next.
There must be a lot better explanations for the controller's responsibilities, but at
least I tried...
[See also: What is the best way of implementing a web application that uses JSP,
servlet and EJB technologies all together following a Model View Controller (MVC)
architecture?
what is the role of controller in MVC architecture
]
JBuilder doesn't really need of any additional setup for working with Servlets. Just
create a new Project and creare a new Web Application. Then when you want to
create a new file, just select "servlet" from the WEB tag of the File|New popup.
Solutions:
Solution A:
1. download http://www.servlets.com/cos/index.html
2. invoke getParameters() on com.oreilly.servlet.MultipartRequest
Solution B:
1. download http://jakarta.apache.org/commons/sandbox/fileupload/
2. invoke readHeaders() in
org.apache.commons.fileupload.MultipartStream
Solution C:
1. download http://users.boone.net/wbrameld/multipartformdata/
2. invoke getParameter on
com.bigfoot.bugar.servlet.http.MultipartFormData
Solution D:
Use MultiPartRequest
Author: Pazhanikanthan Periasamy
(http://www.jguru.com/guru/viewbio.jsp?EID=230166), Apr 9, 2003
Use Oreilley's MultiPartRequest Reusable class for this condition
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import com.oreilly.servlet.multipart.*;
try {
MultipartParser mp = new
MultipartParser(request, 1*1024*1024); // 10MB
Part part;
while ((part = mp.readNextPart()) != null) {
String name = part.getName();
if (part.isParam()) {
// it's a parameter part
ParamPart paramPart = (ParamPart) part;
String value =
paramPart.getStringValue();
out.println("param; name=" + name + ",
value=" + value);
}
else if (part.isFile()) {
// it's a file part
FilePart filePart = (FilePart) part;
String fileName = filePart.getFileName();
if (fileName != null) {
// the part actually contained a
file
long size = filePart.writeTo(dir);
out.println("file; name=" + name +
"; filename=" + fileName +
", filePath=" +
filePart.getFilePath() +
", content type=" +
filePart.getContentType() +
", size=" + size);
}
else {
// the field did not contain a file
out.println("file; name=" + name +
"; EMPTY");
}
out.flush();
}
}
}
catch (IOException lEx) {
this.getServletContext().log(lEx, "error reading
or saving file");
}
}
CommandProcessor cp=new CommandProcessor();
cp.process(request,response);
HttpSession session=request.getSession();
String fname=(String)session.getAttribute("FILENAME");
out.println("returned from cp"+fname);
}
}
<BODY>
</BODY> </HTML>
The Solution B as given by my dear friend is a bit hectic and a bit complex :(
We can try the following solution which I found much simpler (at least in usage).
From a servlet, how do I access files and directories on the client's file
system?
Location: http://www.jguru.com/faq/view.jsp?EID=1045509
Created: Jan 12, 2003 Modified: 2003-01-25 19:22:20.915
Author: Erik Runia (http://www.jguru.com/guru/viewbio.jsp?EID=585265) Question
originally posed by john varghese
(http://www.jguru.com/guru/viewbio.jsp?EID=997638
You cannot access the client's directory structure using a web application (jsp,
servlet, javascript, html) because of security issues. You may need to look into an
applet or other client based application, instead of server based.
[It's not simply a security issue -- it's more basic than that. The servlet runs on the
server; it can only send and receive data to the client via HTTP. HTTP only allows
simple file transfer operations -- no arbitrary remote access. -A]
re
Author: Massimiliano Ragazzi
(http://www.jguru.com/guru/viewbio.jsp?EID=945577), Feb 17, 2003
The only way to access file or directory is applet, but if it's not authenticated i can
only read and not write
Re: re
Author: umair rahim (http://www.jguru.com/guru/viewbio.jsp?EID=1212152), Jan
17, 2005
you can use ListFiles() method with file path as a parameter ..... n you can activate
this method against some specifice text using querey string ..... e.g,
if (quereystring=="file path")
f.listFiles("file path")
Re[2]: re
Author: bitap kalita (http://www.jguru.com/guru/viewbio.jsp?EID=1222505),
Jan 21, 2005
This "file path" has to be that of the server not client machine.As the first
answer says you cannot access client machine.
Re[3]: re
Author: Rajesh Kumar
(http://www.jguru.com/guru/viewbio.jsp?EID=1222672), Feb 7, 2005
Hai people, Then is it possible to upload files from client side like what
yahoomail do? Thanks in advance
How do I execute a servlet from the command line, or from Unix shell
program or Windows BAT file?
Location: http://www.jguru.com/faq/view.jsp?EID=1063884
Created: Mar 6, 2003
Author: Christopher Koenigsberg
(http://www.jguru.com/guru/viewbio.jsp?EID=722897) Question originally posed by
rupali kandarkar (http://www.jguru.com/guru/viewbio.jsp?EID=1051696
Of course as with any Java class, you could put a "main" method in your class that
extends HttpServlet, so you could run it (the main(), not the doGet/doPut/service())
from a command line.
But it wouldn't have the whole server infrastructure set up for it, with the request,
session, response, etc. (which is why you couldn't call the doGet/doPut/service,
unless you have a good "mock object" test scaffolding set up).
Or are you saying that you have some utility classes & methods that might be useful
to run, standalone in a command line situation (e.g. calling them from main()), as
well as from inside a servlet (e.g. calling them from doGet/doPut/service)?
In that case, perhaps you would want to make a Jar file with just the utility classes,
and an application with main() that uses the Jar file, and also a web application WAR
file that uses the Jar file too (in its WEB-INF/lib).
I have server1 and server2(12.23.34.45). Note: I have no control over server2 and
it's a cgi server.
Server1 creates a request to server2. In response, server2 feeds back an html page
with the headers
I display the html to the browser via the OutputStream. Also I obtain the response
headers and attempt to relay it back to the browser. Here is the relay cookie I'm
attempting to create for the next request Note: USER1 is obtained from server2's
response
The next request will be towards server2 but for some reason the cookie doesn't
exist in the request even though I created one for that domain on the response
before it.
Please don't ask why I'm going through all this trouble of relaying back and forth
between 2 servers. I realize a simple POST method from the browser/html would
work just fine, but that couldn't be in this case.
-----------------------------
Look at section 4.3.2 of RFC 2109, linked below. It states that a cookie is rejected if
the following is true:
- The value for the request-host does not domain-match the Domain attribute.
What that means is that you can't set a cookie for a different domain than is being
accessed. NOTE: you _can_ set a cookie that will get sent to all subdomains, ie
www.foo.com and secure.foo.com, but you _can't_ set a cookie on a page requested
from foo.com to be sent to a server in the bar.com domain.
http://www.ietf.org/rfc/rfc2109.txt
Comments and alternative answers
Solution!.....hopefully
Author: Eric Cho (http://www.jguru.com/guru/viewbio.jsp?EID=1051283), Mar 12,
2003
Thanks Jeff,
That actually helped me a lot. What I'm going to do now is put server1 and server2
behind a proxy and funnel the requests in through that. So, both servers will have the
same domain and thus, the cookie persists! Hopefully it works.
Re: Solution!.....hopefully
Author: Manivasakam Ramaswamy
(http://www.jguru.com/guru/viewbio.jsp?EID=1092515), Jun 10, 2003
Hi Eric Cho,
I would like to know how you achieved the task
because i am also in deep trouble.
Re[2]: Solution!.....hopefully
Author: Eric Cho (http://www.jguru.com/guru/viewbio.jsp?EID=1051283),
Jun 17, 2003
Mani, It's the same code as I originally had posted. Except, make sure both
servers are under the same domain. That is the only way I could make the
cookie persist. So what we had done was put a proxy in front of both with the
domain of abc.com. But all requests going to the URI of /x/y/z/* goto server 1
and all requests goint to URI /a/* go to server 2. So now you have to make
sure all your links accomodate this. I believe this handy work with the proxy is
called 'reverse proxying'. Hopefully this helps. Eric
Re[3]: Solution!.....hopefully
Author: Magdi Ahmed
(http://www.jguru.com/guru/viewbio.jsp?EID=316472), Dec 17, 2003
Actually, you didn't need to do all that proxy stuff... just set the DNS for
both servers to be different hosts of the same domain name, so
box01.yourdomain.com and box02.yourdomain.com
If you did it that way, both servers would see cookies set to a domain of
'.yourdomain.com'
Cookie domains and path are set to define the scope of access
Author: Frank Nimphius (http://www.jguru.com/guru/viewbio.jsp?EID=1139332),
Jan 15, 2004
The problem in your request is that you are trying to push a cookie information from
one domain to another. if you know that you want to use cookies to exchange
information between applications of different servers, you can define the cookie
domain to the one for the second server when setting it to teh client Browser. Redirect
to an application that is hosted by the second server and have this application
accessing the cookie. Using cookies may not be the best solution of integrating
applications with each other, but its works. Frank
Re: Cookie domains and path are set to define the scope of access
Author: A L (http://www.jguru.com/guru/viewbio.jsp?EID=1250267), Jun 24,
2005
I tried to set the cookie domain to the second server and redirect the page to that
domain. It won't work. The cookies are not created or are not accessible from the
second domain.
Hi,
No, there are no references in the specifications for that.
As far as I know there is nothing available for that, especially if you need something
that is portable or not server specific.
If you have the source code of the server, it is probably trivial (well, depend how
documented is the code) to write something, otherwise you need to find alternative
solution (like reading and analizing the server configuration files).
But, again, this would be a server specific solution.
Servlet Context
Author: Sushil Chatrani (http://www.jguru.com/guru/viewbio.jsp?EID=1148988),
Aug 27, 2004
U can use HttpServletContextListener to keep track of number of servletContext
Initialized. All the listeners will use the factory using singleton pattern to get the
instance of a controller class to update the count of the servlet context.
Does anyone know if there is a way to check the size of a file (a picture in
my case) that the user can upload from a form *BEFORE* the file is
uploaded?
Location: http://www.jguru.com/faq/view.jsp?EID=1074628
Created: Apr 8, 2003
Author: Matan Amir (http://www.jguru.com/guru/viewbio.jsp?EID=1010674)
Question originally posed by Jerome Iffrig
(http://www.jguru.com/guru/viewbio.jsp?EID=977875
I know that it is possible to check the size of the file on the server side once it has
been completly uploaded by the user, but this is not ideal (e.g. I can always delete
the file from the server if it is too big, but it would have been uploaded in teh first
place, which I would like to avoid).
-----
One obvious solution is to check the HTTP content-length of the file POST request
and cancel the upload if it's too big (throw a ServletException for example). The
problem is that I think IE doesn't care if the server has stopped receiving the file and
continues to upload it anyway.
If I remember right, the Image object loading is asynchronous, so you might need to
define an onload function that will be called when the file is actually loaded.
I have a Servlet and a Servlet Filter that is supposed to apply an xsl to it.
The transformation appears to work, I get back a transformed document,
but it appears (in IE) as if IE thinks its an HTML document (i.e., you see the
<html><body>, etc tags). Viewing source, and saving as an HTML file will
display correctly. How can I correctly set the Content Type of the response?
Location: http://www.jguru.com/faq/view.jsp?EID=1074630
Created: Apr 8, 2003
Author: Vincent Fischer (http://www.jguru.com/guru/viewbio.jsp?EID=1035285)
Question originally posed by Vincent Fischer
(http://www.jguru.com/guru/viewbio.jsp?EID=1035285
I figured this out. Many thanks go out to Matan Amir for pointing me in the right
direction.
I used Ethereal (I couldn't get tcptrace to work), to verify that in fact the content
type was "text/xml", instead of "text/html". So, I finally figured out that instead of:
response.setContentType("text/html");
I wrote:
wrapper.setContentType("text/html");
I'm guessing the reason is because the response and request objects in the Filter
cannot be modified... So instead, I made the changes to the wrapper. Of course, if
I'd set my servlet to send the response as "text/html" this would work too, but the
purpose of the assignment was to change the contentType...
<filter-mapping>
<filter-name>GZIPFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>GZIPFilter</filter-name>
<url-pattern>*.js</url-pattern>
<!--<exclude-pattern>*/SlideMenu.js</exclude-pattern> -->
</filter-mapping>
In the example above, I have a fictitious tag "exclude-pattern" that would exclude
*/SlideMenu.js from the filter mapping.
Good luck.
From a logical point of view, a Servlet/JSP session is similar to an EJB session. Using
a session, in fact, a client can connect to a server and maintain his state.
But, is important to understand, that the session is maintained in different ways and,
in theory, for different scopes.
A session in a Servlet, is maintained by the Servlet Container through the
HttpSession object, that is acquired through the request object. You cannot really
instantiate a new HttpSession object, and it doesn't contains any business logic, but
is more of a place where to store objects.
A session in EJB is maintained using the SessionBeans. You design beans that can
contain business logic, and that can be used by the clients. You have two different
session beans: Stateful and Stateless. The first one is somehow connected with a
single client. It maintains the state for that client, can be used only by that client and
when the client "dies" then the session bean is "lost".
A Stateless Session Bean doesn't maintain any state and there is no guarantee that
the same client will use the same stateless bean, even for two calls one after the
other. The lifecycle of a Stateless Session EJB is slightly different from the one of a
Stateful Session EJB. Is EJB Container's responsability to take care of knowing
exactly how to track each session and redirect the request from a client to the
correct instance of a Session Bean. The way this is done is vendor dependant, and is
part of the contract.
What if ?
Author: rachna chadha (http://www.jguru.com/guru/viewbio.jsp?EID=1077370), Oct
8, 2003
I have seen that many times JSP session is still there but session bean's session expires
? Is there any way to manage this problem ?
Re: What if ?
Author: Bill Schnellinger
(http://www.jguru.com/guru/viewbio.jsp?EID=1120424), Oct 8, 2003
you have to match the <session-timeout> in your web.xml with the statefull
session timeout parameter in your application servers xml file.
For example, weblogic-ejb-jar.xml has a
<stateful-session-descriptor>
<stateful-session-cache>
<max-beans-in-cache>100</max-beans-in-cache>
<idle-timeout-seconds>0</idle-timeout-seconds>
</stateful-session-cache>
</stateful-session-descriptor>
entry.
http://www.jboss.org/j2ee/dtd/jboss_3_0.dtd
An Alternative Description
Author: vimarsh vasavada (http://www.jguru.com/guru/viewbio.jsp?EID=972756),
Oct 8, 2003
The earlier explaination has cleared my clouds.Representing
in different way .
Container View Point :
1. Servlet Container
A HttpServlet.service() represents a client thread.
A logical session is maintaied per such different client
threads.The container manages the association rather
then the Servlet.Hence Servlet from the pool of servlet instances are reusable for
different threads and can be
swaped in between client threads.This is why Servlet
Instance variable are not thread-safe.
Designers Perspective :
1. Servlet
Helps the session management but the servlet developer
needs to invoke SessionManagement API to read/write.
Right candidate for UserInfo,AuthInfo etc.
2.SFB
A well designed component for the stateful processes.
An object state is automaticaly managed by container.Thread-
saftey is guranteed.Developer need not to bother.Right
candidate for Order/Shopping Process.
which is the best way to pass the value from one screen to another either
hiddenor session
Author: lekoria martin (http://www.jguru.com/guru/viewbio.jsp?EID=1124801), Oct
30, 2003
According to theory concept says, session is best way to pass the the value from one
screen to another since there is no limitation in session. what i feel is if u keep so
many data in session will it affect the network. all the session is going to be in
memory in application server only know. pls suggest me when to use hidden, cookie,
session.
Re: which is the best way to pass the value from one screen to another either
hiddenor session
Author: Kimbo Mundy (http://www.jguru.com/guru/viewbio.jsp?EID=1120338),
Nov 15, 2003
Perhaps it's obvious, but don't forget about the simplest way of passing state: For
small bits of data, like the page # in a list of search results, just use a parameter in
the URL.
Re[2]: which is the best way to pass the value from one screen to another
either hiddenor session
Author: sridhar Tirumala
(http://www.jguru.com/guru/viewbio.jsp?EID=1139770), Jan 18, 2004
URL rewriting gives moderate performance because the data has to pass
between the client and server for every request but there is a limitation on
amount of data that can pass through URL rewriting. It gives moderate
performance because of overhead involved on the network for passing data on
every request. But session object mechanism gives better performance because
it stores the session data in memory and reduces overhead on network. Only
session id will be passed between client and server. But it does not scale well
up on increasing session data and concurrent users because of increase in
memory overhead and also increase in overhead on garbage collection. There
choosing the session mechanism out of one of the above approaches not only
depends on performance but also depends on scaling and security factor . The
best approach to maintain a balance between performance, scalability and
security. Mixture of session mechanism and Hidden fields gives both
performance and scalability. By putting secure data in session and non secure
data in hidden fields you can achieve better security
Re[3]: which is the best way to pass the value from one screen to
another either hiddenor session
Author: Bill Bruns
(http://www.jguru.com/guru/viewbio.jsp?EID=1150451), Mar 1, 2004
Isn't it true that there are circumstances where the session variables cannot
be used?
In other words, that some items must be passed by means of URL rewriting
because they are being changed by javaScript code instead of JSP code.
The difference is that javaScript executes on the client but JSP exectues on
the server.
For example, consider a page that asks if the user is a man or a woman, and
has a dropdown list that changes depending on if a man or a woman is
choosing (clothing types: blouse versus shirt). The dropdown list might
only change at the client, not at the server. But the session variables only
exist at the server. In this case, the data can only be passed by URL
parameters. Unless someone knows of a way to use javaScript to change
items at the server, without using parameter passing (aka, URL rewriting)?
Bill
Re[4]: which is the best way to pass the value from one screen to
another either hiddenor session
Author: Shrinivas Vadavadagi
(http://www.jguru.com/guru/viewbio.jsp?EID=1170700), May 17, 2004
You can give the same name in the form, so that you can recognise
what the user has selected. Hence what ever you can do in URL re-
writing can be done through the session management. But there is a
limitation in this as this is no scalable. One study suggests that one can
store upto 3K of data in the session after whicg there will be drop in the
performance. Hence should store the data in the session which are
necessary and clear the session data, if not necessary.
Re[5]: which is the best way to pass the value from one screen to
another either hiddenor session
Author: sathish kumar
(http://www.jguru.com/guru/viewbio.jsp?EID=1185907), Jul 18,
2004
i AM ACCEPTING ANY FIVE DIFFERENCE BETWEEN
THEM.PLEASE IF ANY ONE FOR THIS...
With Tomcat 3.x, by default the servlet container was set up to allow invoking a
servet through a common mapping under the /servlet/ directory.
A servlet could be accessed by simply using an url like this one:
http://[domain]:[port]/[context]/servlet/[servlet full qualified name].
The mapping was set inside the web application descriptor (web.xml), located under
$TOMCAT_HOME/conf.
With Tomcat 4.x the Jakarta developers have decided to stop allowing this by
default. The <servlet-mapping> tag that sets this mapping up, has been
commented inside the default web application descriptor (web.xml), located under
$CATALINA_HOME/conf:
Hi,
The XSS vulnerability has been found at the time Tomcat 4.0.3 has been released
(and 4.1.2 was in beta). The problem was connected to the fact that it was possible
to run some specific classes simply using the /servlet/ mapping.
The Jakarta group that is working on Tomcat has immediately found a solution to the
problem.
The simple, but working solution, was to comment the /servlet/ mapping from the
default web application descriptor (web.xml), located under the
$TOMCAT_HOME/conf. This has been done sinc 4.1.3 beta.
A developer can still uncomment the /servlet/ mapping, but on a standard
installation, that mapping is not available.
Personal note: To be honest, I think that this is also a good choice for writing clearer
web application.
What is GlassFish?
Location: http://www.jguru.com/faq/view.jsp?EID=1255621
Created: Jul 29, 2005
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
The GlassFish Project is Sun's open source application server project. Found at
https://glassfish.dev.java.net/, you can participate in the development of the latest
version of Sun's Java System Application Server PE 9.0. It is based on Java
Enterprise Edition 5.