Sie sind auf Seite 1von 763

Servlets FAQ From jGuru

Generated Sep 13, 2005 2:17:14 PM

Location: http://www.jguru.com/faq/Servlets
Ownership: http://www.jguru.com/misc/user-agree.jsp#ownership.

How do I set my CLASSPATH for servlets?


Location: http://www.jguru.com/faq/view.jsp?EID=141
Created: Sep 3, 1999 Modified: 2001-05-05 14:19:15.228
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

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 JSDK: JSDK_HOME/lib/jsdk.jar


• For Tomcat: TOMCAT_HOME/lib/servlet.jar

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.)

• classes in the webapp/WEB-INF/classes directory


• JAR files in the webapp/WEB-INF/lib directory

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)

The Complete CLASSPATH Guide for Servlets


(http://www.meangene.com/java/classpath.html) by Gene McKenna
(mckenna@meangene.com) has detailed instructions on how to set your CLASSPATH
for JavaWebServer and JRun.

See also http://www.jguru.com/faq/view.jsp?EID=413601


Comments and alternative answers

Important precision : Under Apache (at least with...


Author: Denis BUCHER (http://www.jguru.com/guru/viewbio.jsp?EID=7742), Jan
22, 2000
Important precision : Under Apache (at least with jserv under Linux) you SHOULD
NOT put this in any system path, as it won't work. You must put the new path into
jserv.properties file, that you located maybe into your apache config dir !!!

I've found it simpler to just copy the JAR file to...


Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Jun 15,
2000
I've found it simpler to just copy the JAR file to the extensions directory of your
runtime:

jre/lib/ext

under your JDK directory, as in:


c:\jdk1.3\jre\lib\ext

If you are using JRun (atleast with v2.3.3), adding...


Author: sharad gupta (http://www.jguru.com/guru/viewbio.jsp?EID=100198), Jul 21,
2000
If you are using JRun (atleast with v2.3.3), adding servlet classes in system path won't
work. Instead add the path in jsm.properties file.

Unfortunately, Jaz' extension solution doesn't work...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Sep 17, 2000
Unfortunately, Jaz' extension solution doesn't work for some JARs, notably XML
parsers. I'm not exactly sure why; perhaps it's package name collision. The webapp
solution (WEB-INF/lib) is preferred.

I would not hesitate to have a static block in one...


Author: Aprameya Paduthonse (http://www.jguru.com/guru/viewbio.jsp?EID=4707),
Feb 1, 2001
I would not hesitate to have a static block in one of my early loaded servlets to list the
environment parameters
static
{
Properties envProps = System.getProperties();
System.out.println("__________________________ BEGIN JAVA
SETTINGS _______________________________");
for (Enumeration e = envProps.propertyNames() ;
e.hasMoreElements() ;)
{
String prop = (String)e.nextElement();
System.out.println(prop + " : " +
envProps.getProperty(prop));
}
System.out.println("_____________________________END JAVA
SETTINGS _______________________________");
}
view this
Author: kumar varma (http://www.jguru.com/guru/viewbio.jsp?EID=1225116), Feb
4, 2005
along with classpath explanation can you please give us details about servlet-
api.jar,tools.jar,etc.?

Is it the "servlets" directory or the "servlet" directory?


Location: http://www.jguru.com/faq/view.jsp?EID=142
Created: Sep 3, 1999 Modified: 1999-12-22 11:09:48.603
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

For Java Web Server:

• on the file system, it's "servlets"


c:\JavaWebServer1.1\servlets\DateServlet.class
• in a URL path, it's "servlet"
http://www.stinky.com/servlet/DateServlet

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).

Comments and alternative answers

It depends on your mapping. Virtual path could be ...


Author: Roceller Alvarez (http://www.jguru.com/guru/viewbio.jsp?EID=41828), Apr
28, 2000
It depends on your mapping. Virtual path could be different from the real path.

Re: It depends on your mapping. Virtual path could be ...


Author: Tim Urberg (http://www.jguru.com/guru/viewbio.jsp?EID=510070), Oct
17, 2001
If you have Tomcat the directory will be:

TOMCAT_HOME/webapps/ROOT/WEB-INF/classes

If you're running JRun it will be:

C:\Program Files\Allaire\JRun\servers\default\default-app\WEB-INF\classes

I hope that helps

Why doesn't my servlet work inside a tag?


Location: http://www.jguru.com/faq/view.jsp?EID=143
Created: Sep 3, 1999 Modified: 2000-05-21 14:36:17.445
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)
If you use your servlet inside an SSI, you must use res.getOutputStream() and not
res.getWriter(). Check the server error logs for more details.

Comments and alternative answers

Does anyone here have any experience getting <s...


Author: Slim Whitman (http://www.jguru.com/guru/viewbio.jsp?EID=29020), Mar
27, 2000
Does anyone here have any experience getting <servlet> tags to work under Netscape
Enterprise Server version 4? (I have service pack 3) I don't get any errors, but it's as if
the server never parses the servlet tag. Parse HTML is turned on in the server, without
using the exec tag, and for all html files. (instead of shtml)

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.

Jason Hunter's Servlet book was a defacto when it was...


Author: Matt Woody (http://www.jguru.com/guru/viewbio.jsp?EID=36408), May 12,
2000
Jason Hunter's Servlet book was a defacto when it was released because in 1998. He,
under O'Reilly, released the best servlet book to date. Because he used the
JavaWebServer in all his examples, he frequently used the <servlet> tag. The
<servlet> tag is NOT a part of the Servlet API. It was simply a cool thing that
JavaWebServer supported. I would suggest that you look towards JSP if you like that
idea of combining HTML and Servlets. Otherwise you could create your own utilities
to parse html documents, extract syntax within <servlet> and </servlet>, write to a
different file, compile it, and then somehow tie the compiled code and the html
together. Another option would be to parse an html document, inverse the outlying
html and the syntax within <servlet>, and then compile that. I have quite often
pondered doing this.

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:

public void doGet(HttpServletRequest req, HttpServletResponse res)


throws ServletException, IOException
{
doPost(req, res);
}
Note that implementing the <mono>service()</mono> method is usually not what
you want to do, since HttpServlet provides its own implementation of
<mono>service()</mono> that turns around and calls <mono>doGet(),
doPost(),</mono> etc.

Lee Crocker (LCrocker@INFORMANT.COM): "It's probably cleaner not to override


<mono>service()</mono> when extending HttpServlet. The existing service method
just calls <mono>doGet()</mono>, <mono>doPost()</mono>, etc. as appropriate,
so you can certainly override it if you feel like it, but then you wind up not only
treating GET and POST identically, but also all other HTTP commands, like HEAD,
TRACE, and OPTIONS. If you want GET and POST to do the same thing, just have
<mono>doGet()</mono> and <mono>doPost()</mono> call the same private
method that does all the work."

See also:

• What is the difference between the doGet and doPost methods?


• 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?

Comments and alternative answers

I created a servlet, from which I usually extend, by...


Author: Nicola Ken Barozzi (http://www.jguru.com/guru/viewbio.jsp?EID=39153),
Apr 23, 2000
I created a servlet, from which I usually extend, by making a new method that gets
called by doGet() and doPost() and handles error handling.
Apart from that it is a normal HttpServlet.
CODE:
/**
* Copyright: Copyright (c) 2000
* @author Nicola Ken Barozzi
*/

import java.io.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;

public abstract class WebAppServlet extends HttpServlet


{

public void init(ServletConfig config)


throws ServletException
{
super.init(config);
}
public final void doGet
(
HttpServletRequest request,
HttpServletResponse response
) throws ServletException, IOException
{
doSafeGetOrPostWrapper(request, response);
}

public final void doPost


(
HttpServletRequest request,
HttpServletResponse response
) throws ServletException, IOException
{
doSafeGetOrPostWrapper(request, response);
}

private void doSafeGetOrPostWrapper


(
HttpServletRequest request,
HttpServletResponse response
) throws ServletException, IOException
{
HttpSession CurrentSession;

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)
{
}

}
}

public abstract void doSafeGetOrPost


(
HttpServletRequest request,
HttpServletResponse response,
HttpSession CurrentSession,
) throws Throwable;

Re: I created a servlet, from which I usually extend, by...


Author: Nirav Patel (http://www.jguru.com/guru/viewbio.jsp?EID=424727), May
18, 2001
Exactly...

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.

Re: I created a servlet, from which I usually extend, by...


Author: Ajay P (http://www.jguru.com/guru/viewbio.jsp?EID=1234517), Mar 24,
2005
Hi! When i am trying to compile the code using ApacheTomcat on IE i am getting
the entire code as an output display. How am i suppose to run this servlet? Should
i be saving the code as WebAppServlet.html? Help me out with this.If i am
conceptually wrong then please tell me as what concept is involved with the
execution. Thank you.

Re[2]: I created a servlet, from which I usually extend, by...


Author: Ajay P (http://www.jguru.com/guru/viewbio.jsp?EID=1234517), Mar
24, 2005
Hey i'm sorry.I need to store it in a java file. I don know as where i kept my
brain that time. Its fine now. No need for any reply to the previous message.
Thank you.
How do I fully shut down the server?
Location: http://www.jguru.com/faq/view.jsp?EID=145
Created: Sep 3, 1999 Modified: 1999-12-22 11:10:54.113
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

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".)

Comments and alternative answers

How do I fully shut down the server?


Author: Rajan Kumar (http://www.jguru.com/guru/viewbio.jsp?EID=416254), May 6,
2001
You can shut down the JWS from admin tool; or alternativly by going to NT services
and "stop" the "javawebserver" service.

My browser says "the server returned an invalid or unrecognized response"


-- what gives?
Location: http://www.jguru.com/faq/view.jsp?EID=146
Created: Sep 3, 1999 Modified: 1999-12-22 11:11:42.609
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

This is probably due to a NullPointerException being thrown. There's a bug in JWS


1.1 whereby it doesn't correctly log these exceptions.

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.

What is the HelloWorld Servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=147
Created: Sep 3, 1999 Modified: 2001-12-29 11:08:03.612
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class HelloHttpServlet extends HttpServlet


{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException
{
String name = req.getParameter("name");
if (name == null) name = "Joe";
res.setContentType("text/plain");
ServletOutputStream out = res.getOutputStream();
out.println("Hello, " + name + "!");
}
}
This code responds to an invocation of the form

http://myserver.foo.com/servlet/HelloHttpServlet?name=Fred
Comments and alternative answers

Don't forget to include imports!!!!


Author: Sharat N (http://www.jguru.com/guru/viewbio.jsp?EID=502507), Oct 16,
2001
(for new guys)In the above program, include http imports.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
Thanks
Sharat

function setContentType not found in Tomcat 3.2.1


Author: John Meagher (http://www.jguru.com/guru/viewbio.jsp?EID=813752), Mar
26, 2002
Whenever I javax helloWorld.java, I get this error: function
setContentType(java.lang.String) not found in class
javax.servlet.http.HttpServletResponse Why would I get this message, if my classpath
is ok?

How do I get the name of the currently executing script?


Location: http://www.jguru.com/faq/view.jsp?EID=148
Created: Sep 3, 1999
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

Use req.getRequestURI() or req.getServletPath(). The former returns the path to the


script including any extra path information following the name of the servlet; the
latter strips the extra path info. For example:

URL http://www.purpletech.com/servlets/HelloEcho/extra/info?height=100&width=200
getRequestURI /servlets/HelloEcho/extra/info
getServletPath /servlets/HelloEcho
getPathInfo /extra/info
getQueryString height=100&width=200

This is useful if your form is self-referential; that is, it generates a form which calls
itself again. For example:

out.println("<FORM METHOD=POST ACTION=\"" +


res.encodeURL(req.getServletPath()) +
"\">");
out.println("<INPUT NAME=value>");
out.println("<INPUT TYPE=submit>");
out.println("</FORM>");
(encodeURL adds session information if necessary. See the Sun Servlet Tutorial and
this FAQ's Session Tracking question. Note that this method was renamed from
"encodeUrl" to the properly-capitalized "encodeURL" somewhere around version 2.1
of the servlet spec.)

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.

Comments and alternative answers

I tried to do this in IBM WAS 3.02 and got the error...


Author: Avinash Kachhy (http://www.jguru.com/guru/viewbio.jsp?EID=224947), Oct
9, 2000
I tried to do this in IBM WAS 3.02 and got the error that the method
req.getServletPath() was not defined. Is this correct for WAS or did I do something
wrong?

out.println("Servlet Path = " + req.getServletPath());

Thanks
Avinash

Use this piece of code to demonstrate the physical...


Author: Aprameya Paduthonse (http://www.jguru.com/guru/viewbio.jsp?EID=4707), Feb 1, 2001
Use this piece of code to demonstrate the physical location of the servlet that gets invoked by a virtual
path(URI)
out.println(getServletConfig().getServletContext().getRealPath(request.getRequestURI(

How do I ensure that my servlet is thread-safe?


Location: http://www.jguru.com/faq/view.jsp?EID=150
Created: Sep 3, 1999 Modified: 2003-01-08 14:30:31.956
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

[See also What is the meaning of calling a method or object "thread-safe?" ]

This is actually a very complex issue. A few guidelines:

1. The init() method is guaranteed to be called once per servlet instance,


when the servlet is loaded. You don't have to worry about thread safety inside
this method, since it is only called by a single thread, and the web server will
wait until that thread exits before sending any more threads into your
service() method.
2. Every new client request generates (or allocates) a new thread; that thread
calls the service() method of your servlet (which may in turn call
doPost(), doGet() and so forth).

3. Under most circumstances, there is only one instance of your servlet, no


matter how many client requests are in process. That means that at any
given moment, there may be many threads running inside the service()
method of your solo instance, all sharing the same instance data and
potentially stepping on each other's toes. This means that you should be
careful to synchronize access to shared data (instance variables) using the
synchronized keyword.

(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.)

5. A simple solution to synchronizing is to always synchronize on the servlet


instance itself using &amp;quot;synchronized (this) { ... }
&amp;quot;. However, this can lead to performance bottlenecks; you're
usually better off synchronizing on the data objects themselves.

6. If you absolutely can't deal with synchronizing, you can declare that your
servlet &amp;quot;implements SingleThreadModel&amp;quot;. This
empty interface tells the web server to only send one client request at a time
into your servlet. From the JavaDoc: &amp;quot;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.&amp;quot;
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.

8. The destroy() method is not necessarily as clean as the init() method.


The server calls destroy either after all service calls have been completed, or
after a certain number of seconds have passed, whichever comes first. This
means that other threads might be running service requests at the same time
as your destroy() method is called! So be sure to synchronize, and/or wait
for the other requests to quit. Sun's Servlet Tutorial has an example of how to
do this with reference counting.
9. destroy() can not throw an exception, so if something bad happens, call
log() with a helpful message (like the exception). See the
&amp;quot;closing a JDBC connection&amp;quot; example in Sun's Tutorial.

Comments and alternative answers

Point 3: Isn't it one servlet instance per regist...


Author: sharma MR (http://www.jguru.com/guru/viewbio.jsp?EID=4939), Mar 15,
2000
Point 3: Isn't it one servlet instance per registered name of the servlet?

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?

Point 2: Each client generates a thread which can call...


Author: Tony Biag (http://www.jguru.com/guru/viewbio.jsp?EID=27664), Mar 23,
2000
Point 2: Each client generates a thread which can call doGet() (et al) method.

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)?

3. Maybe. It probably depends on the engine implem...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Mar 24, 2000
3. Maybe. It probably depends on the engine implementation. It might be good to
check the spec and documentation if your logic depends on it.

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.

2. "Every new client request generates a new ...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Apr 3, 2000
2. "Every new client request generates a new thread" -- actually, the servlet engines
are free to implement thread pools, which means there's a chance that two successive
doGets will happen on the same actual thread. You shouldn't make any assumptions
about this either (in case you're tempted to use ThreadLocal variables or some other
bad idea :-).
in case you're tempted to use ThreadLocal variables or some other bad idea
:-).
Author: Pahl Aakh (http://www.jguru.com/guru/viewbio.jsp?EID=1170988), Apr
16, 2005
Alex, Would you please explain why thie could be a problem? I would think that
as long as you assign a new, appropriate, value to ThreadLocal variable before it is
used, it will be used properly! A thread will complete the first request-processing
before it starts the next one even if reused out of the threadpool, won't it. Thanks

Point 3: Reading the "Playing it Smart With Java...


Author: Lars Andersson (http://www.jguru.com/guru/viewbio.jsp?EID=40504), Apr
26, 2000
Point 3: Reading the "Playing it Smart With Java Servlets" by Matthew Ferris and
Michael Bogovich in Servlet Central March 1999, the authors suggest a solution
where a new instance of a transaction class is created for every client request. Calling
this instance's doRun() method would create an execution environment similar to
what you get when using the SingleThreadModel. The benefit would be that you can
maintain common resources such as connection pools in the servlet's doGet() method
before calling the transaction instance's doRun() method. The transaction object can
be pooled for performance, or associated with the session if further processing is
needed in a later request.

This setup sounds good to me, but I have not tried it yet. Any comments?

How local data in servlet is syncronized


Author: Arun Selvaraj (http://www.jguru.com/guru/viewbio.jsp?EID=1105676), Aug
1, 2003
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.)
But at any point of time we will have only one instance created for a single servlet.It
means that there will be a memory allocation for each and every member of that
servlet class only one. So calls to service method will actually use the allocated
memory reference. Then how the local variables inside the service will not be
allocated at sigle place?
And if i declare any other method which is called from service() method in my
servlet, will it be thread-safe (or) do i need to syncronize it?
Please Clarify.

Re: How local data in servlet is syncronized


Author: Steve Xu (http://www.jguru.com/guru/viewbio.jsp?EID=1107576), Aug 9,
2003
don't confuse the instance variable with the local variable inside service method.
instance variable: allocated at the object level, needs to be synchronized. local
variable: allocated on the stack of the calling thread, does not need to be
synchronized.
synchronize the read only instance variable
Author: Deepesh Rastogi (http://www.jguru.com/guru/viewbio.jsp?EID=1119170),
Oct 2, 2003
Do I need to synchronize the instance variable/object, which I am trying to keep for
read only purposes? I am using two instnce variable, the first is the property from file
and the other is an object on which I need to make a method calls to log/store in the
database.I do not think both the variable be synchronized... thanks deepesh

whats the difference


Author: Prashant Jain (http://www.jguru.com/guru/viewbio.jsp?EID=1251496), Jul 2,
2005
what exactly the difference between synchronizing the service method of the servlet
and making the servlet to implement singlethreadmodel ? when there just one instance
of a servlet then synchronizing the service method would actually sync' every request
(thread) calling the servlet. ???

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.

See section 2.3 of the Servlet Essentials tutorial


(http://www.novocode.com/doc/servlet-essentials/) . Also see The Session Tracking
API (http://webreview.com/wr/pub/1999/01/08/bookshelf/) , excerpted from Java
Servlet Programming (http://www.oreilly.com/catalog/jservlet/) by Jason Hunter
(http://webreview.com/wr/pub/au/Hunter_Jason).

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

Also see the FAQ What servlet code corresponds to...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), May 21,
2000
Also see the FAQ What servlet code corresponds to the various "scope" values for the
<jsp:useBean> tag? .

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.

what about the "jsessionid" added to keep the session ?


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.
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)

Here's a clever trick: use a redirect. Drop a cookie on the HttpServletResponse


object, then call response.sendRedirect() to a "phase two" servlet. The "phase
two" servlet then tests whether the cookie was sent back to it. If so, that means the
user accepted the cookie the first time; if not, it means that either the client rejected
the cookie, or the browser doesn't support cookies.

Note that this technique only works if the "phase two" servlet is hidden from the
user; if the user can jump directly to 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.

Alex Chaffee (http://www.stinky.com/alex/, alex@jguru.com) has written a Servlet


that demonstrates this technique called CookieDetector
(http://www.purpletech.com/code/CookieDetector.html)

See also http://www.jguru.com/jguru/faq/view.jsp?EID=138297

How do I integrate HTML design into my Servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=153
Created: Sep 3, 1999 Modified: 2001-01-15 07:31:27.091
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

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.)

See my article at Servlet Central (http://www.servletcentral.com/1998-


12/designprocess.dchtml) for an expansion on these themes.

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.

C. Presentation Templates. This is a good way to put common navigation


elements (button bar, credits, etc) on all of your pages. The technology is built in to
the Java Web Server, and implemented by several (though not all) of the servlet
engines.
Pro: you don't have to enter in the same common HTML for all the countless pages
in your web site.
Con: your servlet code still has to hardcode HTML if it wants to be powerful (see
item B, SSI).

D. JSP Java Server Pages. You write files in HTML format, and embed actual Java
code inside the HTML. This is kind of 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.

Comments and alternative answers

Comments on E and F Page parsers have been written....


Author: Brett Knights (http://www.jguru.com/guru/viewbio.jsp?EID=8054), Jan 27,
2000
Comments on E and F Page parsers have been written. Go to
http://www.docuverse.com/htmlsdk/index.html and you can download the pieces
necessary to parse html files into a dom Document. You can then use dom methods to
modify then emit the results. OR if you prefer F you can suck most of an html page
into an xsl template tag and insert <xsl: tags to format your dynamic output. It's not
great for really dynamic sites but it's an excellent way to have a page designer do a
bunch of work then turn it over to you for installing dynamism (dynamicality? :-)
Saxon is an excellent engine for this.

There's another option: use SSI for Java. It's an SSI...


Author: Joe Morse (http://www.jguru.com/guru/viewbio.jsp?EID=91113), Jun 29,
2000
There's another option: use SSI for Java. It's an SSI parser that runs in your VM, and
it's open source (GPL). It also includes some cool utility classes (which you can
mimic or extend) for creating stateful form elements and other things. There's even an
iterator for printing variable-length collections (e.g. db recordsets, etc). Plus, it's
portable; it will run on any web server with little or no changes. Check it out at
http://www.freecode.com/cgi-bin/viewproduct.pl?8543.

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.)

How do I send email from a servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=154
Created: Sep 3, 1999 Modified: 2000-07-25 12:18:54.284
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

From: James Cooper (pixel@bitmechanic.com)

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.

Comments and alternative answers

If you want to use the JavaMail API, get it and create...


Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Jul 24,
2000
If you want to use the JavaMail API, get it and create a program similar to the Hello
World program.

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 -

http://www.chris.lack.org and choose the java option on the professional menu.

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.

Are there any ISPs that will host my servlets?


Location: http://www.jguru.com/faq/view.jsp?EID=155
Created: Sep 3, 1999 Modified: 2003-04-04 10:57:05.916
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

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:

• Daniel Kehoe (kehoe@fortuity.com) has had "very happy experiences" with


Silicon Valley Web Hosting (http://www.svwh.net/) for several clients.
• Horus Networks - http://www.horus.ch/servlets.shtml
• (http://www.servlets.net) is an ISP geared towards hosting servlets.
• http://www.ebpcs.net
• http://www.mycgiserver.com is free (!) and does EJB too
• http://www.tricreations.com
• http://www.webappcabaret.com
• http://www.cwihosting.com (see comment below)
• http://scorpions.net/
• Rage Media
• Rimu Hosting

A few ISPs have also said that they can host Java applications:

• The Sphere (http://www.thesphere.com/)


• Centralogic (http://www.centralogic.com/)
• Electronaut (http://www.electronaut.com/)

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?

Comments and alternative answers

Horus Networks is very flexible on all services, and...


Author: Denis BUCHER (http://www.jguru.com/guru/viewbio.jsp?EID=7742), Jan
22, 2000
Horus Networks is very flexible on all services, and we would be pleased to host
servlets... c.f. our own programmation tests under http://www.horus.ch/servlets.shtml
http://www.horus-networks.com/servlets.shtml

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!

Re: Web Hosting


Author: dufunk Eugene Rozum
(http://www.jguru.com/guru/viewbio.jsp?EID=1193732), Sep 6, 2004
http://www.prokmu.com

Re[2]: Web Hosting


Author: Eugene Rozum
(http://www.jguru.com/guru/viewbio.jsp?EID=1254770), Jul 24, 2005
Prokmu Jsp hosting http://www.prokmu.net

http://www.ebpcs.net is a very cool one too


Author: Steve Nguyen (http://www.jguru.com/guru/viewbio.jsp?EID=39558), Apr 24,
2000
http://www.ebpcs.net is a very cool one too

If anyone looking for free Servlet/JSP hosting check...


Author: Nilesh Shah (http://www.jguru.com/guru/viewbio.jsp?EID=1810), May 30,
2000
If anyone looking for free Servlet/JSP hosting check this out.
http://www.mycgiserver.com

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

Check out www.wantjava.com They support Tomcat, O...


Author: James Ward (http://www.jguru.com/guru/viewbio.jsp?EID=242591), Nov 1,
2000
Check out www.wantjava.com They support Tomcat, Oracle, and mySQL! They also
have great customer service!

Another good listing of ISPs that support Java Servlets...


Author: Bill Day (http://www.jguru.com/guru/viewbio.jsp?EID=135825), Dec 8,
2000
Another good listing of ISPs that support Java Servlets is at:
www.servlets.com

The listings include contact info and rates.

More more more


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jul 16, 2001

• 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.

Re: CWI Hosting (http://www.cwihosting.com)


Author: Joost Schouten (http://www.jguru.com/guru/viewbio.jsp?EID=581960),
Jan 24, 2004
I just wanted to say that I use CWI hosting aswell, and do appreciate their service.
They have provided me with good support, even on my own code at times.

Just wanted to give them a fair chance.

Joost

re: Webhosting for servlets


Author: richard freeman (http://www.jguru.com/guru/viewbio.jsp?EID=752499), Feb
8, 2002
Zetnet.com will host jsp, sql, mysql, etc. with all of their standard hosting packages
(Ranging from UK£100 per annum).

Drop me a line on 01524 34918 if you are interested in doing so...

4Java.ca - inexpensive and reliable host


Author: support 4javaca (http://www.jguru.com/guru/viewbio.jsp?EID=804843), Mar
20, 2002
They host JSP, Servlet, J2EE. Very inexpensive, only USD$8.50/month!
http://www.4java.ca

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.

Check out http://www.ragemedia.ca


Author: Alex Iljin (http://www.jguru.com/guru/viewbio.jsp?EID=894025), May 27,
2002
Check out http://www.ragemedia.ca They provide J2EE application hosting
(including Servlets, JSP and EJB's) based on Tomcat/Jboss platform, plus PostgreSQL
database is standard for all plans.

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.

Re: Rimu Hosting


Author: Peter B (http://www.jguru.com/guru/viewbio.jsp?EID=1071364), Oct 15,
2003

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.

RE: Java Hosting


Author: Alacarte Java (http://www.jguru.com/guru/viewbio.jsp?EID=1118665), Sep
29, 2003
I am with Alacarte Java Hosting (http://www.alacartejava.com) and we specialize in
low cost Java JSP Hosting, Servlet Hosting, and much more. Checkout our Web Site
at http://www.alacartejava.com
« previous beginning next »

What is the difference between URL encoding, URL rewriting, HTML


escaping, and entity encoding?
Location: http://www.jguru.com/faq/view.jsp?EID=156
Created: Sep 3, 1999 Modified: 2000-09-17 15:25:28.842
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

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).

Example: changing "We're #1!" into "We%27re+%231%21"

URL Rewriting is a technique for saving state information on the user's browser
between page hits. It's sort of like cookies, only the information gets stored inside
the URL, as an additional parameter. The HttpSession API, which is part of the
Servlet API, sometimes uses URL Rewriting when cookies are unavailable.

Example: changing <A HREF="nextpage.html"> into


<A HREF="nextpage.html;$sessionid$=DSJFSDKFSLDFEEKOE"> (or whatever the
actual syntax is; I forget offhand)

(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) .

Comments and alternative answers

HTML Escaping, Entity Encoding


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jan 8, 2003
Yet another form of encoding is called "escaping" or "entity encoding," which
involves transforming special characters, like " into their HTML entity replacements,
like &quot; or &#34;. HTML entities are a convenient (or sometimes mandatory) way
of representing special characters like symbols or international language idiograms.
See http://hotwired.lycos.com/webmonkey/reference/special_characters/ for a list of
the standard HTML entities.

You must HTML-escape characters in fields that your servlet sends as default values
inside form fields, for instance

<INPUT type="text" name="name" value="Stan &quot;The


Man&quot; Museil">

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().

Re: HTML Escaping, Entity Encoding


Author: Christopher Koenigsberg
(http://www.jguru.com/guru/viewbio.jsp?EID=722897), Jan 9, 2003

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.

How can my applet or application communicate with my servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=157
Created: Sep 3, 1999 Modified: 2003-01-09 06:27:13.548
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

It's pretty straightforward. You can use the java.net.URLConnection and


java.net.URL classes to open a standard HTTP connection to the web server. The
server then passes this information to the servlet in the normal way.

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) .

Also, Chad Darby has an article with source code (http://www.j-


nine.com/pubs/applet2servlet/index.htm) on the subject.

And Netscape DevEdge Online has a similar article - Applet-to-Servlet


Communication for Enterprise Applications
(http://developer.netscape.com/viewsource/index_frame.html?content=fields_servlet
/fields_servlet.html) skip to the &amp;quot;Communication Tactics&amp;quot;
section to get to the good part.

See also:

• How can I pass an object from an applet to a 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?
• How can an applet or application pass data to and read output from a CGI
script or Servlet?
• see the section "An Applet That Sends POST Data" here -
http://archive.coreservlets.com/Chapter17.html

Comments and alternative answers

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 '&'.

How can I debug my servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=158
Created: Sep 3, 1999 Modified: 2001-07-19 15:41:41.969
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)
Hoo boy, that's a tough one.

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:

StringBuffer logBuffer = new StringBuffer();

public void log(String s) {


s = new Date().toString() + ": " + s;
System.err.println(s);
logBuffer.append(s);
logBuffer.append("\n");
super.log(s);
}
And here's some code that you can add to the end of your doGet or doPost method
that prints out the entire log after each request:
out.println("<HR>\n<H3>Error log this session:</H3>\n<PRE>");
out.println(logBuffer.toString());
out.println("</PRE><P>");
Both of these should be disabled once you actually ship your servlet, but they can be
very useful during development and debugging.

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 (abc408@hotmail.com) writes:

I am debugging servlets running servletRunner inside of IBM's VisualAge for Java.

On my first servlet project, I used a ton of log messages for debugging.

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.

The setup instructions are at: (http://www.ibm.com/java/education/server-


side/server-side.html)

jRun also claims to have excellent log file support as well as some debugging
facilities.

Eric Gilbertson (eric@bitsource.com) adds:

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:

java_g.exe -debug -Dserver.name="javawebserver"


[extra args...] com.sun.server.ServerProcess
jdb password=[password]
This will start the Web server process and echo a password. The password may be
then used with jdb to attach to the process. Note that this will start only the Web
server, not the admin server.

Sun does not advertise this mechanism which in my mind is the only way to debug
non-trivial servlets.

Comments and alternative answers

Jetty is an open-source HTTP servlet server written...


Author: Kent Johnson (http://www.jguru.com/guru/viewbio.jsp?EID=3211), Dec 22,
1999
Jetty is an open-source HTTP servlet server written in Java. It makes an excellent
servlet debugging and deployment environment. I build Jetty and my servlets and
supporting classes into a single executable that I debug the same as any other
application. I am using CodeWarrior on a Macintosh but this technique should work
with any development tools that can debug an application. Jetty is available from
http://www.mortbay.com.

New Atlanta has a free product called ServletExecD...


Author: Erik Hanson (http://www.jguru.com/guru/viewbio.jsp?EID=38768), Apr 21,
2000
New Atlanta has a free product called ServletExecDebugger which is a debugging
version of their ServletExec product. It consists of a jar file containing some or all of
ServletExec and a small source file containing a main() method. You build that with
your servlets, and then you can use your debugger on your servlets. It should work
with any development environment.

See also this question in the JSP FAQ which describes...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), May 22,
2000
See also this question in the JSP FAQ which describes debugging with VAJ and
Tomcat.

From the tomcat-user mailing list: From: Vincent...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), May 22,
2000
From the tomcat-user mailing list:
From: Vincent Aumont <vincent.aumont@vslab.com>
Organization: Vancouver Software Labs
To: tomcat-user@jakarta.apache.org
Subject: Re: I need to debug a serlet: How can I do it?
To debug your servlets, you need to run tomcat itself in the debugger. To do so, you
must write your own tomcat main (see code below). Note that you must define the
tomcat.home property ( in a properties file or passed on the command line (-Dtomcat.
home=[...]/jakarta-tomcat)
import org.apache.tomcat.startup.Tomcat;
import java.lang.Exception;
import java.util.*;
import java.io.*;

public class Tomcat {

public static void main(String[] args) throws IOException {


try {
Tomcat.main(new String[] {});
} catch (Exception e) {
System.out.println("Can't start Tomcat");
System.out.println(e);
System.exit(0);
}
}
}

With Tomcat 4.1.12 and JDeveloper 9.0.3.... From: Vincent...


Author: Tommy Skodje (http://www.jguru.com/guru/viewbio.jsp?EID=446264),
Nov 18, 2002
... I used this call:
org.apache.catalina.startup.Catalina.main( new String[] { "-config" ,
"D:\\Programs\\Apache\\Tomcat4.1\\conf\\server.xml" , "-debug" , "start" }
.. in place of Tomcat.main(...) call, as well as added each and every jar-file in
Tomcat4.1\server\lib\ and Tomcat4.1\common\lib\ in classpath.

For Symantec Visual Cafe debugging, see Patrick Ch...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), May 31,
2000
For Symantec Visual Cafe debugging, see Patrick Chanezon's Debug JSP and Servlets
with Visual Cafe using Tomcat howto.

You can download the latest version of JBuilder for...


Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362), Aug
8, 2000
You can download the latest version of JBuilder for free and use it to debug your
servlets using Tomcat, the official Servlet reference implementation.

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.

You can view a detailed paper on how to set up you environment at


community.borland.com

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

re: debugging servlets


Author: Bob Mook (http://www.jguru.com/guru/viewbio.jsp?EID=404742), Apr 17,
2001
Oracle has a nice IDE for debugging servlets - JDeveloper. Its runs in a built-in
JSWDK server. bob

Re: re: debugging servlets


Author: Jo Hh (http://www.jguru.com/guru/viewbio.jsp?EID=961119), Jul 23,
2002
debuging servlets is one thing but is there a way to integrate catalina/tomcat to
debug whole sessions like in forte? i couldnt find a way with the actual jdev
release. did you?

Debugging using IntelliJ Ideas


Author: raj subramani (http://www.jguru.com/guru/viewbio.jsp?EID=576334), Mar 6,
2002

I got tomcat working through my Idea's IDE (from Intellij)

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.

You can use IDEA's remote debugging option to debug servlets.

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:

Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:


transport=dt_socket,server=y,suspend=n,address=5000

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:

%_STARTJAVA% %TOMCAT_OPTS% -Djava.


security.policy=="%TOMCAT_HOME%/conf/tomcat.policy"
-Dtomcat.home="%TOMCAT_HOME%" %_MAIN% start %2 %3 %4 %5 %6
%7 %8 %9

Add the JVM parameters you copied from IDEA into that line, so you have something
like:

%_STARTJAVA% %TOMCAT_OPTS% -Djava.


security.policy=="%TOMCAT_HOME%/conf/tomcat.policy"
-Dtomcat.home="%TOMCAT_HOME%" -Xdebug -Xnoagent -Djava.
compiler=NONE -Xrunjdwp:
transport=dt_socket,server=y,suspend=n,address=5000 %_MAIN%
start %2 %3 %4 %5 %6 %7 %8 %9

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.

Re[2]: Debugging using IntelliJ IDEA


Author: Justin Hopper (http://www.jguru.com/guru/viewbio.jsp?EID=855419),
Apr 26, 2002
Yes, yes, yes this is a very nice feature of both IntelliJ and Java. However, I
have found that while running Tomcat 3.2 and IntelliJ 2.5.2 in this remote
debugger, that everytime I hit an exception an "native" access violation would
occur. This would cause Tomcat to shutdown and obviously end the debugging
session.

In order to get around this I had to include the

-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

Oddly enough, this seemed to speed up the debugger response as well.

One other thing that I would like to add is that the

TOMCAT_OPTS
variable was put there so the it can be set to the value of all of these additional
parameters.

So an alternative would be to not modify the "startServer:" portion of the script


but rather initialize the TOMCAT_OPTS variable to the list of options
specified below. Either way will result in the same behavior, it is just that
using the variable will allow you to turn debugging on and off by setting and
unsetting the TOMCAT_OPTS variable from some external action (i.e.
separate "startup.*" scripts).

Thanks for posting this solution. Justin

Re: Debugging using IntelliJ Ideas


Author: raj subramani (http://www.jguru.com/guru/viewbio.jsp?EID=576334),
Apr 2, 2002

PS: In response to the question asked (repeatedly)

• 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).

(CookieDetector (http://www.purpletech.com/code/CookieDetector.html) has


an example, with source code, of sending a redirect.)

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.

Focus on Java (http://java.miningco.com/library/weekly/aa090299.htm) has a brief


article describing the use of the Java 2 JPEGCodec class.

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:

• A list of Java Image links is at Purple Technology


• See also How can I plot data on a graph or chart from a ser... on plotting
charts and graphs from a servlet.
• Is there any way to generate offscreen images without relying on the native
graphics support?
• How can I display tif graphics in my Java applet?
• Reading TIF file with a servlet, converting it into...

Comments and alternative answers

Remember the IMG tag


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Dec 16, 2001
Remember, to display an image inside an HTML page, you have to use the IMG tag,
like
<IMG src="/mywebapp/myimageservlet">
Just writing the data to the servlet response isn't going to work, unless you're writing
an entire image/gif or image/jpeg document.

code to write imgs on the fly from a jsp


Author: kamalesh kam (http://www.jguru.com/guru/viewbio.jsp?EID=1158032),
Mar 28, 2004
<%@ page import="javax.servlet.http.*"%> <%@ page import="java.io.*"%>
<%@ page import="java.awt.*"%> <%@ page import="java.util.Random"%>
<%@ page import="java.awt.Color"%> <%@ page
import="java.awt.image.*"%> <%@ page
import="Acme.JPM.Encoders.GifEncoder"%> <%@ page
import="com.sun.image.codec.jpeg.JPEGCodec"%> <%@ page
import="com.sun.image.codec.jpeg.JPEGImageEncoder"%> <%BufferedImage
image= new BufferedImage(500,500, BufferedImage.TYPE_INT_RGB);
Graphics g=image.getGraphics(); Random r=new Random(); g.fillRect(r,r,r,r);
FileOutputStream fos=new FileOutputStream("c:/ewr.jpg"); JPEGImageEncoder
encoder= JPEGCodec.createJPEGEncoder(fos); encoder.encode(image); %>
Jake stone adds source code
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Dec 16, 2001
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{

File f = new
File(System.getProperty("user.home")+"\\zoewrap.jpg");
JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(new
FileInputStream(f));
BufferedImage image =decoder.decodeAsBufferedImage() ;

// Send back image


ServletOutputStream sos = response.getOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);
encoder.encode(image);
}
Re: Jake stone adds source code
Author: Ping Long (http://www.jguru.com/guru/viewbio.jsp?EID=799119), May
15, 2002
Alex,
I got cached image problem in my application. I need to update image without
changing name.
Your idea may fix my problem. I would like to know when I can get those classes
such as:
JPEGImageDecode, JPEGImageEncoder, JPEGCodec.
Thanks in advance.
PL

Re[2]: Jake stone adds source code


Author: jpeg jones (http://www.jguru.com/guru/viewbio.jsp?EID=885462),
May 20, 2002

These classes are in the com.sun.image.codec.jpeg. package; they should be in


your jdk 1.3 (or whatever) src.jar

Re[3]: Jake stone adds source code


Author: Ohad Kravchick
(http://www.jguru.com/guru/viewbio.jsp?EID=1025885), Nov 14, 2002
I have a problem with that. i made a painter applet, and i need to write the
result of the painting to the server (asp). i've created an asp page which gets
posted data, from the applet (ACME.GifEncoder), and it still doesnt work.
will you please help me, i'm stuck badly. go and take a look at the painter:
my Painter send me email for response.....

Regarding the cache problem


Author: Thomas Isaksen (http://www.jguru.com/guru/viewbio.jsp?EID=1132932),
Dec 9, 2003
I think I had the same problem when trying to display an image fetched from a
servlet talking to the db. I simply added another parameter to the url which caused
the cache problem to go away:
First I had: <img src="/servlet/ImageServlet?id=n"/>
which didn't work, it was cached and showed the same image all the time.
So I put this in:
<img src="/servlet/ImageServlet?id=n&rnd=some_random_number"/>
and the image caching problem is gone :-)
"some_random_number" can be as simple as putting the value of
System.currentTimeMillis() or using java.util.Random to come up with a value.
Hope this helps.

How do I upload a file to my servlet or JSP?


Location: http://www.jguru.com/faq/view.jsp?EID=160
Created: Sep 3, 1999 Modified: 2003-01-11 10:39:24.072
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

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 &amp;quot;file&amp;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.

• Jason Hunter's MultipartRequest (available from http://www.servlets.com)

• Apache Jakarta Commons Upload (package org.apache.commons.upload)


"makes it easy to add robust, high-performance, file upload capability to your
servlets and web applications"

• CParseRFC1867 (available from http://www.servletcentral.com).

• HttpMultiPartParser by Anil Hemrajani, at the isavvix Code Exchange

• There is a multipart/form parser availailable from Anders Kristensen


(http://www-uk.hpl.hp.com/people/ak/java/, ak@hplb.hpl.hp.com) at
http://www-uk.hpl.hp.com/people/ak/java/#utils.

• JavaMail also has MIME-parsing routines (see the Purple Servlet References).

• Jun Inamori has written a class called


org.apache.tomcat.request.ParseMime which is available in the Tomcat
CVS tree.

• JSPSmart has a free set of JSP for doing file upload and download.

• UploadBean by JavaZoom claims to handle most of the hassle of uploading for


you, including writing to disk or memory.

• There's an Upload Tag in dotJ


Once you process the form-data stream into the uploaded file, you can then either
write it to disk, write it to a database, or process it as an InputStream, depending on
your needs. See How can I access or create a file or folder in the current directory
from inside a servlet? and other questions in the Servlets:Files Topic for information
on writing files from a Servlet.

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.]

Comments and alternative answers

Jun Inamori has written a class called org.apache....


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), May 8, 2000
Jun Inamori has written a class called org.apache.tomcat.request.ParseMime which is
available in the Tomcat CVS tree.

Jason Hunter has written a class called com.oreilly.servlet.MultipartRequest available


on Servlets.com

Re: Jun Inamori has written a class called org.apache....


Author: Turgut Z. Yesilyurt
(http://www.jguru.com/guru/viewbio.jsp?EID=443071), Jul 27, 2001
Hi, Could you please tell me what to do after I download his package and before
create instance of MultipartRequest. I download it and put in my class path but the
compiler does not find it.
Many thanks.
Turgut

Re: Jun Inamori has written a class called org.apache....


Author: Arnaud Palazzi (http://www.jguru.com/guru/viewbio.jsp?EID=1032208),
Nov 29, 2002
Hi,

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.

I complie and run the Jason Hunter's MultipartRequest,...


Author: Zuofeng Zeng (http://www.jguru.com/guru/viewbio.jsp?EID=240547), Nov
16, 2000
I complie and run the Jason Hunter's MultipartRequest, but it can not write local
system for uploaded file. How do? [Use java.io.FileOutputStream et al.

You may need to pass in the location of the "incoming" directory as a servlet
initialization parameter.

-Alex]

Re: I complie and run the Jason Hunter's MultipartRequest,...


Author: Hong Cao (http://www.jguru.com/guru/viewbio.jsp?EID=428109), May
24, 2001
Try this:
multi = new MultipartRequest(request, dirName, 10*1024*1024); //
10MB

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();
}
}

Re[2]: I complie and run the Jason Hunter's MultipartRequest,...


Author: Alexander Greco
(http://www.jguru.com/guru/viewbio.jsp?EID=1070397), Mar 27, 2003
I would really like to know what needs to be passed to the request parameter:
multi = new MultipartRequest(request, dirName, 10*1024*1024); // 10MB I
would assume that dirName is the path where the file rests on the client
machine but what is request? PLEASE HELP ME, I am totally confused

Re: I complie and run the Jason Hunter's MultipartRequest,...


Author: James Shipley (http://www.jguru.com/guru/viewbio.jsp?EID=9564), Sep
19, 2001
Is there a way to set the destination directory (i.e. where to save the file on the
server) dynamically, instead of with a 'static' init value?

I recently re-implemented Jason's MultipartRequest...


Author: Geoff Soutter (http://www.jguru.com/guru/viewbio.jsp?EID=12542), Nov 29,
2000
I recently re-implemented Jason's MultipartRequest - that class is now a thin wrapper
around a new class called MultipartRequest. This new class allows one to get at the
data without buffering it or writing it to disk. It also has fixes to avoid performance
problems associated with poorly implemented servlet containers. I donated it back to
Jason in honour of the service he has provided the java/servlet community and he has
uploaded it onto servlets.com; so feel free to check it out.

Geoff, I am very interested in what you have done but...


Author: Ian Davies (http://www.jguru.com/guru/viewbio.jsp?EID=266997), Dec 1,
2000
Geoff, I am very interested in what you have done but I cannot find it on servlets.com.
Can you be more specific as to its whereabouts?

Thanks.

Re: Geoff, I am very interested in what you have done but...


Author: Geoff Soutter (http://www.jguru.com/guru/viewbio.jsp?EID=12542), May
3, 2001
Er whoops. I should have said "a new class MutipartParser" above. Anyway,
check out these JavaDoc links to Jasons site: Heres the new MultipartParser class.
It allows you to read FileParts which have a writeTo(File) and
writeTo(OutputStream) method

The free class files from JSPSmart are the easiest...


Author: Iain Delaney (http://www.jguru.com/guru/viewbio.jsp?EID=255644), Dec 15,
2000
The free class files from JSPSmart are the easiest way to go, their sample pages work
fine and are simple to figure out. Why is their site written in ASP though? :)

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.

Here is my code as a jsp:

<%@ page import="com.jspsmart.upload.*" %>


<jsp:useBean id="ff" class="com.jspsmart.upload.SmartUpload"
scope="page" />
<%
String[] dir =
{ "C:\\temp\\tip.portal\\","/dp6.2/tip.portal/" };
String fn = request.getParameter("filename");
String cn = request.getParameter("clientno");
int id = -1;

if ( request.getServerName().equalsIgnoreCase("localhost")
) {
id = 0;
}
else {
id = 1;
}

String fid = dir[id] + cn + java.io.File.separator + fn;

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;
}
%>

This gives an error:

2001-09-24 17:18:06 - Ctx( /tip ): IllegalStateException in: R(


/tip + /client/docs/view.jsp + null)
OutputStream is already being used for this request

As a servlet:

package tip;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;
import com.jspsmart.upload.*;

public class viewClientSiteDocs extends TipServlet{

private String[] TARGET_DIR =


{ "C:\\TEMP\\tip.portal\\","/dp6.2/tip.portal/" };

private ServletConfig config;

public void init(ServletConfig config) throws


ServletException {
super.init(config);
this.config = config;
}

public void doPost(HttpServletRequest


req,HttpServletResponse res) throws ServletException {
doGet(req,res);
}

public void doGet(HttpServletRequest


req,HttpServletResponse res) throws ServletException {
String clientno = req.getParameter("clientno");
String filename = req.getParameter("filename");
int i =
( req.getServerName().equalsIgnoreCase("localhost") ) ? 0 : 1;
SmartUpload ff = new SmartUpload();
try {
String fid = TARGET_DIR[i] + clientno +
java.io.File.separator + filename;
ff.initialize( config,req,res );
ff.setForcePhysicalPath(true);
ff.downloadFile(fid,"application/pdf");
}
catch ( SmartUploadException e ) {
e.printStackTrace(System.err);
}
catch ( IOException e ) {
if ( e instanceof
java.io.FileNotFoundException ) {
try {

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.

Any ideas ???

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.

Thanks very very much for your posting!

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:wqs0006@sina.com
« previous beginning next »

How do I access a database from my servlet or JSP?


Location: http://www.jguru.com/faq/view.jsp?EID=161
Created: Sep 3, 1999 Modified: 2001-07-21 11:42:29.019
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

[See also How can I pool my database connections so I don't ...]

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) .

An interesting article on connection pools is at


http://webdevelopersjournal.com/columns/connection_pool.html.

From the tomcat-user mailing list, here is some code for storing a JDBC connection in
an instance variable:
From: "Koen Dejonghe" <koen_dejonghe@hotmail.com>
To: tomcat-user@jakarta.apache.org
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.*;

public final class YourClass extends HttpServlet {


Connection con = null;

public void init() throws ServletException {

String url = getServletContext().getInitParameter("url");


String uid = getServletContext().getInitParameter("uid");
String pwd = getServletContext().getInitParameter("pwd");

try {
//Register the JDBC driver
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch( Exception e ) {
e.printStackTrace();
}//end catch

//Get a connection to the database


try {
con = DriverManager.getConnection(url, uid, pwd);
} catch( Exception e ) {
e.printStackTrace();
}//end catch

}//end init()

public void destroy() {


try {
//Close the connection to the database
con.close();
} catch( Exception e ) {
e.printStackTrace();
}
}

public void doGet(HttpServletRequest req,


HttpServletResponse res)
throws ServletException, IOException{

try {
[...]
Statement st = con.createStatement();
[ more JDBC code ]
}
catch (SQLException e) {
[ ... ]
}
}
Comments and alternative answers

Sir, You have opened the connection in init method...


Author: Jayaramu DS (http://www.jguru.com/guru/viewbio.jsp?EID=70417), Jun 13,
2000
Sir,
You have opened the connection in init method and closing it in the destroy method. I
heard that keeping connection open for long time is not good. In your example
connection is made once and service method is executed for each request. What is
your opinion?

Re: Sir, You have opened the connection in init method...


Author: Paul Deschamps (http://www.jguru.com/guru/viewbio.jsp?EID=955735),
Jul 18, 2002
A friend of mine told me a good rule on this issue..

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?

it takes more time...

so if your just after the mustard. don't if you need relish


too then do.
Paul..

Re[2]: Sir, You have opened the connection in init method...


Author: Jayaramu DS (http://www.jguru.com/guru/viewbio.jsp?EID=70417),
Jul 18, 2002
Hi Paul..

I really appreciate your response.

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

Re[3]: Sir, You have opened the connection in init method...


Author: Paul Deschamps
(http://www.jguru.com/guru/viewbio.jsp?EID=955735), Jul 19, 2002
exactly.. you wouldn't keep you fridge open all morning
would you.. :) all your milk would spoil :)
But if you know that you need mustard. and someone might be
asking for relish. well leave it open for a bit.

JUST MAKE SURE YOU CLOSE THE FRIDGE!!..

Re[4]: Sir, You have opened the connection in init method...


Author: ilana mush
(http://www.jguru.com/guru/viewbio.jsp?EID=960896), Jul 23, 2002
Hi Paul

I connect my servlet from a java class. My question is how do you put


all the data (like url) into the servletContext?

Thanks,ilana

Sir Jayaramu DS, I think that it is good to initialize...


Author: Rafael Coutinho (http://www.jguru.com/guru/viewbio.jsp?EID=115513), Aug
20, 2000
Sir Jayaramu DS, I think that it is good to initialize your connection just one time,
then all the request will be faster because this will the connection will be already
opened. I know that the question wasn't aimed to me but this is my opinion. Bye

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 it an acceptable security risk to transmit database passwords across


HTTP? (If you're in an intranet, then the answer may well be "yes.")

Is there a way to get an automatic feed of database user IDs from the DB to
the servlet?

Is there a performance hit to opening and closing a connection once per


request? Once per session? (The answer to this is usually "yes" -- DB
connections can take many many seconds or even minutes to open -- which
is why connection pools are needed in the first place.)

There's no universal answer to any of these questions -- you have to figure


it out for yourself.

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.

Have a great day!!

Dangerous code example


Author: B B (http://www.jguru.com/guru/viewbio.jsp?EID=875134), May 11, 2002
The example code is buggy and dangerous at best. Many RDBMS systems do not
allow multiple threads using the same connections. Even if they do, performing
transaction control calls from different threads using the same connection will
commit/abort unrelated database activities. I urge you to remove the example from
this page.

Re: Dangerous code example


Author: Suresh N.R (http://www.jguru.com/guru/viewbio.jsp?EID=982088), Aug
13, 2002
You are absolutely right. This is code is a bad example of Java coding and it has to
be removed from here or correct it immediately.

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.

How can I implement a thread-safe JSP page?


Location: http://www.jguru.com/faq/view.jsp?EID=368
Created: Nov 5, 1999 Modified: 2000-08-14 11:24:16.55
Author: Govind Seshadri (http://www.jguru.com/guru/viewbio.jsp?EID=14)

You can make your JSPs thread-safe by having them implement the
SingleThreadModel interface.

This is done by adding the directive

<%@ page isThreadSafe="false" %>

within your JSP page.

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.

Comments and alternative answers

More importantly, avoid using the <%! DECLARE %>...


Author: John Millaway (http://www.jguru.com/guru/viewbio.jsp?EID=68085), Jun
10, 2000
More importantly, avoid using the <%! DECLARE %> tag for variables. If you do
use this tag, then you should set isThreadSafe to true, as mentioned above. Otherwise,
all requests to that page will access those variables, causing a nasty race condition.

SingleThreadModel is not recommended for normal use....


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Aug 14, 2000
SingleThreadModel is not recommended for normal use. There are many pitfalls,
including the example above of not being able to use <%! %>. You should try really
hard to make them thread-safe the old fashioned way: by making them thread-safe :-)

See How do I ensure that my servlet is thread-safe?

How <%!DECLARE%> block will be represented in Servlet?


Author: Venugopal V.V. (http://www.jguru.com/guru/viewbio.jsp?EID=467584), Aug
2, 2001
Hi..I want to know how a <%!DECLARE%> block in a JSP will be represented when
the JSP gets converted to Servlet? And is there any place where i can read how that
block will be represented in Servlet? Can anyone please throw a light on this issue? I
also wanted to know what isThreadSafe is for and how it is related to DECLARE
block?

Re: How %!DECLARE% block will be represented in Servlet?


Author: Gundluri Manjula
(http://www.jguru.com/guru/viewbio.jsp?EID=1047986), Jan 19, 2003
If u declare variables using <%!Declare %>, it is translated in to instance variables
in the converted servlet. If isThreadSafe is false,N number of instances will be
there in the webserver to process concurrent client request. So the improtant
operations should be synchronised. We can not synchronize a instance variable.So
<%! declare %> is avoided when isThreadSafe is false

Everyone should really read and understand JSP sychronization issues


Author: David Peterson (http://www.jguru.com/guru/viewbio.jsp?EID=819818), Feb 5,
2003
Read this section:
http://developer.java.sun.com/developer/onlineTraining/JSPIntro/contents.html#JSPIntro7

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

response.setHeader("Cache-Control","no-store"); //HTTP 1.1


The difference between no-cache and no-store is a bit dodgy, but apparently no-
cache is the more polite keyword. -Alex]

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

Comments and alternative answers

Netscape is unable to print.


Author: Nathan Hartley (http://www.jguru.com/guru/viewbio.jsp?EID=534015), Nov
20, 2001
When I implement this, Netscape is no longer able to print. Does anybody know how
to get around this?

Re: Netscape is unable to print.


Author: Tombee K (http://www.jguru.com/guru/viewbio.jsp?EID=141375), Sep
21, 2002
Try this example.
Following code will help you to print in Netscape.
<html>
<head>
<script language="javascript">
function printer() {
window.self.focus();
window.self.print();
}
</script>
<body>
<form name="form1">
print
</form>
</body>
</html>

Solving this problem for IE 5.0


Author: Shannon Moschetti (http://www.jguru.com/guru/viewbio.jsp?EID=435388),
Jan 29, 2002
Despite setting the headers as described above, I was unable to stop IE 5.0 from
caching. I see that there's a comment at the bottom of this implementation suggestion
regarding this version of IE. Does anyone have a solution for it?

Re: Solving this problem for IE 5.0


Author: Shannon Moschetti
(http://www.jguru.com/guru/viewbio.jsp?EID=435388), Jan 30, 2002
I'm sending a solution to my own question. I've had success with this... I'm
appending a random number parameter to the end of my servlet/jsp URL.
Different address, no caching issue.

Re[2]: Solving this problem for IE 5.0


Author: Girish Chawla
(http://www.jguru.com/guru/viewbio.jsp?EID=805191), Mar 20, 2002
Just two questions 1)Was your environment on Novell LAN ? 2)Did you set
the "Check for newer versions of stored pages" to automatically or every visit
to the page ? I am on Novell LAN and my problem disappears when I set the
"Check for newer versions of stored pages" to "every visit to the page".

Re[3]: Solving this problem for IE 5.0


Author: Eric Maziade
(http://www.jguru.com/guru/viewbio.jsp?EID=537157), Apr 8, 2002
Setting this option disables the cache on your web browser only and will
not affect other users accessing your web page...

Maze

Re[2]: Solving this problem for IE 5.0


Author: Subhasmita Sahu
(http://www.jguru.com/guru/viewbio.jsp?EID=1192643), Aug 12, 2004
I am facing the same problem in caching jsp page.Can you please send me the
code,how you solved that. Thanks in advance.

Re: Solving this problem for IE 5.0


Author: najib ahmad (http://www.jguru.com/guru/viewbio.jsp?EID=1023021),
Aug 12, 2003
i added this code to the page.

<meta http-equiv="expires" content=<%= new java.util.Date() %>>


<meta http-equiv="no-cache">

added within the head tags.it worked for all browsers.

The IE5.5 behaves inconsistly.


Author: Jason Kong (http://www.jguru.com/guru/viewbio.jsp?EID=500085), Mar 29,
2002
I used the method in an application. Some jsp pages expire immediatly and some
expire after user loged out. While both are Okey for me, the inconsistency is
unacceptable.

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);
%>

I am also doing this at the very bottom of the JSP file:

</body> <!-- end of the content body -->


<HEAD>
<META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">
</HEAD>
</html>

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[3]: How do I prevent the output of my JSP or Servlet pages from


being cached by the browser?
Author: Lotzy David
(http://www.jguru.com/guru/viewbio.jsp?EID=873685), Jul 25, 2002
It seems that only if you have submits on page with method post, it
functioning the code below suplied as solution for the problem

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

and the page expires.

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[3]: 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
ok I got it!!! I used the: <head> <META HTTP-EQUIV="PRAGMA"
CONTENT="NO-CACHE"> </head> I put that at both the beginning and
end of the page (just to be sure :) ) as well as: <%
response.setHeader("Cache-Control","no-cache"); //HTTP 1.1
response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching
response.setHeader("Cache-Control","no-store"); //HTTP 1.1 %> It doesn't
cache the page. YEA!!!

Re[4]: 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
I tried the same. But it doesn't work for me. Could you please give me
little more details. what IE version you used. Mine is IE5.0 I appreciate
your help. kind Regards, kennedy alagappan

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

Re[4]: How do I prevent the output of my JSP or Servlet pages


from being cached by the browser?
Author: Dan Fineman
(http://www.jguru.com/guru/viewbio.jsp?EID=1012429), Oct 15, 2002
I'm also unable to stop IE5.0 (on mac OSX) from caching, using any or
all of the tricks outlined in this page. Does anyone have a definitive
answer out there? Please let me know, if so.

Re[5]: How do I prevent the output of my JSP or Servlet pages


from being cached by the browser?
Author: Peter Lee
(http://www.jguru.com/guru/viewbio.jsp?EID=1010910), Dec 31,
2002
It's work for me. I suggest using IE 5.5 or higher
« previous beginning next »

How does a servlet communicate with a JSP page?


Location: http://www.jguru.com/faq/view.jsp?EID=739
Created: Nov 9, 1999 Modified: 2000-08-14 11:25:42.992
Author: Govind Seshadri (http://www.jguru.com/guru/viewbio.jsp?EID=14)

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.

<jsp:useBean id="fBean" class="govi.FormBean" scope="request"/>


<jsp:getProperty name="fBean" property="name" />
<jsp:getProperty name="fBean" property="addr" />
<jsp:getProperty name="fBean" property="age" />
<jsp:getProperty name="fBean" property="personalizationInfo" />
Comments and alternative answers

All depends on how do you want this call to take place...


Author: David Garcia (http://www.jguru.com/guru/viewbio.jsp?EID=17915), Aug 16,
2000
All depends on how do you want this call to take place and where JSP and servlets are
located.
Some possible ways are:

• Using the response.sendRedirect. This way your browser is enquired about


redirecting to the target URL. This may generate an unacceptable amount of
traffic between calls
• Using the requestDispatcher.forward method. This way you cann´t change the
parameter in the request object (while using standar packages).
• Creating a URLConnection to the target URL. This is some kind of "dirty"
approach but usefull when the URL chain is spread over multiple hosts.

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).

Show me an example of POST request chaining using JSPs and servlets.


Location: http://www.jguru.com/faq/view.jsp?EID=740
Created: Nov 9, 1999 Modified: 2000-10-24 10:32:50.172
Author: Govind Seshadri (http://www.jguru.com/guru/viewbio.jsp?EID=14)

[See also http://www.jguru.com/jguru/faq/view.jsp?EID=231318]

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.

<jsp:useBean id="fBean" class="govi.FormBean" scope="request"/>


<jsp:setProperty name="fBean" property="*" />
<jsp:forward page="/servlet/JSP2Servlet" />

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.

public void doPost (HttpServletRequest request,


HttpServletResponse response) {

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

<jsp:useBean id="fBean" class="govi.FormBean" scope="request"/>

<jsp:getProperty name="fBean" property="name" />

</body>

</html>

Comments and alternative answers

This article sounds like something I would like to...


Author: Karen Fulcher Scholz (http://www.jguru.com/guru/viewbio.jsp?EID=22177),
Mar 9, 2000
This article sounds like something I would like to do, that is: - have the user enter
values in a jsp page - automatically send those values to a bean - call a servlet that
will use the bean The part I am struggling with is that I can not seem to BOTH update
the bean AND call a servlet. In your article, you mention that you "automatically call
the bean's setter methods for properties which match the names of the posted form
elements". I understand the automatic calling of the bean's setter methods, but where
are the form elements that you use to get the values from? When I changed my code
to include the jsp:forward line like you have, I did not get an opportunity to enter
values in my form fields. If you have an example that shows the form fields, it would
be most appreciated. Thanks. Karen Fulcher Scholz karenfs@mapinfo.com

Karen, you need to create an HTML page that contains...


Author: Michael Lamers (http://www.jguru.com/guru/viewbio.jsp?EID=29658), Mar
29, 2000
Karen, you need to create an HTML page that contains the form with the appropriate
fields. The form should point at the first JSP page.

Question about string Tokenizer


Author: sss sss (http://www.jguru.com/guru/viewbio.jsp?EID=407777), Apr 22,
2001
If the string is 'this~is~~a~test',The Stringtokenizer reads it as 'this is a test'
treating two tokens as one token when nexttoken() method is used.But I want it to
show a space in between if it comes across two tokens repeatedly. i.e I want to
dispaly it as this is (space) a test Without keeping empty spaace manually as
'this~is~ ~a~test' can u tell any method of doing it?

Hi there, Forgive the newbie question... I understand...


Author: Jonathan Kaplan (http://www.jguru.com/guru/viewbio.jsp?EID=217553), Sep
27, 2000
Hi there, Forgive the newbie question... I understand the power of automatically
calling the bean's setter methods. However, is there a particular reason why we
need/want the servlet JSP2Servlet to specifically be servlet as opposed to another jsp
page?

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

Re: Servlet chaining


Author: ravin kancharla (http://www.jguru.com/guru/viewbio.jsp?EID=1189460),
Aug 11, 2004
hi , i think its better u init the config parameters of the super class .

How can I further optimize my servlets?


Location: http://www.jguru.com/faq/view.jsp?EID=1014
Created: Nov 15, 1999
Author: Govind Seshadri (http://www.jguru.com/guru/viewbio.jsp?EID=14)

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:

PrintWriter out = res.getWriter();


StringBuffer sb = new StringBuffer();
...
//concatenate html to StringBuffer
//set len and write it out
res.setContentLength(sb.length());
out.print(sb);
Comments and alternative answers

Why should the length of the data stream be indicated...


Author: Shashidhar S.H. (http://www.jguru.com/guru/viewbio.jsp?EID=4801), Jan
13, 2000
Why should the length of the data stream be indicated while writing the output using
String Buffer?

It allows the server to use HTTP Keepalive, which ...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jan 17, 2000
It allows the server to use HTTP Keepalive, which reduces the number of socket
connections on successive requests from the same client.

Does it really improve performance(by using the HTTP...


Author: Rangarajan Mangudi Parthasarathy
(http://www.jguru.com/guru/viewbio.jsp?EID=347775), Mar 16, 2001
Does it really improve performance(by using the HTTP keep alive) or only makes
coding simple and offers no other advantage.

Re: Does it really improve performance(by using the HTTP...


Author: Luke Nezda (http://www.jguru.com/guru/viewbio.jsp?EID=137832), Oct
12, 2001
HTTP/1.1 with its KeepAlive feature allows less TCP connections -> less
overhead -> more performance

From Benoit Quintin


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Feb 28, 2002
Benoit Quintin, Feb 6, 2002 [replies:1]
Many ways:

• 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.

What's a better approach for enabling thread-safe servlets and JSPs?


SingleThreadModel Interface or Synchronization?
Location: http://www.jguru.com/faq/view.jsp?EID=1015
Created: Nov 15, 1999 Modified: 2001-06-15 10:33:42.289
Author: Govind Seshadri (http://www.jguru.com/guru/viewbio.jsp?EID=14)

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.

Comments and alternative answers

See this FAQ entry for more information on Servlets...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Feb 5, 2000
See this FAQ entry for more information on Servlets and Thread Safety.

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)

We know that session tracking uses cookies by default to associate a session


identifier with a unique user. If the browser does not support cookies, or if cookies
are disabled, you can still enable session tracking using URL rewriting.

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.

Adding the session ID to a link is greatly simplified by means of of a couple of


methods: response.encodeURL() associates a session ID with a given URL, and if you
are using redirection, response.encodeRedirectURL() can be used by giving the
redirected URL as input.

Both encodeURL() and encodeRedirectedURL() first determine whether cookies are


supported by the browser; if so, the input URL is returned unchanged since the
session ID will be persisted as a cookie.

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

<%@ page session="true" %>


<%
Integer num = new Integer(100);
session.putValue("num",num);
String url =response.encodeURL("hello2.jsp");
%>
<a href='<%=url%>'>hello2.jsp</a>

hello2.jsp

<%@ page session="true" %>


<%
Integer i= (Integer )session.getValue("num");
out.println("Num value in session is "+i.intValue());
%>
Comments and alternative answers

URL rewriting does not work with Apache 1.3.12 + ...


Author: Alberto Yano (http://www.jguru.com/guru/viewbio.jsp?EID=36307), Apr 14,
2000
URL rewriting does not work with Apache 1.3.12 + TomCat 3.1b under Win95

enabling session if the browser has disabled cookies.


Author: Rajesh Nair (http://www.jguru.com/guru/viewbio.jsp?EID=467592), Aug 23,
2001
response.encodeURL can be used only if there is arequest to the next page. If the user
navigates directly to the next page by clicking on a menu link how do we track the
session

Re: enabling session if the browser has disabled cookies.


Author: Sanjit Singh (http://www.jguru.com/guru/viewbio.jsp?EID=533804), Nov
7, 2001
Hi Rajesh, I have the same problem that has been mentioned by you on this forum.
Did you find an answer to it? I would be grateful if you could help me out.
Thanks! Sanjit

""""response.encodeURL can be used only if there is arequest to the next page. If


the user navigates directly to the next page by clicking on a menu link how do we
track the session"""""

Re[2]: enabling session if the browser has disabled cookies.


Author: Adrian Albu (http://www.jguru.com/guru/viewbio.jsp?EID=873488),
May 10, 2002
hi, you should put for every link on your pages the new url if the session is
disabled or cookies are not enabled. I mean for every possibilities to get to a
page of your site there should be added whatever you want to be in the session
(as if it were the session object) so if the user writes in the location(address)
bar the url for one of you pages and you do not whant him there without first
login then you must check for some session id and if not present prompt him to
login or something.

Re[3]: enabling session if the browser has disabled cookies.


Author: Faiz Ali (http://www.jguru.com/guru/viewbio.jsp?EID=1126494),
Nov 5, 2003
Why don't you use HttpSession object. The HttpSession object were
introduced were to make simple the high level details. An HttpSession
Object is valid for as long as the user is in the session. That means across
web pages. For example, if you have a user who is not a member, he can
still use your web site to browse, and the session will keep track.

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

link - Render an HTML anchor or hyperlink

Renders an HTML 'a' element as an anchor definition (if "linkName" is specified) or


as a hyperlink to the specified URL. URL rewriting will be applied automatically,
to maintain session state in the absence of cookies. The content displayed for this
hyperlink will be taken from the body of this tag.

Just use the html taglib to write your link and you don't have to worry about cookies
or the encode() method.

What about hiding the "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.

Can I invoke a JSP error page from a servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=1347
Created: Nov 29, 1999 Modified: 2000-08-14 11:23:11.967
Author: Govind Seshadri (http://www.jguru.com/guru/viewbio.jsp?EID=14)

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:

protected void sendErrorRedirect(HttpServletRequest request,


HttpServletResponse response, String errorPageURL,
Throwable e)
throws ServletException, IOException {
request.setAttribute ("javax.servlet.jsp.jspException", e);
getServletConfig().getServletContext().
getRequestDispatcher(errorPageURL).forward(request,
response);
}

public void doPost(HttpServletRequest request,


HttpServletResponse response) {
try {
// do something
} catch (Exception ex) {
try {
sendErrorRedirect(request,response,"/jsp/MyErrorPage.jsp",ex);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Comments and alternative answers

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...

Re: Automatic in 2.3?


Author: Zoltan Grose (http://www.jguru.com/guru/viewbio.jsp?EID=269390),
Mar 20, 2002
I've been playing around with this in Tomcat 4.0 a little bit. If you have error-page
elements in your web.xml you can throw a new ServletException using the
Throwable constructor. In my test case I have
<error-page>
<exception-
type>java.lang.NullPointerException</exception-type>
<location>/null.html</location>
</error-page>
If I wanted to set that error to display, I could write:
throw new ServletException(new java.lang.NullPointerException());
If you are using error-code elements, you can use the sendError method of the
HttpServletResponse to kick of the error page.
<error-page>
<error-code>100</error-code>
<location>/myPage.html</location>
</error-page>
response.sendError(100);

Re[2]: Automatic in 2.3?


Author: Zoltan Grose (http://www.jguru.com/guru/viewbio.jsp?EID=269390),
Mar 21, 2002
Hmm. Now it seems just
throw new java.lang.NullPointerException();
does the trick. Well, rest assured, the functionality works, you just may have to
fuss about a bit.

Re[2]: Automatic in 2.3?


Author: Nicolas Marchildon
(http://www.jguru.com/guru/viewbio.jsp?EID=1002155), Jan 27, 2003
Yes, this works great for static pages. But what if I want to forward to a JSP or
a servlet that will look at the actual exception? For a JSP with the
isErrorPage="true" page directive, it does not work, as the
javax.servlet.jsp.jspException request attribute does not contain the
exception. Where can we get this information?

Re[3]: Automatic in 2.3?


Author: Nicolas Marchildon
(http://www.jguru.com/guru/viewbio.jsp?EID=1002155), Jan 27, 2003
Found my answer:
http://nagoya.apache.org/bugzilla/show_bug.cgi?id=1867 :(

Re[4]: Automatic in 2.3?


Author: Chris Hyzer
(http://www.jguru.com/guru/viewbio.jsp?EID=1006024), Jul 17, 2003
There is an easy solution, it just takes a little bit of work, if you work
with the API... this works great (especially per the above comment
where if you are completely Model 2 and the servlet didnt open a
stream for the response!)

In your controller servlet, use this structure with an exception wrapper:

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {

try {

//servlet controller logic


//input here...

} catch (Throwable t) {

//set the exception the same way that jsp does


request.setAttribute("javax.servlet.jsp.jspExceptio
n", t);

//forward the control to your jsp error page


RequestDispatcher dispatcher
= request.getRequestDispatcher("errorPage.jsp");
dispatcher.forward(request, response);
}
}

Re[5]: Automatic in 2.3?


Author: a c
(http://www.jguru.com/guru/viewbio.jsp?EID=1242588), May 5,
2005
I noticed you have a lower case j in jspException. When I tried it
with an uppercase J, I got an error. Why is this?

Can a servlet maintain a JTA UserTransaction object across multiple servlet


invocations?
Location: http://www.jguru.com/faq/view.jsp?EID=2572
Created: Dec 14, 1999
Author: Jerry Smith (http://www.jguru.com/guru/viewbio.jsp?EID=9)

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.

In short: Make sure you look for the "W"!

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:

http://www.objexcel.com/workingjava.htm#Web Server Benchmarks

Comments and alternative answers

In general, Perl CGI will be slower than JSP or Se...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Dec 22, 1999
In general, Perl CGI will be slower than JSP or Servlets, because the Perl executable
needs to launch as a separate process, then Perl needs to initialize itself, then load in
the script, then compile the script, and finally execute the script. There are
enhancements to Perl CGI that allow a script to stay resident (e.g., FastCGI and
mod_perl), but even then it's not going to be faster than Java a priori -- it will be
faster if and only if the code is written better, that's all.

Although techniques like FastCGI send multiple req...


Author: Govind Seshadri (http://www.jguru.com/guru/viewbio.jsp?EID=14), Dec 22,
1999
Although techniques like FastCGI send multiple requests to the same process, they
offer significant overhead due to the process-context switching that has to take place.
Servlets, on the other hand, consume less system resources due to the lightweight
thread context switch that has to be performed in servicing a client request.

My understanding is that in some respects JSP-gene...


Author: John Guthrie (http://www.jguru.com/guru/viewbio.jsp?EID=3778), Dec 30,
1999
My understanding is that in some respects JSP-generated servlet code is faster than
human-written servlet code. For instance, where a human programmer would code:
out.println ("<H1>Look out</H1>"); out.println ("Sharks ahead"); a good JSP
implementation would put all the strings in a char array and write() them, a la: private
static final char _chunk_0[] = { '','H','1','>','L','o','o','k', ' ','o','u','t','','/','H','1',
'>','\r','\n','S','h','a','r','k', 's',' ','a','h','e','a','d','\r', '\n' }; out.write(_chunk_0);

About that "lightweight thread context switch" -- ...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Dec 31, 1999
About that "lightweight thread context switch" -- that's true if you're using a Java Web
Server, but most web servers are written in C and must launch a separate process for
the Servlet JVM. So the request actually does have to go through a socket and swap in
a different (heavyweight) process. Of course, some servlet engines launch the Java
VM in-process, but most do not. (I'm not sure which do and which do not. I know
Apache mod_jserv launches a separate process.)

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)

Try telling the applet to call


getAppletContext().showDocument("http://foo.com/whatever/bl
ah.doc"). That makes the browser responsible for fetching and saving the
document (including putting up the "Save As" dialog).

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.

Comments and alternative answers

Also see this FAQ for more information on downloading...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Feb 5, 2000
Also see this FAQ for more information on downloading files from servlets:
http://www.jguru.com/jguru/faq/view.jsp?EID=10646

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:

SHELL=C:\COMMAND.COM C:\ /E:4096 /P

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.

Comments and alternative answers

I added this setting to my config.sys and I also i...


Author: Luc Luong (http://www.jguru.com/guru/viewbio.jsp?EID=29681), Mar 29,
2000
I added this setting to my config.sys and I also increased the environment memory
size to 4096 in DosPrompt windows. Nothing helped.

Replace 4096 by 5096 or by any larger value.


Author: arun puri (http://www.jguru.com/guru/viewbio.jsp?EID=301533), Feb 28,
2001
Replace 4096 by 5096 or by any larger value.

I need to communicate from my servlet to another independent process.


Can I use the RequestDispatcher instead of opening a socket connection?
Location: http://www.jguru.com/faq/view.jsp?EID=4224
Created: Jan 6, 2000 Modified: 2000-06-03 14:36:16.703
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

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

Does it mean that attributes set with ServletReque...


Author: Maxim Senin (http://www.jguru.com/guru/viewbio.jsp?EID=21992), Mar 8,
2000
Does it mean that attributes set with ServletRequest.setAttribute() or any other non-
String object available thru ServletRequest CANNOT be sent to servlet or jsp on
another server? I.e. I cannot pass instance of JavaBean to servlet located on Yahoo!
website?

That's right -- you definitely can't count on variables...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Mar 9, 2000
That's right -- you definitely can't count on variables (session or otherwise) being
available in a different JVM, let alone a whole different web site! This broaches
another big topic -- persistence of variables across load-balanced servers -- but that
deserves a FAQ of its own.

1. Well, engine could try to download requested re...


Author: Maxim Senin (http://www.jguru.com/guru/viewbio.jsp?EID=21992), Mar 9,
2000
1. Well, engine could try to download requested resource, instantiate it locally and
pass necessary data to it. But I agree, it doesn't make any sense.
2. I understand why RequestDispatcher.forward() can only access resources WITHIN
SAME ServletContext.
But:
a. servlet engine can use it's sendRedirect() method to forward to remote resource
even though it cannot pass it's ServletRequest or ServletResponse.
b. what if I want to include() some data from Yahoo! website into content that my
servlet is returning? There's nothing wrong with that. Anyway: even if servlet engine
would not let me include() resource from Yahoo!, I can still just copy content from
them by opening URL connection and copying data from URL.getInputStream() to
ServletOutputStream.

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 (jmangaliman@dc.com)
Comments and alternative answers

Anil Bhatt (anilkumarbhatt@hotmail.com) writes: Yes,...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jan 26, 2000
Anil Bhatt (anilkumarbhatt@hotmail.com) writes: Yes, I think a new attribute can be
added using the setAttribute(String key, Object o) method of the Request Object eg.
req.setAttribute("action", "delete");
then the request can be forwarded using the requestdispatcher object.
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(url);
rd.forward(req, res);
Where url is the srting containg the url of the destination servlet, req and res are
request and response objects respectively.

Actually, I think there's a difference between Request...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), May 30,
2000
Actually, I think there's a difference between Request Parameters and Request
Attributes. So the question is still unanswered.

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

Construct your own ActionForward


Author: Jason Tang (http://www.jguru.com/guru/viewbio.jsp?EID=1231997), Mar 11,
2005
If you use structs and your project didn't allow you use request.setAttribute() to pass
the value to next action, just try construct your own ActionForward object and add
your parameters into it. Example
....
ActionForward forward = mapping.findForward("success");
StringBuffer bf = new StringBuffer(forward.getPath());
bf.append("?id=1");//add parameter here
return new ActionForward(bf.toString(),false);

How do I call one servlet from another servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=5049
Created: Jan 15, 2000 Modified: 2001-09-26 14:11:21.807
Author: Sameer Tyagi (http://www.jguru.com/guru/viewbio.jsp?EID=4381)

[ Short answer: there are several ways to do this, including

• 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.

Comments and alternative answers

An easy way is to make an HTTP request from within...


Author: Yakov Sirotkin (http://www.jguru.com/guru/viewbio.jsp?EID=6342), Jan 26,
2000
An easy way is to make an HTTP request from within the first servlet. After that, you
can read it line by line and do what you want. Like this:
try {
URL news = new URL("http://myserver/myservlet");
BufferedReader in = new BufferedReader(new
InputStreamReader(news.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
out.println(inputLine);
}
in.close();
}
catch (Exception e){}

Re: An easy way is to make an HTTP request from within...


Author: Delarie Oliver (http://www.jguru.com/guru/viewbio.jsp?EID=388919),
Mar 27, 2001
I want to forward the request from servlet1 on one server to the request in servlet2
on another server. Where do I put the HttpServletRequest object in the above
code?

How to call one servlet from another servlet. I tried...


Author: kumar subramanian (http://www.jguru.com/guru/viewbio.jsp?EID=17901),
Feb 25, 2000
How to call one servlet from another servlet. I tried the option which you specified
here. getting the handle of one servlet within another servlet. How to call a servlet
from an application. If called the servlet should not return an html page Istead it
should return a set of values which i can use in my application.

Kumar: on the client side, you must simply write a...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), May 17,
2000
Kumar: on the client side, you must simply write a parser to process the InputStream.
It's not hard. You can use the StreamTokenizer class to help.

See also this FAQ


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), May 17,
2000
See also this FAQ: How can my applet communicate with my servlet?

I want to call a method on an instance of a servlet....


Author: nitin k (http://www.jguru.com/guru/viewbio.jsp?EID=137461), Sep 14, 2000
I want to call a method on an instance of a servlet. for eg. lets say we have a
saveState() method in all servlets in a web application which writes to the
database(picked up from Jason Hunters book). I need to call this method from another
servlet.

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?

Make an object that both servlets can share via ap...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Sep 14, 2000
Make an object that both servlets can share via application (context) properties; put
the method there instead.

But that object will be accessible from any servlet...


Author: nitin k (http://www.jguru.com/guru/viewbio.jsp?EID=137461), Sep 15, 2000
But that object will be accessible from any servlet in the application. Is there any
elegant way by which i can call a method in a servlet from the other servlet?

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

You should probably redesign your app so the &quot...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Sep 17, 2000
You should probably redesign your app so the "state" you're describing is in a data
object that contains all these properties and state. A servlet should really not contain
much state; if you find a servlet growing too big then it's probably time to refactor.
Think of the servlet as a simple request processor, sitting on top of more complex data
storage and business logic objects.

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.

If you use the URLConnection, and want to preserve...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Nov 7, 2000
If you use the URLConnection, and want to preserve session information, you'll need
to add the session cookie to the URLConnection request. See this FAQ for
information on how to do that.

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

...unless it's part of the WAR


Author: William Pietri (http://www.jguru.com/guru/viewbio.jsp?EID=142508), Nov
16, 2001
If the file is part of the web application, you can get the proper path from the
ServletContext:
String filename = getServletContext().getRealPath("/WEB-
INF/appconfig.xml");

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. :(

Re: ...unless it's part of the WAR


Author: William Pietri (http://www.jguru.com/guru/viewbio.jsp?EID=142508),
Jan 1, 2002
Excellent point! The servlet container I was testing with automatically expands
the WARs. Sorry for the confusion.

Re[2]: ...unless it's part of the WAR


Author: Chris Bailey
(http://www.jguru.com/guru/viewbio.jsp?EID=906038), Jun 6, 2002
And, even in servlet containers that expand the WAR, getRealPath may
still return null (it does in Tomcat 4.0.3 for example). I'm wondering the
same thing. I'd like to be able to write files into a subdirectory in my
expanded servlet directory, but I don't see how to do this if the web app is
in a WAR file.

Re[3]: ...unless it's part of the WAR


Author: James Flagg
(http://www.jguru.com/guru/viewbio.jsp?EID=1014787), Oct 20, 2002
For reading files within your WAR archive, you could use
ServletContext.getResourceAsStream("/myfile.xml"). This may only
work if the file you want is in WEB-INF/classes. And this doesn't help
at all if you want to write to the file. :(

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

But watch out if you have a multiple-server config...


Author: Peter Kobak (http://www.jguru.com/guru/viewbio.jsp?EID=8747), Jan 25,
2000
But watch out if you have a multiple-server configuration. Not all application servers
guarantee that application-level attributes will propagate between all servers, or even
all JVMs in the same server. (For instance, Netscape Application Server 4.0 only sets
application attributes in the current JVM.)

anil chakravarthy (anilchak1@hotmail.com) suggests...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jan 26, 2000
anil chakravarthy (anilchak1@hotmail.com) suggests using the System Properties
object, using System.getProperties().put(key, foo); and Foo foo =
(Foo)System.getProperties.get(key); . However, this is not recommended,
since System Properties are global to the entire VM. Use Servlet Attributes instead.

Also see the FAQ What servlet code corresponds to...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), May 21,
2000
Also see the FAQ What servlet code corresponds to the various "scope" values for the
<jsp:useBean> tag? .

Using the ServletContext object is dependent on the...


Author: shivashis bose (http://www.jguru.com/guru/viewbio.jsp?EID=79345), Jul 21,
2000
Using the ServletContext object is dependent on the servlet container implementation
of a web server.

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

Re: Using the ServletContext object is dependent on the...


Author: Biswajit Ganguly
(http://www.jguru.com/guru/viewbio.jsp?EID=1171166), May 17, 2004

A better way to do would be to keep a singleton class which maintains application


level data and instialise it from within the init method of any servlet that is marked
for loading at startup of the server.

I really can't understand how subclassing servlets is going to help to share


application level data .

I don't see how having all the servlets in the same...


Author: Guillaume Barreau (http://www.jguru.com/guru/viewbio.jsp?EID=249459),
Nov 9, 2000
I don't see how having all the servlets in the same application inherit from a common
ancestor would solve this problem. An object of class Child and an object of class
Parent do not actually share any data when Child extends Parent.
What are all the different kinds of servers? (Such as Web Servers,
Application Servers, etc)
Location: http://www.jguru.com/faq/view.jsp?EID=5917
Created: Jan 20, 2000 Modified: 2000-12-20 10:06:49.031
Author: Paul Danckaert (http://www.jguru.com/guru/viewbio.jsp?EID=5801)

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.

Starting at the basic level, a user is typically submitting a request to a system


through a web browser. (We are conveniently ignoring all other types of clients (RMI,
CORBA, COM/DCOM, Custom, etc..) for the time being for purposes of clarity.) The
web request must be received by a Web Server (otherwise known as an HTTP
Server) of some sort. This web server must handle standard HTTP requests and
responses, typically returning HTML to the calling user. Code that executes within the
server environment may be CGI driven, Servlets, ASP, or some other server-side
programming language, but the end result is that the web server will pass back
HTML to the user.

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?

Comments and alternative answers

The following link provides a list of all available...


Author: Govind Seshadri (http://www.jguru.com/guru/viewbio.jsp?EID=14), Feb 3,
2000
The following link provides a list of all available web servers (HTTP servers). It also
offers detailed information regarding the functionality offered by each of them.

http://serverwatch.internet.com/webservers.html

Here's a great comparison chart listing all the Java...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Apr 12, 2000
Here's a great comparison chart listing all the Java application servers:
http://www.flashline.com/Components/appservermatrix.jsp

There are three types of servlet engines: 1) StandAlone...


Author: Shuchi Agarwal (http://www.jguru.com/guru/viewbio.jsp?EID=30635), May
2, 2000
There are three types of servlet engines: 1) StandAlone Servlet Engine: It is a web
server that includes built in support for servlets.For eg Java Web Server etc. 2) Add on
Servlet Engine:It functions as a plug-in for an existing server,a server that was not
originally designed with servlets in mind.For eg JServ, JRun,IBM WebSphere etc. 3)
Embeddable Servlet Engine:It is a lightweight server deployment platform that can be
embeddable in another application. That application becomes the true server.For eg
JavaServerEngine etc.

what are all the different web servers that support...


Author: krishna murthy (http://www.jguru.com/guru/viewbio.jsp?EID=274676), Dec
21, 2000
what are all the different web servers that support servlet 2.0 technology ?

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.

Should I override the service() method?


Location: http://www.jguru.com/faq/view.jsp?EID=8824
Created: Jan 25, 2000 Modified: 2000-01-26 05:55:45.502
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

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 some cases it does make sense to override the s...


Author: Oliver Burn (http://www.jguru.com/guru/viewbio.jsp?EID=16181), Mar 9,
2000
In some cases it does make sense to override the service() method. For example, on
the project I am working on we have a lot of Servlets that need to perform the same
checks (for example, is the session authenticated) before processing the request.
Rather than having to copy the logic into each Servlet we write, we developed a
common base class that extends HttpServlet. The logic inside the service method is
effectively:
service(...) {
common processing logic....
super.service(...);
}

What exactly are the housekeeping functions that s...


Author: Evan Owens (http://www.jguru.com/guru/viewbio.jsp?EID=123877), Sep 17,
2000
What exactly are the housekeeping functions that service() provides?

More reasons not to


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jan 9, 2003
Michael Dean writes:

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?

(And if performance is really your primary concern, never "micro-optimize" before


profiling. Chances are, the code you've written has some bottlenecks that make the
performance impact of these extra method calls negligible. As a matter of fact, the
code you write to replace the functionality you are losing might just contain some of
these bottlenecks. :)

Re: More reasons not to


Author: john b (http://www.jguru.com/guru/viewbio.jsp?EID=1059477), Feb 22,
2003
Okay, but what if I wanted to let my servlet decide if it wants to
process the request locally or forward it onto another servlet
server? Wouldn't it be best to decide that in the service(..)
method?

What work is happening towards creating Servlet API v2.3?


Location: http://www.jguru.com/faq/view.jsp?EID=8876
Created: Jan 26, 2000 Modified: 2000-01-26 05:57:08.695
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out:
http://java.sun.com/aboutJava/communityprocess/jsr/jsr_053_jspservlet.html

What is a servlet development framework?


Location: http://www.jguru.com/faq/view.jsp?EID=9092
Created: Jan 26, 2000 Modified: 2000-01-31 09:02:31.121
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

A 'servlet development framework' is a package which helps us create servlet-based


solutions more efficiently and effectively.

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.

For example, check out:

WebMacro

Most Application Servers contain their own frameworks. See this question on the
FAQ.

Is there a mailing list for the discussion of servlets?


Location: http://www.jguru.com/faq/view.jsp?EID=9247
Created: Jan 27, 2000 Modified: 2000-01-31 09:41:04.907
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

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

listserv@java.sun.com
with a message body of:
subscribe SERVLET-INTEREST

Also, check out the archive of the mailing list.

Comments and alternative answers

There's also an advanced servlet list, albeit with...


Author: Tom Copeland (http://www.jguru.com/guru/viewbio.jsp?EID=1396), Mar 20,
2000

There's also an advanced servlet list, albeit with very low traffic (as of 3/20/00). More
info can be found here.

tomcat-user@jakarta.apache.org is a great place for...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jun 21, 2000
tomcat-user@jakarta.apache.org is a great place for discussion of Tomcat-related
servlet/JSP issues.

Also, look at advanced-servlets@egroups.com


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Aug 16, 2000
Also, look at advanced-servlets@egroups.com

How do I open and redirect to a popup window from a servlet? (Under


certain circumstances I want my servlet to bust out of the frames and
redirect to another servlet or page.)
Location: http://www.jguru.com/faq/view.jsp?EID=10507
Created: Jan 31, 2000 Modified: 2002-12-04 16:47:32.187
Author: Brett Knights (http://www.jguru.com/guru/viewbio.jsp?EID=8054) Question
originally posed by David Thompson
(http://www.jguru.com/guru/viewbio.jsp?EID=5551

You can't do this directly but it is easy to do indirectly using JavaScript.

Essentially you return a page that has as its onLoad event code that opens a page
and gets your new data.

Your servlet would create or return a page that contains:

<head>
...
<script language="javascript">
function bustOut(){
var newWin = window.open("the real url", ....); // params and stuff

window.onLoad = bustOut; //this should work but often doesn't. Lack of


parens () is correct.
</script>
</head>
<body onLoad="bustOut()">

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

Comments and alternative answers

Another way to open a new browser window is to use...


Author: Tom Copeland (http://www.jguru.com/guru/viewbio.jsp?EID=1396), Mar 17,
2000

Another way to open a new browser window is to use the target element, i.e.:

<a href="http://www.slashdot.org" target="_blank">Open Slashdot in a


new window!</a>

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.

Re: Another way to open a new browser window is to use...


Author: Irfan Ahmed (http://www.jguru.com/guru/viewbio.jsp?EID=457477), Jul
23, 2001
What should I do to make the resulting browser window without browser's URL
bar, forward - backward buttons ?

Thanks in advance
Irfan

Re[2]: Another way to open a new browser window is to use...


Author: Peter Wainwright
(http://www.jguru.com/guru/viewbio.jsp?EID=578769), Dec 10, 2001
try
<head>
...
<script language="javascript">
function bustOut(){
var newWin = window.open("the real url",
"subWindow","height=500,width=700,resizable=yes,scrollbars=yes");
}

window.onLoad = bustOut; //this should work but often doesn't.


Lack of parens () is correct.
</script>
</head>
<body onLoad="bustOut()">

Eat at Joe's

</body>
</html>

Re[3]: Another way to open a new browser window is to use...


Author: chellaganesh K
(http://www.jguru.com/guru/viewbio.jsp?EID=985820), Aug 20, 2002
It works fine. But when ever the back or forward button is pressed opens a
new window. I dont know how to stop this.

Re[4]: Another way to open a new browser window is to use...


Author: Peter Wainwright
(http://www.jguru.com/guru/viewbio.jsp?EID=578769), Aug 20, 2002
try using an event handerler other that onload().

Re[5]: Another way to open a new browser window is to use...


Author: Shalini Tandon
(http://www.jguru.com/guru/viewbio.jsp?EID=1181823), Jun 26,
2004

Hi,I am also trying to do something similar that is checking some


thing in database when a page is submitted and give a jsp in popup
window when a particular condition is there using window .onload
while page is coming back, everything works fine except when I try
to use browser back button,I get that popup back and by clicking
buttonson that popup, I can redo database transaction, How can I
avoid it, any suggestion is highly appreciated

Popup window using javascript


Author: zhidong zhao (http://www.jguru.com/guru/viewbio.jsp?EID=1049276), Feb
14, 2003
When using javascript function window.open() to popup a new window in jsp, The
window

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

them in query string, but how to transfer objects?

Which is the best servlet server or servlet engine (best performance,


easiest, etc)?
Location: http://www.jguru.com/faq/view.jsp?EID=10629
Created: Feb 1, 2000 Modified: 2000-06-03 14:42:30.024
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Guillem Valls
(http://www.jguru.com/guru/viewbio.jsp?EID=5830

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.

Comments and alternative answers

The new iPlanet Web Server 4.0 is supposed to offer...


Author: Tom Khamis (http://www.jguru.com/guru/viewbio.jsp?EID=22263), Mar 9,
2000
The new iPlanet Web Server 4.0 is supposed to offer great servlet performance. See
www.i-kinetics.com for a white paper

JSDK and JSWDK are development environments, intended...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Apr 30, 2000
JSDK and JSWDK are development environments, intended to be compatible with
various versions of the servlet spec but not for production use in a high-load
environment. They are written in Java and available from Sun.

Sun has a fairly comprehensive list of Servlet Engines...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), May 11,
2000
Sun has a fairly comprehensive list of Servlet Engines (now called "Servlet
Containers" I suppose) at http://java.sun.com/products/servlet/industry.html.

Why doesn't response.sendRedirect(response.encodeURL(url)) work?


Location: http://www.jguru.com/faq/view.jsp?EID=10632
Created: Feb 1, 2000 Modified: 2000-02-01 08:09:31.471
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Raveenthirakumar Rajagopal
(http://www.jguru.com/guru/viewbio.jsp?EID=9644

Use response.sendRedirect(response.encodeRedirectURL(url)) instead. It will


correctly rewrite the URL for clients that don't support cookies.
Comments and alternative answers

It still doesnt answer the question. _Why_ doesnt it...


Author: Jan Sundin (http://www.jguru.com/guru/viewbio.jsp?EID=11515), Feb 4,
2000
It still doesnt answer the question. _Why_ doesnt it work? What are the differences
between encodeUrl and encodeRedirectUrl.

please clarify some web servers which supports url...


Author: srikanth narasimhan (http://www.jguru.com/guru/viewbio.jsp?EID=11221),
Feb 26, 2000
please clarify some web servers which supports urlrewite, because i had problems
with JSWK2.1 and in OAS but it worked fine with JWS2.0

How do I download a (binary, text, executable) file from a servlet or JSP?


Location: http://www.jguru.com/faq/view.jsp?EID=10646
Created: Feb 1, 2000 Modified: 2001-11-02 07:54:23.779
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)
Solution 1: Just use HTTP! This has nothing to do with servlets per se. Make sure
the file is on your web server. Then you can either embed a link for your user to
click, as

<a href="runme.exe">Click here to download the Runme app</a>


or have your servlet or JSP send a redirect to the file, as
response.sendRedirect("http://myserver.com/files/runme.exe");
or get fancy with JavaScript (see this FAQ for inspiration).

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

Comments and alternative answers

Amit Ghaste (ghaste@usa.net) writes: Hi, I have to...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Feb 18, 2000
Amit Ghaste (ghaste@usa.net) writes: Hi, I have to download files from the server to
the user, I have code which works just fine in Netscape, but the same is not working
in IE. here is the code sample. for a pdf file _________________________
response.setContentType ("application/pdf");
response.setHeader ("Content-Disposition", "attachment;
filename=\"syntax.pdf\"");
ServletOutputStream op = response.getOutputStream ();
while ((in != null) && ((length = in.read(buf)) != -1))
{
// the data has already been read into buf
System.out.println("Bytes read in: " +
Integer.toString(length));
op.write(buf,0,length);
}
_________________________
I dont want to give direct links to the files itself, if it is the only option left.

Re: Amit Ghaste (ghaste@usa.net) writes: Hi, I have to...


Author: Bill Chatfield (http://www.jguru.com/guru/viewbio.jsp?EID=439189),
Jun 14, 2001
I'm using IE5.0 and jswdk-1.0.1. I have to spell "attachment" as "attachement" to
get the PDF to load in the browser instead of downloading. If I spell it as
"attachment" it always gives me a download dialog box.

Re: Amit Ghaste (ghaste@usa.net) writes: Hi, I have to...


Author: Brien Hodges (http://www.jguru.com/guru/viewbio.jsp?EID=454110), Jul
12, 2001
I am using:
<%@ page contentType="application/download" %>

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

Re: Amit Ghaste (ghaste@usa.net) writes: Hi, I have to...


Author: ali javed (http://www.jguru.com/guru/viewbio.jsp?EID=475292), Aug 13,
2001
Hello, I used the source code you have used but it is not working. The problem is
that one file gets downloaded but on the same page when I cilck some other link,
it displays error "getOutputStream() has already been called for this response until
I refresh that page. It is an illegalstateException." Please, solve my problem.
THANX ali javed

Solution 2 works great for binary files under netscape,...


Author: Matthew Conway (http://www.jguru.com/guru/viewbio.jsp?EID=24615),
Mar 15, 2000
Solution 2 works great for binary files under netscape, and under IE 5 it also
downloads the file correctly. Unfortunately IE ends up thinking it still is waiting on
something, so the hourglass never goes away, and the globe keeps on spinning. Is
there any way to prevent this from happening?

Re: Solution 2 works great for binary files under netscape,...


Author: Benjamin Kallauch
(http://www.jguru.com/guru/viewbio.jsp?EID=451966), Jul 9, 2001
maybe it is a solution to give it an out.close(), but I am really not sure.

I was setting the Content-disposition header to be...


Author: Matthew Conway (http://www.jguru.com/guru/viewbio.jsp?EID=24615),
Mar 16, 2000
I was setting the Content-disposition header to be "attachment;filename=foo.zip" in
order to provide a suitable default filename for the client's Save As dialog. Setting it
instead to be just "filename=foo.zip" got rid of my problem with IE waiting forever.

Re: I was setting the Content-disposition header to be...


Author: vinay salehithal (http://www.jguru.com/guru/viewbio.jsp?EID=504996),
Sep 27, 2001
Hi, I am downloading a csv file from the server. I am too facing the same
propblem of IE waiting for ever after finishing the download. As per your
suggestion I tried to set the Content-Disposition header to just
"filename=myfilename.csv", but after doing this, when i click on my download
link the save as or open popup is not being shown, instead leads to opening of the
csv file in the browser itself. Please let me know if u have any ideas on this

Re: I was setting the Content-disposition header to be...


Author: aytac sen (http://www.jguru.com/guru/viewbio.jsp?EID=516073), Oct
10, 2001
Hi, I try to download files from the server also, and the solution that suggests
setting Content-Disposition header to just "filename=..." causes the problem you
mentioned for some other file types also(like .doc, .mp3).

especially when the ContentType is "APPLICATION/OCTET-STREAM"

So how to avoid this and have the popup window still ?? If any solution is
reached can you inform please.

Thanks.

Re: Re: I was setting the Content-disposition header to be...


Author: vinay salehithal
(http://www.jguru.com/guru/viewbio.jsp?EID=504996), Oct 10, 2001
Hi, In our case, since we were downloading a csv file we have set the
content type to 'application/csv'. Apart from this, the problem was occuring
with IE browsers and not with Netscape. We were also facing a problem
with IE 5.5 in which once a download link was clicked the other links
became unoperational. We managed to solve this(rather a workaround) as
follows: 1. Detect the browser type. 2. If(IE5.0) { Content-Disposition:
attachment; filename=\"myfilename.csv \";" } else { Content-Disposition:
anyWord;filename=\"myfilename.csv \";" } I hope this helps. Regards

Re: I was setting the Content-disposition header to be...


Author: aytac sen
(http://www.jguru.com/guru/viewbio.jsp?EID=516073), Oct 11, 2001
I want to explain my situation and what I tried till now:
Part p= getTheAppropriatePartSomeHow();

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;

while ((len = is.read(b)) != -1) {


oout.write(b, 0, len);
}
is.close();
out.flush();
oout.close();

The important point is the line:

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

• If I have the code as


response.setHeader("Content-Disposition", "attachment;
filename=\"" + p.getFileName() + "\";");
then: <it forces for a download>
e.g.
for a x.jpg file
BR>it opens a "File Download" Dialog Box, with options
"Open file" or "Save to disk"

if you choose: "Save To Disk" option then it shows the "Save


As" dialog with the CORRECT filename, and by pressing OK,
it saves the file, but HOURGLASS never goes away(The
problem defined before in the thread) to prevent this I tried to
follow the answers given here (like just giving the filename in
the Content-Disposition, result is explained above.)
but if you choose: "Open File From Current Location" then it
does nothing, and just the HOURGLASS never goes away

• If I have the code as

response.setHeader("Content-Disposition", "attachment;
filename=\"" + p.getFileName() + "\";");

NOTE: The difference is that "Content- Disposition" is written


WITH A SPACE in between and not like " Content-
Disposition", I saw that in

http://www.jguru.com/faq/view.jsp?EID=252010
Re: In my servlet I am trying to let the user download… (By
seema bhatnagar)

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 for c.bmp, whose content-type was also


APPLICATION/OCTET-STREAM, and for some other files, it
opens a "File Download" Dialog Box, with options "Open file"
or "Save to disk"

if you choose: in both "Save To Disk" and "Open File" options


it SHOWS THE FILENAME IN A FALSE way… (Showing the
.jsp file's name to be saved) and saves in this format…

So the only problem with the last case is that IT CAN`T get the
correct filenames to where to save the parts.

***So since you're reading this sentence, then you probably


read all the cases that I tried to explain… If you have any
suggestions about how to solve the problems for any case,
please share with me, thanks***

Re: Re: I was setting the Content-disposition header to be...


Author: vinay salehithal
(http://www.jguru.com/guru/viewbio.jsp?EID=504996), Oct 11,
2001
Hi, Do you want all those files to be seen in yr browser or to be
saved with Download popup? Also which browser/version are you
working with? Looking at yr last case have you tried this:
response.setHeader("Content-[space]Disposition", "anyword;
filename=\"" + p.getFileName() + "\";");

Re: Re: Re: I was setting the Content-disposition header to


be...
Author: aytac sen
(http://www.jguru.com/guru/viewbio.jsp?EID=516073), Oct 11,
2001
Both can be acceptable. If it CAN show the content in the
browser then it is ok... (But download Popup will be better for
my case)
In brief;

• download popup for all types of files is better for me


• in case that it is easier to construct the other way(I mean
-files seen in the browser and download when needed-
behaviour like "inline"), then it is acceptable also...

navigator.appVersion returns 4.0 (compatible; MSIE


5.0; Windows NT; DigExt)

and yes I tried the case you suggested, it doesn't work at


all... It always opens a download popup, asking whether
to "Save" or "Open the document" , and in each case: It
responds with the .jsp file's name, so it tries to open/save
the content as like a text file...

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.

Re: Re: I was setting the Content-disposition header to be...


Author: Jonathan Downey
(http://www.jguru.com/guru/viewbio.jsp?EID=330209), Oct 19,
2001
Hi,
I had the same problem. Basically we wanted to always trigger the
Download from an InputStream with the correct filename being
displayed. This code works perfectly with IE 5.5 and Netscape
protected void doGet(HttpServletRequest req,
HttpServletResponse resp) {
String fileToFind = req.getParameter("file");

if(fileToFind == null) return;

File fname = new File(fileToFind);


System.out.println("Save As: "+fname.getName() );
if(!fname.exists()) return;

FileInputStream istr = null;


OutputStream ostr = null;
resp.setContentType("application/binary");
resp.setHeader("Content-Disposition", "attachment;
filename=\"" + fname.getName() + "\";");
try {
istr = new FileInputStream(fname);
ostr = resp.getOutputStream();
int curByte=-1;
while( (curByte=istr.read()) !
=-1)
ostr.write(curByte);

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());
}
}

This code uses a FileInputStream. But it's easy to adapt to any


stream really. I just used a FileInputStream for demonstration
purposes. The actual servlet will be getting the InputStream from an
FTP class. Anyone know any problems with this code?

Jonathan

Re: Re: Re: I was setting the Content-disposition header to


be...
Author: Jonathan Downey
(http://www.jguru.com/guru/viewbio.jsp?EID=330209), Oct 19,
2001
Ooops, the
try {
resp.flushBuffer();
} catch(Exception ex){
System.out.println("Error flushing the Response:
"+ex.toString());
}

bit should be left out, it keeps throwing a


Error flushing the Response: java.io.IOException:
Response has been close
error.

Re: Re: Re: Re: I was setting the Content-disposition


header to be...
Author: aytac sen
(http://www.jguru.com/guru/viewbio.jsp?EID=516073), Oct
19, 2001

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 + "\";");

so i can't find a solution to "hourglass staying busy"

Re: I was setting the Content-disposition header to be...


Author: shree m (http://www.jguru.com/guru/viewbio.jsp?EID=714860), Jan 9,
2002
Hi all!
I can download csv data to open in excel properly. I'm using only IE 5.0 and above
and jrun3.1 server. I'm posting the data (generated on the client side) as follows:
<html>
<body>
<FORM name="csv_form"
action="http://localhost:8000/csvpingserver/mycsvfile.csv"
method= "post">
<INPUT type= "hidden" value='a 70k chars looooong string'
name= "csv_data">
<INPUT id=btn_Download type=submit value=Download>
</form>
</body>
</html>

Servlet is as follows:
public void service(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException

// Set Content Type

res.setContentType("application/ms-excel");

// Init Locals

String method = req.getMethod();

OutputStream os = res.getOutputStream();

OutputStreamWriter osw = new OutputStreamWriter(os,


"UTF8");
PrintWriter out = new PrintWriter(osw);

// Validate Method

if(method.compareToIgnoreCase("POST") != 0)

out.println("Error:");

out.close();

return;

try
{

// Get CSV Data

String strCsvData = req.getParameter("csv_data");

// Return CSV Data

if(strCsvData != null)
{

char [] chCsvData = strCsvData.toCharArray();

res.setHeader("Content-Disposition",
"attachment;filename=test.csv")
;

res.setIntHeader("Content-length",
chCsvData.length);

out.write(chCsvData);

out.flush();

else

out.println("Error: No CSV Data found!");

out.close();

catch (Exception e)
{

System.err.println("Caught Exception: " +


e.getMessage());

out.println("Error: Invalid Data sent to


Servlet!");

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)?

Re[2]: I was setting the Content-disposition header to be...


Author: Nagaraja Settra
(http://www.jguru.com/guru/viewbio.jsp?EID=1211062), Nov 15, 2004
Do this in your code to fix the issue of open/save dialog showing TWICE,
res.setContentType("application/download");
res.setHeader("Content-Disposition",
"filename=\"locationOutput.csv\"");
Notice the following things here,
1. Content type is set to application/download
2. There is no attachment in the Content-Disposition header.

Re[2]: I was setting the Content-disposition header to be...


Author: Manu Bhatia
(http://www.jguru.com/guru/viewbio.jsp?EID=1227325), Feb 15, 2005
Did you solve this problem? I am having the same problem, but cannot find
any solution to it. I am trying to open an XML file.

I found that if there were spaces in the filename I...


Author: Tom Copeland (http://www.jguru.com/guru/viewbio.jsp?EID=1396), Mar 16,
2000

I found that if there were spaces in the filename I needed to use something like this:

res.setHeader("Content-Disposition", "attachment; filename=\"" +


file.getName() + "\"");

RFC 1806 discusses this in excruciating detail.


« previous beginning next »

Is the threading concurrency problem more pronunced in a multi-processor


environment than in a single-processor environment?
Location: http://www.jguru.com/faq/view.jsp?EID=11132
Created: Feb 3, 2000 Modified: 2000-06-03 14:43:20.1
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question
originally posed by sharma MR (http://www.jguru.com/guru/viewbio.jsp?EID=4939

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.

Because servlets by their nature are intended to be used in a multi-client


environment, they should always either implement SingleThreadModel or be
designed for thread safety. Note that making a servlet thread safe does not imply
that the methods need to be declared as synchronized; synchronization is just one
of the many techniques that can be used to impose thread safety.

See this FAQ for more information.

How can I pass an object from an applet to a servlet ?


Location: http://www.jguru.com/faq/view.jsp?EID=11409
Created: Feb 4, 2000 Modified: 2000-12-19 19:32:31.159
Author: Sylvain GIBIER (http://www.jguru.com/guru/viewbio.jsp?EID=11408)
Question originally posed by claude hussenet
(http://www.jguru.com/guru/viewbio.jsp?EID=2828

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?

Comments and alternative answers

See also this FAQ


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Mar 9, 2000
See also this FAQ

When I send an object from Applet to Servlet it throws...


Author: Ognyan Ivanov (http://www.jguru.com/guru/viewbio.jsp?EID=208864), Feb
7, 2001
When I send an object from Applet to Servlet it throws me an java.io.EOFExeption
code expected. I did all with object input/output streams, and from servlet to applet it
works fine. Can somebody to give me some tips . 10X in advance.

[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]

Re: When I send an object from Applet to Servlet it throws...


Author: Shahid Pathan (http://www.jguru.com/guru/viewbio.jsp?EID=526649),
Oct 22, 2001
Hi ,Ognyan we had faced the similar problem in my last project where we had lots
of applet-servlet ,servlet-servlet commincation.It took us 2-3 days to finally land
with a solution for above,but couldn't really understand why it did so.Anyway
,remember whenever you go for servlet-applet communication one sided
communication works but if you go for applet-servlet communication it has to be
2 way communication i.e send some dummy values from servlet back to applet. I
hope it works for you.

How do I read and output a text file from a Servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=11569
Created: Feb 4, 2000 Modified: 2000-06-17 12:54:15.461
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by aaron tenney
(http://www.jguru.com/guru/viewbio.jsp?EID=9147

Try the following:


import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class MessageServlet extends HttpServlet {


public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws IOException, ServletException
{
// output an HTML page
res.setContentType("text/html");

// load a configuration parameter (you must set


this yourself)
String root = getInitParameter("root");

// print some html


ServletOutputStream out = res.getOutputStream();
out. println("<html>");
out.println("<head><title>Message of the
Day</title></head>");
out.println("<body><h1>Today's Message:</h1>");

// print the file


InputStream in = null;
try {
in = new BufferedInputStream
(new FileInputStream(root + "/message.txt")
);
int ch;
while ((ch = in.read()) !=-1) {
out.print((char)ch);
}
}
finally {
if (in != null) in.close(); // very important
}

// 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.

Comments and alternative answers

Does this piece of code handle the concurrency problem...


Author: arijith roy (http://www.jguru.com/guru/viewbio.jsp?EID=11704), Feb 5, 2000
Does this piece of code handle the concurrency problem inherent with multiple users
accessing the servlet at the same time ? I see a potential problem in the above
scenario.

reading from a config or property file


Author: cy [missing] (http://www.jguru.com/guru/viewbio.jsp?EID=1089211),
Aug 14, 2003
I wan to write a servlet that reads from a property files eg ClassName.properties
Cos I am thinking of writing a login servlet which is connected to a LDAP server.
But I wan my servlet to read the ClassName.properties file after the user logs in to
the LDAP server. An example of a properties file username1=john
username2=peter username3=david so if any of the above user logs in, it will
display an admin page. Just wondering anyone got a sample code on this? Please
email to yihwen@singnet.com.sg Thanks Yih Wen

There's no concurrency problem if you're just reading...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jun 17, 2000
There's no concurrency problem if you're just reading files. If you are simultaneously
trying to write a file you could encounter problems.

I thought each "service" method ran in it's...


Author: Stephen McConnell (http://www.jguru.com/guru/viewbio.jsp?EID=248618),
Feb 21, 2001
I thought each "service" method ran in it's own thread, so as long as you don't use
instance variables, there would be no concurrency problem (as long as the file you are
reading is not locked by another user).

[Yes, that's the concurrency problem we're talking about :-) -Alex]

How to make the same for binary data? (image/jpg).


Author: aa aa (http://www.jguru.com/guru/viewbio.jsp?EID=446955), Aug 20, 2001
Can you modify and show the code?

Re: How to make the same for binary data? (image/jpg).


Author: Ronny Dev (http://www.jguru.com/guru/viewbio.jsp?EID=784643), Mar
6, 2002

Hi, instead of using response.getOutputStream() to get ServletOutputStream


object use response.getWriter() method to get PrintWriter Object, but before doing
so set the content type(refer API doc for response.getWriter()) and then proceed as
above.

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.

CGI Variable Servlet Request Method


SERVER_SOFTWARE ?
The name and version of the information server software answering the request (and
running the gateway). Format: name/version
SERVER_NAME getServerName()
The server's hostname, DNS alias, or IP address as it would appear in self-referencing
URLs.
GATEWAY_INTERFACE N/A
The revision of the CGI specification to which this server complies. Format: CGI/revision
SERVER_PROTOCOL getProtocol()
The name and revision of the information protcol this request came in with. Format:
protocol/revision
SERVER_PORT getServerPort()
The port number to which the request was sent.
REQUEST_METHOD getMethod()
The method with which the request was made. For HTTP, this is "GET", "HEAD",
"POST", etc.
PATH_INFO getPathInfo()
The extra path information, as given by the client. In other words, scripts can be accessed
by their virtual pathname, followed by extra information at the end of this path. The extra
information is sent as PATH_INFO. This information should be decoded by the server if it
comes from a URL before it is passed to the CGI script.
PATH_TRANSLATED getPathTranslated()
The server provides a translated version of PATH_INFO, which takes the path and does
any virtual-to-physical mapping to it.
SCRIPT_NAME getServletPath()
A virtual path to the script being executed, used for self-referencing URLs.
getQueryString()
QUERY_STRING also see getParameter() ,
getParameterValues(), etc..
The information which follows the ? in the URL which referenced this script. This is the
query information. It should not be decoded in any fashion. This variable should always be
set when there is query information, regardless of command line decoding.
REMOTE_HOST getRemoteHost()
The hostname making the request. If the server does not have this information, it should
set REMOTE_ADDR and leave this unset.
REMOTE_ADDR getRemoteAddr()
The IP address of the remote host making the request.
AUTH_TYPE getAuthType()
If the server supports user authentication, and the script is protects, this is the protocol-
specific authentication method used to validate the user.
REMOTE_USER getRemoteUser()
If the server supports user authentication, and the script is protected, this is the username
they have authenticated as.
? - but if a server supports RFC
REMOTE_IDENT 931, it should probably pass this
in getRemoteUser()
If the HTTP server supports RFC 931 identification, then this variable will be set to the
remote user name retrieved from the server. Usage of this variable should be limited to
logging only.
CONTENT_TYPE getContentType()
For queries which have attached information, such as HTTP POST and PUT, this is the
content type of the data.
CONTENT_LENGTH getContentLength()
The length of the said content as given by the client.
The HTTP header lines received from the client, if any,
The HTTP Headers are available
are placed into the environment with the prefix HTTP_
through getHeader(String),
followed by the header name. An example of this is the
getHeaders(String) and
HTTP_ACCEPT variable which was defined in
getHeaderNames()
CGI/1.0. Another example is the header User-Agent.
HTTP_ACCEPT getHeader("Accept")
The MIME types which the client will accept, as given by HTTP headers. Other protocols
may need to get this information from elsewhere. Each item in this list should be separated
by commas as per the HTTP spec. Format: type/subtype, type/subtype
HTTP_USER_AGENT getHeader("User-Agent")
The browser the client is using to send the request. General format: software/version
library/version.
Comments and alternative answers

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

Re: Found Answer


Author: Ragefan Nicolas (http://www.jguru.com/guru/viewbio.jsp?EID=498395),
Sep 17, 2001
i have the same problem and including your piece of code did not solve my
problem ...

Re[2]: Found Answer


Author: Jeff Huntington
(http://www.jguru.com/guru/viewbio.jsp?EID=721370), Jan 15, 2002
I too am currently having this problem. That solution did not solve it. I would
appreciate any response.

Re[3]: Found Answer


Author: Alex best
(http://www.jguru.com/guru/viewbio.jsp?EID=1079313), Apr 25, 2003
I had the same pb and putting the whole Auth stuff in the <location>
directive solve th pb.

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

After (no directory auth):


<location /> (whole site, all ports with virtual hosts)
AuthName "MY AUTH NAME"
AuthType Basic
PerlAuthenHandler blabla
require valid-user
</location>
OK : I get my req.getRemoteUser() !
or if you want, you can only do it on <location /servlets>...

Problem with server variable when using tomcat and IIS


Author: Leto ATom (http://www.jguru.com/guru/viewbio.jsp?EID=711725), Jan 7,
2002
I'm using IIS with the ISAPI filter and Tomcat 3.24 i can't get PATH_INFO and
PATH_TRANSLATED info, they are all null. Any one's got an Idea ?
Re: Problem with server variable when using tomcat and IIS
Author: gold bell (http://www.jguru.com/guru/viewbio.jsp?EID=547577), Jan 16,
2002
me,too.If you find answer,please tell me. thanks.

How do I prevent the output of my servlet from being cached by the


browser?
Location: http://www.jguru.com/faq/view.jsp?EID=11761
Created: Feb 5, 2000 Modified: 2000-02-07 06:05:18.659
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

See this Question in the JSP FAQ.

How can my application get to know when a HttpSession is removed (when


it time-outs)?
Location: http://www.jguru.com/faq/view.jsp?EID=12141
Created: Feb 7, 2000 Modified: 2000-06-03 14:45:15.689
Author: Kent Johnson (http://www.jguru.com/guru/viewbio.jsp?EID=3211) Question
originally posed by Jan Sundin
(http://www.jguru.com/guru/viewbio.jsp?EID=11515

Define a class, say SessionTimeoutNotifier, that implements


javax.servlet.http.HttpSessionBindingListener. Create a
SessionTimeoutNotifier object and add it to the user session. When the session is
removed, SessionTimeoutNotifier.valueUnbound() will be called by the servlet
engine. You can implement valueUnbound() to do whatever you want.

[Source code example anyone? -Alex]

Comments and alternative answers

so can this be used to track the users who are cur...


Author: Robin Paul (http://www.jguru.com/guru/viewbio.jsp?EID=80982), Jun 29,
2000
so can this be used to track the users who are currently logged into the system???

There isn't a "reference" (or whatever) ...


Author: Wilian Zurita (http://www.jguru.com/guru/viewbio.jsp?EID=130129), Aug
18, 2000
There isn't a "reference" (or whatever) implementation for such a Listener? I only
need to invalidate the session. This is pretty easy to do, but I think that this task is
soooo common, so i think such a Listener could be provided on the servlet package.
(or anywhere)....

[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.*;

public class TestSessionServer extends HttpServlet


{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String command = req.getParameter("command");
HttpSession session = req.getSession(true);
session.setMaxInactiveInterval(180);
session.setAttribute("SessionObjName", new SessionTimeoutNotifier());
System.out.println("The command you typed was : "+command);
out.println("You typed : "+command);
out.println("Your session id is : "+session.getId());
} // End of doGet method
}

class SessionTimeoutNotifier implements HttpSessionBindingListener


{
SessionTimeoutNotifier()
{
}
public void valueBound(HttpSessionBindingEvent event)
{
System.out.println("The session has started : "+event.getSession().getId());
}

public void valueUnbound(HttpSessionBindingEvent event)


{
System.out.println("The session has ended : "+event.getSession().getId());
}
}

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.*;

public class TestSessionServer extends HttpServlet


{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String command = req.getParameter("command");
HttpSession session = req.getSession(true);
session.setMaxInactiveInterval(180);
session.setAttribute("SessionObjName", new SessionTimeoutNotifier());
System.out.println("The command you typed was : "+command);
out.println("You typed : "+command);
out.println("Your session id is : "+session.getId());
} // End of doGet method
}

class SessionTimeoutNotifier implements HttpSessionBindingListener


{
SessionTimeoutNotifier()
{
}
public void valueBound(HttpSessionBindingEvent event)
{
System.out.println("The session has started : "+event.getSession().getId());
}

public void valueUnbound(HttpSessionBindingEvent event)


{
System.out.println("The session has ended : "+event.getSession().getId());
}
}

Re: Source Code....


Author: Nicolas Bétheuil (http://www.jguru.com/guru/viewbio.jsp?EID=850916),
Apr 23, 2002
i have a mistake,

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 ?

I use tomcat 3.2

From another answer:


Author: jon spencer (http://www.jguru.com/guru/viewbio.jsp?EID=895842),
May 29, 2002
you should only add objects that are serializable to an HttpSession.
Specifically, a JDBC Connection object is not serializable, so should not be
added to the session (despite the example 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!)
http://www.jguru.com/faq/view.jsp?EID=151

Re[2]: Source Code....


Author: Tony He (http://www.jguru.com/guru/viewbio.jsp?EID=1234658), Mar 24,
2005
take a look at this article, you should close your connection while doing
valueUnbound()
http://www.di.unipi.it/~ghelli/bdl/A97329_03/web.902/a95882/basics.htm#1013407

Re: Source Code....


Author: yudan maivar (http://www.jguru.com/guru/viewbio.jsp?EID=940142), Jul
8, 2002
I have tried to implement your code on JSP unsecssesfuly can you please tell me
how do i implement it on JSP ?? thanks

Re[2]: Source Code....


Author: Bilal Ahmed (http://www.jguru.com/guru/viewbio.jsp?EID=1105422),
Jul 31, 2003
Hi, Did you ever get your question answered? I am in the same situation where
I need to do a timeout and cleanup through JSP. Thanks.

Re[3]: Source Code....


Author: yudan maivar
(http://www.jguru.com/guru/viewbio.jsp?EID=1057092), Aug 2, 2003
you have to implement HttpSessionListener:
public class DBmanager implements
javax.servlet.http.HttpSessionListener{
and then add this 2 functions:
public void sessionDestroyed(HttpSessionEvent se){}
public void sessionCreated(HttpSessionEvent se)

good luck
yudan maivar

Re[4]: Source Code....


Author: Bilal Ahmed
(http://www.jguru.com/guru/viewbio.jsp?EID=1105422), Aug 11, 2003
Hi Yudan, Thanks for your answer. It seems like HttpSessionListener is
a feature of JDK1.4. I am looking for a solution in jdk1.3. If you have
any other suggestions, please let me know. Thanks!

Re[5]: Source Code....


Author: Elmar Christen
(http://www.jguru.com/guru/viewbio.jsp?EID=399683), Jun 30,
2004
As far as I know, the HttpSessionListener class forms part of the
servlet.jar Version 2.3+
You should be able to work with it with jdk1.3 without problems.
Don't forget to add you Listener-Implementations in the listener tag
of the web.xml.
Note: This tag is not recognized by all servers. For example:it
works for tomcat 4+, but not in 3.2
And: I ve heard, that some events will fire at different moments
when changing from jdk1.3 to 1.4: for example, the destroyed
method is invoked after the session has been destroyed when using
1.3, but when using 1.4, it will fire just before - well, that what I ve
heard. Haven tried it yet, I til than I won't believe it.
Hope I could help.

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.

These are retorical questions for you to think about:

• 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.

Hope this helps you.

Sincerely,

Thomas Dietrich

Repost from: http://www.jguru.com/forums/view.jsp?EID=445695

Re: Using JSP's and Servlets...


Author: ajay kumar (http://www.jguru.com/guru/viewbio.jsp?EID=1064984), Apr
3, 2003
Hi..!! Dietrich.. do u wanna say that in servlets programming both presentation
layer and implimentation layer r clubbed together and jsp programming deals with
only presentation layer.

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.

Comments and alternative answers

To clarify: The <%@include> directive acts like...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Feb 11, 2000
To clarify: The
<%@include>
directive acts like C "#include", pulling in the text of the included file and compiling
it as if it were part of the including file. By contrast, the
<jsp:include>
tag compiles the file as a separate JSP file, and embeds a call to it in the compiled
JSP.

How can I download files from a URL using HTTP?


Location: http://www.jguru.com/faq/view.jsp?EID=13198
Created: Feb 10, 2000 Modified: 2001-07-23 10:54:02.662
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question
originally posed by Govind Seshadri PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=14

One way to do this is by using a URLConnection to open a stream to your desired


URL, then copy the data out of the stream to a file on your local file system. As an
example, here's a little snippet of code which lets you download the jGuru logo to
your machine:

URL url = new URL("http://www.jguru.com/images/logo.gif");


URLConnection connection = url.openConnection();
InputStream stream = connection.getInputStream();
BufferedInputStream in = new BufferedInputStream(stream);
FileOutputStream file = new FileOutputStream("logo.gif");
BufferedOutputStream out = new BufferedOutputStream(file);
int i;
while ((i = in.read()) != -1) {
out.write(i);
}
out.flush();
Note the use of "Stream" classes instead of "Reader" classes. This is done because in
general a URL may contain binary data, as in this example. Also note that both the
input and the output streams are buffered - this greatly speeds the download time
and is far more efficient that reading and writing a single byte at a time, especially
over the network.
Comments and alternative answers

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

Putting of extra ^ M in my file when I stream it out for download


Author: Hey Arnold (http://www.jguru.com/guru/viewbio.jsp?EID=462807), Nov 7,
2001
This is the example I used
=================================================
URL url = new URL("http://www.jguru.com/images/logo.gif");
URLConnection connection = url.openConnection();
InputStream stream = connection.getInputStream();
BufferedInputStream in = new BufferedInputStream(stream);
FileOutputStream file = new FileOutputStream("logo.gif");
BufferedOutputStream out = new BufferedOutputStream(file);
int i;
while ((i = in.read()) != -1) {
out.write(i);
}
out.flush();

================================================
It downloaded all the content of the file, but it put in extra ^M in my files...thus
conrrupting it.. Can anyone help?? Thanks!

Re: Putting of extra ^ M in my file when I stream it out for download


Author: muthukrishnan anbumani
(http://www.jguru.com/guru/viewbio.jsp?EID=1193471), Aug 16, 2004

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?

The Code in the first reply


Author: Tom Cat (http://www.jguru.com/guru/viewbio.jsp?EID=851623), May 1,
2002
I inserted the Code in my JSP page but nothing seems to happen when i view it from
IE please advice

Re: The Code in the first reply


Author: afi afi (http://www.jguru.com/guru/viewbio.jsp?EID=1138618), Jan 12,
2004
sucked in

What's new with the Java Servlet 2.2 API?


Location: http://www.jguru.com/faq/view.jsp?EID=13422
Created: Feb 11, 2000 Modified: 2002-03-01 17:33:38.717
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

I read this article on the past : http://www.javaworld.com/jw-10-1999/jw-10-


servletapi.html. Exactly what you're looking for. This article explains also the
difference between 2.1 & 2.2 API.

Can I use Tomcat or JavaWebServer as a service on Windows NT or


Windows 2000?
Location: http://www.jguru.com/faq/view.jsp?EID=13457
Created: Feb 11, 2000 Modified: 2001-11-03 12:07:05.805
Author: Kumar Allamraju (http://www.jguru.com/guru/viewbio.jsp?EID=12218)
Question originally posed by Eric Lebetsamer
(http://www.jguru.com/guru/viewbio.jsp?EID=12240
For Tomcat:

Download jk_nt_service.exe and follow the instructions in the document "NT-


Service-howto.html" (on the Jakarta Web site and included in the Tomcat distros).
Also see the minimalistic users guide, included with the Tomcat distribution.

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

You can try to use Jsrvany to run Tomcat as an NT ...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Apr 3, 2000
You can try to use Jsrvany to run Tomcat as an NT service -- if anyone has any
success, please let us know exactly how you did it.

Use Jsrvany.
Author: Tom Copeland (http://www.jguru.com/guru/viewbio.jsp?EID=1396), Apr 3,
2000
Use Jsrvany.

I used jk_nt_service.exe (http://jakarta.apache.or...


Author: Alexandre Hermida (http://www.jguru.com/guru/viewbio.jsp?EID=272757),
Dec 13, 2000
I used jk_nt_service.exe
(http://jakarta.apache.org/builds/tomcat/release/v3.2.1/bin/win32/i386/). I used it on
win2000/Tomcat 3.1 and it´s working very well.

Re: I used jk_nt_service.exe (http://jakarta.apache.or...


Author: Al Brown (http://www.jguru.com/guru/viewbio.jsp?EID=420656), May
12, 2001
Works fine when using JDK 1.2.2, but 1.3 won't work when user logs off NT.

Re: Re: I used jk_nt_service.exe (http://jakarta.apache.or...


Author: Jim Kabage (http://www.jguru.com/guru/viewbio.jsp?EID=478916),
Aug 17, 2001
I get the same problem on Windows 2000 SP2 and Tomcat 3.2. The service
shuts down without a trace when the user logs off. Once the user logs back in,
the process can be started up manually without a problem. Anybody know
why? Thanks.

I can't start Tomcat using jk_nt_service.exe. The error...


Author: Dmitry Ryzhevich (http://www.jguru.com/guru/viewbio.jsp?EID=208194),
Jan 1, 2001
I can't start Tomcat using jk_nt_service.exe. The error is "Jakarta service couldn't be
started -> the service didn't report an error -> net helpmsg 3534". How should my file
wrapper.properties look like? Variables wrapper.java_home, wrapper.tomcat_home
are not enough.

Re: I can't start Tomcat using jk_nt_service.exe. The error...


Author: Al Brown (http://www.jguru.com/guru/viewbio.jsp?EID=420656), May
12, 2001
Make sure the log files jvm.stdout and jvm.stderr exist.

Re: I can't start Tomcat using jk_nt_service.exe. The error...


Author: piyush batwal (http://www.jguru.com/guru/viewbio.jsp?EID=498423),
Sep 17, 2001
i m in deaparate need for the answer of the same please help me if you know
pbatwal@indaitimes.com

Re: I can't start Tomcat using jk_nt_service.exe. The error...


Author: Shaman Jain (http://www.jguru.com/guru/viewbio.jsp?EID=1131268),
Dec 1, 2003
hello, i'm also stuck with same problem, is ur problem solved and if yes then pls
do let me know thanx in advance Shaman

FYI: java services on NT are about to standardize ...


Author: Brian Ewins (http://www.jguru.com/guru/viewbio.jsp?EID=301660), Jan 13,
2001
FYI: java services on NT are about to standardize (yay!), so soon all servlet engines
should work much the same way. To see what is proposed (and to get hold of an NT
implementation of the java daemon engine) take a look at the Java Daemons proposal:
http://java.sun.com/aboutJava/communityprocess/jsr/jsr_096_daemon.html. The spec
won't finalize until November 2001 but you could expect Tomcat to have an
implementation before then.
Re: FYI: java services on NT are about to standardize ...
Author: Laurent Mihalkovic
(http://www.jguru.com/guru/viewbio.jsp?EID=407112), Apr 10, 2002
Indeed the page contains a proposal. Section 3.1 even has links to a PDF file as
well as a zip file containing some source code. However, the top right hand corner
of the document has a big Withdrawn

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).

Comments and alternative answers

Check out Tip #41: POSTing via Java revisited and...


Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4), Apr 26,
2000
Check out Tip #41: POSTing via Java revisited and HTTPClient.
Is there any way to detect the cookies from a servlet invoked by the
<SERVLET> tag from a shtml page?
Location: http://www.jguru.com/faq/view.jsp?EID=14267
Created: Feb 14, 2000 Modified: 2000-06-03 14:49:39.549
Author: Kumar Allamraju (http://www.jguru.com/guru/viewbio.jsp?EID=12218)
Question originally posed by takoe henry
(http://www.jguru.com/guru/viewbio.jsp?EID=12248

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());

getting current path during initialisation of a servlet


Author: Chris Joelly (http://www.jguru.com/guru/viewbio.jsp?EID=1055217), Feb
10, 2003
Hello! how can i get the current path to the filesystem during servlets initialisation
phase? For example to read config files relative to the servlet path? Thx, Chris

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")

See this question in the JSP FAQ:


http://www.jguru.com/jguru/faq/view.jsp?EID=12253 for a class which embodies
lots of good info about the browser.

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]

Comments and alternative answers

http://www.browserhawk.com has a bean to do browser...


Author: David Holmes (http://www.jguru.com/guru/viewbio.jsp?EID=16037), Feb
19, 2000
http://www.browserhawk.com has a bean to do browser feature detection, including
whether or not cookies are enabled.
I want to use url rewriting as the default mechanism for maintaining the
session ID rather than make use of a cookie. How do I enable this when
creating a new session with JSP or servlets?
Location: http://www.jguru.com/faq/view.jsp?EID=15027
Created: Feb 16, 2000 Modified: 2000-10-11 13:44:58.177
Author: Mobushir Hingorjo (http://www.jguru.com/guru/viewbio.jsp?EID=11910)
Question originally posed by Marco Hunsicker
(http://www.jguru.com/guru/viewbio.jsp?EID=11275

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

Resin supports url-rewriting by config


Author: pablo gutierrez (http://www.jguru.com/guru/viewbio.jsp?EID=552419), Nov
25, 2001

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.

Comments and alternative answers

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.

Re: Thread safety


Author: Games Id (http://www.jguru.com/guru/viewbio.jsp?EID=1168668), May
5, 2004
You just have repeated what Govind wrote in your confused english

Re[2]: Thread safety


Author: Murthy V (http://www.jguru.com/guru/viewbio.jsp?EID=1247172),
Jun 4, 2005
Do not use SingleThreadModel as it can not guarantee thread safety in case of
session variables and static variables. In fact SingleThreadModel is deprecated
from Servlet 2.4 onwards.

Re[3]: Thread safety


Author: Dan F (http://www.jguru.com/guru/viewbio.jsp?EID=1258757),
Aug 19, 2005
So what are commonly accepted best practices in coarse-grained (i.e.,
servlet-level) thread-safety?

Dan

How can I stress test a servlet / JSP page?


Location: http://www.jguru.com/faq/view.jsp?EID=15748
Created: Feb 18, 2000 Modified: 2001-06-15 10:32:49.034
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Sathish Kishore Baji
(http://www.jguru.com/guru/viewbio.jsp?EID=15379

Allaire has a ServletKiller product available for free at


http://www.allaire.com/products/jrun/ServletAddOn.cfm that will stress test your
servlets. Some additional non-servlet-specific stress testing tools are e-Load from
RSW Software (http://www.rswsoftware.com/products/eload.html), Microsoft's Web
Application Stress Tool (http://homer.rte.microsoft.com/), and Apache's JMeter
(http://java.apache.org/jmeter/index.html).
Comments and alternative answers

ServletKiller is apparently rolled into JRUN. The...


Author: Sreenivas Gudavalli (http://www.jguru.com/guru/viewbio.jsp?EID=232158),
Oct 23, 2000
ServletKiller is apparently rolled into JRUN. The following is a blurb from the web
page referred to by the link in the answer.
Discontinued.
JRun Servlet Add-on products are no longer sold or supported stand-alone. This
functionality has been incorporated into JRun 3.0, which is currently available for sale
through the Allaire Online Store, or through any one of our national and international
value added resellers.
[Fortunately, JRun has a free download. Is ServletKiller in it? -Alex]

wget works great if you've got unix. Just give it...


Author: Terence Parr (http://www.jguru.com/guru/viewbio.jsp?EID=1), Nov 7, 2000
wget works great if you've got unix. Just give it a url and let 'er rip! Can set the depth
of penetration etc...

The best way to test any web application is probably...


Author: Ivar Vasara (http://www.jguru.com/guru/viewbio.jsp?EID=262588), Nov 25,
2000
The best way to test any web application is probably httpunit, a superset for the Junit
testing suite.

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 :

the first method is the aliasing which describes a series of servlets to be


executed
the second one is to define a new MIME-Type and associate a servlet as
handlers As I don't really use the second one, I'll focus on the aliasing.

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.

The srvA servlet code should look like :

public class srvA extends HttpServlet {


...
public void doGet (...) {
PrintWriter out =res.getWriter();
rest.setContentType("text/html");
...
out.println("Hello Chaining servlet");
}
}
All the servlet srvB has to do is to open an input stream to the request object and
read the data into a BufferedReader object as for example :
BufferedReader b = new BufferedReader( new
InputStreamReader(req.getInputStream() ) );
String data = b.readLine();
b.close();
After that you can format your output with the data.
It should work straigthforward with Java Web Server or Jserv too. Just look at in
their documentation to define an alias name. Hope that it'll help.
Comments and alternative answers

Servlet chaining is an unsupported feature of many...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Mar 9, 2000
Servlet chaining is an unsupported feature of many servlet engines that unfortunately
didn't make it into the spec. So future releases of servlet engines may not support it.
JSWDK (and I think Tomcat) does *not* support servlet chaining.

You can write in servlet chaining-like functionality...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), May 8, 2000
You can write in servlet chaining-like functionality by using the RequestDispatcher.
Search this FAQ or read the API documentation or spec for more information.

See also Is there a way I can capture the output of...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jul 6, 2000
See also Is there a way I can capture the output of a servlet, without immediately
sending it to the client response stream?

Why there are no constructors in servlets?


Location: http://www.jguru.com/faq/view.jsp?EID=18825
Created: Feb 28, 2000 Modified: 2000-03-07 18:21:28.277
Author: Dharminder Dharna (http://www.jguru.com/guru/viewbio.jsp?EID=18824)
Question originally posed by Lalit Chhablani
(http://www.jguru.com/guru/viewbio.jsp?EID=14929

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

What is servlet environment?


Author: shivesh singh (http://www.jguru.com/guru/viewbio.jsp?EID=1215107), Dec
15, 2004
as it is described that servlet environment takes care of instantiating the servlet, an
explicit constructor is not needed what exactly is this servlet environment?

If I store an image as a BLOBs in my database, and I use getBinaryStream


to retrieve the value, how can I show it in a browser?
Location: http://www.jguru.com/faq/view.jsp?EID=20336
Created: Mar 4, 2000 Modified: 2000-06-03 14:51:45.556
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

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

How to handle multiple concurrent database requests/updates when using


JDBC with servlets?
Location: http://www.jguru.com/faq/view.jsp?EID=21658
Created: Mar 8, 2000 Modified: 2000-06-03 14:53:21.093
Author: MAHESH MULCHANDANI
(http://www.jguru.com/guru/viewbio.jsp?EID=18395) Question originally posed by
Irfan Mohamed (http://www.jguru.com/guru/viewbio.jsp?EID=12472

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.

Comments and alternative answers

Multiple database access concurrently


Author: Shanker Srivastava (http://www.jguru.com/guru/viewbio.jsp?EID=1215848),
Dec 12, 2004
How do I send the SQL queires to get the data from different database which are on
different machine, and all the data execution should happen concurrently, so that I can
save the time, and get the data with in a very short time.

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

In short GenericServlet is protocol independent, w...


Author: Deepak Kalra (http://www.jguru.com/guru/viewbio.jsp?EID=99188), Jul 24,
2000
In short GenericServlet is protocol independent, whereas HttpServlet is protocol
dependent

In GenericServlets you cannot use Cookies or HttpS...


Author: Kiran Kumar (http://www.jguru.com/guru/viewbio.jsp?EID=18386), Oct 29,
2000
In GenericServlets you cannot use Cookies or HttpSession.

Session tracking is not possible, redirection is not possible.

Http servlets overrides doGet and doPost methods. ...


Author: ramcharan charan (http://www.jguru.com/guru/viewbio.jsp?EID=279628),
Dec 22, 2000
Http servlets overrides doGet and doPost methods. Generic servlet overides service
method.

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

diff between http servlets and generic servlets


Author: san re (http://www.jguru.com/guru/viewbio.jsp?EID=1255630), Aug 19,
2005
Http servlet is the sub class of Generic sevlet so all the life cycle methods available in
the generic servlets are available to the Http servlets. Http servlets provides methods
that supports cookies,sessions etc.while generic servlets are not. Http servlet
request,Http servlet responce methods extends generic servlet request,generic servlet
responce.

How do you share session objects between servlets and JSP?


Location: http://www.jguru.com/faq/view.jsp?EID=22841
Created: Mar 10, 2000 Modified: 2000-08-16 15:10:26.832
Author: anil chakravarthy (http://www.jguru.com/guru/viewbio.jsp?EID=7769)
Question originally posed by Kedar Sardesai
(http://www.jguru.com/guru/viewbio.jsp?EID=21703

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?

For a detailed example which demonstrates the sharing...


Author: Govind Seshadri (http://www.jguru.com/guru/viewbio.jsp?EID=14), Apr 7,
2000
For a detailed example which demonstrates the sharing of sessions between JSPs and
servlets, see: http://www.javaworld.com/javaworld/jw-12-1999/jw-12-ssj-
jspmvc.html

Does it work the other way round ?? If so How ??


Author: al still (http://www.jguru.com/guru/viewbio.jsp?EID=482248), Jan 9, 2002

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

Any help will be appreciated Thanks

I can't get this to work!


Author: David Vairin (http://www.jguru.com/guru/viewbio.jsp?EID=814797), Mar
27, 2002
When I open my jsp it creates a new session. I can't seem to open a jsp from a servlet
and keep the same session. Any help.

Can I get at the OutputStream that is buried underneath


ServletContext.log()? If so how can I modify it?
Location: http://www.jguru.com/faq/view.jsp?EID=22877
Created: Mar 10, 2000 Modified: 2001-07-19 15:43:15.832
Author: Peter Wang (http://www.jguru.com/guru/viewbio.jsp?EID=22876) Question
originally posed by Mark Anderson
(http://www.jguru.com/guru/viewbio.jsp?EID=21995

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.

How do I set the content encoding of the response to "x-gzip"? I am trying


to send HTML data in gzip format, hoping the client will automatically
deflate it
Location: http://www.jguru.com/faq/view.jsp?EID=22902
Created: Mar 10, 2000 Modified: 2000-03-10 13:11:12.101
Author: Peter Wang (http://www.jguru.com/guru/viewbio.jsp?EID=22876) Question
originally posed by Stephane Boury
(http://www.jguru.com/guru/viewbio.jsp?EID=22044

Make sure you set HttpServletResponse by response.setContentType("application/x-


gzip" ); A user would have the choice to open with WinZip plugin or save as WinZip
file extension to be deflated later on. Very few browsers understand how to deflate
this directly and display it.
Comments and alternative answers

You can do it more or less with a servlet:


Author: Cron Iceman (http://www.jguru.com/guru/viewbio.jsp?EID=995942), Sep 6,
2002
import java.io.*;
import java.util.zip.GZIPOutputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.http.*;

public class GzipServlet extends HttpServlet


{

public void doGet(HttpServletRequest httpservletrequest,


HttpServletResponse httpservletresponse)
throws ServletException, IOException
{
doPost(httpservletrequest, httpservletresponse);
}
public void doPost(HttpServletRequest httpservletrequest,
HttpServletResponse httpservletresponse)
throws ServletException, IOException
{
String s = httpservletrequest.getHeader("Accept-Encoding");
boolean flag = false;
if(s != null && s.indexOf("gzip") >= 0)
flag = true;
if(flag)
{
httpservletresponse.setHeader("Content-Encoding",
"gzip");
javax.servlet.ServletOutputStream servletoutputstream =
httpservletresponse.getOutputStream();
GZIPOutputStream gzipoutputstream = new
GZIPOutputStream(servletoutputstream);
String s1 = "";
s1 = s1 + "<html>";
s1 = s1 + "<br>Go ahead and add text and code...it will
compress it.";
s1 = s1 +
"<br>_____________________________________________________";
s1 = s1 + "<br>this was compressed";
s1 = s1 + "<br>this was compressed";
gzipoutputstream.write(s1.getBytes());
gzipoutputstream.close();
servletoutputstream.close();
return;
} else
{
PrintWriter printwriter =
httpservletresponse.getWriter();
httpservletresponse.setContentType("text/html");
printwriter.println("<html>");
printwriter.println("Your browser does not support GZIP
encoding. Please upgrade");
printwriter.println("</html>");
printwriter.flush();
printwriter.close();
return;
}
}

public GzipServlet()
{
}
}

Re: You can do it more or less with a servlet:


Author: Naveen Talati (http://www.jguru.com/guru/viewbio.jsp?EID=1261526),
Sep 9, 2005
Hi , I am using ie6 browser, does ie6 automatically deflate gzip and display it.
When i try to open up the servlet response, the winzip is taking over and i want to
avoid it. Is there a way to make this possible. Best Regards, Naveen Kumar Talati.
[ADP]

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

A far easier way to do it is with the HTTP custom tag...


Author: Mike Cannon-Brookes
(http://www.jguru.com/guru/viewbio.jsp?EID=26527), Mar 21, 2000
A far easier way to do it is with the HTTP custom tag in the External library of the
IN16 JSP Tags at http://sourceforge.net/project/?group_id=1282.

Here's an example of the syntax:


<ext:http method="get" url="http://www.jguru.com" var="content">

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).

Check it out at http://sourceforge.net/project/?group_id=1282


SSI for Java also has a utility class that will include...
Author: Joe Morse (http://www.jguru.com/guru/viewbio.jsp?EID=91113), Jun 29,
2000
SSI for Java also has a utility class that will include the contents of any external URL.
This is *way* better than having to schlep through JSP...keeping content/presentation
and logic separate.

Hey, stop taking unnecessary digs at JSP! Using a...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jul 6, 2000
Hey, stop taking unnecessary digs at JSP! Using a jsp:include tag, a custom Taglib
tag, a Servlet, a Scriptlet, a SSI, and so forth are all equally valid ways of including
external content into your page. All of them allow you to say "here's where I want
some external content to go," and that's plenty clean.

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).

Here is the Code For it.It will retreive the Contents...


Author: Deepak Kalra (http://www.jguru.com/guru/viewbio.jsp?EID=99188), Jul 14,
2000
Here is the Code For it.It will retreive the Contents From Specified URL and Wite to
Disk.You can Directly Display the Data
import java.net.*;
import java.io.*;
import java.lang.String;
import java.net.*;

public class URLReader {


public static void main(String[] args) throws Exception
{

URL yahoo = new URL("specify url");

try {
yahoo.openConnection();
}

catch (MalformedURLException e) {
System.out.println(e.getMessage());
}

BufferedReader in = new BufferedReader(new


InputStreamReader(yahoo.openStream()));
DataOutputStream outfile = new DataOutputStream(new
FileOutputStream("foo.txt"));
String inputLine;
int lenline;

while ((inputLine =in.readLine()) != null) {


inputLine = inputLine.trim();
inputLine = inputLine + "\n";

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.

Any ways around this? Thanks!

Re: Authentication/Session issues?


Author: Mark Hilgart (http://www.jguru.com/guru/viewbio.jsp?EID=1181392),
Jun 24, 2004
I don't know about custom tags, but you can copy cookies over with one line if
you're using Java URL connections:
URL url = new URL("http://...");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestProperty("Cookie",request.getHeader("Cookie"));

// rest of the code is similar to Deepak Kalra's post

How do I setup a cookie to expire after a certain time?


Location: http://www.jguru.com/faq/view.jsp?EID=23334
Created: Mar 12, 2000 Modified: 2000-06-03 14:56:22.605
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

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

Comments and alternative answers

See also How can I specify which kind of cookies (...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jun 17, 2000
See also How can I specify which kind of cookies (single-session cookies or
persistent cookies) I want to use ?

See also If the lifespan of a cookie is left unspe...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Aug 11, 2000
See also If the lifespan of a cookie is left unspecified by not invoking the
Cookie.setMaxAge( int ) method, how long will such a cookie be retrievable by the
server?

How can I implement a password-protected servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=23768
Created: Mar 13, 2000 Modified: 2000-08-13 16:46:31.372
Author: niels thorwirth (http://www.jguru.com/guru/viewbio.jsp?EID=23766)
Question originally posed by Rajeev Singh
(http://www.jguru.com/guru/viewbio.jsp?EID=17777

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]

Comments and alternative answers

Niels would like me to clarify his answer: The given...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Apr 3, 2000
Niels would like me to clarify his answer:
The given URL describes how to implement HTTP authentication manually, if you're
running inside a servlet engine that doesn't support it (like servletrunner). The normal
API for accessing user authentication information is to use methods in
HTTPServletRequest like getRemoteUser()

The above link has stopped working; try http://www...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Apr 24, 2000
The above link has stopped working; try
http://www.trudat.com/trudat/authentication.html instead for the time being.

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.

As I understood once the HTTP authentification suc...


Author: Christian Ringler (http://www.jguru.com/guru/viewbio.jsp?EID=89969), Jul
10, 2000
As I understood once the HTTP authentification succeded, the username/password is
stored in the browser cache and gets transmitted to each following request.

Now my question is if I can invalidate that login programmatically (LOGOFF), so


that the user can leave his browser window open alone or reconnect to a different
user?

Re: Can you invalidate HTTP authentication credent...


Author: Tim Kientzle (http://www.jguru.com/guru/viewbio.jsp?EID=225219), Oct 9,
2000
Re: Can you invalidate HTTP authentication credentials?

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.

well, people, i've seen with my own eyes how a web...


Author: jv Moreno (http://www.jguru.com/guru/viewbio.jsp?EID=346055), Mar 8,
2001
well, people, i've seen with my own eyes how a web app takes the username directly
from the cliente, without any username/password prompt. How the hell have they
done it?

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.]

However, you can use HttpSessionBindingListeners to track live sessions, e.g.:

class SqlNotifier implements HttpSessionBindingListener {

protected Connection con;

public SqlNotifier(Connection con){


this.con = con;
}

public void valueBound(HttpSessionBindingEvent e) {


HttpSession session = e.getSession();
// log creation to a database
....
}
}

public void valueUnbound(HttpSessionBindingEvent e) {


HttpSession session = e.getSession();
// log destruction...
...
}
}
and:
session.putValue("logon.sqlnotifier",new SqlNotifier(sql));
upon creation of a new session.

[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;

final HttpSession session = context.getSession( sessionId );


userId = (String)session.getValue("UserID");
creation = session.getCreationTime();
lastAccess = session.getLastAccessedTime();
Calendar currentTime =
Calendar.getInstance(TimeZone.getTimeZone("EST"));
currentTime.setTime( new Date(creation));
Date estCreatTime =currentTime.getTime();
currentTime.setTime( new Date(lastAccess));
Date estLastAccess = currentTime.getTime();
data.append( "\n\t<tr><td>" )
.append( ++counter )
.append( "</td><td>" )
.append( userId )
.append( "</td><td>" )
.append( creation==0 ? "Not Available" :
estCreatTime.toString() )
.append( "</td><td>" )
.append( lastAccess==0 ? "Not Available"
:estLastAccess.toString())
.append( "</td></tr>" );
}
data.append("Hi");
return data.toString();
}
%>
<body>
<div class="PageTitle">Active Sessions:</div>
<hr color="#000000" noshade>
<table class="DataTable" width="100%" cellspacing=0
cellpadding=0 border=1>
<tr>
<th>#</th>
<th>User</th>
<th>Creation Time</th>
<th>Last Access</th>
</tr>
<% out.println( getActiveSessionData( request )
);%>
</table>
<form><input type="submit" value="Refresh"
onClick="location.reload();"></form>
</body>
Comments and alternative answers

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?

2. The tip says to call

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]

Comments and alternative answers

How can I make a servlet reload every time I test it...


Author: Sirajuddin Shaik (http://www.jguru.com/guru/viewbio.jsp?EID=96701), Jul
18, 2000
How can I make a servlet reload every time I test it in NES (iPlanet) environment?
(Please reply to sshaik@uswest.com.)

tomcat recompiling servlets


Author: brendan spinks (http://www.jguru.com/guru/viewbio.jsp?EID=434164), Jun
5, 2001
i would have thought there would be a way to make tomcat recompile by altering the
relevant context in the server.xml file...why not!?!?!

Re: tomcat recompiling servlets


Author: Nguyen Van Tuyen
(http://www.jguru.com/guru/viewbio.jsp?EID=726795), Jan 24, 2002
Turn on Servlet Reloading

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.

To turn on servlet reloading, edit install_dir/conf/server.xml and add a


DefaultContext subelement to the main Service element and supply true for the
reloadable attribute. The easiest way to do this is to find the following comment:

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.

Re[2]: tomcat recompiling servlets


Author: Cherrie Yuen (http://www.jguru.com/guru/viewbio.jsp?EID=829615),
Apr 8, 2002
I added the "DefaultContext" subelement. However, servlets still don't
automatically reload. Everytime I need to shutdown->startup the server.

is ur problem solved ? if yes please reply


Author: Abhisek Sinha
(http://www.jguru.com/guru/viewbio.jsp?EID=926898), Jul 19, 2002
hi cherrie ! i have the same problem as urs of restarting servlet again and
again. if ur problem was solved please do reply me. i have changed the
"DefaultContext"subelement,but no help.
Abhisek

Re: is ur problem solved ? if yes please reply


Author: David Emmett
(http://www.jguru.com/guru/viewbio.jsp?EID=983878), Aug 16, 2002
Hi,
I had the same problem. I ended up doing the following, which seemed
to work:
1. Edit the .java source file
2. Edit a JSP page, which calls the servlet
This forces Tomcat to recompile the JSP page, and while it is
recompiling the JSP page, it checks to see if the servlet has been
altered, and recompiles it.

David

Re: is ur problem solved ? if yes please reply


Author: Moho Proho
(http://www.jguru.com/guru/viewbio.jsp?EID=1030259), Nov 25, 2002
<Context
ClassName="org.apache.catalina.core.StandardContext"
cachingAllowed="true"
charsetMapperClass="org.apache.catalina.util.
CharsetMapper" cookies="true" crossContext="false" debug="0"
docBase=
"/blabla"
mapperClass="org.apache.catalina.core.StandardContextMapper"
path="/blabla" privileged="false" reloadable="true"
swallowOutput="false"
useNaming="true"
wrapperClass="org.apache.catalina.core.StandardWrapper"
loaderClass="org.apache.catalina.loader.WebappClassLoader"
checkInterval="1">
...
</Context>
should help, at least reloadable should be set to true,
checkInterval just makes it faster (interval on how
often the server checks if the file is changed in seconds, default if not set is
15).
However it still can take a while (3-5)seconds, and i believe
cashingAllowed could be set to
false to make it faster, but I haven't checked it out yet.

Re[3]: tomcat recompiling servlets


Author: ravikant prasad
(http://www.jguru.com/guru/viewbio.jsp?EID=1208374), Nov 1, 2004
Do one thing, Login as tomcat manager, and reload the application,
everytime u recompile the servlet. This saves ur time in stopping and
restarting the server. If it helps, then please do tell me.

How can my application or applet programmatically use HTTPS to talk to a


servlet? Can I do it with just the Java 2 SDK?
Location: http://www.jguru.com/faq/view.jsp?EID=24672
Created: Mar 15, 2000 Modified: 2001-01-07 13:24:39.029
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question
originally posed by Benoit Xhenseval
(http://www.jguru.com/guru/viewbio.jsp?EID=3363

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.

Sun provides a reference implementation of JSSE, along with sample programs,


which you can download from http://java.sun.com/products/jsse/. It comes in both a
"domestic version" (US/Canada) and an "export version" (all other countries).

Comments and alternative answers

Update to previous answer


Author: Dave Miller (http://www.jguru.com/guru/viewbio.jsp?EID=1073116), Apr 3,
2003
As of 1.4, Https is included in J2SDK. Url url = new
URL("https//www.yourweb.com"); HttpsURLConnection connection =
(HttpsURLConnection) url.openConnection();

Re: Update to previous answer


Author: arch level zhu (http://www.jguru.com/guru/viewbio.jsp?EID=1065574),
Apr 30, 2003
can you tell me a demo of it!3q and my mail is: arch_level@mailease.net

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

There is no standard method/mechanism to unload a servlet from memory. Some


servers, like JWS, provide the means to load and unload servlets from their
administration module. Others, like Tomcat, require you to just replace the WAR file.
Comments and alternative answers

If the servlet is not invoked, it still exists in web...


Author: mark zacksky (http://www.jguru.com/guru/viewbio.jsp?EID=27501), Mar 23,
2000
If the servlet is not invoked, it still exists in web server's memory? On my
understanding, servlet is only instantiated when it's invoked. I don't understand
load/unload a servlet, do you mean register/unregister a servlet?

Tomcat 3.1 has experimental support for servlet class...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), May 17,
2000
Tomcat 3.1 has experimental support for servlet class reloading. If you drop in a new
class file, the server will unload the existing servlet instance and load in the new class
and instantiate it.

Mark: "loading" means loading the servlet...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), May 17,
2000
Mark: "loading" means loading the servlet class, creating a new instance of the
servlet, and calling its init() method. During development, you may want to change
the servlet class and reload it without restarting the web server.

How to unload the servlet ??


Author: Utpal Gandhi (http://www.jguru.com/guru/viewbio.jsp?EID=412696), Apr
30, 2001
Try using BEA's WebLogic. You can "Hot Deploy" the servlets means you can
undeploy or redeployed the servlets.

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:

//set RMI Security Manager<br> System.setSecurityManager(new


WebSpaceSecurityManager());

Comments and alternative answers

Beware -- some vendors have broken implementations...


Author: Jeff Williams (http://www.jguru.com/guru/viewbio.jsp?EID=231946), Oct 19, 2000
Beware -- some vendors have broken implementations of the security manager that will prevent this
type of access control from working. If you are running third-party code, you should be aware that it
might be able to seriously compromise your server.

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

Here's some code I use in the doGet of a TestServlet to test security...

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 );

System.out.println( " CodeSource: " +


this.getClass().getProtectionDomain().getCodeSource().getLocation() + p );
System.out.println( " -- allowed -- " + p );
}
catch( Exception e ) { System.out.println( " -- rejected -- " +
e.getMessage() + p ); }
/*
try
{
out.println( h2o + "Trying some dangerous J2EE calls..." + h2c );
String hack = request.getParameter( "hack" );
Cookie[] cookies = request.getCookies();
out.println( " -- allowed -- " + p );
int x = 1 + 2 + 3;
System.out.println( hack ); // use it
int y = 1 + 2 + 3;
System.out.println( cookies ); // use it
String m = "COOKIE: " + cookies[0]; // use it again
cookies = new Cookie[10]; // reset it
String n = "COOKIE: " + cookies[5]; // use it again
}
catch( Exception e ) { out.println( " -- rejected -- " + e.getMessage() +
p ); }
*/

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?

crypt for Java


Author: Dieter Wimberger (http://www.jguru.com/guru/viewbio.jsp?EID=25708), Jan
16, 2004
See:
http://www.mtclimber.net/other/code/JCrypt.java
http://locutus.kingwoodcable.com/jfd/crypt.html

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.

Things you have to take care about:

• 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:
&lt;img src="http://www.mydomain.com/PictureServlet?id=35"&gt;
(Sure you can use more params if you need to do so.)
• Use some simple or sophisticated caching algorithm to limit your systems
load.

Be sure to check the Servlet FAQ for questions on Servlets.


Comments and alternative answers
About your last point of "Use some simple or ...
Author: Billy Collins (http://www.jguru.com/guru/viewbio.jsp?EID=301635), Jan 13,
2001
About your last point of "Use some simple or sophisticated caching algorithm to limit
your system's load." Do you have any suggestions/advice/sample_code?

Thanks!

It is a Good Idea to wrap your stored media with the...


Author: Brian Ewins (http://www.jguru.com/guru/viewbio.jsp?EID=301660), Jan 13,
2001
It is a Good Idea to wrap your stored media with the javax.activation.DataSource API
- this will allow you to use the media as described above in servlets and in JAF-aware
UI frameworks (eg to browse your DB). You should store the MIME type along with
the image in the DB, otherwise you will have to figure it out. The JAF currently
recognizes MIME types by file extension, but you can easily hardcode what is in
apache's mime.magic to recognize the leading bytes of files, and with a bit more effort
actually use that file. (use a PushbackInputStream to pull out the first few bytes)

The simplest cache is a hashtable. Use WeakHashMap...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jan 15, 2001
The simplest cache is a hashtable. Use WeakHashMap to avoid filling up memory.
More sophisticated in-memory caches are all over the place; for instance, see my
http://www.purpletech.com/ for com.purpletech.util.Cache.

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 manojp@dsmsoft.com

Calling DLL from jsp is not possible??


Author: sonica singh (http://www.jguru.com/guru/viewbio.jsp?EID=1209769), Nov 8,
2004
I m trying to call a dll from jsp program. For that i have written a bean that is calling a
java program that should call the DLL. But this is giving error as
java.lang.UnsatisfiedLinkError But the same code is working in java.

Re: Calling DLL from jsp is not possible??


Author: siddhartha vutharkar
(http://www.jguru.com/guru/viewbio.jsp?EID=1233974), Mar 21, 2005
there are three ways to call a dll one is keep the dll in winnt/system32 dir use
System.loadLibrary("yourdll")

second give absolute path and use System.load("c:\yourdir\yourdll.dll")

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

if any one knows any other methods, I would be glad to know

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

See http://www.cookiecentral.com/faq/ and these FAQ answers.

Where can I find an online servlet tutorial?


Location: http://www.jguru.com/faq/view.jsp?EID=28246
Created: Mar 24, 2000 Modified: 2000-04-03 13:43:02.177
Author: Tom Copeland (http://www.jguru.com/guru/viewbio.jsp?EID=1396)

There's a pretty good one here.


Comments and alternative answers

Don't forget about the Sun tutorial at http://java...


Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Jul 26,
2000
Don't forget about the Sun tutorial at http://java.sun.com/docs/books/tutorial/servlets/
and Dick Baldwin has some good Servlet (and other) stuff at
http://home.att.net/~baldwin.r.g/scoop/tocadv.htm.

Not to mention Stefan Zeiger's Servlet Essentials ...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Sep 18, 2000
Not to mention Stefan Zeiger's Servlet Essentials course.

What distinguishes a JavaBean from a Servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=29087
Created: Mar 27, 2000 Modified: 2000-04-21 08:29:19.253
Author: Andreas Schaefer (http://www.jguru.com/guru/viewbio.jsp?EID=25162)
Question originally posed by David Markert
(http://www.jguru.com/guru/viewbio.jsp?EID=27407

JavaBeans are a set of rules to follow to create reusable software components, or


beans. This contains properties and events. At the end you have a component which
could be examined by a program (like an IDE) to allow the user of your JavaBean
component to configure it and to run in its Java programs.

Servlets are Java classes running in a Servlet engine implementing a particular


interface: Servlet, forcing you to implement some methods (service()). The servlet is
an extension of your web server where this servlet is running on and only lets you
know when a user requests a GET or POST calls from a web page to your servlet.

So, both have nothing in common except Java.

Is there a standard place to write temporary files needed for servlets?


Location: http://www.jguru.com/faq/view.jsp?EID=29790
Created: Mar 29, 2000 Modified: 2000-06-21 15:15:46.807
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

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

Temp Files as HTTP


Author: Sudhanshu Kapoor (http://www.jguru.com/guru/viewbio.jsp?EID=1088462),
May 27, 2003
Can a file stord in this temp location be accessed as HTTP URL ?

Where does the output of System.out and System.err go in a servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=31687
Created: Apr 3, 2000 Modified: 2001-07-19 15:44:44.852
Author: Maxim Senin (http://www.jguru.com/guru/viewbio.jsp?EID=21992)
Question originally posed by NISHANT JAIN
(http://www.jguru.com/guru/viewbio.jsp?EID=29836

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.

Some servlet engines have a special property to disable/enable output to standard


streams for servlets.

Read your servlet engine documentation to find out where it stores its log files.

Comments and alternative answers

Typically, a servlet container redirects standard out...


Author: Scott Stirling (http://www.jguru.com/guru/viewbio.jsp?EID=1785), Apr 6,
2000

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

It depends on the Servlet Engines. For instance, with...


Author: Peter Wang (http://www.jguru.com/guru/viewbio.jsp?EID=22876), Jun 11,
2000
It depends on the Servlet Engines. For instance, with Websphere, System.err and
System.out both write output to files like this jvm_stderr and jvm_stdout.

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.

As an example, here is an application that looks up a word in the Merriam-Webster


online dictionary:

import java.net.*;
import java.io.*;

public class Post {

public static void main(String[] args) {


try {
URL url = new URL("http://www.m-w.com/cgi-bin/dictionary");
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter ostream = new
OutputStreamWriter(connection.getOutputStream());
BufferedWriter out = new BufferedWriter(ostream);
out.write("book=Dictionary&va=doggerel\r\n");
out.flush();
out.close();

InputStream stream = connection.getInputStream();


BufferedInputStream in = new BufferedInputStream(stream);
int i = 0;
while ((i = in.read()) != -1) {
System.out.write(i);
}
in.close();
}
catch (MalformedURLException e) {
}
catch (IOException ee) {
}
}
}
Note that the data is sent using the write() method of the URLConnection's output
stream. This data must be URL-encoded (use the URLEncoder class to do this). In the
example above, the data is unchanged after URL-encoding.

The same technique may be used by an applet. However, browser security


restrictions usually prevent an applet from connecting to a host other than the one
from which the applet class was downloaded.

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.

How can I download files from a URL using FTP?


Location: http://www.jguru.com/faq/view.jsp?EID=32634
Created: Apr 5, 2000 Modified: 2001-07-23 10:55:19.883
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question
originally posed by Sreelatha kattamuri
(http://www.jguru.com/guru/viewbio.jsp?EID=32547

Follow the instructions in the FAQ at


http://www.jguru.com/jguru/faq/view.jsp?EID=13198, substituting "ftp" for "http" in
the URL.
Comments and alternative answers

How can I get a list of files using ftp?


Author: Luke Latimer (http://www.jguru.com/guru/viewbio.jsp?EID=449934), Aug
13, 2001

The above worked a treat, but I need to get a list of files at a remote directory, and
only download the newest one.

Is this possible using this method?

Re: How can I get a list of files using ftp?


Author: maria rosa ariosto
(http://www.jguru.com/guru/viewbio.jsp?EID=712982), Jan 8, 2002
The pourpouse of this script resolving your problem :).
ft=new FtpClient("125.10.2.3",21);
TelnetInputStream is = null;
byte []b = null;
synchronized (this){
is=ft.list();
new Thread().sleep(2000);
}
b= new byte [is.available()];
is.read(b);
Re[2]: How can I get a list of files using ftp?
Author: andrew cheng (http://www.jguru.com/guru/viewbio.jsp?EID=981880),
Aug 12, 2002
I try the script,but it not works. Could you tell me where the problem is?? Or
more detail of the script

User and password seems not to work in ftp URL...


Author: Alain Coetmeur (http://www.jguru.com/guru/viewbio.jsp?EID=867480), Jul
7, 2003
I can't connect on ftp: url having user and password set ftp://user:password@host is
this normal, known, and is ther any turnaround...

How much data we can store in a session object?


Location: http://www.jguru.com/faq/view.jsp?EID=32704
Created: Apr 5, 2000 Modified: 2000-06-21 15:18:04.318
Author: Maxim Senin (http://www.jguru.com/guru/viewbio.jsp?EID=21992)
Question originally posed by Nagaraj shyagale
(http://www.jguru.com/guru/viewbio.jsp?EID=29160

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.

Comments and alternative answers

Use common sense -- try to figure out the average size...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Apr 6, 2000
Use common sense -- try to figure out the average size of the data you're storing,
multiplied by the expected maximum number of active concurrent user sessions
(bearing in mind that sessions take some time to expire), and make sure it's within the
limit of your server's RAM.

Generally, large amounts of data should be stored persistently on disk or in a


database, and loaded in only as needed. You can use a cache such as the one at Purple
Tech to make more efficient use of memory.

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

Also see extensive info on WAR in Fields & Kolb...


Author: Buck Melton (http://www.jguru.com/guru/viewbio.jsp?EID=125151), Sep 20,
2000
Also see extensive info on WAR in Fields & Kolb "Web Development with
JavaServer Pages" (Manning)

WAR file info


Author: Soumen Deb (http://www.jguru.com/guru/viewbio.jsp?EID=1222243), Jan
26, 2005
WAR files are simply zip files, these files when deployed on the server get exploded
or unzipped on the server with its information in the web.xml file

WAR file can be created using WINZIP of windows or jar -cvf option of the jar
utility.

simply zip it with Winzip and rename it to .war extension

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

rename it to jsp-examples1.war and drop in webapps folder of jakarta-tomcat

start jakarta

automatically the server sets the contxt path as /jsp-examples1

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:

• How can my applet communicate with my servlet?


• How can I pass an object from an applet to a servlet ?
• 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?

Comments and alternative answers

Can you please explain how to rewrite the session info...


Author: San Sandhu (http://www.jguru.com/guru/viewbio.jsp?EID=34758), Apr 11,
2000
Can you please explain how to rewrite the session info from an servlet to Applet and
then applet calling the servlet again (second time) with the session info. Thanks

You don't have to do anything special on the servlet...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Apr 11, 2000
You don't have to do anything special on the servlet side. The servlet engine takes
care of setting the session cookie. All you have to do is make sure the applet reads it,
and sends it back.

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.

Umm, excuse me if I'm being stupid, but I just did...


Author: John Econopouly (http://www.jguru.com/guru/viewbio.jsp?EID=295282),
Jan 29, 2001
Umm, excuse me if I'm being stupid, but I just did some tests, and it appears that
using URLConnection() the applet is automatically returning the sessionId that the
servlet sets (also automatically). That is, in both IE5 and NN4, without explicitly
adding anything to the header the applet was sending back, the servlet was able to
recognize the sessionId as the same across repeated calls from the same applet. So my
guess is that if you run your applet from within one of these browsers, they
automagically add in the cookies to all your URLConnections. Any naysayers?

Re: Umm, excuse me if I'm being stupid, but I just did...


Author: Tom Hubalek (http://www.jguru.com/guru/viewbio.jsp?EID=1125528),
Nov 3, 2003

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?

If it is not a standard then it could stop work in future versions of Java

Thanks a lot Tom

HTTPClient preserves cookies. See this comparison chart...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Feb 25, 2001
HTTPClient preserves cookies. See this comparison chart between URLConnection
and HTTPClient.

How do I use the DLLs from Tomcat to Servlet-enable Microsoft IIS?


Location: http://www.jguru.com/faq/view.jsp?EID=34691
Created: Apr 11, 2000 Modified: 2000-11-04 14:54:52.105
Author: Sylvain GIBIER (http://www.jguru.com/guru/viewbio.jsp?EID=11408)
Question originally posed by Arnar Freyr Guðmundsson
(http://www.jguru.com/guru/viewbio.jsp?EID=26079

Look at the Tomcat IIS How to file located at the address :


http://jakarta.apache.org/tomcat/jakarta-tomcat/src/doc/tomcat-iis-howto.html (or
http://jakarta.apache.org/cvsweb/index.cgi/jakarta-tomcat/etc/tomcat-iis-
howto.html if the website version is out of date).
Comments and alternative answers

What about IIS 5 on Win2000? Has anyone tried this...


Author: Evan Raskob (http://www.jguru.com/guru/viewbio.jsp?EID=236331), Oct 25,
2000
What about IIS 5 on Win2000? Has anyone tried this on a production server, or is this
all conjecture?
I have just configured IIS 5 on Win 2000 to work with...
Author: Raistlin Majere (http://www.jguru.com/guru/viewbio.jsp?EID=253181), Nov
21, 2000
I have just configured IIS 5 on Win 2000 to work with Tomcat 3.2 beta 8 as an out-
process. However, I am unable to get it to work in-process ... After configuring it
according to the In-Process HOWTO (http://jakarta.apache.org/tomcat/jakarta-
tomcat/src/doc/in-process-howto.html), I get a null pointer exception and msgs saying
"Failed to loadLibrary() .../jni_connect.dll" and then following that a msg saying
"Library .../jni_connect.dll loaded" It is after these 2 messages that the null pointer
exception occurred. Can anyone help ?

Re: I have just configured IIS 5 on Win 2000 to work with...


Author: shan fu (http://www.jguru.com/guru/viewbio.jsp?EID=405378), Apr 18,
2001
yeah, I have the same problem...actually even on NT4.0Sp6, this error occurs.
Hope someone can give us a light...

I wrote a small Windows program to configure IIS and...


Author: Poh Heng Lee (http://www.jguru.com/guru/viewbio.jsp?EID=261583), Nov
23, 2000
I wrote a small Windows program to configure IIS and Tomcat. Feel free to download
and use it at: http://www.namesdb.com/leeph/Kitten.zip

Delphi source code included.

Re: I wrote a small Windows program to configure IIS and...


Author: midge bongco (http://www.jguru.com/guru/viewbio.jsp?EID=382917),
Mar 20, 2001
Hi Poh, I could sure use this program you've written. However, the link you
provided is not valid anymore? could you forward the link to
mbongco@hotmail.com? Thanks!

broken links on jakarta.apache.org


Author: Donnacha O'Meara (http://www.jguru.com/guru/viewbio.jsp?EID=475568),
Aug 13, 2001
The links provided in your message unfortunately do not exist. I've emailed the
webmaster at jakarta.apache.org but have had no reply. Does anyone know where
these links have been moved to?

Re: broken links on jakarta.apache.org


Author: Andy Woods (http://www.jguru.com/guru/viewbio.jsp?EID=482464), Aug
23, 2001
Look in the \doc folder of the Tomcat download

Can an ASP page call Servlets or JSP, and vice versa?


Location: http://www.jguru.com/faq/view.jsp?EID=34704
Created: Apr 11, 2000 Modified: 2000-08-24 19:06:21.95
Author: Rajesh Danda (http://www.jguru.com/guru/viewbio.jsp?EID=34699)
Question originally posed by Dewayne Richardson
(http://www.jguru.com/guru/viewbio.jsp?EID=10342

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.

Comments and alternative answers

Can this servlet access session objects made by the...


Author: partha bhattacharjee (http://www.jguru.com/guru/viewbio.jsp?EID=140515),
Sep 22, 2000
Can this servlet access session objects made by the asp?

[No, but see http://www.jguru.com/jguru/faq/view.jsp?EID=109106 -Alex]

Could you describe the architecture behind jGuru.com: JSP, Servlets,


database, servers, transactions etc...?
Location: http://www.jguru.com/faq/view.jsp?EID=34896
Created: Apr 11, 2000 Modified: 2002-11-20 12:23:54.439
Author: Terence Parr (http://www.jguru.com/guru/viewbio.jsp?EID=1) Question
originally posed by Benoit Xhenseval
(http://www.jguru.com/guru/viewbio.jsp?EID=3363

[Updated Nov 20, 2002 to remove old description and point at some articles. TJP]

jGuru.com Case-Study.

Little Nybbles of Development Wisdom.

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.

I felt that there should be a way to do it from JavaScript; unfortunately, JavaScript


doesn't seem to have an onWindowClose handler. JavaScript expert Daniel Zen of
Zen Digital writes:

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...)

<BODY onUnload="javascript code">

which won't work if javascript is disabled.

Also, the onUnload handler only works in IE.

If anyone figures out a way to make this work, please let us know.

P.S. Thanks to the many people who submitted answers!

Comments and alternative answers

I was just surfing randomly when I got stuck in Porn...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), May 17,
2000
I was just surfing randomly when I got stuck in Porn Site Hell. You know: a region of
the web where opening or closing any window opens up 5 new windows, all with a
dozen ads for porn or warez sites, ad infinitum. The more windows you close, the
more windows get opened, until you have to reboot.

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()'>

Close me to invalidate the session

</body>

close.jsp:

<% request.getSession(true).invalidate(); %>


<script language="JavaScript">
<!-- start hiding
function Load() {
self.close();
}

// end hiding -->

</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.

Re: I was just surfing randomly when I got stuck in Porn...


Author: Shiva dacherla (http://www.jguru.com/guru/viewbio.jsp?EID=477339),
Nov 14, 2001

Hi,

I think this onUnload() works only in IE not in Netscape. Let me know if my


assumption is wrong. I tried it's not working.

Thanks

Shiva

Re[2]: I was just surfing randomly when I got stuck in Porn...


Author: Jose Thachil (http://www.jguru.com/guru/viewbio.jsp?EID=1156050),
Mar 20, 2004
onUnload() sometimes work in Netscape.I think you have to change your
settings in Netscape.

unload.html code should read: close.jsp not close.html


Author: Daniel Zen (http://www.jguru.com/guru/viewbio.jsp?EID=34944), Oct
16, 2003
Alex, I am sure a few people are copying your code directly, and don't notice the
mistake. However, in general this is definitely the correct course of action for the
overall question.

sessions expire automatically when browser is closed


Author: Frans Verhoef (http://www.jguru.com/guru/viewbio.jsp?EID=428343), May
25, 2001
My understanding is that sessions are automatically expiring after the user has closed
the browser. This is because sessions are using non-persistant cookies. In other words,
the cookies are stored in memory, and therefore disappear after your browser closes.

Re: sessions expire automatically when browser is closed


Author: Brandon Greene (http://www.jguru.com/guru/viewbio.jsp?EID=432416),
Jun 1, 2001
True, the cookie no longer exists on the client. But the session still exists on the
server until it "times out". The server has no way of knowing that you've closed
your browser and keeps the session available. Just in case you fell asleep for
awhile or something.

Re: Re: sessions expire automatically when browser is closed


Author: Nicolas Rinaudo
(http://www.jguru.com/guru/viewbio.jsp?EID=449986), Jul 5, 2001
I've found a workaround for this in my current project. I don't know if it's
possible to port it to other projects, but it may be usefull, so...
For statistical purposes, I keep a session table in a database. This table contains
a primary key, some statistical info(time of connection, last accessed date, ...),
and a session state(open, closed, timeout). I keep a persistent cookie on the
client containing the database id of his current session. When the client logs
off properly, this cookie is invalidated. That way, whenever a client crashes
and tries to log back in, he will first send the content of that cookie. The JSP
page can then check the session's state in the table. If it's anything else than
open, the user will have to give his login and password. Otherwise, we now
know that (a) the client lost the session without logging off and (b) he didn't
time out yet. What I do is log the user back in without asking for a login and
password. There's an obvious security flaw here, since anyone could read the
client's cookie content and send a query with the same session database id,
thus logging in as a user without having to specify a login and password. In
our application this is really not important, but if you need tighter security you
can just display a message like 'You appeared to have been disconnected.
Please reenter login and password', and do the connection process all over
again. This way, even if the user crashes, he doesn't have to wait a whole
timeout delay to log back in.

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.

Re[3]: sessions expire automatically when browser is closed


Author: FeiFei Lim
(http://www.jguru.com/guru/viewbio.jsp?EID=813747), Mar 26, 2002
Hi.. can I know do u use a session variable in servlet to keep track of the
following? thanks.. ---> I keep a persistent cookie on the client containing
the database id of his current session. When the client logs off properly,
this cookie is invalidated.

how to open a new page from a function which is called on onUnload


event.
Author: praveen homkar
(http://www.jguru.com/guru/viewbio.jsp?EID=1203629), Oct 6, 2004
how to open a new page from a function within the java script which is called
on onUnload event.?

any other technique other than these..??


Author: Hari prasad (http://www.jguru.com/guru/viewbio.jsp?EID=478617), Aug 20,
2001
Hi, My problem here is that, iam using "Tapestry frame work" for front end, not
servelet or jsps. even i know two way of implementing this problem as 1. use of
onUnload()method which is very difficult to implement 2. Killing the session object
within stipulated time , this is not good choice inour application. If u any technique
other than above two, let me know, to fit these into my application

Re: any other technique other than these..??


Author: Shiva dacherla (http://www.jguru.com/guru/viewbio.jsp?EID=477339),
Nov 5, 2001
Hi,

I don't know what "Tapestry frame work" means. I am using Applet-Servlet


communication for my application. I have a problem to invalidate the session
whenever the user closes the browser without clicking the Logout button. The
technique I have used here is , whenever you close the browser ,Applets Destroy
method will be called automatically and from there I am sending small request to
Servelet to invalidate the user's session. I don't know whether this helps you or
not.

This may be usefull for peolpe who is working on Applet-Servlet communication


projects.

Thanks Shiva

Re: Re: any other technique other than these..??


Author: Shiva dacherla
(http://www.jguru.com/guru/viewbio.jsp?EID=477339), Nov 13, 2001

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.

Does any one has any ideas.

Thanks

Shiva Dacherla

Re[2]: any other technique other than these..??


Author: Slim Driss (http://www.jguru.com/guru/viewbio.jsp?EID=133997),
Mar 5, 2004
Hi, I'm working on Applet-Servlet communication project using Http
Tunneling. I'm stucked about how to have a session tracking between Applet
and Servlet. The session is lost between two invocation :-( Could you help me
please! Thanks, Slamer

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

OnUnload does not work i IE


Author: praveen homkar (http://www.jguru.com/guru/viewbio.jsp?EID=1203629),
Oct 5, 2004
I tried onUnload event in IE but its not working.Please tell me if i need to change
IE settings,Give an example code
onUnload works
Author: Rafael Reyes (http://www.jguru.com/guru/viewbio.jsp?EID=930682), Jun 27,
2002
I'm not sure I understand the comment above but in my tests onUnload in IE is
executed when the browser closes. In turn onUnload can execute a transaction on a
servlet to deallocate/invalidate the session. Am I missing something? -Rafael

Re: onUnload works


Author: Roger Smith (http://www.jguru.com/guru/viewbio.jsp?EID=1067929),
Mar 19, 2003
I am not sure about the information regarding the availability of onUnload for NN
but o'reilly indicates that window.onUnload is available for NN2+, IE/Win4+ and
IE/Mac4+

Re[2]: onUnload works


Author: suraj berwal (http://www.jguru.com/guru/viewbio.jsp?EID=993073),
Jul 10, 2003
onUnload works for the following cases also:
1.using back,forward or refresh button from the IE/NN toolbar.
2.using refresg using context menu or F5 button.
3.when a different link is requested.

the point is how many checks can u put so that a logout


doesn't happen when user is just browsing the site and not
closing the browser window.

Re[3]: onUnload works


Author: Edgar D'Souza (http://www.jguru.com/guru/viewbio.jsp?EID=1160867), Apr 6, 2004
Hi,
I found this to be a problem too, onUnload fires when the user is still browsing.
Though I'm working in PHP, my solution is Javascript-and-popup-based; I'm posting it in the h

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();
}

2) Hook it up in your BODY tag:


<BODY onLoad="PopupWatchdog();">
3) Here's the contents of watchdog.php:
<?
session_cache_limiter("nocache");
?>
<HTML>
<HEAD>
<!-- Edgar D'Souza, 05 Apr 2004:
Watchdog page continuously polls its parent (opener) for existence;
when it finds that the window is closed, it sets its own location
to the logout page so the user session is released.
-->
<SCRIPT Language="JavaScript">
var timerID = null;

var timerRunning = false;

function startWatching()

// Make sure the clock is stopped

stopWatching();

timerID = setInterval("doLogout()",800);

timerRunning = true;

function stopWatching()

if(timerRunning) {clearInterval(timerID) };

timerRunning = false;

}
function doLogout()

stopWatching();

if (window.opener == null || window.opener.closed.toS

//alert('You killed my parent! Waaaahhhhhh!!!

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)

Re[4]: onUnload works


Author: Antony Raja
(http://www.jguru.com/guru/viewbio.jsp?EID=1172127), May 19, 2004
Actually when the window closed by the user the screen width and
height must changed.So we trace that screen.width and do the operation
of killing the session.Otherwise we can write the listener for tracking of
session.We write a class which implements HttpSessionListener.and kill
the session.
« previous beginning next »

Is there a way I can set my servlets to do thread pooling?


Location: http://www.jguru.com/faq/view.jsp?EID=34947
Created: Apr 11, 2000 Modified: 2000-06-21 15:33:45.323
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Sunil Kumar
(http://www.jguru.com/guru/viewbio.jsp?EID=7687

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.

How can I create a servlet that will initialize connections to different


systems, in a way that other servlets can use them?
Location: http://www.jguru.com/faq/view.jsp?EID=34948
Created: Apr 11, 2000 Modified: 2000-06-21 15:34:22.005
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Luis Gonzalez
(http://www.jguru.com/guru/viewbio.jsp?EID=8286

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.

Do any servlet engines support servlet chaining?


Location: http://www.jguru.com/faq/view.jsp?EID=34955
Created: Apr 11, 2000 Modified: 2000-06-21 15:36:46.879
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by George Thomas
(http://www.jguru.com/guru/viewbio.jsp?EID=16788
Servlet Chaining was a feature of several early servlet engines, but has been
removed from the spec. There has been some talk of officially adding it, but for now,
servlets must explicitly "chain" by using RequestDispatcher.

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.

Comments and alternative answers

agreed, but is using the requestdispatcher really ...


Author: alok kumar (http://www.jguru.com/guru/viewbio.jsp?EID=266253), Nov 30,
2000
agreed, but is using the requestdispatcher really chaining, as against chaining in JWS
through admin applet(i.e. output of one servlet to another as input)?? isnt
requestdispatcher used for forwarding rather than chaining??

Re: agreed, but is using the requestdispatcher really ...


Author: Kris P (http://www.jguru.com/guru/viewbio.jsp?EID=1181970), Jun 28,
2004
I support this answer...I feel RequestDispatcher do forwarding the requests. I am
not sure if this interface do chaining. In Servlet Chaining, the first servlet in the
chain will work on the Request Object, produces some response to that request
and forward the Response Object and a makes a Request to the next Servlet. If
you use the forward( ) method RequestDispatcher the first servlet cannot produce
any response but can modify the Response object.

Re[2]: agreed, but is using the requestdispatcher really ...


Author: Kris P (http://www.jguru.com/guru/viewbio.jsp?EID=1181970), Jun
28, 2004
Plsease consider the last sentense in the above comment as "If you use the
forward( ) method RequestDispatcher the first servlet cannot produce any
response but can modify the Request object".

What is the difference between the doGet and doPost methods?


Location: http://www.jguru.com/faq/view.jsp?EID=34956
Created: Apr 11, 2000 Modified: 2000-08-10 10:05:17.315
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Atul Yamkanmardi
(http://www.jguru.com/guru/viewbio.jsp?EID=28202

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?

Comments and alternative answers

Basically the browser always asks for pages via GET,...


Author: Nicola Ken Barozzi (http://www.jguru.com/guru/viewbio.jsp?EID=39153),
Apr 23, 2000
Basically the browser always asks for pages via GET, and can send form data both as
GET or POST. The main difference is that GET has restrictions on the size of the
parameters sent; this means that it is usually better using POST for form requests.

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.

What is the difference between encodeRedirectUrl and encodeURL?


Location: http://www.jguru.com/faq/view.jsp?EID=34959
Created: Apr 11, 2000 Modified: 2000-04-11 17:58:57.424
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Khoivu N (http://www.jguru.com/guru/viewbio.jsp?EID=32600

encodeURL and encodeRedirectURL are methods of the HttpResponse object. Both


rewrite a raw URL to include session data if necessary. (If cookies are on, both are
no-ops.)

encodeURL is for normal links inside your HTML pages.

encodeRedirectURL is for a link you're passing to response.sendRedirect(). It has


slightly different syntax requirements too gory to get into here.

See this FAQ for more details.

Comments and alternative answers


Like so: <a href="<%=response.encodeU...
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jun 17, 2000
Like so:
<a href="<%=response.encodeURL("/jobs/typist.html")%>">Typist</a>

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 :-)

For encodeRedirectURL, try


response.sendRedirect(encodeRedirectURL("/foo/bar.html"));

Can I use System.exit() in servlets?


Location: http://www.jguru.com/faq/view.jsp?EID=35013
Created: Apr 11, 2000 Modified: 2000-04-11 18:11:29.726
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by shivkumar nayak
(http://www.jguru.com/guru/viewbio.jsp?EID=32829

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? :-)

I am opening a single JDBC connection in my init() method. Do I need to


synchronize on the Connection or the Statement object?
Location: http://www.jguru.com/faq/view.jsp?EID=35020
Created: Apr 11, 2000 Modified: 2000-06-21 15:37:52.594
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by ashish arya
(http://www.jguru.com/guru/viewbio.jsp?EID=29906

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

From within a servlet, you can invoke the ServletContext.getServerInfo() method as


follows:
String thisServer=
getServletConfig().getServletContext().getServerInfo();

If you are using JSP, you can use this expression:

<%= application.getServerInfo() %>


Comments and alternative answers

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.

This fragment tells me the Servlet Engine version:

Servlet Engine:
<%= session.getServletContext().getMajorVersion()
%>.<%= session.getServletContext().getMinorVersion() %>

Does anybody know how to find the JSP version?

Answer: Tested on Tomcat 5.0


Author: Kevin St. Clair (http://www.jguru.com/guru/viewbio.jsp?EID=1192485), Aug 11,
2004
The JSP code below displays the Servlet specification, the JSP specification, and application
server info:
<div class="spacer">
Servlet Engine:
<%= session.getServletContext().getMajorVersion() %>.<%=
session.getServletContext().getMinorVersion() %>
</div>
<div class="spacer">
JSP Engine:
<%=
JspFactory.getDefaultFactory().getEngineInfo().getSpecificationVersion()%>
</div>
<div class="spacer">
Application Server:
<%= application.getServerInfo()%>
</div>

How can I get the absolute URL of a servlet/JSP page at runtime ?


Location: http://www.jguru.com/faq/view.jsp?EID=35175
Created: Apr 12, 2000 Modified: 2000-06-16 15:23:39.132
Author: Frank Steidinger (http://www.jguru.com/guru/viewbio.jsp?EID=34216)
Question originally posed by Jérôme CAHUZAC
(http://www.jguru.com/guru/viewbio.jsp?EID=17646

You can get all the necessary information to determine the URL from the request
object. To reconstruct the absolute URL from the scheme, server name, port, URI
and query string you can use the URL class from java.net. The following code
fragment will determine your page's absolute URL:

String file = request.getRequestURI();


if (request.getQueryString() != null) {
file += '?' + request.getQueryString();
}
URL reconstructedURL = new URL(request.getScheme(),
request.getServerName(),
request.getServerPort(),
file);
out.println(URL.toString());

Comments and alternative answers

You can also use the following utility class: jav...


Author: Craig Deelsnyder (http://www.jguru.com/guru/viewbio.jsp?EID=41424), Apr
27, 2000
You can also use the following utility class:

javax.servlet.http.HttpUtils

which has a getRequestURL(HttpServletRequest req) method (returns a


StringBuffer). It does about the same thing as noted in the original answer.

Thanks! We were having some problems in our appli...


Author: Al Scherer (http://www.jguru.com/guru/viewbio.jsp?EID=63091), Jun 7,
2000
Thanks! We were having some problems in our application with relative URLs getting
mixed up as we traversed between directories.

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.

Isnt the request object inside a jsp page an instance...


Author: sadfjh sdkfjhkdshf (http://www.jguru.com/guru/viewbio.jsp?EID=282540),
Jan 26, 2001
Isnt the request object inside a jsp page an instance of ServletRequest NOT
HttpServletRequest so it doesnt have getRequestURI? I presumed this was a feature
as jsp shouldnt know how it is being accessed.

Re: Isnt the request object inside a jsp page an instance...


Author: Julison Mendonca
(http://www.jguru.com/guru/viewbio.jsp?EID=429254), May 27, 2001
In the first anwser, where can I find the URL class?

Can't get the sample to work...


Author: Ken Young (http://www.jguru.com/guru/viewbio.jsp?EID=901514), Aug 29,
2002
this is my error: [29/Aug/2002:18:33:23] info ( 353): JSP: JSP1x compiler threw
exception org.apache.jasper.JasperException: Unable to compile class for
JSP/usr/local/iplanet/servers/https-
w3/config/../ClassCache/_jsps/_it/_helpdesk/_index2_jsp.java:238: Class
_jsps._it._helpdesk.TheURL not found. TheURL reconstructedURL = new
TheURL(request.getScheme(), ^

Can a Servlet access an SAP database?


Location: http://www.jguru.com/faq/view.jsp?EID=35870
Created: Apr 13, 2000 Modified: 2000-06-21 15:39:38.918
Author: Sandeep Prabhu (http://www.jguru.com/guru/viewbio.jsp?EID=32615)
Question originally posed by Sanjay Mistry
(http://www.jguru.com/guru/viewbio.jsp?EID=17764

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

I believe the "middleware" comment is mi...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Apr 24, 2000
I believe the "middleware" comment is misleading; the servlets *are* the middleware,
since they connect more-or-less directly to SAP via BAPI. Am I mistaken?

No Since your servlets will be talking to the Appl...


Author: Sandeep Prabhu (http://www.jguru.com/guru/viewbio.jsp?EID=32615), May
1, 2000
No Since your servlets will be talking to the Application server part of SAP (to get the
business object like sales order, customers etc.)rather than the Database server, You
will be needing middleware like Orbix from IONA tech or VisualEdge for Java from
IBM(AccessBuilder component) or HAHT products. Hope this helps Sandeep

Re: No Since your servlets will be talking to the Appl...


Author: Xavier Martin (http://www.jguru.com/guru/viewbio.jsp?EID=741065),
Jan 30, 2002
SAP provides a Java API called JCO (SAP Java Connector) to interface directly to
SAP via RFC. You can execute RFCs and BAPIs directly from your servlet/no
need for an ORB or anything like that

Re[2]: No Since your servlets will be talking to the Appl...


Author: Trex Lim (http://www.jguru.com/guru/viewbio.jsp?EID=525897),
Mar 18, 2003
Xavier Martin:

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?

How about JCA?

What is the return type of ServletRequest.getAttribute(


"javax.servlet.request.X509Certificate" ), the method of retrieving client
certificates in the Servlet 2.2 API?
Location: http://www.jguru.com/faq/view.jsp?EID=37556
Created: Apr 18, 2000 Modified: 2000-08-13 16:30:24.769
Author: Len Norton (http://www.jguru.com/guru/viewbio.jsp?EID=37422)

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.

How can I plot data on a graph or chart from a servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=37785
Created: Apr 19, 2000 Modified: 2001-08-19 20:55:22.641
Author: Aaron DeLong (http://www.jguru.com/guru/viewbio.jsp?EID=37781)
Question originally posed by aidas suhail
(http://www.jguru.com/guru/viewbio.jsp?EID=34212

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

There is some not-quite-ready-for-primetime code at...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Apr 19, 2000
There is some not-quite-ready-for-primetime code at Purple Technology for creating
charts and graphs, and saving them as GIFs.

Also, see the Purple Servlet Resource List, in the images section.

See also this FAQ on drawing images from servlets....


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Apr 20, 2000
See also this FAQ on drawing images from servlets.

A free solution is possible: expose graph data as XML,...


Author: Nicola Ken Barozzi (http://www.jguru.com/guru/viewbio.jsp?EID=39153),
Apr 25, 2000
A free solution is possible: expose graph data as XML, transform with XSL into SVG
or VML and send that to the client.

Possible practical solutions:

• 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: A free solution is possible: expose graph data as XML,...


Author: Raj Subramani (http://www.jguru.com/guru/viewbio.jsp?EID=515135),
Oct 9, 2001
SVG can now be viewed directly with IEv6.0. For other browsers you need to
install an SVG plug-in from adobe. Also Servlet's can direct svg data to a JSP
page, which can be configured to display this SVG data. This is neatly explaind by
SUN

Another option is to use the KLG Software Group JClass...


Author: Shuchi Agarwal (http://www.jguru.com/guru/viewbio.jsp?EID=30635), May
1, 2000
Another option is to use the KLG Software Group JClass and Acme Encoder to
encode it and sent it back as a GIF.

Re: Another option is to use the KLG Software Group JClass...


Author: sashidhar Muthyala
(http://www.jguru.com/guru/viewbio.jsp?EID=700981), Dec 24, 2001
Hi, I downloaded the JCServerChart evaluation kit from their web site & tried. I
have been getting OutOfMemoryError. Even the tomcat demos give the same
error. Have you faced this problem? I appreciate your help. Thanks, Sashi.

t-chart is another solution; it costs a few hundred...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jun 3, 2000
t-chart is another solution; it costs a few hundred bucks for source code

JFreeChart is an open-source class library for gen...


Author: David Gilbert (http://www.jguru.com/guru/viewbio.jsp?EID=19371), Jun 25,
2000
JFreeChart is an open-source class library for generating charts in Java. I'm messing
around with it at the moment so that it can be used with servlets...
http://www.jrefinery.com

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

A few others: MonarchCharts Protoview JFCSuite P...


Author: Roger Hand (http://www.jguru.com/guru/viewbio.jsp?EID=292314), Jan 3,
2001
A few others:

• MonarchCharts
• Protoview JFCSuite PowerChart
• ExpressChart

Re: A few others: MonarchCharts Protoview JFCSuite P...


Author: andrew watson (http://www.jguru.com/guru/viewbio.jsp?EID=489616),
Oct 11, 2001
I am using a software package from Altio. This client-server solution is sending
XML data to the client, which converts the XML into tables and charts. Check
out: www.altio.com and look at their demos...

Re: A few others: MonarchCharts Protoview JFCSuite P...


Author: Jaume Ba (http://www.jguru.com/guru/viewbio.jsp?EID=827369), Jul 9,
2002
RChart als works as servlet, it can even generate image maps to have interactive
charts: http://www.java4less.com/charts_e.htm
JClass ServerChart from Sitraka
Author: Roger Hand (http://www.jguru.com/guru/viewbio.jsp?EID=292314), Oct 11,
2001
I've been using JClass ServerChart from Sitraka (formerly KL Group). It's been
working very reliably for us, although our loads have been pretty light. As of early
2000 (when I did my research) it gave you far more control over different chart
parameters than the alternatives. Of course, with that control comes complication . . .

Re: JClass ServerChart from Sitraka


Author: sashidhar Muthyala
(http://www.jguru.com/guru/viewbio.jsp?EID=700981), Dec 24, 2001
Roger, Hi, I downloaded the JCServerChart evaluation kit from their web site &
tried. I have been getting OutOfMemoryError. Even the tomcat demos give the
same error. Have you faced this problem? I appreciate your help. Thanks, Sashi.

Professional SVG Charting from Elansoft


Author: Praveen Raju (http://www.jguru.com/guru/viewbio.jsp?EID=532537), Nov 6,
2001
If you want world-class charting with drill-downs, chart in a chart, intitutive
navigation, drag and drop etc. Elansoft's AgileBlox Chart 1.0 is what you need. Check
out http://www.elansoft.com/es2/elansoft/inside/demo.html All the features are
possible with writing very few lines of code.

Re: Professional SVG Charting from Elansoft


Author: Kate Novac (http://www.jguru.com/guru/viewbio.jsp?EID=1095517), Jun
19, 2003
Would Elansoft care to comment on the fraud-charges at:
http://www.manero.org/weblog/archives/000083.html ? Why any one pay 13 times
more for the SVG Chart product than Flash Chart product FusionCharts? Cost:
Agileblox cost US$1,350 verses just US$99 for FusionCharts. Agileblox needs
ASV3 (Adobe SVG Viewer 3.0). However, if you call Adobe for any help or bugs,
they tell you that it is not a supported product. Also, they refuse to comment about
any future plans for ASV or patches, which led many to speculate that ASV would
be discontinued. It is installed on about 7% of the computers. On the other hand
FusionCharts needs Macromedia's Flash-player, which is installed on well over
99% computers. Can you get an official statement from Adobe that ASV going to
be their one-year from now and Adobe would fix bugs or release patches to ensure
compatibility with future releases of IE-browsers?

How can I invoke a servlet from JavaScript?


Location: http://www.jguru.com/faq/view.jsp?EID=39154
Created: Apr 23, 2000 Modified: 2001-02-02 05:06:58.85
Author: Nicola Ken Barozzi (http://www.jguru.com/guru/viewbio.jsp?EID=39153)
Question originally posed by Armaity Rupa
(http://www.jguru.com/guru/viewbio.jsp?EID=32852
Yes, and it is quite easy. You just have to remember that a servlet is seen by the
browser like a normal web page with its URL. Just call it lke you would call a web
page. It is also possible to use servlet data in javascript without changing page. For
example I am using Microsoft XML data islands that get XML data from a servlet.
CODE:

<HTML>

<SCRIPT>
function display()
{
data.transformNodeToObject(ss.XMLDocument,
resultTree.XMLDocument);
document.write(resultTree.xml);
}
</SCRIPT>

<SCRIPT FOR="window" EVENT="onload">


data.async = false;
data.load("../servlet/SQLResult");
ss.async = false;
ss.load("MyStyleSheet.xsl");
display();
</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

Short answer: a JSP is a Servlet that thinks it's a Web page.

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
%>).

Comments and alternative answers

Though the both are identical, they have different...


Author: Rajesh Ankareddy (http://www.jguru.com/guru/viewbio.jsp?EID=66095), Jun
21, 2000
Though the both are identical, they have different roles in the Model View Controller
(MVC) architecture. View corresponds to JSP, Controller corresponds to Servlet and
Model to BusinessLogic + Database.

Servlet used as Views..


Author: Cheju Thomas (http://www.jguru.com/guru/viewbio.jsp?EID=389628),
Mar 28, 2001
Why can't servlets be used as views when they can handle content presentation ?
Why do they have to be a controller only ?

Re: Servlet used as Views..


Author: sachin kulkarni
(http://www.jguru.com/guru/viewbio.jsp?EID=1219090), Jan 2, 2005
Now a days we dont use servlets for View because of it's
complexities.However, JSP is very simple and after compilation unit, web
container implicitly converts to servlets and does the "controller" job in MVC
architecture.

What is server push? How do I use it from a servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=39953
Created: Apr 25, 2000 Modified: 2001-11-03 21:07:11.641
Author: Nicola Ken Barozzi (http://www.jguru.com/guru/viewbio.jsp?EID=39153)
Question originally posed by ahmed mohammad
(http://www.jguru.com/guru/viewbio.jsp?EID=34131

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.

Comments and alternative answers

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/

Can I include a static HTML file in a servlet response using the


RequestDispatcher?
Location: http://www.jguru.com/faq/view.jsp?EID=39955
Created: Apr 25, 2000 Modified: 2000-06-21 15:41:39.714
Author: Nicola Ken Barozzi (http://www.jguru.com/guru/viewbio.jsp?EID=39153)
Question originally posed by Jiger Patel
(http://www.jguru.com/guru/viewbio.jsp?EID=30998

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

How can I install Tomcat 3.1 without DSO? Can I just...


Author: Bryan Green (http://www.jguru.com/guru/viewbio.jsp?EID=124065), Aug
10, 2000
How can I install Tomcat 3.1 without DSO? Can I just build mod_jserv as part of
Apache and then install Tomcat?

When using sendRedirect, I always get a page returned stating: "Document


moved." Is it possible to go directly to the redirected page?
Location: http://www.jguru.com/faq/view.jsp?EID=41049
Created: Apr 27, 2000 Modified: 2000-04-30 11:20:25.606
Author: Nicola Ken Barozzi (http://www.jguru.com/guru/viewbio.jsp?EID=39153)
Question originally posed by Iain STIRZAKER
(http://www.jguru.com/guru/viewbio.jsp?EID=10849

There are two possibilities.

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.

CODE: PageName is a String containing the redirect URL


response.sendRedirect(PageName);

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.

CODE: PageName is a String containing the redirect URL

PrintWriter TempWriter = response.getWriter();

TempWriter.print("<HTML><HEAD>"+
"&lt;META HTTP-EQUIV=\"Refresh\"
CONTENT=\"5";URL=\""+PageName+"\"&gt;"+
"&lt;/HEAD&gt;<BODY>Redirecting to: &lt;A href="+PageName+"
\"&gt;"+PageName+"&lt;/A&gt;&lt;/BODY&gt;&lt;/HTML&gt;");

TempWriter.flush();
TempWriter.close();
Comments and alternative answers

Many browsers will apparently display a "document...


Author: Erik Hanson (http://www.jguru.com/guru/viewbio.jsp?EID=38768), May 19,
2000
Many browsers will apparently display a "document moved" message when you are
redirecting from one page to the same page. The browser thinks you are in a redirect
loop and just displays the message instead of redirecting.

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" );

You should place the response.sendRedirect() at the...


Author: david huang (http://www.jguru.com/guru/viewbio.jsp?EID=60385), May 31,
2000
You should place the response.sendRedirect() at the end of your code, that means you
can't place any more code after you call response.sendRedirect().

You also have to call sendRedirect before sending any...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), May 31,
2000
You also have to call sendRedirect before sending any output whatsoever. Don't even
tempt yourself by acquiring the output stream. So, structure your logic:
if (shouldRedirect) {
response.sendRedirect(...)
}
else {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print(...)
}

Re: You also have to call sendRedirect before sending any...


Author: Daniel Ahern (http://www.jguru.com/guru/viewbio.jsp?EID=850273),
Apr 22, 2002
response.sendRedirect works but sometimes certain browsers will throw a
document moved if the URL is not encoded properly. Internet explorer is more
forgiven than netscape. Certain characters will make netscape show the document
has moved message; so run parameters through the java.net.encodeURL.encode()
method and this'll let the redirect flow smothly.

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]

This is what a browser may see:

-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">

How do you check for the existence of a cookie?


Location: http://www.jguru.com/faq/view.jsp?EID=41198
Created: Apr 27, 2000 Modified: 2000-06-21 15:45:23.834
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

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;
}
}
}

How do I install Apache and Tomcat with SSL / HTTPS support?


Location: http://www.jguru.com/faq/view.jsp?EID=41239
Created: Apr 27, 2000 Modified: 2001-02-25 16:45:02.851
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

STeve Punte, from the Tomcat Users List, writes:


The web site http://www.ccl.net/cca/software/UNIX/apache/index.shtml was great
for me on getting SSL operational. Not for the faint of heart!

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/.

Comments and alternative answers

You can add SSL support to a standalone Tomcat (and...


Author: Volker Stolz (http://www.jguru.com/guru/viewbio.jsp?EID=24071), Jun 13,
2000
You can add SSL support to a standalone Tomcat (and almost any other server,e.g.
IMAP) with OpenSSL and stunnel. Usually './configure; make; make install' is
sufficient.

I'm having difficulties trouble shooting a problem...


Author: emmy Harrison (http://www.jguru.com/guru/viewbio.jsp?EID=348656), Mar 10, 2001
I'm having difficulties trouble shooting a problem we're experiencing with an Apache Tomact
configuration??? I'm the developer (not systems admin) trying to determine if the code or
configuration needs changing... Symptons:One app server has a certificate on it and is
configured to handle all traffic to https://securedomainname.com where secureServlet1,
secureServlet2, and secureJsp exist only on this one machine. (1 of 5 app servers handling
traffic) secureJSP calls https://securedomainname.com/servlet/secureSErvlet1 calls
https://securedomainname.com/servlet/secureSErvlet2 and forwards to secureJSP using
getServletConfig().getServletContext().getRequestDispatcher("/jsp/links.jsp").forward(request
, response); I thought both these methods, by specifying https URL, and the forward are
guaranteed to stay on the secure app server. But it appears as if sometimes ( getting page not
found, and leaving secure server errors ) this traffic is going to another app server. Any
clues???

Is there a chat servlet out there?


Location: http://www.jguru.com/faq/view.jsp?EID=41395
Created: Apr 27, 2000 Modified: 2000-04-30 12:45:46.798
Author: qqqqqq qqqqqq (http://www.jguru.com/guru/viewbio.jsp?EID=41393)
Question originally posed by anurag gupta
(http://www.jguru.com/guru/viewbio.jsp?EID=37343

http://apache.wrox.co.uk/projsp/chap05/index.shtml#74
Comments and alternative answers

A servlet chatroom implementation is available at :...


Author: Team [JavaZOOM] (http://www.jguru.com/guru/viewbio.jsp?EID=104856),
Jul 18, 2000
A servlet chatroom implementation is available at :
http://www.javazoom.net/jzservlets/jzchat10/jzchat.html It should work under any
servlet engine. SERVLET API 2.0 compliant.

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

(thanks to Virgilio Garcia for pointing this one out)

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...

How can my servlet class which subclasses GenericServlet/HttpServlet


provide an RMI service?
Location: http://www.jguru.com/faq/view.jsp?EID=41803
Created: Apr 28, 2000 Modified: 2000-06-21 15:46:21.555
Author: Mikael Jakobsson (http://www.jguru.com/guru/viewbio.jsp?EID=41777)
Question originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

Instead of letting your service subclass the java.rmi.server.UnicastRemoteObject


class it is possible to make a call to the static method in the same class:
exportObject(Remote). Thus you should let your class subclass
GenericServlet/HttpServlet and implement a Remote interface. In the
init(ServletContext) method your instance can export itself.
A simple example follows (exception handling omitted) :
public class MyServlet extends HttpServlet implements MyRemoteInterface
{
public void init(ServletContext ctx) {
UnicastRemoteObject.exportObject(this);
}

// rest of code goes here...

}
Good luck!
Comments and alternative answers

You can also just use delegation -- make a normal ...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Apr 30, 2000
You can also just use delegation -- make a normal Remote Object by extending
UnicastRemoteObject in the normal way; then in your servlet's init method, you
create an instance of that remote object and register it with the name server. Then
other objects can access it using normal RMI calls. As a bonus, you could have your
servlet intercept HTTP GET or POST calls to invoke methods on the remote object.

I do not understand the above suggestion by Alex. ...


Author: erik leedom (http://www.jguru.com/guru/viewbio.jsp?EID=205011), Sep 13,
2000
I do not understand the above suggestion by Alex. If you do this how is the
RemoteObject that is containted within the servlet going to access the servlet's data
and methods, which is what it would have to do to provide the functionality that the
original question requested? You would have to pass the UnicastRemoteObject
instance a refrence to the servlet right? Which wouldn't be so bad but I would hazard
is not quite as clean as the original response

How do I delete a cookie set by a servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=42225
Created: Apr 29, 2000 Modified: 2000-08-13 17:11:40.912
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4) Question
originally posed by Armaity Rupa
(http://www.jguru.com/guru/viewbio.jsp?EID=32852

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

Thanks a lot. A simple solution as that is highly ...


Author: Armaity Rupa (http://www.jguru.com/guru/viewbio.jsp?EID=32852), May 2,
2000
Thanks a lot. A simple solution as that is highly appreciated.

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?

Re: Not working


Author: R Thackston (http://www.jguru.com/guru/viewbio.jsp?EID=1119662),
Oct 5, 2003
Try setting the cookie back in the response. In other words, get the cookie, set the
max age, then add the cookie to the response:
Cookie c = request.getCookies()[i];

c.setMaxAge(0);

response.addCookie(c);

Re[2]: Not working


Author: David Han (http://www.jguru.com/guru/viewbio.jsp?EID=1184718),
Jul 8, 2004
Works for netscape but not IE6. Any idea?

Here is the code

biCookie = new Cookie("testing", "testing");


biCookie.setMaxAge(0);
biCookie.setPath("/");
biCookie.setDomain("whatever my site domain");
response.addCookie(biCookie);
response.sendRedirect("What ever URL");

Best Regards

When will a servlet engine send the HTTP response header? Is it


immediately after getWriter/getOutputStream is called, or is it just before
any call to write()?
Location: http://www.jguru.com/faq/view.jsp?EID=42232
Created: Apr 29, 2000 Modified: 2000-04-30 12:20:32.071
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4) Question
originally posed by lee yeow leong
(http://www.jguru.com/guru/viewbio.jsp?EID=3804
This is an implementation specific detail of the servlet engines. I.e., it depends. Of
course, at the very best, once you've flushed content to the client, there's no way
back. :-)

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.

How do I set init parameters in the servlet engine?


Location: http://www.jguru.com/faq/view.jsp?EID=42541
Created: Apr 30, 2000 Modified: 2001-05-01 08:44:38.616
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Ian Phillips
(http://www.jguru.com/guru/viewbio.jsp?EID=38182

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.

See this FAQ for information on passing an init param to a JSP.

Comments and alternative answers

Resin: Look for the resin.conf file in your Resin1...


Author: John Saccoccio (http://www.jguru.com/guru/viewbio.jsp?EID=97733), Jul 6,
2000
Resin: Look for the resin.conf file in your Resin1.1/conf directory. It's a typical XML
based configuration file that has sample of how to set servlet init and application
parameters.

Java Web Server : We can set the init parameter in...


Author: pradeep chonat (http://www.jguru.com/guru/viewbio.jsp?EID=240326), Nov
15, 2000
Java Web Server : We can set the init parameter in JWS by specifying the initArgs
property for the concerned servlet in
HOME/properties/server/javawebserver/webpageservice directory.

Can a servlet act as an HTTP client?


Location: http://www.jguru.com/faq/view.jsp?EID=42553
Created: Apr 30, 2000 Modified: 2000-06-21 15:50:24.286
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Sean Shelby
(http://www.jguru.com/guru/viewbio.jsp?EID=39297
Yes. Use the standard java.net.URL class, or "roll your own" using
java.net.Socket. See the HTTP spec at W3C for more detail.

Feedback to this FAQ has additional information about initiating an HTTP connection
from Java.

Comments and alternative answers

Also bear in mind that servlets (as well as applets,...


Author: Nicola Ken Barozzi (http://www.jguru.com/guru/viewbio.jsp?EID=39153),
May 2, 2000
Also bear in mind that servlets (as well as applets, JavaBeans, and so on) are also
normal Java classes, which means that in them you can do anything as far as Java and
its libraries are concerned.

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.

What are the advantages of using Servlets rather than CGIs?


Location: http://www.jguru.com/faq/view.jsp?EID=43542
Created: May 2, 2000 Modified: 2000-05-02 13:11:36.09
Author: Mikael Jakobsson (http://www.jguru.com/guru/viewbio.jsp?EID=41777)
Question originally posed by Gilbert Banks
(http://www.jguru.com/guru/viewbio.jsp?EID=17542

When a normal CGI script (or program) is executed, it is spawned in a separate


process by the web server, and the output of that process becomes the resulting
page that is sent back to the client. Each request to the web server will result in a
new process beeing started. Starting a process will create some overhead, in
performance and in memory usage.

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.

There are of course other advantages.


• Java is a well structured language suitable for larger systems. Many of the
script languages used for CGI are formidable for small scripts and
applications, but when larger systems are built, it is not uncommon to find
that the code is a horror to maintain.
• It is probably easier to find a capable Java programmer than a
Perl/CSH/PHP3/... programmer. This is a point not to be forgotten if you want
someone else to be able to take over and/or understand your code.

Undoubtedly there are other advantages, but I stop here. I just want to add that:

Using the correct technology is not as important as using the technology


correctly.

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

The ServletContext interface includes methods getMajorVersion() and


getMinorVersion() to tell you what version of the Servlet API is in use.

[Alex Chaffee adds:]

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?

Comments and alternative answers

So, for example, JSWDK 1.0.1, which supports the S...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), May 5, 2000
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...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), May 5, 2000
From a JSP, you can use the implicit application object to access the
ServletContext. For example:
Major: <%=application.getMajorVersion()%>

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)

If you know any more, please submit feedback. -Alex]

JRun 3.0 (Right now in RC1) will support clustering with an add-on. check
http://www.allaire.com for info.

[Prasad Thammineni adds:]

In WebSphere Application Server Advanced Edition, you have to enable persistent


sessions in order to support session clustering. Also, you have to employ a load
balancer like CISCO local director to distribute HTTP requests across multiple web
servers/servlet engines.

[victor tago (vtago@yahoo.com) adds: ]

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!

[See also http://www.jguru.com/faq/view.jsp?EID=418461 -Alex]

Comments and alternative answers


WebLogic server has supported robust clustering of...
Author: Monte Kluemper (http://www.jguru.com/guru/viewbio.jsp?EID=36918), May
8, 2000
WebLogic server has supported robust clustering of servlets, EJBs, etc. for over a
year!

What does clustering mean in this context? Is it load...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jun 14, 2000
What does clustering mean in this context? Is it load balancing with sharing of session
data?

In WebSphere Application Server Advanced Edition the...


Author: Richard Raszka (http://www.jguru.com/guru/viewbio.jsp?EID=7963), Jul 3,
2000
In WebSphere Application Server Advanced Edition the sessions are shared across
multiple machines by storing the information in a Database. This can be DB2 (comes
with WebSphere) or other supported databases (Oracle).This imposes a performance
hit on the ability to retreive sessions quickly and requires more resources.

Has anybody come across a cluster that has been i...


Author: nair suraj (http://www.jguru.com/guru/viewbio.jsp?EID=271956), Dec 30,
2000
Has anybody come across a cluster that has been implemented using the iPlanet
application server which fundamentally has servlets in a distributed environment?

Enhydra also has an JSP/Servlet engine and is capable...


Author: Ivo Limmen (http://www.jguru.com/guru/viewbio.jsp?EID=327483), Feb 22,
2001
Enhydra also has an JSP/Servlet engine and is capable of clustering. Enhydra is open
source and can be downloaded at www.enhydra.org, they also have an Enterprise
Edition. It's a complete Application Server.

Tomcat 4 can be configured to support Session Sharing


Author: scotty kwok (http://www.jguru.com/guru/viewbio.jsp?EID=451827), Mar 9,
2002

Tomcat 4 has implemented a Persistent Manager over


JDBCStore/FileStore.It manage sessions by storing in & loading
from a database/directory.

By configuring your Tomcat(s) to use Persistent Manager and


pointing to the same database/directory, you can actually share
your session data across load-balanced servers.

For example, I use Tomcat4.0 & mysql, steps are:


1. create table in database for holding sessions:

create table tomcat_sessions (


session_id varchar(100) not null primary key,
valid_session char(1) not null,
max_inactive int not null,
last_access bigint not null,
session_data mediumblob
);

2. Copy the JDBC driver (.jar) into $CATALINA_HOME/server/lib/, so that


container can find your Driver
3. Update server.xml, to force Tomcat to use PersistentManger over a
JDBCStore

<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&amp;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>

Note: Because PersistentManager is orginially NOT intended for real-time storage


of session. That 's why checkInterval="1", maxIdleSwap="0",
maxIdleBackup="0" are necessary here to force the session to write to database
immediately(with 1-2s delay) after it is created/accessed.

Hope that future version of Tomcat will have sth. like RealTimePersistentManager.

Details refer to: http://jakarta.apache.org/tomcat/tomcat-4.0-


doc/config/manager.html

Have JSP or Servlets anything similar to ASP's event "Session_OnStart"?


Location: http://www.jguru.com/faq/view.jsp?EID=44037
Created: May 3, 2000 Modified: 2000-06-21 16:03:14.016
Author: Chanan Braunstein (http://www.jguru.com/guru/viewbio.jsp?EID=44032)
Question originally posed by Guillem Valls
(http://www.jguru.com/guru/viewbio.jsp?EID=5830

The JRun product from Allaire adds a global.jsa file with events for session and
application.
Comments and alternative answers

Or, you could use the following code: public void...


Author: Joe Morse (http://www.jguru.com/guru/viewbio.jsp?EID=91113), Jul 3, 2000
Or, you could use the following code:
public void doXXX(...) {

HttpSession ses = req.getSession(false);


if(ses == null) { //session will be new
ses = req.getSession(true);
} else { //session is not new
...
}

Hello, My problem falls on similar lines. I want to...


Author: vijay panchal (http://www.jguru.com/guru/viewbio.jsp?EID=335050), Feb
21, 2001
Hello, My problem falls on similar lines. I want to know how I can retrive
HttpSession state just before it gets invalidated/timeout. I tried out with
HttpSessionBindingListener but When thecontrol goes to "valueUnbound()", session
state is already lost. Regards,
Vijay Panchal

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"?

Re: using global.jsa


Author: neeraja narayanan
(http://www.jguru.com/guru/viewbio.jsp?EID=399701), Apr 10, 2001
only JRun support global.jsa

Re[2]: using global.jsa


Author: guru prasanth (http://www.jguru.com/guru/viewbio.jsp?EID=847725),
Dec 17, 2002
but if there any other way i can implement the same using someother server.
regards guru

What are the advantages and disadvantages of the different forms of


session tracking (cookies, session objects, hidden fields, URL rewriting)?
Location: http://www.jguru.com/faq/view.jsp?EID=44914
Created: May 5, 2000 Modified: 2000-08-13 16:42:15.757
Author: Simon Wong (http://www.jguru.com/guru/viewbio.jsp?EID=44276) Question
originally posed by arun prathap
(http://www.jguru.com/guru/viewbio.jsp?EID=43168

Here are the advantages and disadvantages I found with them:


Technique Advantages Disadvantages
1. size and number of cookies
stored are limited.
2. it stored as plain-text in a
1. simple
specific directory, everyone can
Cookies 2. don't need to send data back to us,
view and modify them. Personal
browser can participate in this task.
information is exposed.
3. it won't work if the security level
set too high in browser.
1. the documents needs to
embedded the data inside, waste
bandwidth. e.g., if you have to
conduct a web-based survey with
multiple pages using hidden fields.
1. simple You have to embed the result from
Hidden
2. No effect on security level setting in previous pages in the next page.
Fields
browsers. 2. Everyone can see the embedded
data by viewing the original source
code.
3. If the user surfs to a different
site, or to a static section of the
same site, the state is lost.
URL 1. Every data is appended on the URL => 1. URL is lengthy and the length of
the URL is limited, can't store
much information.
2. The URL contains data. If you
easy to debug. send this URL to your friends, they
Rewriting
2. Works even if users disable cookies might see your information.
3. If the user surfs to a different
site, or to a static section of the
same site, the state is lost.
Session usually use either cookies or URL
rewriting (depends on security setting of
browser) to make it function. Each user
will have its own unique session ID to
identify himself. The session data will be
Session
stored in the server and we can use the None :-)
Objects :
session ID to access these data. The
session ID will be sent to user either
cookies or URL Rewriting. Since the data
are stored in server, the size of data is
theoretically unlimited.
Comments and alternative answers

disagree. sessions are OK if your JVM don't crash....


Author: leo shikida (http://www.jguru.com/guru/viewbio.jsp?EID=302805), Jan 15,
2001
disagree. sessions are OK if your JVM don't crash. If this happens, everybody
currently using sessions loose their sessions at the same time. K.

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.

public MyResponse postRequest(MyRequest myRequest) {

try {
// Open the connection
URL url = new URL(getCodeBase(), "myServlet");
URLConnection uc = url.openConnection();

// Post the request


uc.setDoOutput(true);
uc.setDoInput(true);
uc.setUseCaches(false);
uc.setRequestProperty("Content-type",
"java-internal/" +
myRequest.getClass().getName());
ObjectOutputStream out =
new ObjectOutputStream(uc.getOutputStream());
out.writeObject(myRequest);
out.flush();

// Read the response


ObjectInputStream in =
new ObjectInputStream(uc.getInputStream());
return (MyResponse) in.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

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.

public void doPost(HttpServletRequest req, HttpServletResponse res)


throws ServletException, IOException {

try {
// Read the resquest
ObjectInputStream ois =
new ObjectInputStream(req.getInputStream());
MyRequest myRequest =
(MyRequest) ois.readObject();

// Format the response from the session data


HttpSession session = req.getSession(true);
MyResponse myResponse =
new MyResponse(session.fooData);

// Send the response


ObjectOutputStream oos =
new ObjectOutputStream(res.getOutputStream());
oos.writeObject(myResponse);
} catch (Exception e) {
e.printStackTrace();
}
}
Comments and alternative answers

See also When you communicate with a servlet from an...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Aug 14, 2000
See also 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?

Can I have multiple browser windows use different session IDs?


Location: http://www.jguru.com/faq/view.jsp?EID=46305
Created: May 8, 2000 Modified: 2000-06-21 16:18:50.91
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Renny Bas (http://www.jguru.com/guru/viewbio.jsp?EID=44238
No. Sessions are referenced using cookies, and cookies are set per-client, not per-
window.

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.

Comments and alternative answers

I believe this depends on if you're using single-s...


Author: Rob Dickinson (http://www.jguru.com/guru/viewbio.jsp?EID=47338), May
10, 2000
I believe this depends on if you're using single-session cookies or persistent cookies.
Single-session cookies are stored in the browser's memory cache, so two browser
instances would see different cookies (and therefore different sessions). Persistent
cookies (which reside on the hard disk) are limited to one per client. Please correct me
if I'm wrong, since I'm using this technique <G>!

There's a difference between multiple instances of...


Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), May 10,
2000
There's a difference between multiple instances of the browser and multiple browser
windows. Multiple browser windows is one instance. All windows share the cookies.
Multiple instances would allow one to have separate session IDs as they are separate
clients. I believe you have the persistent cookie part correct.

Use hidden fields or URL rewriting instead


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), May 5, 2001
Michael Wax adds:

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?

Name some Web sites that make extensive use of Servlets.


Location: http://www.jguru.com/faq/view.jsp?EID=46314
Created: May 8, 2000 Modified: 2000-05-11 10:06:07.657
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Snoopy Boy
(http://www.jguru.com/guru/viewbio.jsp?EID=43866

jGuru makes use of both Servlets and JSP, naturally.

Sun has a small list of "Servlets in the Real World" at


http://java.sun.com/products/servlet/industry.html#real.

See also this question in the JSP FAQ for a list of JSP-using sites.

Please submit other sites you know of as feedback to this question.

Comments and alternative answers

WebHelp (running Tomcat; see also this FAQ.)


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), May 17,
2000
WebHelp (running Tomcat; see also this FAQ.)

ya we have developed a site called http://www.su...


Author: Kiran Kumar (http://www.jguru.com/guru/viewbio.jsp?EID=18386), Oct 29,
2000
ya we have developed a site called http://www.supportifa.com which is 100%
servlets.

Check out http://www.pilotpal.com/logbook which uses...


Author: Roshan Shrestha (http://www.jguru.com/guru/viewbio.jsp?EID=130068), Feb
27, 2001
Check out http://www.pilotpal.com/logbook which uses servlets with XML/XSL as
the presentation method

Site uses Servlets, JSP and EJB


Author: Anand Balasubramanian
(http://www.jguru.com/guru/viewbio.jsp?EID=56405), Jul 2, 2001
We have developed a site using Servlets, JSP and EJB
www.signatureflight.com

Why do GenericServlet and HttpServlet implement the Serializable


interface?
Location: http://www.jguru.com/faq/view.jsp?EID=46477
Created: May 9, 2000 Modified: 2000-05-10 17:45:18.376
Author: Nicola Ken Barozzi (http://www.jguru.com/guru/viewbio.jsp?EID=39153)
Question originally posed by Mohan Thomas
(http://www.jguru.com/guru/viewbio.jsp?EID=19527

GenericServlet and HttpServlet implement the Serializable interface so that servlet


engines can "hybernate" the servlet state when the servlet is not in use and
reinstance it when needed or to duplicate servlet instances for better load balancing.
I don't know if or how current servlet engines do this, and it could have serious
implications, like breaking references to objects gotten in the init() method without
the programmer knowing it. Programmers should be aware of this pitfall and
implement servlets which are stateless as possible, delegating data store to Session
objects or to the ServletContext. In general stateless servlets are better because
they scale much better and are cleaner code.

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

Session management is automatic if the server supports load-balancing on more


machines.
The JavaWorld article What's New in Java Servlet API 2.2? clarifies on the subject in
the paragraph Distributed Applications.

The following is taken from that doc.

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.

The specification dictates that, for an application marked as distributable in its


deployment descriptor, there will be a single ServletContext instance per JVM. This
means the context attributes cannot be used to share global information. Global
information in a distributed app needs to be stored externally from the Web server,
as is the case in database or EJB component.
An application marked as distributable also has special rules for user sessions.
Servers will use session affinity to efficiently manage user state across multiple back-
end servers. This means that all requests that are part of a single session from a
particular user are to be handled by only one JVM at a time. This in turn eliminates
the need to constantly replicate session information across all the back-end servers.
Responsibility for the session can be moved to another server between user
requests, though in practical terms this is unlikely to occur frequently. Still, to enable
the moving of a session, all objects placed into a session by servlets in a distributed
application must implement Serializable. A Web server can throw an
IllegalArgumentException if this condition is not met. Nondistributed apps, of
course, can store any objects into the session.

Comments and alternative answers

See also http://www.jguru.com/jguru/faq/view.jsp?E...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jul 6, 2000
See also http://www.jguru.com/jguru/faq/view.jsp?EID=44035

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.

Comments and alternative answers

I have to disagree (somewhat) with the comment that...


Author: Shaun Childers (http://www.jguru.com/guru/viewbio.jsp?EID=30243), May
17, 2000
I have to disagree (somewhat) with the comment that "...your controller is Session
beans...", because it really "depends" on the architecture of the system. The Session
beans will not look up any Entity beans or invoke any methods on an Entity bean
without a client invoking a method on the Session bean itself. In other words, the
controller could be an independent Java application, or a C++ application using
CORBA, or a combination of HTML/WML page with servlets, or another EJB
application. The controller really takes on multiple forms depending on the
architecture of the system. If I had a simple system constructed of EJB beans, with
JSP's providing the interface between the client (web) and the application, then the
JSP's (actually servlets compiled from JSP) would be the controller. If I had an RMI
application on another server talking directly to the Session beans of my server, then
the RMI application is the controller.

I am working on a large project using model view a...


Author: Vibhu Srinivasan (http://www.jguru.com/guru/viewbio.jsp?EID=60278), May
31, 2000
I am working on a large project using model view architecture. Here goes my two
cents worth of an architecture that has produced good results for us

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.

This is the model.

Now about the controller and the view:

• All the JSP's talk to servlets which are the controllers.


• The servlets control creation and setting various properties on the java beans.
• The java beans are broken to two kinds.
1. Data access beans
2. Presentation beans
• The servlets create the presentation beans which are tied to some screens .
• The JSPs only read information from the java beans.
Check out the blueprints from sun for some good analysis!

Re: I am working on a large project using model view a...


Author: Anupam De (http://www.jguru.com/guru/viewbio.jsp?EID=958113), Mar
15, 2003
I have a question - if you are using JSP/Beans combination, then the View model
will be tying in the bean hard coding the data to the table with the html codes.
How best to separate it out ? One I was thinking was with Hashtables/Array ? But
I am looking or complete separation of the presentation layer from any code
snippets of Java. I am using Apache Tomcat 4.0.1

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?

How do I send a WML page as a response from a servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=48359
Created: May 12, 2000 Modified: 2000-05-16 16:51:42.795
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

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");

Is Tomcat robust enough for production use?


Location: http://www.jguru.com/faq/view.jsp?EID=49745
Created: May 16, 2000 Modified: 2000-06-21 16:27:33.755
Author: Matthew Dornquast (http://www.jguru.com/guru/viewbio.jsp?EID=27320)
Question originally posed by John Mitchell PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=4

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.

No known issues at this time! The site is Webhelp.com

Comments and alternative answers


Can you give any details regarding versions of apache and tomcat your are
using?
Author: Bronson Silva (http://www.jguru.com/guru/viewbio.jsp?EID=716572), Jan
10, 2002

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:

memory allocated to each jvm?

solaris:

apache:

tomcat:

connector module used: mod_webapp, mod_jk, mod_jserver?

Are you doing any clustering/failover?

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

Why is my cookie is expiring before the time set using the


Cookie.setMaxAge method?
Location: http://www.jguru.com/faq/view.jsp?EID=49794
Created: May 16, 2000 Modified: 2000-06-21 16:28:52.895
Author: Matthew Dornquast (http://www.jguru.com/guru/viewbio.jsp?EID=27320)

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

Servlets extend the server-side functionality of a website. Servlets communicate with


other application(s) on that server (or any other server) and perform tasks above
and beyond the "normal" static HTML document. A servlet can receive a request to
get some information through EJB from one or more databases, then convert this
data into a static HTML/WML page for the client to see, for example. Even if the
servlet talks to many other applications all over the world to get this information, it
still looks like it happened at that website.

RMI (Remote Method Invocation) is just that - a way to invoke methods on remote
machines. It is way for an application to talk to another remote machine and execute
different methods, all the while appearing as if the action was being performed on
the local machine.

Servlets (or JSP) are mainly used for any web-related activity such as online
banking, online grocery stores, stock trading, etc. With servlets, you need only to
know the web address and the pages displayed to you take care of calling the
different servlets (or actions within a servlet) for you. Using RMI, you must bind the
RMI server to an IP and port, and the client who wishes to talk to the remote server
must know this IP and port, unless of course you used some kind of in-between
lookup utility, which you could do with (of all things) servlets.

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

You have to use HTTP like everyone else.

See How can my applet communicate with my servlet? and How do I call one servlet
from another servlet?

What are the main differences between Servlets and CGI?


Location: http://www.jguru.com/faq/view.jsp?EID=51048
Created: May 18, 2000 Modified: 2000-05-26 16:23:10.589
Author: Simon Brown (http://www.jguru.com/guru/viewbio.jsp?EID=44588)
Question originally posed by Harihara Rao Velamala
(http://www.jguru.com/guru/viewbio.jsp?EID=30512

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

You can find that method in java.net.URLEncoder.

ie: String Args = URLEncoder.encode("The raw data you want to encode");

[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,...


Author: Monty Shaw (http://www.jguru.com/guru/viewbio.jsp?EID=30689), Jun 10,
2000

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 '&lt;', etc.

Is there a better way?

Re: Is this question about encoding URL GET parameters,...


Author: Alain Renaud (http://www.jguru.com/guru/viewbio.jsp?EID=416804),
May 7, 2001
I've used this little gimmick that takes advantage of the HTML classes built-in the
J2SE to do the reverse, converting from HTML encoding to text (in the package
javax.swing.text.html): HTMLDocument doc = new HTMLDocument();
HTMLEditorKit kit = new HTMLEditorKit(); Reader rd = new
StringReader("<title>School - &Eacute;cole</title>"); kit.read(rd,doc,0);
System.out.println(doc.getProperty(Document.TitleProperty)); So, I guess the
reverse of that code should do the trick you need, although I did not test it...
HTMLDocument doc = new HTMLDocument(); HTMLEditorKit kit = new
HTMLEditorKit(); Writer wr = new StringWriter();
doc.putProperty(Document.TitleProperty, "School - École");
kit.write(wr,doc,0,100); System.out.println(wr.toString());

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,

null, null, "quot", null, null, null, "amp", null,


null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null,
null, null, null, null, "lt", null, "gt", 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, 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, 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, null,

"nbsp", "iexcl", "cent", "pound", "curren", "yen", "brvbar",


"sect",
"uml", "copy", "ordf", "laquo", "not", "shy", "reg", "macr",
"deg", "plusmn", "sup2", "sup3", "acute", "micro", "para",
"middot",
"cedil", "sup1", "ordm", "raquo", "frac14", "frac12",
"frac34", "iquest",

"Agrave", "Aacute", "Acirc", "Atilde", "Auml", "Aring",


"Aelig", "Ccedil",
"Egrave", "Eacute", "Ecirc", "Euml", "Igrave", "Iacute",
"Icirc", "Iuml",
"Eth", "Ntilde", "Ograve", "Oacute", "Ocirc", "Otilde",
"Ouml", "times",
"Oslash", "Ugrave", "Uacute", "Ucirc", "Uuml", "Yacute",
"THORN", "szlig",

"agrave", "aacute", "acirc", "atilde", "auml", "aring",


"aelig", "ccedil",
"egrave", "eacute", "ecirc", "euml", "igrave", "iacute",
"icirc", "iuml",
"eth", "ntilde", "ograve", "oacute", "ocirc", "otilde",
"ouml", "divide",
"oslash", "ugrave", "uacute", "ucirc", "uuml", "yacute",
"thorn", "yuml",
};

-gwolfe

Is there a problem with calling Response.sendRedirect() after


Response.addCookie() ?
Location: http://www.jguru.com/faq/view.jsp?EID=53251
Created: May 21, 2000 Modified: 2000-05-21 13:49:57.176
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Shalabh Nigam
(http://www.jguru.com/guru/viewbio.jsp?EID=47481

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. seanm@narus.com
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.

Re: Your solution works perfectly.


Author: Anbuchezhian Chelliah
(http://www.jguru.com/guru/viewbio.jsp?EID=1144363), Feb 7, 2004
When a page redirect occurs at the Apache (using ErrorDocument directive in
Apache) do you think that cookies from two different browsers could get mixed
up?

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.

----------------------------------------------------------------------

<jsp:useBean class="foo.Counter" scope="application" />

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).

The servlet equivalent of the above useBean action is:

foo.Counter counter =
(foo.Counter)getServletContext().getAttribute("counter");
if (counter == null) {
counter = new foo.Counter();
getServletContext().setAttribute("counter", counter);
}
----------------------------------------------------------------------

<jsp:useBean id="counter" class="foo.Counter"


scope="session" />

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.

The servlet equivalent of the above useBean action is:

HttpSession session = request.getSession(true);


foo.Counter counter =
(foo.Counter)session.getValue("counter");
if (counter == null) {
counter = new foo.Counter();
session.putValue("counter", counter);
}
----------------------------------------------------------------------

<jsp:useBean id="counter" class="foo.Counter"


scope="request" />

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.

The servlet equivalent of the above useBean action is:

foo.Counter counter =
(foo.Counter)request.getAttribute("counter");
if (counter == null) {
counter = new foo.Counter();
request.setAttribute("counter", counter);
}
----------------------------------------------------------------------

<jsp:useBean id="counter" class="foo.Counter" scope="page"


/>

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:

foo.Counter counter = new foo.Counter();


Comments and alternative answers

superb! crystal clear!!


Author: Rosdi Kasim (http://www.jguru.com/guru/viewbio.jsp?EID=479028), Aug
17, 2001
Superb!.. the explanation is crystal clear!! I am looking for this info all over.., and this
page explain it all. Thanks god for the Internet! ...and the author of the answer too.. :-)

Re: superb! crystal clear!!


Author: Rotti Sowmindra (http://www.jguru.com/guru/viewbio.jsp?EID=487648),
Dec 30, 2001
Yes Really superb but what one can do is go and check the temporary java files
generated by the web server while compiling the JSP page.We can get answers to
all our questions Regards Sowmindra

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

This is what I was looking for..


got more than I expected.I would like
to thank the author for his explanation in such detail.

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. :-)

For jsp page script, more info about page scope.


Author: Roger Hand (http://www.jguru.com/guru/viewbio.jsp?EID=292314), Oct 1,
2001
If you're using script in a jsp page, as opposed to just jsp bean tags as shown above,
you can use the following form to put an already instantiated object into the page
context so it can be used via Bean tags.
<%
foo.Counter counter = new foo.Counter();
//use counter object in scriptlet . . .
//now let's set it up so we can use it with jsp bean tag . . .
pageContext.setAttribute("counter", MyPhoneNumberBean);
%>
Hello, World!
Counter value is <jsp:getProperty name="counter"
property="counterValue"/>

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 ...)

For older APIs...


Author: Josh Marquart (http://www.jguru.com/guru/viewbio.jsp?EID=30693),
Aug 9, 2002
it should've been . . .
pageContext.setAttribute("counter", counter);

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);

for session scoped Objects. You can also substitute


PageContext.APPLICATION_SCOPE
PageContext.REQUEST_SCOPE
and
PageContext.PAGE_SCOPE
in place of "PageContext.SESSION_SCOPE" depending on the scope you
want to deal with.

Help!! With setAttribute


Author: Jennifer Johnson (http://www.jguru.com/guru/viewbio.jsp?EID=531401), Oct
26, 2001
I am trying to pass a variable to a bean that has a parametarized constructor. I only
want the constructor to be initiallized once. Below is the code I am using to call the
bean:

<%String ttree1 = new String("fins.tb_reports");


BotLevBean1 botlev1 = (BotLevBean1)getServletContext().getAttribute("botlev1");
if (botlev1 == null) { botlev1 = new BotLevBean1(ttree1);
getServletContext.setAttribute("botlev1", botlev1); }
I am getting this error:
/u01/sdk/jsp_scratch/jsp/_treejsp2/_arvartree_bud_2ejsp.java:109: Undefined variable
or class name: getServletContext getServletContext.setAttribute("botlev1", botlev1);

Please Help!!! What am I doing wrong?


Thanks!!! %>

Re: Help!! With setAttribute


Author: oleg morenkov (http://www.jguru.com/guru/viewbio.jsp?EID=579913),
Dec 11, 2001
getServletContext()

good but i still get error


Author: priyadarshi upadhyaya
(http://www.jguru.com/guru/viewbio.jsp?EID=325951), Jan 4, 2002
Hi i m using <jsp:useBean id="t" class="testbean" /> <% t.var11=11 %> <% // here
var11 is int type variable and is defined in testbean.testbean is initialized by a
servlet.But when i run this JSP page ,I get error saying variable t is not initialized.but
if i initialize testbean in JSP , i lose my data which is set by servlet please help me out

Re: good but i still get error


Author: sreenivas ananthakrishna
(http://www.jguru.com/guru/viewbio.jsp?EID=752289), Feb 8, 2002
Priya, Hope your question has been answered by now. If now, make sure that the
scope of the bean in the jsp:useBean tag is same as the scope in which it was
created. for ex: in the servlet if you are storing the bean in ServletContext , you
need to specify
<jsp:useBean id="t" class="testbean" scope="application" />
like wise, for request:
servlet : request.setAttribute("t",t);
JSP: request.getAttribute("t");
for session :
servlet : request.getSession(true).putValue("t",t);
jsp: <jsp:useBean id="t" class="testbean" scope="session" />

hope this works, if not please let me know how you are creating and storing the
bean in the servlet thanks, sreeni

Re[2]: good but i still get error


Author: priyadarshi upadhyaya
(http://www.jguru.com/guru/viewbio.jsp?EID=325951), Feb 9, 2002
thnx anath I appreciate your reply..anyway i tried it out and it worked out. u
can view my site at www.mycgiserver.com/~priyadarshi786/ its totally in JSP
and i took lots of help from jguru FAQs ..Jguru realy helps..thnx jguru
priyadarshi
extremely useful
Author: jay denis (http://www.jguru.com/guru/viewbio.jsp?EID=792493), Apr 9,
2002
Thanks! I have been puzzled by this question for a long time. Thanks for giving such
clear a n answer.

Question
Author: mark faine (http://www.jguru.com/guru/viewbio.jsp?EID=1122412), Oct 18,
2003
In your example for request scope:

<jsp:useBean id="counter" class="foo.Counter" scope="request" />

The servlet equivalent of the above useBean action is:

foo.Counter counter = (foo.Counter)request.getAttribute("counter");


if (counter == null) {
counter = new foo.Counter();
request.setAttribute("counter", counter);
}

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!

its simply the best help


Author: jai prakash (http://www.jguru.com/guru/viewbio.jsp?EID=1189709), Jul 30,
2004
i got what i looking for. thanks

How can I support HTTPS (SSL) in a servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=53931
Created: May 22, 2000 Modified: 2000-08-24 19:10:45.933
Author: Jim Garrett (http://www.jguru.com/guru/viewbio.jsp?EID=53862) Question
originally posed by Al Buk (http://www.jguru.com/guru/viewbio.jsp?EID=47884
The servlet technology by design already supports https (SSL). However, the way
this works is not through the servlet technology but through the Web Server. The
web server controls whether information is done securely (https) versus non-securely
(http).

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.

Comments and alternative answers

Tomcat supports SSL, either through Apache, or on its...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jun 21, 2000
Tomcat supports SSL, either through Apache, or on its own (currently in an unstable
state, though it should work in time for the next major release).

Does anybody know how to do that for Apache/JServ ?...


Author: Victor Stratan (http://www.jguru.com/guru/viewbio.jsp?EID=134872), Oct
26, 2000
Does anybody know how to do that for Apache/JServ ? [Yes, see the Tomcat
documentation web site. -A]

Can the security context be passed between a web container (servlets/jsp)


and an EJB container ? When the servlet calls an EJB I want its identity to
be that of the original web client authenticated with a certificate.
Location: http://www.jguru.com/faq/view.jsp?EID=53955
Created: May 22, 2000 Modified: 2000-08-13 16:38:04.872
Author: Siva Visveswaran (http://www.jguru.com/guru/viewbio.jsp?EID=46210)
Question originally posed by Daniel Weimer
(http://www.jguru.com/guru/viewbio.jsp?EID=25540

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.

Comments and alternative answers

Some vendors, like Pramati, provide a facility where...


Author: Asit Padhi (http://www.jguru.com/guru/viewbio.jsp?EID=61648), Jul 18,
2000
Some vendors, like Pramati, provide a facility where the security credentials of the
web client are first authenticated by the web container and when the Servlet calls the
EJB components the same security context is passed on to the EJB container.

Re: Some vendors, like Pramati, provide a facility where...


Author: Nilesh Shah (http://www.jguru.com/guru/viewbio.jsp?EID=1810), Sep
19, 2002
Is this still true?. We are want to use Resin servlet engine at web layer and
weblogic 7.0 at EJB layer.

Can we pass security context from resin to weblogic?. Can JAAS help use
here?.

If we use weblogic at both layer that it passes the context.

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.

How can we use a servlet as a proxy for communications between two


applets?
Location: http://www.jguru.com/faq/view.jsp?EID=56017
Created: May 24, 2000 Modified: 2000-09-18 13:13:36.54
Author: Jim Garrett (http://www.jguru.com/guru/viewbio.jsp?EID=53862) Question
originally posed by kavala mallikarjun
(http://www.jguru.com/guru/viewbio.jsp?EID=44978

Jim Garrett writes:


One way to accomplish this is to have the applets communicate via TCP/IP sockets to
the servlet. The servlet would then use a custom protocol to receive and push
information between applets. However, this solution does have firewall problems if
the system is to be used over and Internet verses an Intranet.
Alex Chaffee adds:
You could also have the applets use HTTP to communicate with the servlet, using the
standard URLConnection classes as described in How can my applet communicate
with my servlet?. This is more likely to get through the firewall, but it means that the
second (receiver) applet must continually poll the servlet to check for new
information.
Jim Garrett continues:
One other solution which works with simple data is to combine Java Applet
technology with Java Scripts. Since an applet can communicate with Java Script, and
Java Script can communicate with applets, it is possible to create an environment
where JavaScript is used to pass information between applets. This solution works
when the data being sent between applets is text data.
[ Douglas E Miller had given some source code examples. It has been pointed out to
me that this code is actually from the Java Tutorial; you can look at the KnockKnock
example at
http://java.sun.com/docs/books/tutorial/networking/sockets/clientServer.html. Of
course, the KnockKnockServer isn't actually a servlet, which is kind of important for
the sake of the example, but you can probably figure it out from here. In this
architecture, the servlet must spawn a thread (probably in its init() method) that
opens and listens on a socket. This does not use HTTP at all, though you can extend
the doGet() method to provide a status page. That means it's still sensitive to
firewalls. -Alex ]

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!

A PUT allows you to "put" (upload) a resource (file) on to a webserver so that it be


found under a specified URI. DELETE allows you to delete a resource (file). These are
both additions to HTTP/1.1 and are not usually used. HEAD returns just the HTTP
headers for a resource. TRACE and OPTIONS are also HTTP/1.1 additions and also
rarely used.

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?

How can I design my servlet/JSP so that query results get displayed on


several pages, like the results of a search engine? Each page should display,
say, 10 records each and when the next link is clicked, I should see the
next/previous 10 records and so on.
Location: http://www.jguru.com/faq/view.jsp?EID=60818
Created: May 31, 2000 Modified: 2000-10-03 10:16:08.397
Author: Richard Raszka (http://www.jguru.com/guru/viewbio.jsp?EID=7963)
Question originally posed by arun prathap
(http://www.jguru.com/guru/viewbio.jsp?EID=43168

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).

Joe Sam Shirah adds:

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 approaches discussed above are good for a few ...


Author: jeyabalan sethuraman
(http://www.jguru.com/guru/viewbio.jsp?EID=120328), Aug 5, 2000
The approaches discussed above are good for a few hundreds of records as mentioned
above. What is the best approach when the result set is huge ( for example, more than
10000 records ) ?

As noted above, there are many ways to do this, but...


Author: yogesh tk (http://www.jguru.com/guru/viewbio.jsp?EID=200141), Oct 6,
2000
As noted above, there are many ways to do this, but all basically involve storing a
variable in order to know which set of records is to be shown next. Following are
three methods of storing the count:

1. Keep the count in the session.


2. Keep a hidden field in the page.
3. Place this count in the URL as a part of the QueryString.

The servlet then uses the count in its logic to determine the next set of records to
display.

Having had the same problem I found that in PostgreSQL...


Author: Tarmo Kallas (http://www.jguru.com/guru/viewbio.jsp?EID=227773), Oct
13, 2000
Having had the same problem I found that in PostgreSQL database one can make
SQL-queries so that resultSet returns only records from certain record to certain
record (e.g. records 5->10)
In SELECT statement one needs only add LIMIT and OFFSET atributes (e.g.
'SELECT * FROM table_name ORDER BY one_field_name LIMIT 5 OFFSET 5' this
statement should return the records from 5 to 10 in table_name table when sorted by
one_field_name field).

See the LIMIT CLAUSE documentation in the PostgreSQL documentation for


additional information.

I have never been able to figure out if there is any...


Author: martin smith (http://www.jguru.com/guru/viewbio.jsp?EID=260406), Dec 31,
2000
I have never been able to figure out if there is any way to have the DBMS retain a
scrollable cursor/resultset and feed only parts of it to the client or mid-tier.

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.)

Is this implementable within Oracle?

Re: I have never been able to figure out if there is any...


Author: Prasoon Kumar Choudhary
(http://www.jguru.com/guru/viewbio.jsp?EID=588711), Dec 18, 2001
There are many solutions to this problem. I agree that if the result set is a too
large, storing 1000 of record in session will not be a good idea. Better solution
will be to get record from database for each page. If you are working with mysql
there is a limit key work that will help you the featch for the particular page. On
oracle there is no such keyword but there is a query throught which you can select
record form middle of the total selected record for your search condition. say you
are fetching emp name from emp table and you want names from 20th to 30th
record for a search criteria say in emp in city newyork. The query will be
select x.emp_name from (select rownum y, emp_name from emp where
city='newyork')x where x.y between 20 and 30;
I have used this many time in my projects
Re[2]: I have never been able to figure out if there is any...
Author: Ajay Sharma (http://www.jguru.com/guru/viewbio.jsp?EID=746666),
Feb 4, 2002
Hi Prasoon , U are absolutely right , but the this is possible only in MYSQL
.But if U see Oracle , it isn't possible. I feel there are a number of ways U can
do this and it all depends upon the application requirements. Ajay Sharma

Re[3]: I have never been able to figure out if there is any...


Author: Prasoon Choudhary
(http://www.jguru.com/guru/viewbio.jsp?EID=264897), Feb 5, 2002
The query you see above works with oracle. Rownum ect is part of oracle
sql implementation. On Mysql you do not have rownum if you are working
with mySql use Limit keword

Re[4]: I have never been able to figure out if there is any...


Author: Robert Williams
(http://www.jguru.com/guru/viewbio.jsp?EID=1080681), Apr 30, 2003
How about for Microsoft SQL Server? Is there any keyword like
rownum or limit?

Re[2]: I have never been able to figure out if there is any...


Author: E L (http://www.jguru.com/guru/viewbio.jsp?EID=819637), Apr 1,
2002

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..

Re[3]: I have never been able to figure out if there is any...


Author: Prasoon Choudhary
(http://www.jguru.com/guru/viewbio.jsp?EID=264897), Apr 1, 2002
You will have you fire a select count(*) from emp where city='newyork'
before that. you can store this count in session so that you dont have to do
this for every page. This will work well for most of the cases where count
will not change very frequently i,e there is not much insert or delete taking
place on the table.

"select x.emp_name from (select rownum y, emp_name from emp where


city='newyork')x where x.y between 20 and 30;"
Author: X F (http://www.jguru.com/guru/viewbio.jsp?EID=887397), May 28,
2002
select emp_name from emp where city = 'newyork' and rownum < 31
MINUS
select emp_name from emp where city = 'newyork' and rownum < 20

this clause will perform better, i think so but no test.

Re: "select x.emp_name from (select rownum y, emp_name from emp


where city='newyork')x where x.y between 20 and 30;"
Author: segmoti segmoti
(http://www.jguru.com/guru/viewbio.jsp?EID=415596), Jun 15, 2002
One of the issues I find (in the query you have given with a minus clause)
is inability to sort by using 'order by' clause. For a query like 'select
emp_name from emp where city = 'newyork' and rownum < 20 order by
emp_name' 'Rownum' is executed before the order by clause. So if I put
both rownum and order by in a query, then oracle first gets the set of rows
as evaluated using rownum and then sorts it. Whereas behaivor I require is
that sort the records first and then use rownum to limit the rows. Any idea
how to get past it? Regards Mohit

Good Sql,but can not execute under ODBC for access


Author: Jeason Zhao
(http://www.jguru.com/guru/viewbio.jsp?EID=1037417), Dec 13, 2002
Good Sql,but can not execute under ODBC for access

Re[2]: I have never been able to figure out if there is any...


Author: HAKAN YILDIZ
(http://www.jguru.com/guru/viewbio.jsp?EID=1175989), Jun 3, 2004
what about if I have a query containing a group by clause in it. My query is :
select /*+ ALL_ROWS +*/ policeno pno,bitistarih bittar,Sum(primfark)
prim,sum(komisyonfark) komisyon from police where statu='E' and
baslangictarih<to_date'01/05/2005','dd/MM/yyyy') and
bitistarih>=to_date('01/05/2005','dd/MM/yyyy') group by policeno,bitistarih
order by policeno )pol this query gets about 2 million rows and I go through
these rows for calculating something,and my compiler(jdk 1.3.1) gives an
outofmemory exception in the middle. I dont want to increase heap size of jvm
. I want to get rows in three or more parts like the example you gave. but as I
mentioned I have a group by clause in my query and I am forced to put
rownum into groupby. if I do that I got wrong data from query ! has anybody
suggestion about this. thanks lot.

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.

At the client level

import java.net.*;
import java.io.*;

public class HTTP_post


{
static URL u;
public static void main(String args[])
{
String s=URLEncoder.encode("A Test string to send to a
servlet");

try
{
HTTP_post post = new HTTP_post();
post.u = new URL("http://myhost/servlet");

// Open the connection and prepare to POST


URLConnection uc = u.openConnection();
uc.setDoOutput(true);
uc.setDoInput(true);
uc.setAllowUserInteraction(false);

DataOutputStream dstream = new


DataOutputStream(uc.getOutputStream());

// The POST line


dstream.writeBytes(s);
dstream.close();

// Read Response
InputStream in = uc.getInputStream();
int x;
while ( (x = in.read()) != -1)
{
System.out.write(x);
}
in.close();

BufferedReader r = new BufferedReader(new


InputStreamReader(in));
StringBuffer buf = new StringBuffer();
String line;
while ((line = r.readLine())!=null) {
buf.append(line);
}

}
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...


Author: Richard Raszka (http://www.jguru.com/guru/viewbio.jsp?EID=7963), Jun 3,
2000

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.

Re: I agree with Alex, the approach I have taken is to...


Author: Priya Selva (http://www.jguru.com/guru/viewbio.jsp?EID=1109586), Aug
19, 2003
Hi All, I'm using com.oreilly.servlet package for uploading file through html. I
want to use the same package for file upload through Java client. Can anyone help
me to write the java client ? Thanks in advance --Selva

File Uplod Servlet: Java Client for com.oreilly.servlet package


Author: Priya Selva (http://www.jguru.com/guru/viewbio.jsp?EID=1109586),
Aug 20, 2003
I figured it through a web forum.
Here is the code for the Java Client

import java.io.*;
import java.net.*;

public class ServletCom {

public static void main(String[] args)


throws Exception
{

HttpURLConnection conn = null;


BufferedReader br = null;
DataOutputStream dos = null;
DataInputStream inStream = null;

InputStream is = null;
OutputStream os = null;
boolean ret = false;
String StrMessage = "";
String exsistingFileName = "C:\\account.xls";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";

int bytesRead, bytesAvailable, bufferSize;

byte[] buffer;

int maxBufferSize = 1*1024*1024;

String responseFromServer = "";

String urlString =
"http://localhost:8080/FileUpload/requestupload";

try
{
//------------------ CLIENT REQUEST

FileInputStream fileInputStream = new FileInputStream( new


File(exsistingFileName) );

// open a URL connection to the Servlet

URL url = new URL(urlString);

// Open a HTTP connection to the URL

conn = (HttpURLConnection) url.openConnection();

// Allow Inputs
conn.setDoInput(true);

// Allow Outputs
conn.setDoOutput(true);

// Don't use a cached copy.


conn.setUseCaches(false);

// Use a post method.


conn.setRequestMethod("POST");

conn.setRequestProperty("Connection", "Keep-Alive");

conn.setRequestProperty("Content-Type", "multipart/form-
data;boundary="+boundary);

dos = new DataOutputStream( conn.getOutputStream() );

dos.writeBytes(twoHyphens + boundary + lineEnd);


dos.writeBytes("Content-Disposition: form-data;
name=\"upload\";"
+ " filename=\"" + exsistingFileName +"\"" + lineEnd);
dos.writeBytes(lineEnd);

// create a buffer of maximum size

bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];

// read file and write it into form...

bytesRead = fileInputStream.read(buffer, 0, bufferSize);

while (bytesRead > 0)


{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}

// send multipart form data necesssary after file data...

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);
}

catch (IOException ioe)


{
System.out.println("From ServletCom CLIENT REQUEST:"+ioe);
}

//------------------ read the SERVER RESPONSE

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

How to realize streaming proxy


Author: Mirko Geilert
(http://www.jguru.com/guru/viewbio.jsp?EID=1147488), Feb 19, 2004
Hi,

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

Re: File Uplod Servlet: Help Required


Author: Kumar Uttam
(http://www.jguru.com/guru/viewbio.jsp?EID=1149406), Feb 26, 2004
I am using the same file provided by you.It compiles and connection is
made when server is running.But still the file is not uploaded in the folder
mentioned.Can u pls provide a solution to this.I have to upload an XML
file I am using jakarta tomcat as webserver. Thanks in advance. Can mail
me at uttam.kumar@iGate.com import java.io.*; import java.net.*; public
class ServletCom { public static void main(String[] args) throws Exception
{ HttpURLConnection conn = null; BufferedReader br = null;
DataOutputStream dos = null; DataInputStream inStream = null;
InputStream is = null; OutputStream os = null; boolean ret = false; String
StrMessage = ""; String exsistingFileName ="C:\\TimeSheet.xml"; String
lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int
bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize =
1*1024*1024; String responseFromServer = ""; //String urlString =
"http://192.168.221.63:80"; // String urlString =
"http://localhost:8080/FileUpload/requestupload"; String urlString =
"http://localhost:8080/examples/jsp";
//"http://localhost:8080/examples/jsp/Timeperiod/Timeperiod.xml" try
{ //------------------ CLIENT REQUEST FileInputStream fileInputStream =
new FileInputStream( new File(exsistingFileName) ); // open a URL
connection to the Servlet URL url = new URL(urlString);
System.out.println("URL::::::::::"+url); // Open a HTTP connection to the
URL conn = (HttpURLConnection) url.openConnection();
conn.setAllowUserInteraction(true); // Allow Inputs conn.setDoInput(true);
// Allow Outputs conn.setDoOutput(true); // Don't use a cached copy.
conn.setUseCaches(false); // Use a post method.
conn.setRequestMethod("POST"); conn.setRequestProperty("Connection",
"Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-
data"); // conn.getResponseCode() ; dos = new
DataOutputStream(conn.getOutputStream()); conn.getResponseMessage();
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes(exsistingFileName); dos.writeBytes(lineEnd); // create a
buffer of maximum size bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new
byte[bufferSize]; // read file and write it into form... bytesRead =
fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0)
{ dos.write(buffer, 0, bufferSize); bytesAvailable =
fileInputStream.available(); bufferSize = Math.min(bytesAvailable,
maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); }
// send multipart form data necesssary after file data...
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); }
catch (IOException ioe) { System.out.println("From ServletCom CLIENT
REQUEST:"+ioe); } //------------------ read the SERVER RESPONSE 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);
} catch (Exception e) { System.out.println("From ServletCom CLIENT
REQUEST:"+e); } } }

When you use readLine() to read data over a socket...


Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10), Oct 26, 2000

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.

I have been using HTTPClient to make posts from Java...


Author: Jim Coker (http://www.jguru.com/guru/viewbio.jsp?EID=2), Oct 26, 2000
I have been using HTTPClient to make posts from Java programs and it has worked
well so far, and is very easy to use. It also handles cookies smoothly, and is LGPL. I
plan to use it to build testing programs for jGuru.

Re: I have been using HTTPClient to make posts from Java...


Author: hari prasad (http://www.jguru.com/guru/viewbio.jsp?EID=1059077), Feb
21, 2003
hai can u help me i have seen the code to send the text string to servlet and servlet
reads it can u help me to have a example to send a xml file to servlet and servlet
send back the xml file to the client please its urgent

what about connecting to a J2EE app server?


Author: John Nilson (http://www.jguru.com/guru/viewbio.jsp?EID=27129), Dec 31,
2001
Will this work when/if the client gets a form based authentication response, that is the
JSEE login page with a <form> , j_security_check etc. How do you handle this case
and then set the username and password back, which I imagine have to be encrypted
as well? John

What version of the Servlets or JSP specification is supported by my favorite


servlet product? (JSDK, JSWDK, Tomcat, J2EE, etc.)
Location: http://www.jguru.com/faq/view.jsp?EID=64205
Created: Jun 3, 2000 Modified: 2000-08-13 14:39:09.242
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

Related FAQs:

• What's the difference between the JSDK and the JSWDK? And what's the
current version?

The following table summarizes the confusion.

Product Product Version Servlet spec JSP spec


Tomcat 3.1 2.2 1.1
Tomcat 3.0 2.2 1.1
Sun J2EE Reference Implementation beta 2.2 ?
Sun JSWDK 1.0.1 2.1 1.0.1
Sun JSDK 2.1 2.1 none
Sun JSDK 2.0 2.0 none
Allaire JRun 3.0 2.2 1.1
Sun Java Web Server 2.0 2.1 -
Sun Java Web Server 1.1 2.0 -
Sun/Netscape iPlanet Web Server 4.1 2.2 ?
Please add information for other servlet engines as feedback to this FAQ; I'll
incorporate it into the table.
Comments and alternative answers

JRun 3.0 -- Servlet 2.2, JSP 1.1


Author: Larry Kim (http://www.jguru.com/guru/viewbio.jsp?EID=71699), Jun 10,
2000
JRun 3.0 -- Servlet 2.2, JSP 1.1

Enhydra 3.0 -- Servlet 2.2, JSP 1.1


Author: Klaus Krull (http://www.jguru.com/guru/viewbio.jsp?EID=136930), Aug 28,
2000
Enhydra 3.0 -- Servlet 2.2, JSP 1.1

Oracle JVM rel 3 supports Servlet 2.2 and JSP 1.1


Author: Kuassi Mensah (http://www.jguru.com/guru/viewbio.jsp?EID=267862), Dec
2, 2000
Oracle JVM rel 3 supports Servlet 2.2 and JSP 1.1

jo! 1.0b3
Author: Roger Chung-Wee (http://www.jguru.com/guru/viewbio.jsp?EID=448003),
Jun 30, 2001

Supports Servlet 2.2 and JSP 1.1. Available from tagtraum.com.

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).

Thijs Stalenhoef adds:

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

convert HTML to XML


Author: amit shukla (http://www.jguru.com/guru/viewbio.jsp?EID=870149), May 7,
2002
Hope this can help : public org.w3c.dom.Document
executeXML(org.w3c.dom.Document request) { return _execute(request) ; } public
org.w3c.dom.Document execute(HTTPServletRequest iRequest)
{ org.w3c.dom.Document request = iRequest.getRequestDoc(); return
_execute(request) ; } public org.w3c.dom.Document
_execute(org.w3c.dom.Document request) { String xml = this.execute(request);
org.w3c.dom.Document response = parser.parse(xml); xml = null; return response; }

if objective is for parsing HTML, JTIDY or JDK's HTML parser can be


considered
Author: Avani Shah (http://www.jguru.com/guru/viewbio.jsp?EID=28330), Jul 23,
2003
JTIDY is an open source and HTML parser is available in JDK1.4 (swing parser)

The answer is JEDI


Author: Daniel Matyas (http://www.jguru.com/guru/viewbio.jsp?EID=445610), Jan
20, 2005
JEDI - the most complex project solving this problem.
http://www.ipsi.fraunhofer.de/oasys/projects/jedi/ Good luck

Is there a way to run Tomcat under JView (Microsoft's Java VM)?


Location: http://www.jguru.com/faq/view.jsp?EID=66180
Created: Jun 8, 2000 Modified: 2000-08-24 19:02:13.343
Author: Nicola Ken Barozzi (http://www.jguru.com/guru/viewbio.jsp?EID=39153)
Question originally posed by Pramod Thuse
(http://www.jguru.com/guru/viewbio.jsp?EID=44250

I found this answer at the Tomcat FAQ.

Can Jakarta use Microsoft's JVM?


ealtman Last Mod: 2000-03-27 01:55:47.0

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.

How do I deal with multi-valued parameters in a servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=71968
Created: Jun 10, 2000 Modified: 2000-06-17 17:12:16.352
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by stephen marshall
(http://www.jguru.com/guru/viewbio.jsp?EID=53636

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

You can separate each value by a '|' inside a single...


Author: Nexus6 Free (http://www.jguru.com/guru/viewbio.jsp?EID=12709), Jun 17,
2000
You can separate each value by a '|' inside a single input value tag !
<input type=text value="1|2|3|4">
You can split this value by a '|' ...

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:

com.foo.dbBean bean = new com.foo.dbBean();


//call setters to initialize bean
req.setAttribute("dbBean", bean);
url="..."; //relative url for display jsp page
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(url);
rd.forward(req, res);

The bean can then be accessed within the JSP page via the useBean tag as:

<jsp:useBean id="dbBean" class="com.foo.dbBean"


scope="request"/>
...
<%
//iterate through the rows within dbBean and
//access the values using a scriptlet
%>
Also, it is best to design your application such that you avoid placing beans into the
session unless absolutely necessary. Placing large objects within the session imposes
a heavy burden on the performance of the servlet engine. Of course, there may be
additional design considerations to take care of - especially if your servlets are
running under a clustered or fault-tolerant architecture.

Comments and alternative answers

We currently are not allowed to use beans at our site....


Author: Doug Weems (http://www.jguru.com/guru/viewbio.jsp?EID=69536), Jun 13,
2000
We currently are not allowed to use beans at our site. To communicate with servlets,
we use something similiar to above code w/o the bean stuff. We pass information
back and forth with the session object. It's clunky, but it works.

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.

Comments and alternative answers

Yes, but there is a limit that will be reached given...


Author: J Majik (http://www.jguru.com/guru/viewbio.jsp?EID=61152), Jun 17, 2000
Yes, but there is a limit that will be reached given enough concurrent users,
reguardless of what you set the max heap to (especially with something like XML
parsing where a 150K document requires 7 MEGS of heap to process!). In that case,
an OutOfMemory error occurs and potentially screws up many people's sessions.
Would you have to catch the OutOfMemory error throughout your code? I'd like to
think there's a more elegant solution...

You can theoretically put try { ... } catch (OutO...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jun 17, 2000
You can theoretically put
try {
...
}
catch (OutOfMemoryError e) {
// print appropriate error message, like "the server
// is experiencing a lot of requests, please try
// again later"
}
in your doGet() routine. I don't see why an OOM would screw up other sessions,
assuming the garbage collector works... You may also try calling System.gc()
explicitly, which used to help back in JDK 1.0 days.

How can I use a servlet to generate a site using frames?


Location: http://www.jguru.com/faq/view.jsp?EID=69191
Created: Jun 14, 2000 Modified: 2000-06-14 23:14:45.768
Author: Vincent Cirel (http://www.jguru.com/guru/viewbio.jsp?EID=69061) Question
originally posed by Susan P (http://www.jguru.com/guru/viewbio.jsp?EID=63595

In general, look at each frame as a unique document capable of sending its own
requests and receiving its own responses. You can create a top servlet (say,
FrameServlet) that upon invocation creates the frame layout you desire and sets the
SRC parameters for the frame tags to be another servlet, a static page or any other
legal value for SRC.

---------------------- SAMPLE ----------------------

public void doGet(HttpServletRequest request,


HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = new PrintWriter (response.getWriter());

out.println("<html>");
out.println("<head>Your Title</head>");

// definingthe three rows of Frames for the main page


// top : frm_1
// middle : frm_2
// bottom : frm_3

out.println("<frameset rows=12%,70%,* cols=*>");


out.println("<frame src=/servlets/MenuServlet
name=frm_1>");
out.println("<frame src=/servlets/DummyServlet?mode=full
name=frm_2>");
out.println("<frame src=/servlets/DummyServlet?mode=small
name=frm_3>");
out.println("</frameset>");

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.

Comments and alternative answers

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.*

//create a Socket object connected to port 514 (shell/cmd


port used by rsh)

Socket mySock = new Socket("destination host",514);

//get the output stream for the socket

DataOutputStream outStream;

outStream = new DataOutputStream(mySock.getOutputStream());

//construct the command string

String rshStr = "whatever command you want to send"

//send it on its way

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

Is there a way I can capture the output of a servlet, without immediately


sending it to the client response stream?
Location: http://www.jguru.com/faq/view.jsp?EID=75971
Created: Jun 14, 2000 Modified: 2000-10-16 13:10:44.361
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by stanley santiago
(http://www.jguru.com/guru/viewbio.jsp?EID=70999

[In other words, I want to override/specify the response.getServletOutputStream().


To be even more specific, why is there not something like
response.setServletOutputStream()?]

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?.

Jason Hunter's CacheHttpServlet contains a class called CacheHttpResponse (and a


corresponding CacheServletOutputStream) that saves all its output to a buffer. In
theory, you can create one of these, and pass it into a RequestDispatcher's forward()
or include() methods, then read the buffer when it's complete. You may have to
massage some fields so they match the caller's ServletResponse. If anybody tries
this, please let me know (submit a feedback)!

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.

I'd love to see source code demonstrating this, though.

Do any commerical or free servlet containers currently support the retrieval


of client and server certificates?
Location: http://www.jguru.com/faq/view.jsp?EID=71670
Created: Jun 16, 2000 Modified: 2000-12-12 19:37:04.466
Author: Prasad Thammineni (http://www.jguru.com/guru/viewbio.jsp?EID=36479)
Question originally posed by Len Norton
(http://www.jguru.com/guru/viewbio.jsp?EID=37422

[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?]

WebSphere Application Server 3.0+ supports retrieval of client certificates. Refer to


http://www-
4.ibm.com/software/webservers/appserv/doc/v30/ae/web/doc/howto/itaccssl.html.

Comments and alternative answers

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 ?

Can you send me those examples to lenz@softexport.com.br ?


Thanks

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

More current benchmarks


Author: Marcel Offermans (http://www.jguru.com/guru/viewbio.jsp?EID=5070), Nov
21, 2001

Has anybody found any more recent benchmarks? The servlet engines mentioned
have all been replaced by newer versions or products.

Surely, somebody must still be doing benchmarks before deciding on a specific


platform.

How to configure Nescape Enterprise Server to use a Resource Bundle


(file.properties)?
Location: http://www.jguru.com/faq/view.jsp?EID=71716
Created: Jun 17, 2000 Modified: 2000-06-17 12:19:36.854
Author: Prasad Thammineni (http://www.jguru.com/guru/viewbio.jsp?EID=36479)
Question originally posed by sakesan k.
(http://www.jguru.com/guru/viewbio.jsp?EID=50946

The file.properties file should be present in the same directory as the class file
loading the properties.

How can I specify which kind of cookies (single-session cookies or


persistent cookies) I want to use ?
Location: http://www.jguru.com/faq/view.jsp?EID=75969
Created: Jun 17, 2000 Modified: 2000-08-11 13:23:50.836
Author: Vincent Cirel (http://www.jguru.com/guru/viewbio.jsp?EID=69061) Question
originally posed by Leonid Blokh
(http://www.jguru.com/guru/viewbio.jsp?EID=64684

Refer to Sun's Servlet API Reference at


http://java.sun.com/products/servlet/2.2/javadoc/
and take a look at Cookie class constructor and methods.

In general:

// create the cookie


Cookie c = new Cookie("stringname","stringvalue");

// 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

You could also use :

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.

See also How do I setup a cookie to expire after a certain time?

What is HTTP tunneling viz. RMI?


Location: http://www.jguru.com/faq/view.jsp?EID=77164
Created: Jun 17, 2000 Modified: 2000-06-21 13:59:18.491
Author: Suja Rao (http://www.jguru.com/guru/viewbio.jsp?EID=62310) Question
originally posed by Nagaraj Sivashanmugam
(http://www.jguru.com/guru/viewbio.jsp?EID=11016

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.

Comments and alternative answers

How is this done ?


Author: Klearhos Klearhou (http://www.jguru.com/guru/viewbio.jsp?EID=540399),
Jul 7, 2002
How somebody could implement that ? Assuming he already has an HTTP server
(that is probably needed).

What is HTTP tunneling, in the general sense?


Location: http://www.jguru.com/faq/view.jsp?EID=74588
Created: Jun 17, 2000 Modified: 2000-06-21 14:00:02.888
Author: Prasad Thammineni (http://www.jguru.com/guru/viewbio.jsp?EID=36479)
Question originally posed by Nagaraj Sivashanmugam
(http://www.jguru.com/guru/viewbio.jsp?EID=11016

HTTP tunneling is a general technique whereby arbitrary data may be sent via an
HTTP connection to and from CGI scripts or Java Servlets on a Web server. This is
done by serializing the data to be transmitted into a stream of bytes, and sending an
HTTP message with content type "application/octet-stream".

HTTP tunneling is also referred to as Firewall tunneling.

Refer to:

• "HTTP Tunneling" for an illustrated example in Java.


• "Firewall Tunneling" for an example of a Java Client connecting to a Java
server through a firewall/proxy.

See also this question in the RMI FAQ.

Comments and alternative answers

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...

RE: What is HTTP tunneling, in the general sense?


Author: Luigi Viggiano (http://www.jguru.com/guru/viewbio.jsp?EID=101985), Jun
24, 2001
Hello,
Suppose your computer is behind a firewall but HTTP connection is allowed and is
made through a proxy server. This is a common scenario, isn't that? You can use the
HTTP Tunneling to connect outside the firewall thru the proxy.
Example: why you are able to connect with you browser to
http://www.somehost.com:8080 if just HTTP port (80) is allowed by the firewall? It's
done thru HTTP tunelling: your browser sends to the proxy an HTTP connection
request like this:
CONNECT www.somehost.com:8080 HTTP/1.0
User-agent: Mozilla/1.1N
then the proxy tunnels the request via HTTP protocol to port 8080 of
www.somehost.com and enstablishes the connection.
The proxy can response something like:
HTTP/1.0 200 Connection established
Proxy-agent: Netscape-Proxy/1.1
200 is the code saying "ok"; if it's <> 200 the connection is not enstablished.

This works just fine for other ports and protocols.


Regards, Luigi.

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

• How do I use the DLLs from Tomcat to Servlet-enable IIS?


• Can I use Tomcat or JavaWebServer as a service on NT?

Comments and alternative answers

Also refer to the recently published article at Use...


Author: Prasad Thammineni (http://www.jguru.com/guru/viewbio.jsp?EID=36479),
Jun 21, 2000
Also refer to the recently published article at Use Microsoft's Internet Information
Server as a Java servlet engine

Re: Also refer to the recently published article at Use...


Author: warrell HARRIES
(http://www.jguru.com/guru/viewbio.jsp?EID=318121), Apr 4, 2001
Where is this article!!!! I have followed the instructions to the letter and can't get
it working!!!

Since the HttpSession object is stored in VM heap memory, is there a limit to


number or size of the HttpSession objects on the server?
Location: http://www.jguru.com/faq/view.jsp?EID=75823
Created: Jun 17, 2000 Modified: 2000-06-17 16:43:23.495
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Amit Singh
(http://www.jguru.com/guru/viewbio.jsp?EID=68394

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.

See also http://www.jguru.com/jguru/faq/view.jsp?EID=44035 and


http://www.jguru.com/jguru/faq/view.jsp?EID=46481

How can I do load balancing using Java Web Server?


Location: http://www.jguru.com/faq/view.jsp?EID=74624
Created: Jun 17, 2000 Modified: 2000-06-17 16:48:55.052
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

Beyond simple HTTP request load balancing you cannot implement advanced load
balancing capabilities with Java Web Server.

See How do I "load balance" my application? for more information.

How do I pick up the attachment from the client's machine, in a web-based


email system?
Location: http://www.jguru.com/faq/view.jsp?EID=81033
Created: Jun 20, 2000 Modified: 2001-07-23 10:50:29.979
Author: Andrea Pompili (http://www.jguru.com/guru/viewbio.jsp?EID=51802)
Question originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

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

<input type="radio" name="topping"


value="pepperoni">Pepperoni

<input type="radio" name="topping"


value="anchovies">Anchovies

If the user selects "Pepperoni" then request.getParameter("topping") will return the


string "pepperoni".

For lists using the <select multiple> FORM tag, multiple values can be returned for
the same parameter name. When that can happen, use
request.getParameterValues("param") which returns a String[] you can iterate
through.

It's bad form (so to speak), but you can also duplicate other element types, like
Name 1: <input type="text" name="name" value="Dick">

Name 2: <input type="text" name="name" value="Jane">

These also get returned in an array by request.getParameterValues().

See http://hotwired.lycos.com/webmonkey/99/30/index4a.html for a good tutorial


on HTML FORMs.

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:

<form method=post action=/servlet/FooServlet>


Value1 <input name="one">
Value2 <input name="two">
Value3 <input name="three">
<input type=submit>
</form>

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>

");

//print out the value of 2nd input element

pw.println("<h2>Two: "+two[0]+"</h2>

");

//print out the value of 3rd input element


pw.println("<h2>Three: "+three[0]+"</h2>

");

Comments and alternative answers

Great for early servlets


Author: John Hollingsworth (http://www.jguru.com/guru/viewbio.jsp?EID=487396),
Aug 30, 2001
...but how do I use this with J2EE 1.3 without getting a deprication warning?
HttpUtils is a depricated object now....

Re: Great for early servlets


Author: Gundluri Manjula
(http://www.jguru.com/guru/viewbio.jsp?EID=1047986), Jan 22, 2003
We can use request.getParameterNames() which will return Enumeration of
element names in the page
for example we have created the form
Page1.jsp
<html>
<body>
<form method="post" action="page2.jsp">
<input type="text" name="one">
<input type="text" name="two">
<input type="text" name="three">
<input type="submit" value="Test">
</form>
</body>
</html>
page2.jsp
<html>
<body>
<form >
<%@ page import="java.util.*" %>
<%
String str = null;
Enumeration enum = request.getParameterNames();
while(enum.hasMoreElements()){
str = (String)enum.nextElement();
out.println(request.getParameter(str)+"
");
}
%>
</form>
</body>
</html>
The result of this form will be the values entered in the previous form

How do I separate presentation (HTML) from business logic (Java) when


using servlets?
Location: http://www.jguru.com/faq/view.jsp?EID=91180
Created: Jun 29, 2000 Modified: 2001-01-15 08:28:54.918
Author: Joe Morse (http://www.jguru.com/guru/viewbio.jsp?EID=91113)

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.

2. Use a templating/parsing system: Hmm...I know you're about to rant about


re-inventing the wheel, but it's not that bad (see below). Plus, it really does pay to
take this approach; you can have a group of programmers working on the Java code,
and a group of HTML producers maintaining the interface. So now you probably want
to know how to do it...so read on.

Use SSI!
Remember SSI? It hasn't gotten much attention in recent years because of
embeddable scripting languages like ASP and JSP, but it still remains a viable option.
To leverage it in the servlet world, I believe the best way is to use an API called SSI
for Java from Areane. This API will let you emulate SSI commands from a templating
system, and much more. It will let you execute any command on any system,
including executing java classes! It also comes with several utility classes for creating
stateful HTML form elements, tables for use with iteration, and much more. It's also
open source, so it's free and you can tweak it to your heart's content! You can read
the SSI for Java documentation for detailed info, but the following is an example of
its use.
Here's the servlet:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import com.areane.www.ssi.*;

public class SSITemplatingServlet extends HttpServlet {


private String templateFilesDirectory =
"d:\\projects\\idemo\\templates\\"; //Holds path to template files

/**Handles GET requests; defers every request to the POST


processor*/
public void doGet(HttpServletRequest req, HttpServletResponse
res)
throws ServletException, IOException,
FileNotFoundException {doPost(req, res);}

/**Handles all requests. Processes the request,


*saves the values, parses the file, then feeds the file to the
out stream*/
public void doPost(HttpServletRequest req, HttpServletResponse
res)
throws ServletException, IOException,
FileNotFoundException {
HttpSession ses = req.getSession(true);

Properties context = null;


if((context = (Properties)ses.getValue("user.context"))
== null) { //if properties doesn't already exist, create it.
context = new Properties();
}

//Write parameters to Properties object


Enumeration paramNames = req.getParameterNames();
String curName, curVal;
while(paramNames.hasMoreElements()) {
curName = (String)paramNames.nextElement();
curVal = req.getParameter(curName);
context.setProperty(curName, curVal);
}

//Save the values to the session


ses.putValue("user.context", context);

//Parse the page and stream to the client


String templateName = req.getParameter("template");
// Get the file name of the template to use
res.setContentType("text/html");
SsiPage page =
SsiParser.parse(this.templateFilesDirectory + templateName); //Parsing
occurs here
page.write(res.getWriter(), context); //Stream to the
client

page = null; //clean up


}
}

Now, just create a template file, pass the servlet the template file name, and have at
it!
Comments and alternative answers

Don't be afraid of using ONLY servlets! If you want...


Author: Yakov Sirotkin (http://www.jguru.com/guru/viewbio.jsp?EID=6342), Jul 6,
2000
Don't be afraid of using ONLY servlets!

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.

I have found a good article about this subject in ...


Author: Ze'ev B (http://www.jguru.com/guru/viewbio.jsp?EID=2224), Dec 2, 2000
I have found a good article about this subject in JavaWorld called "Solve your servlet-
based presentation problems" at http://www.javaworld.com/javaworld/jw-11-2000/jw-
1103-presentation.html

We have been using webmacro, wich is a free templa...


Author: ido ido (http://www.jguru.com/guru/viewbio.jsp?EID=291815), Jan 3, 2001
We have been using webmacro, wich is a free templating/parsing system. It works
realy well. All of your html files are seperate from the servlet. The home page is
www.webmacro.org. Hope this helps.

A great new "third way" solution -- with...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jan 15, 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.)

Use XML ...


Author: Angus McDonald (http://www.jguru.com/guru/viewbio.jsp?EID=476304),
Aug 14, 2001
The simplest way we have found to do just this is to use XML/XSLT.

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.

XMLC, which Alex mentions above, sounds fantastic, inasmuch as it lets


designers work in tools that only know HTML (but know it well,) so long as those
tools can assign id attributes (which they dang well better be able to!)

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:

<input type=submit name="Direction" value="left"><br>


<input type=submit name="Direction" value="right"><br>
<input type=submit name="Direction" value="up"><br>
<input type=submit name="Direction" value="down"><br>

Then the getParameter("Direction") from the HttpRequest would extract the


value pressed by the user, either "left", "right", "up" or "down". A simple comparision
in the servlet with the these values could occur and processing based on the submit
button would be performed.

Similiarly,for submit buttons with different names on a page, each of these values
could be extracted using the getParameter() call and acted on. However, in a
situation where there are multiple buttons, common practice would be to use one
name and multiple values to identify the button pressed.
Comments and alternative answers

Doesn't work with images


Author: Rob Ellis (http://www.jguru.com/guru/viewbio.jsp?EID=532765), Jan 6,
2002
This doesn't seem to work for submissions using type=image.

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.

Re: Doesn't work with images


Author: Damon Anderson (http://www.jguru.com/guru/viewbio.jsp?EID=775042),
Feb 27, 2002

It still works with TYPE=IMAGE, just a little bit differently. Given:

<INPUT TYPE=IMAGE NAME="foo" VALUE="Save">

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:

<INPUT TYPE=IMAGE NAME="_go_left" SRC="left.gif">


<INPUT TYPE=IMAGE NAME="_go_right" SRC="right.gif">
<INPUT TYPE=IMAGE NAME="_go_up" SRC="up.gif">
<INPUT TYPE=IMAGE NAME="_go_down" SRC="down.gif">

...

Enumeration params = request.getParameterNames();


while (params.hasMoreElements()) {
String param = (String)params.nextElement();
if (param.startsWith("_go_")) {
String direction = param.substring("_go_".length());

// ...
}
}

(Untested, this is just off the top of my head.)

Re[2]: Doesn't work with images


Author: Damon Anderson
(http://www.jguru.com/guru/viewbio.jsp?EID=775042), Feb 27, 2002
Sorry, you also need to check for the ".x" and ".y" suffix and remove/ignore it,
obviously. With that addition, this technique has worked pretty well for me. I
use it for servlet dispatching, and it works with both TYPE=SUBMIT and
TYPE=IMAGE without any backend changes. (It also avoids having to change
any Java code when the HTML designer decides to change VALUE="Submit"
to VALUE="Save".)

Re: Doesn't work with images


Author: Harsh Sugandhi (http://www.jguru.com/guru/viewbio.jsp?EID=401509),
May 2, 2002
Well you can do it by javascript. What you have to do for this is write a Javascript
like this:
<html>
</head>
<script Language="JavaScript">
function changeAction(aForm,aButtonName)
{
if(aButtonName == "A")
aForm.action = A.html
else if(aButtonName == "B")
aForm.action = B.html
else
aForm.action = C.html
}
</script>
</head>
<body>
<form name="abc" action="abc.html" method="Post">
<input type="submit" name="A" value="A"
onClick="changeAction(this.form,this.name)">

<input type="submit" name="B" value="B"


onClick="changeAction(this.form,this.name)">

<input type="submit" name="C" value="C"


onClick="changeAction(this.form,this.name)">
</body>
</html>
Enjoy. Harsh.

Is it possible to use the method ServletContext.getRequestDispatcher() to


ascertain the presence or the absence of a server resource?
Location: http://www.jguru.com/faq/view.jsp?EID=92548
Created: Jul 3, 2000 Modified: 2000-07-03 14:47:26.801
Author: Avi Kak (http://www.jguru.com/guru/viewbio.jsp?EID=26410)

Some examples of servlets in the community literature seem to suggest that


ServletContext.getRequestDispatcher() could be used to determine the presence
or the absence of a server resource. But the truth of the matter is that it cannot.
In what follows, I will first mention an example that is posted at a tutorial at the Java
Developer Connection that could potentially create this wrong impression about the
return value of ServletContext.getRequestDispatcher(). I'll then show a simple
servlet that someone just beginning with servlets could find useful for testing this
method.

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.*;

public class CheckDispatcherServlet extends HttpServlet


{
public void service (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(
"/servlets/nonExistentFile.html"); // for Tomcat3.1
// "/servlets/welcome.html"); // for
Tomcat3.1
// "/WEB-INF/servlets/nonExistentFile.html"); // for
jsdk2.1

System.out.println( "" + dispatcher );

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.)

• For Tomcat3.1, I have placed this servlet in the following directory



• C:\tomcat\webapps\avi-servlets\WEB-INF\classes\

where avi-servlets is a directory that I created for some servlets.

• For jsdk2.1, I put this servlet in



• C:\jsdk2.1\avi-servlets\WEB-INF\servlets\

• Since Tomcat3.1 is not allowed to serve any files under WEB-INF, the
"welcome.html" resource file in the commented out line in the code sits in the
directory

• C:\tomcat\webapps\avi-servlets\servlets\

whereas for jsdk2.1, it can sit in the same directory as the servlet.

What is "hot deployment" in WebLogic?


Location: http://www.jguru.com/faq/view.jsp?EID=97622
Created: Jul 6, 2000 Modified: 2000-07-06 12:37:25.632
Author: Keith Schwartz (http://www.jguru.com/guru/viewbio.jsp?EID=27189)
Question originally posed by rajasekhar pokuri
(http://www.jguru.com/guru/viewbio.jsp?EID=81912
"Hot Deployment" in weblogic is the act of deploying, re-depolying, and un-deploying
EJBs while the server is still running (you don't have to shutdown the server to
deploy an EJB).

see:
http://www.weblogic.com/docs51/classdocs/API_ejb/EJB_deployover.html#1054622

Comments and alternative answers

Also, the beans that are "Hot Deployed" are...


Author: Anoop Sehdev (http://www.jguru.com/guru/viewbio.jsp?EID=208040), Sep
17, 2000
Also, the beans that are "Hot Deployed" are not retained when the server is restarted.
To retain the bean, it's entry has to be made in the weblogic.properties file.

Regards
Anoop Sehdev

What is meant by the term "business logic"?


Location: http://www.jguru.com/faq/view.jsp?EID=97696
Created: Jul 6, 2000 Modified: 2000-07-06 13:17:00.956
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Ramkumar Krishnamurthy
(http://www.jguru.com/guru/viewbio.jsp?EID=89709

"Business logic" is just a fancy way of saying "code." :-)

More precisely, in a three-tier architecture, business logic is any code that is not
specifically related to storing and retrieving data (that's "data storage code"), or to
formatting data for display to the user (that's "presentation logic"). It makes sense,
for many reasons, to store this business logic in separate objects; the middle tier
comprises these objects. However, the divisions between the three layers are often
blurry, and business logic is more of an ideal than a reality in most programs. The
main point of the term is, you want somewhere to store the logic and "business
rules" (another buzzword) of your application, while keeping the division between
tiers clear and clean.

Can an EJB handle (RMI remote reference) be stored in an HttpSession?


Location: http://www.jguru.com/faq/view.jsp?EID=97963
Created: Jul 7, 2000 Modified: 2000-07-09 06:39:45.243
Author: David Garcia (http://www.jguru.com/guru/viewbio.jsp?EID=17915) Question
originally posed by David Garcia
(http://www.jguru.com/guru/viewbio.jsp?EID=17915

[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?).

Comments and alternative answers

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

To offer printing from an applet in order to print on the client computer, is


the only good solution to have a print servlet and upload the print file from
the applet to the servlet and then download the print file back to the client
browser?
Location: http://www.jguru.com/faq/view.jsp?EID=98857
Created: Jul 9, 2000 Modified: 2000-07-13 08:33:35.487
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by ananda bagley
(http://www.jguru.com/guru/viewbio.jsp?EID=75027

Yes! :-)

That reminds me of a riddle:

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.)

Comments and alternative answers

A few other possibilities that come to mind are: Set...


Author: Andre van Dalen (http://www.jguru.com/guru/viewbio.jsp?EID=7570), Jul
17, 2000
A few other possibilities that come to mind are:
• Set the MAYSCRIPT parameter in your applet tag and call a JavaScript
subroutine with the data you want to get printed / shown. The javascript
subroutine can then write that data into a frame to get it printed. See this FAQ
for a code example.
• Copy the data onto the clipboard and have the user or some JavaScript paste it
before printing it.
• Have a servlet generate the document based on parameters posted by the
applet

Another option is print from the applet using the ...


Author: delfim martins (http://www.jguru.com/guru/viewbio.jsp?EID=9614), Jul 21,
2000
Another option is print from the applet using the PrintJob. The only disadvantage is
that you will have to sign the applet and the user will have to trust you. However, with
this method you have full control of what is going to the printer.

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:

In the override definitions of the doGet(HttpServletRequest,


HttpServletResponse) method in the files CatalogServlet.java,
ShowCartServlet.java, Cashier.servlet, BookDetailServlet.java, and in the
override definition of the doPost(HttpServletRequest, HttpServletResponse)
method in the file ReceiptServlet.java, replace the invocation

ShoppingCart cart =
(ShoppingCart)session.getValue(session.getId());

by

ShoppingCart cart =
(ShoppingCart)session.getAttribute(session.getId());

and the invocation

session.putValue(session.getId(), cart);
by

session.setAttribute(session.getId(), cart);

The methods getValue(String) and putValue(String, Object) declared for the


HttpSession interface have been deprecated in the Servlet2.2 API and replaced by
the getAttribute(String) and setAttribute(String, Object) methods.

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

This would be useful for reattaching a user to a preexisting session. [Unfortunately,


this behavior has been deemed dangerous. The code below used to work, but has
been deprecated as of Servlet API version 2.1. (The method
HttpSessionContext.getSession(String sessionid) has been deprecated.)

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);

// next, maybe in another servlet or object


// recover target ID
String idOldSesion=database.recoverID();

// recover target HttpSession


HttpSession currentSesion=request.getSession(false);
HttpSessionContext sCtx=currentSesion.getSessionContext();
HttpSession recoveredOldSesion=sCtx.getSession(idOldSesion);

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.

Can JRun be configured so that it converts GET or POST parameters encoded


in UTF-8 correctly into Unicode for use in the Java servlet?
Location: http://www.jguru.com/faq/view.jsp?EID=100767
Created: Jul 12, 2000 Modified: 2000-07-18 02:55:27.27
Author: Andy Malakov (http://www.jguru.com/guru/viewbio.jsp?EID=89102)
Question originally posed by Frank Renftle
(http://www.jguru.com/guru/viewbio.jsp?EID=94444

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 &#123; 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)

If getHeader("User-Agent") returns "WebTV", then your client is using a WebTV


browser and you can customize the display accordingly.

Can I use Basic HTTP Authentication using Apache+JServ?


Location: http://www.jguru.com/faq/view.jsp?EID=103759
Created: Jul 17, 2000 Modified: 2000-07-21 19:19:08.246
Author: Joshua Lynch (http://www.jguru.com/guru/viewbio.jsp?EID=103303)
Question originally posed by Mike Reedy
(http://www.jguru.com/guru/viewbio.jsp?EID=98127

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:

<Location /your/servlet/url >


AuthName "your realm"
AuthType Basic
AuthUserFile /your/user/file
require valid-user
</Location>
This <Location> directive tells Apache to restrict access to the specified URL, so
don't use the filesystem path to your servlet. Use the servlet's URL.

You will also need to create a user file with htpasswd. See the Apache Week article
for details.

Comments and alternative answers

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...

Can I call a CGI script from a servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=104987
Created: Jul 18, 2000 Modified: 2000-07-19 20:31:41.242
Author: Shirish Bathe (http://www.jguru.com/guru/viewbio.jsp?EID=88588)
Question originally posed by anshu shah
(http://www.jguru.com/guru/viewbio.jsp?EID=88223

[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)

public void doPost(HttpServletRequest request,


HttpServletResponse response)
throws IOException, ServletException {

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());

//Sending parameter to URL/CGI


outStream.println("dataname="
+ URLEncoder.encode("Shirish")+"&datavalue="
+ URLEncoder.encode("Bathe"));
//outStream.println("dataname=Shirish&datavalue=Bathe");

outStream.flush();
outStream.close();

// reading from URL


DataInputStream inStream;
String inputLine;

inStream = new DataInputStream(connection.getInputStream());


while (null != (inputLine = inStream.readLine())) {
//System.out.println(inputLine);
out.println(inputLine);
}
inStream.close();
} catch (MalformedURLException me) {
System.err.println("MalformedURLException: " + me);
} catch (IOException ioe) {
System.err.println("IOException: " + ioe);
}
For detail please visit :
http://java.sun.com/docs/books/tutorial/networking/urls/readingWriting.html.

Hope this will solve your problem.

Comments and alternative answers

What if the call from the servlet to the CGI is not...


Author: Pat Hong (http://www.jguru.com/guru/viewbio.jsp?EID=222295), Oct 4,
2000
What if the call from the servlet to the CGI is not a simple URL call, but a call to a
perl module (in CGI)? And vise versa?

Here's a servlet wrapper that makes it easy.


Author: Roger Hand (http://www.jguru.com/guru/viewbio.jsp?EID=292314), Jun 14, 2001
Some of the code provided above has been deprecated. Here's a more up-to-date (servlet
spec 2.2) example that I have made into a servlet for easy use (see useage example at top). I
have used this servlet to successfully pass html form values to a legacy cgi (via POST)
along with additional values from the Java app. Since you're basically intercepting the
request you can do whatever you want with the parameters, and the user will never see the
parameters you add since they never hit his browser, not even as hidden fields. BTW, I
haven't tested the functionality to add headers much, but believe it should work.

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();

/* by default, we pass existing params from the originating page,


but this can be suppressed if desired. */
private boolean passExistingParams = true;

/**Initialize global variables*/


private static final String CONTENT_TYPE = "text/html";
private static final int ARRAY_POS_PARAMNAME = 0;
private static final int ARRAY_POS_PARAMVALUE = 1;
private static final int ARRAY_POS_HEADERNAME = 0;
private static final int ARRAY_POS_HEADERVALUE = 1;
private static final boolean debug = true;

public void init(ServletConfig config) throws ServletException {


super.init(config);
}
public void setParam(String paramName, String paramValue) {
String[] arrayParamName_Value = {paramName,
URLEncoder.encode(paramValue)};
vectParams.add(arrayParamName_Value);
}

public void setParam(String paramName, int paramValue) {


setParam(paramName, Integer.toString(paramValue));
}

public void setHeader(String headerName, String headerValue) {


String[] arrayHeaderName_Value = {headerName, headerValue};
vectHeaders.add(arrayHeaderName_Value);
}

public void Go(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
boolean debug = false;
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();

try{

/**
* First we SEND the request to the web server
*/

URL url = new URL(urlForward);


URLConnection connection = url.openConnection();
connection.setDoOutput(true);

if (debug) System.out.println("Opened connection to " +


urlForward);

/* ADD our NEW HEADERS here */


/* We don't pass on any existing headers
It could be we may want to pick and choose a few to send on */
for (int iHeader = 0;iHeader < vectHeaders.size(); iHeader++) {
String[] arrayHeaderName_Value =
(String[])vectHeaders.get(iHeader);
connection.setRequestProperty(arrayHeaderName_Value[ARRAY_POS_HE
ADERNAME], arrayHeaderName_Value[ARRAY_POS_HEADERVALUE]);
if (debug) System.out.println("Added header " +
arrayHeaderName_Value[ARRAY_POS_HEADERNAME] +
" with value " +
arrayHeaderName_Value[ARRAY_POS_HEADERVALUE]);
} //next header

PrintStream outStream =
new PrintStream(connection.getOutputStream());

/* Pass on EXISTING PARAMS here (if desired)


These are parameters set in the original form from the browser.
It seems we should just be able to pass them on, but I haven't
found a way,
so we've gotta recreate them here.
*/
String paramString = "";
if (passExistingParams) {
Enumeration enumPNames = request.getParameterNames();

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) {

/* ADD our NEW PARAMS here */


for (int iParam = 0;iParam < vectParams.size(); iParam++) {
String[] arrayParamName_Value =
(String[])vectParams.get(iParam);
paramString += arrayParamName_Value[ARRAY_POS_PARAMNAME] + "=" +
arrayParamName_Value[ARRAY_POS_PARAMVALUE] + "&";
} //next parameter

/* get rid of last '&' */


if (paramString.endsWith("&")) {
paramString = paramString.substring(0, paramString.length() -
1);
}

if (debug) System.out.println("paramString is " + paramString);


//Sending parameter to URL/CGI
outStream.println(paramString);

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()));

/* this was in example, but is deprecated usage */


//inStream = new DataInputStream(connection.getInputStream());
while (null != (inputLine = inStream.readLine())) {
out.println(inputLine);
}
inStream.close();
} catch (MalformedURLException me) {
System.err.println("MalformedURLException: " + me);
} catch (IOException ioe) {
System.err.println("IOException: " + ioe);
}
vectParams.clear();

/**Clean up resources*/
public void destroy() {
}
public void setUrlForward(String newUrlForward) {
urlForward = newUrlForward;
}
public void setPassExistingParams(boolean newPassExistingParams) {
passExistingParams = newPassExistingParams;
}
}

How can I load a resource file from a servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=106003
Created: Jul 19, 2000 Modified: 2001-07-17 09:54:31.996
Author: Shirish Bathe (http://www.jguru.com/guru/viewbio.jsp?EID=88588)
Question originally posed by Anh Le
(http://www.jguru.com/guru/viewbio.jsp?EID=9885

[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.*;

public class ResourceServlet extends HttpServlet {


ResourceBundle rb = null;

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws IOException, ServletException {
response.setContentType("text/html");

PrintWriter out = response.getWriter();


HttpSession session = request.getSession(true);

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>");
}

public void doPost(HttpServletRequest request,


HttpServletResponse response)
throws IOException, ServletException
{
doGet(request, response);
}

------------------- LocaleStrings.properties ---------------------


Question=How are you?
title=This page is in english

------------------- LocaleStrings_fr.properties ---------------------


Question=Comment allez-vous?
title=This page is in Franch

------------------- LocaleStrings_de.properties ---------------------


Question=Wie geht es Ihnen?
title=This page is in German

Hope it is solution you required?

Have a nice day...

Shirish
(bathe@satyamonline.com)

Comments and alternative answers

I used a different method to get user's language within...


Author: Stefano Bussolon (http://www.jguru.com/guru/viewbio.jsp?EID=132699),
Sep 21, 2000
I used a different method to get user's language within a servlet:
Locale loc = Locale.ENGLISH; // the default
String language = request.getHeader("Accept-Language");
if (language == null) return loc;
if (language.equalsIgnoreCase ("en")) {
loc = Locale.ENGLISH;
}
if (language.equalsIgnoreCase ("it")) {
loc = Locale.ITALIAN;
}
if (language.equalsIgnoreCase ("de")) {
loc = Locale.GERMAN;
}
// and so on for fr, es ....
return loc;

Stefano

Stefano's comment is accurate as long as the browser...


Author: Jean-Baptiste Quenot
(http://www.jguru.com/guru/viewbio.jsp?EID=214329), Jan 23, 2001
Stefano's comment is accurate as long as the browser accepts only one language. If
this is not the case, its code will fail. Instead, one has to split the header according to
';'s and trim the extra space.

What is a servlet bean?


Location: http://www.jguru.com/faq/view.jsp?EID=107022
Created: Jul 20, 2000 Modified: 2000-07-20 18:57:40.945
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by shiva vithal
(http://www.jguru.com/guru/viewbio.jsp?EID=55743

A servlet bean is a serializable servlet that follows the JavaBeans component


architecture, basically offering getter/setter methods.

As long as you subclass GenericServlet/HttpServlet, you are automatically


Serializable.

If your web server supports them, when you install the servlet in the web server, you
can configure it through a property sheet-like interface.

Why do we need to call super.init(config) in the init method of a servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=108815
Created: Jul 23, 2000 Modified: 2000-07-24 19:44:53.011
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Sridhar Nama
(http://www.jguru.com/guru/viewbio.jsp?EID=100882

Just do as you're told and you won't get hurt! :-)

Because if you don't, then the config object will get lost. Just extend HttpServlet, use
init() (no parameters) and it'll all work ok.

From the Javadoc: init() - A convenience method which can be overridden so that
there's no need to call super.init(config).

Comments and alternative answers


since the Servlet interface defines a method called...
Author: Arindam Chattopadhya
(http://www.jguru.com/guru/viewbio.jsp?EID=340736), Feb 28, 2001
since the Servlet interface defines a method called getServletConfig(),you should
either save the servletconfig object and implement the getServletConfig()method
yourself or pass the object to the parent class using super.init(). However this is done
for backward compatibility(before version 2.1).In version 2.1 you don't require to call
that super.init()

Re: since the Servlet interface defines a method called...


Author: Igor Zelfon (http://www.jguru.com/guru/viewbio.jsp?EID=517887), Oct
11, 2001
Where do you set the parameters for the config objects in Visual Cafe4? Thanks,
Igor. Please reply by e-mail to izelfon@fleetcc.com

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

The only means of communicating between a Servlet to ASP is via standard


GET/POST mechanisms, like by submitting a FORM. Either adding information to the
URL or passing in the request header. You can simulate the FORM submittal yourself,
or just have it be the ACTION of the FORM.
Comments and alternative answers

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):

public void testWelcomePage() throws Exception {


WebConversation conversation = new WebConversation();
WebRequest request = new GetMethodWebRequest(
"http://www.meterware.com/servlet/TopSecret" );

WebResponse response = conversation.getResponse( request );


WebForm forms[] = response.getForms();
assertEquals( 1, forms.length );
assertEquals( 1, forms[0].getParameterNames().length );
assertEquals( "name", forms[0].getParameterNames()[0] );
}
With a little training, test cases of this sort can be written by an HTML developer and
run against the user interface on a regular basis.
Comments and alternative answers

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.

Using Xalan from Apache you can do this:

import org.apache.xpath.XPathAPI;
import org.w3.dom.*;

Node responseRoot = response.getDOM().getDocumentElement();


NodeList tableRows = XPathAPI.selectNodeList(responseRoot,
"//table[@id='mytable']/tr");
assertEquals(10, tableRows.getLength());

This will test if the table in the response with the id attribute 'mytable' contains 10
rows.

What is a servlet engine?


Location: http://www.jguru.com/faq/view.jsp?EID=112410
Created: Jul 27, 2000 Modified: 2000-07-27 06:47:04.632
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by karuppanan rameshkumar
(http://www.jguru.com/guru/viewbio.jsp?EID=102591
A "servlet engine" is a program that plugs in to a web server and runs servlets. The
term is obsolete; the preferred term now is "servlet container" since that applies
both to plug-in engines and to stand-alone web servers that support the Servlet API.

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

Your question really should be broken in two.

1-What is the most efficient way of serving pages from a Java object?. There you
have a clear winner in the Servlet. Althought if you are going to change the static
content of the page often is going to be a pain because you'll have to change Java
code. The second place in speed is for JSP pages. But, depending on your
application, the difference in speed between JSP pages and raw servlets can be so
small that is not worth the extra work of servlet programming.

2-What is the most efficient way of accessing a database from Java?. If JDBC is the
way you want to go the I'd suggest to pick as many drivers as you can (II,III,IV or
wathever) and benchmark them. Type I uses a JDBC/ODBC bridge and usually has
lousy performance. Again, go for the simplest (usually type IV driver) solution if that
meets you performance needs.

For database applications, the performance bottleneck is usually the database, not
the web server/engine. In this case, the use of a package that access JDBC with
connection pooling at the application level used from JSP pages (with or withouth
beans as middleware) is the usual choice. Of course, your applications requirements
may vary.

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:

1. Access tool (http://hostname:9090)


2. Enter User Id/Password (by default it is admin/admin)
3. Select service (Web service)
4. Click on "manage" button. You will get a popup screen with all settings.
5. Click on network tree node, On right hand side you will get text box for entering
port no.
6. Change port number with desire one.
7. click on restart button.

Hope this is solution for the problem. In case If you want more info please contact
me on bathe@satyamonline.com

Thanks

Shirish

I have created a remote reference to an EJB in FirstServlet. Can I put the


reference in a servlet session and use that in SecondServlet?
Location: http://www.jguru.com/faq/view.jsp?EID=114024
Created: Jul 29, 2000 Modified: 2000-07-29 05:59:08.95
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Nagaraj shyagale
(http://www.jguru.com/guru/viewbio.jsp?EID=29160

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.

Can I send multiple responses for a single request?


Location: http://www.jguru.com/faq/view.jsp?EID=114957
Created: Jul 31, 2000 Modified: 2000-07-31 05:02:36.133
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Deepak Kulkarni
(http://www.jguru.com/guru/viewbio.jsp?EID=84086

No. That doesn't even make sense :-)

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:

1. HTTP Basic Authentication

An authentication protocol defined within the HTTP protocol (and based on


headers). It indicates the HTTP realm for which access is being negotiated and
sends passwords with base64 encoding, therefore it is not very secure. (See
RFC2068 for more information.)

2. HTTP Digest Authentication

Like HTTP Basic Authentication, but with the password transmitted in an


encrypted form. It is more secure than Basic, but less then HTTPS
Authentication which uses private keys. Yet it is not currently in widespread
use.

3. HTTPS Authentication (SSL Mutual Authentication)

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.

4. Form Based Login


A standard HTML form (static, Servlet/JSP or script generated) for logging in.
It can be associated with protection or user domains, and is used to
authenticate previously unauthenticated users.
The major advantage is that the look and feel of the login screen can be
controlled (in comparison to the HTTP browsers' built in mechanisms).

To support 1., 3., and 4. of these authentication mechanisms is a requirement of the


J2EE Specification (as of v1.2, 3.4.1.3 Required Login Mechanisms). (HTTP Digest
Authentication is not a requirement, but containers are encouraged to support it.)

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.

Here is a sample of a conforming HTML login form:

<form method="POST" action="j_security_check">


<input type="text" name="j_username">
<input type="password" name="j_password">
</form>

Known Servlet containers that support FORM-based login are:

• iPlanet Application Server


• Tomcat (the reference implementation of the Java Servlet API)

URL Pointers:

1. Java Servlet API Specification 2.2


2. J2EE Platform Specification

Comments and alternative answers

The above form is incorrect. The parameter should read...


Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362), Jan
17, 2001
The above form is incorrect. The parameter should read j_username, not j_user_name.

This feature is also supported in WebLogic 5.1 (I tested with sp8) and 6.0

[OK, I've fixed it above. -Alex]


See also
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Oct 19, 2001
See also form based authentication

With regard to automatic servlet reloading in Tomcat 3.1, what happens if


one servlet makes references to other servlets in the same webapp? Will
automatic reloading get enabled for all such servlets?
Location: http://www.jguru.com/faq/view.jsp?EID=115575
Created: Jul 31, 2000 Modified: 2000-08-03 21:04:55.078
Author: Avi Kak (http://www.jguru.com/guru/viewbio.jsp?EID=26410)

The short answer to the question is: No.

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.

To demonstrate this behavior of Tomcat 3.1, I have constructed the following


example that consists of two simple mutually referencing servlets called
TestServlet_1 and TestServlet_2. In my Tomcat 3.1 container, both these servlets
are in a webapp called test-suite and reside in the directory
TOMCAT_HOME/webapps/test-suite/WEB-INF/classes. In accordance with the jGuru
FAQ posting, I have enabled automatic reloading for this webapp by including the
following element in the server.xml file in the TOMCAT_HOME/conf directory:

<Context path="/test-suite" docBase="webapps/test-suite" debug="0"


reloadable="true" > </Context>

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.

Here is the code for the two servlets:

////////// file: TestServlet_1.java //////////

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class TestServlet_1 extends HttpServlet {

public void init() throws ServletException


{
System.out.println("TestServlet_1 being loaded into the
container");
}

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType( "text/html" );
PrintWriter out = response.getWriter();

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>" );
}
}

////////// file: TestServlet_2.java //////////

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class TestServlet_2 extends HttpServlet {

public void init() throws ServletException


{
System.out.println("TestServlet_2 being loaded into the
container");
}

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType( "text/html" );
PrintWriter out = response.getWriter();

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

As far as i know it depends on the location of the next target url.

• 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]

Comments and alternative answers


The second alternative holds good only for GET request...
Author: Shailesh Dangi (http://www.jguru.com/guru/viewbio.jsp?EID=97397), Jan
12, 2001
The second alternative holds good only for GET request where the parameters are
encoded in the query String in the URL.

How do you deal with POST?

[See http://www.jguru.com/jguru/faq/view.jsp?EID=231318 for the answer. -A]

Wrapper to make it easy . . .


Author: Roger Hand (http://www.jguru.com/guru/viewbio.jsp?EID=292314), Jun 18,
2001
See my alternative answer about a servlet wrapper I wrote to make this easy, at:
http://jguru.com/faq/view.jsp?EID=104987

Re: Wrapper to make it easy . . .


Author: Tommy Skodje (http://www.jguru.com/guru/viewbio.jsp?EID=446264),
Jul 10, 2001
I used Roger's code, with some modifications needed to pass on sessionid. Just
thought that someone else might need to do the same, here it is:
package com.ragingnet.util;

import java.io.*;
import java.util.*;
import java.net.*;

import javax.servlet.*;
import javax.servlet.http.*;

/** 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]
* setPassExistingHeaders(boolean) [optional - default is
TRUE]
* setParam(paramName, paramValue) [multiple times if
desired]
* setHeader(headerName, headerValue) [multiple times if
desired]
*
* Then call Go(request, stream): response is written to stream
*
* @author Roger Hand, Tommy Skodje
* @date June 27, 2001
* Downloaded from jguru.
*/
public class PassPostRequestServlet { // extends HttpServlet {
private String urlForward = null;
private Vector vectParams = new Vector();
private Vector vectHeaders = new Vector();

/* by default, we pass existing params from the originating


page,
but this can be suppressed if desired. */
private boolean passExistingParams = true;
private boolean passExistingHeaders = true;

/**Initialize global variables*/


private static final String CONTENT_TYPE = "text/html";
private static final int ARRAY_POS_PARAMNAME = 0;
private static final int ARRAY_POS_PARAMVALUE = 1;
private static final int ARRAY_POS_HEADERNAME = 0;
private static final int ARRAY_POS_HEADERVALUE = 1;
private static final boolean debug = false; // true;

public void init(ServletConfig config) throws ServletException {


// super.init(config);
}

public void setParam(String paramName, String paramValue) {


String[] arrayParamName_Value = {paramName,
URLEncoder.encode(paramValue)};
vectParams.add(arrayParamName_Value);
}

public void setParam(String paramName, int paramValue) {


setParam(paramName, Integer.toString(paramValue));
}

public void setHeader(String headerName, String headerValue) {


String[] arrayHeaderName_Value = {headerName, headerValue};
vectHeaders.add(arrayHeaderName_Value);
}

/** Should pass on request to desired url, and return result


in outBuf */
public void Go(HttpServletRequest request , OutputStream
outBuf ) {
try{
PrintWriter out = new PrintWriter( outBuf );
// First we SEND the request to the web server
URL url = new URL(urlForward);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);

if (debug) System.out.println("Opened connection to " +


urlForward);
// Pass on EXISTING HEADERS here (if desired)
if (passExistingHeaders) {
Enumeration enumHNames = request.getHeaderNames();
while(enumHNames.hasMoreElements()) {
String headerName = (String)enumHNames.nextElement();
Enumeration enumHeaders = request.getHeaders(
headerName );
while ( enumHeaders.hasMoreElements() )
setHeader( headerName, (String)
enumHeaders.nextElement() );
}
} //if (passExistingHeaders) {

// ADD our NEW HEADERS here


for (int iHeader = 0;iHeader < vectHeaders.size();
iHeader++) {
String[] arrayHeaderName_Value =
(String[])vectHeaders.get(iHeader);
connection.setRequestProperty(
arrayHeaderName_Value[ARRAY_POS_HEADERNAME] ,
arrayHeaderName_Value[ARRAY_POS_HEADERVALUE]
);
if (debug) System.out.println("Added header " +
arrayHeaderName_Value[ARRAY_POS_HEADERNAME] +
" with value " +
arrayHeaderName_Value[ARRAY_POS_HEADERVALUE]);
} //next header

PrintStream outStream =
new PrintStream(connection.getOutputStream());

/* Pass on EXISTING PARAMS here (if desired)


These are parameters set in the original form from the
browser.
It seems we should just be able to pass them on, but I
haven't found a way,
so we've gotta recreate them here.
*/
String paramString = "";
if (passExistingParams) {
Enumeration enumPNames = request.getParameterNames();

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) {

// ADD our NEW PARAMS here


for (int iParam = 0;iParam < vectParams.size(); iParam++)
{
String[] arrayParamName_Value =
(String[])vectParams.get(iParam);
paramString +=
arrayParamName_Value[ARRAY_POS_PARAMNAME] + "=" +
arrayParamName_Value[ARRAY_POS_PARAMVALUE] + "&"
;
} //next parameter

/* get rid of last '&' */


if (paramString.endsWith("&")) {
paramString = paramString.substring(0,
paramString.length() - 1);
}

if (debug) System.out.println("paramString is " +


paramString);
//Sending parameter to URL/CGI
outStream.println(paramString);

outStream.flush();
outStream.close();

// RECEIVE response from web server and pass it back

String inputLine;

BufferedReader inStream =
new BufferedReader( new
InputStreamReader(connection.getInputStream()));

// this was in example, but is deprecated usage


//inStream = new
DataInputStream(connection.getInputStream());
while (null != (inputLine = inStream.readLine())) {
out.println(inputLine);
}
inStream.close();
out.flush();
out.close();
} catch (MalformedURLException me) {
System.out.println("MalformedURLException: " + me);
} catch (IOException ioe) {
System.out.println("IOException: " + ioe);
} catch (Throwable t) {
System.out.println("Exception: " + t.toString() );
}
vectParams.clear();
vectHeaders.clear();
} // Go
/** Clean up resources */
public void destroy() { }
public void setUrlForward(String newUrlForward) { urlForward =
newUrlForward; }
public void setPassExistingParams( boolean newPassExistingParams
) {
passExistingParams = newPassExistingParams;
}
public void setPassExistingHeaders( boolean
newPassExistingHeaders ) {
passExistingHeaders = newPassExistingHeaders;
}

} // class

I cant get the first example to work


Author: Michael O Connor (http://www.jguru.com/guru/viewbio.jsp?EID=412596),
Jun 22, 2001
I'm using tomcat 3.2 , and have changed the HelloWorldExample servlet supplied to
include the forward lines

RequestDispatcher rd = null;
String targetURL = "/examples/servlet/teststartpage3";
ServletContext ctx = this.getServletContext();
rd = ctx.getRequestDispatcher(targetURL);
rd.forward(request,response);

And still all i get is a blank page on helloworldexample when i run it

Re: I cant get the first example to work


Author: mike cunneen (http://www.jguru.com/guru/viewbio.jsp?EID=455381), Jul
25, 2001
try changing the url from:
/examples/servlet/teststartpage3
to:
/textstartpage3

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

Comments and alternative answers

disabling use of cookies for sessions in tomcat


Author: Bob Rudis (http://www.jguru.com/guru/viewbio.jsp?EID=494420), Nov 28,
2001
in server.xml, you need to create a Context entry for your web app and add:
cookies="false"
in order for it to not use cookies by default.

Re: disabling use of cookies for sessions in tomcat


Author: Vipul Garg (http://www.jguru.com/guru/viewbio.jsp?EID=799638), May
8, 2002
I tried to set cookie="false" for my context entry but when I restart my server after
making changes the servet.xml file is reloaded and the changes made are lost.
More clues regarding this will be helpful. Let me know if there is any setting to be
done to not change the server.xml file on restarting of the server. regds, vipul

What about 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.

Re: What about jsessionid ?


Author: Minh NGO
(http://www.jguru.com/guru/viewbio.jsp?EID=1224287), Jan 31, 2005
Since the <html:form> tag uses response.encodeURL(), it will append the
jsessionId value in the action attribute of the form if cookies are disabled

When using JavaMail with the Java WebServer, I get an


AccessControlException. How do I disable the security checks to permit
this?
Location: http://www.jguru.com/faq/view.jsp?EID=117574
Created: Aug 2, 2000 Modified: 2000-08-13 16:29:50.283
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

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

Have you tried calling flush() on the ServletOutputStream?


Comments and alternative answers

We've tried things like setting the buffer size in...


Author: Ofer Shaked (http://www.jguru.com/guru/viewbio.jsp?EID=62619), Aug 4,
2000
We've tried things like setting the buffer size in Tomcat and calling flush(). In fact,
when using Tomcat alone, it works fine. The thing is that when using it in
combination with Apache and the JServ module it looks as if apache insists on
buffering anyway.

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:

J2SDK 1.3.0 introduced a HTTP/1.1 client implementation. Web servers


such as Apache return chunked encoded response to HTTP 1.1 clients, but
the chunked encoding handling of J2SDK 1.3.0 and 1.3.1 don't stream the
chunked response from the server. In practice, this means that methods
such as java.net.URLConnection.getInputStream don't return until the
server's response is finished. This problem is described in bug 4333920.
Workaround: For Apache, the workaround is to put the following in
following in httpd.conf

BrowserMatch "Java1\.3\..[0-1]" downgrade-1.0

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

Is there an alternate solution to this


Author: Anuj Murarka (http://www.jguru.com/guru/viewbio.jsp?EID=558146), Apr 3,
2002
The solutions works fine. But when this package is integrated with my applet the size
goes up drastically and my applet takes ages while downloading to the browser. Is
there any other short alternative of doing the upload. Some means where file data
stream can be posted to my servlet that handles the upload job.

In some of the Servlet2.2 API, eg. getSession(boolean create), it says that


"you must call this method before the response is committed". What does it
mean by "committing" the response?
Location: http://www.jguru.com/faq/view.jsp?EID=119666
Created: Aug 4, 2000 Modified: 2000-08-08 01:10:35.882
Author: Prasad Thammineni (http://www.jguru.com/guru/viewbio.jsp?EID=36479)
Question originally posed by jon c
(http://www.jguru.com/guru/viewbio.jsp?EID=109673
In Servlet 2.2 API, a servlet container is allowed to buffer the response in order to
improve performance. The output and header information that is written to the
response object is buffered and usually flushed or committed when the doPost(),
doGet() or service() method returns. You can also flush the buffer programmatically.
Once the buffer is flushed or committed, any headers you set will be ignored by the
container. That is what the specification is referring to when it says that certain
methods should be called before the response is committed.

Where do I specify JVM system properties for a servlet container? For an


application, I would say "java -Dfoo=bar ..." [Note: this will have many
answers, for the many engines]
Location: http://www.jguru.com/faq/view.jsp?EID=119671
Created: Aug 4, 2000 Modified: 2000-08-08 00:50:05.851
Author: Prasad Thammineni (http://www.jguru.com/guru/viewbio.jsp?EID=36479)
Question originally posed by Amol Kher
(http://www.jguru.com/guru/viewbio.jsp?EID=91021

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)

The Java Developer Connection tutorial on servlets contains a very instructive


example that shows how servlet can be used for processing HTML forms. This
example was written for JSDK 2.1.

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

DataInputStream disStructure = new DataInputStream(


fisStructure );

by
BufferedReader disStructure = new BufferedReader( new
InputStreamReader( fisStructure ));

and, in the servlet class file FormDisplayServlet.java, replace the invocation

DataInputStream disData = new DataInputStream( fisData );

by

BufferedReader disData = new BufferedReader( new


InputStreamReader( fisData ) );

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

while ( ( inputLine = disStructure.readLine() ) != null ) {


//....
}

since the method available() is not defined for BufferedReader.

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:

1. In the FormDisplayServlet.java file, change the statement


2.
3. fisData = new FileInputStream(
"c:\\JavaWebServer1.1\\servlets\\" + paramDataFile );
4.

to
fisData = new FileInputStream( "C:/tomcat/webapps/form-
processing/servlets/" + paramDataFile );

5. In the FormDisplayServlet.java file, change the statement


6.
7. out.println( "<form method=POST
ACTION=\"http://localhost:8080/servlet/FormProcessingServlet\">"
);
8.

to

out.println( "<form method=POST


ACTION=\"http://localhost:8080/form-
processing/servlet/FormProcessingServlet\">" );

9. In the FormProcessingServlet.java file, change the statement


10.
11. isStructure = context.getResourceAsStream(
paramStructureFile[0]);
12.

to

isStructure = context.getResourceAsStream( "/servlets/" +


paramStructureFile[0]);

How can the data within an HTML form be refreshed automatically


whenever there is a change in the database?
Location: http://www.jguru.com/faq/view.jsp?EID=121817
Created: Aug 8, 2000 Modified: 2000-08-09 11:36:47.578
Author: David Garcia (http://www.jguru.com/guru/viewbio.jsp?EID=17915) Question
originally posed by nitesh ambastha
(http://www.jguru.com/guru/viewbio.jsp?EID=120716

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]

Perhaps (if possible), could be simpler using an automatic JavaScript refreshing


function that force page reload after a specified time interval.

[Search the FAQ on "redirect" for more information on this technique. -Alex]

Comments and alternative answers

You might like to check out PUSHLETS on www.justob...


Author: Christopher Morrison (http://www.jguru.com/guru/viewbio.jsp?EID=97335),
Aug 9, 2000
You might like to check out PUSHLETS on www.justobjects.nl

When the case is servlets?


Author: the mask (http://www.jguru.com/guru/viewbio.jsp?EID=426947), Jun 5, 2001
JSP has already done its work by virtue of its own properties, but what can one do
when the same page is generated using a servlet where the output is a static HTML
page with a couple of applets showing the information?

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.

Comments and alternative answers

You can get a little tool called xvfb: http://www....


Author: Steven Newton (http://www.jguru.com/guru/viewbio.jsp?EID=44606), Aug
8, 2000
You can get a little tool called xvfb: http://www.sunworld.com/sunworldonline/swol-
03-2000/swol-03-xvfb.html

I found the answer on my own. You can use a virtual...


Author: David Noel (http://www.jguru.com/guru/viewbio.jsp?EID=119574), Aug 8,
2000
I found the answer on my own. You can use a virtual frame buffer server that comes
with Xwindows. The program is caled Xvfb. Another solution is to replace the AWT
package with a 100% Java version that implements the native graphic functions. An
AWT replacement can be found at www.eteks.com. Using either one of these
solutions will allow you to run a headless server.

I have written a class called PureImage which does...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Aug 24, 2000
I have written a class called PureImage which does this. It creates an offscreen image
in a buffer, and uses another class called PureGraphics to draw to it. No Toolkit
required. These classes are available at the Purple Technology web site.

In addition to allowing a graphics servlet to run on a Unix box without an X server


running, this also solves the problem of an NT box whose graphics card is running in
black-and-white or a low-bit mode, where images end up dithered or otherwise
uglified.

Unfortunately, PureGraphics hasn't been completely implemented. Its drawImage()


method works, but drawLine() only works for non-diagonal lines (where either x1=x2
or y1=y2), and most other drawing methods haven't been implemented. Anyone with
a copy of a Computer Graphics 101 textbook want to help?

This option will be available in JDK1.4 code-named...


Author: Davanum Srinivas (http://www.jguru.com/guru/viewbio.jsp?EID=2011), Aug
25, 2000
This option will be available in JDK1.4 code-named merlin. Look at
http://developer.java.sun.com/developer/bugParade/bugs/4281163.html at javasoft for
more details.

You can also look at the public review draft of Merlin at


http://java.sun.com/aboutJava/communityprocess/review/jsr059/merlin.pdf. Search
for "Headless" as the technical term they use for this mode of operation is named
"Headless java".

Another VFB program


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), May 5, 2001
Alessandro A. Garbagnati reports:

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.

Re: Another VFB program


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jul 15,
2001
However, see Does anyone have solved the "no default font" error in the "pja"
package? for a strange issue with PJA.

Re: Another VFB program


Author: BRACCHI CABANNES Christophe
(http://www.jguru.com/guru/viewbio.jsp?EID=513801), Oct 8, 2001
Need for assistance!
On the level localhost/windows JPA goes very well but I have a problem on UNIX:
_X11TransSocketINETConnect: Can't connect: errno = 111
java.awt.AWTError: Graphics2D can't be instantiated
at
com.eteks.java2d.PJAGraphicsEnvironment.createGraphics(PJAGraphicsEnv
ironment.java:110)
at
com.eteks.java2d.PJABufferedImage.createGraphics(PJABufferedImage.jav
a:112) etc....

Would somebody have it an idea? Thank.

Re[2]: Another VFB program


Author: Stephen Oostenbrink
(http://www.jguru.com/guru/viewbio.jsp?EID=1018151), Oct 28, 2002
Hi, Did you ever solve this problem? - Stephen

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

Sharmila Kannangara, Jun 1, 2001 [4]


You can load up the XFree86 package from your Linux installation CDs. This has a executable called
Xvfb which runs a virtual X server.

Set you DISPLAY environment variable to localhost:1.0

Then invoke Xvfb thusly :

Xvfb :1 -screen 0 1600x1200x8 &


I've used this on Linux and Solaris 8 successfully.

Herold Knauf, Aug 13, 2001 [1]

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.

Sharmila Kannangara, Sep 2, 2001


You may have to get the source code and recompile the binaries. I had to do this in order to install
under Solaris.

paul carver, Sep 2, 2001 [1]


If using Tomcat, how do you associate the Xvfb and screen with the Tomcat daemon at boot time?

Sharmila Kannangara, Sep 2, 2001


I didn't have to do anything special for the Tomcat configuration. Setting your DISPLAY variable as I
mentioned should take of it.

I realize that invoking setMaxAge(0) for a cookie causes the cookie to be


deleted. But since such deletions obviously cannot be instantaneous, is it
possible for a server to retrieve such a cookie during its next interaction
with the client?
Location: http://www.jguru.com/faq/view.jsp?EID=123363
Created: Aug 9, 2000 Modified: 2000-08-10 08:46:06.8
Author: Avi Kak (http://www.jguru.com/guru/viewbio.jsp?EID=26410)

The answer is yes. My answer is based on the following interesting observation I


made concerning the lifespan of a cookie for which the server has invoked the
setMaxAge method with zero argument:
Let's say your browser is pointing to a servlet that creates and deposits on the client
side a cookie whose maximum age was set to zero by the server. The cookie will still
be available for a short length of time after the server has processed the original
browser request from the client. This can be checked by hitting the reload button on
the client browser.
The practical implications of this observation are that there can be a measurable
latency associated with the demise of a cookie for which the server has invoked
setMaxAge(0). During this latency, the cookie is still available to the server for the
next request from the client.

As my test example reveals, this latency is not caused by server-client


propagation delays. This latency is between the moment a client receives
notification that the cookie is to be deleted and the moment the client
actually deletes the cookie.

I have tested this observation under the following conditions:

1. A Solaris machine running Tomcat 3.1 as a stand-alone server and a Windows


NT machine as a client on which the Netscape browser pointed to
http://rvl2.ecn.purdue.edu:8080/test-suite/servlet/TestZeroLifespan
2. On a Windows NT machine with the browser pointing to
http://localhost:8080/test-suite/servlet/TestZeroLifespan

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.

Number of cookies retrieved: 0


Number of cookies retrieved: 1
Number of cookies retrieved: 1
Number of cookies retrieved: 0
Number of cookies retrieved: 0
Number of cookies retrieved: 0
Number of cookies retrieved: 1
Number of cookies retrieved: 1
Number of cookies retrieved: 1
....
....

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.

Here is the code for the servlet:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class TestZeroLifespan extends HttpServlet {

public void doGet (HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
Cookie cookie = new Cookie( "status", "retrieved" );

cookie.setMaxAge( 0 );

response.setContentType("text/html");
response.addCookie( cookie );

Cookie cookies[] = request.getCookies();

System.out.println( "Number of cookies retrieved: " +


cookies.length );

PrintWriter out = response.getWriter();


out.println("<html>" +
"<head><title>Cookie Information</title></head>" +
"<body bgcolor=\"#FFFFFF\">" +
"<h1>Cookie Information</h1><table>");
if (cookies != null) {
for(int i=0, n=cookies.length; i < n; i++) {
out.println ("<tr><td>" + cookies[i].getName() +
"</td>");
out.println ("<td>" + cookies[i].getValue() +
"</td></tr>");
}
}
out.println("</table></body></html>");
out.close();
}
}
Comments and alternative answers

Interesting. Sounds like a bug in Netscape. What v...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Aug 10, 2000
Interesting. Sounds like a bug in Netscape. What version of Netscape are you using?
[Avi says: 4.73 for Windows NT]

Does anyone get this behavior with Internet Explorer or other browsers?

If the lifespan of a cookie is left unspecified by not invoking the


Cookie.setMaxAge( int ) method, how long will such a cookie be retrievable
by the server?
Location: http://www.jguru.com/faq/view.jsp?EID=124357
Created: Aug 10, 2000 Modified: 2000-08-11 13:27:52.961
Author: Avi Kak (http://www.jguru.com/guru/viewbio.jsp?EID=26410)

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.*;

public class TestCookieLifespan extends HttpServlet {

public void doGet (HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException
{
Cookie cookie1 = new Cookie( "name1:", "value1" );
Cookie cookie2 = new Cookie( "name2:", "value2" );
Cookie cookie3 = new Cookie( "name3:", "value3" );
Cookie cookie4 = new Cookie( "name4:", "value4" );
Cookie cookie5 = new Cookie( "name5:", "value5" );

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 );

Cookie cookies[] = request.getCookies();

System.out.println( "Number of cookies retrieved: " +


cookies.length );

PrintWriter out = response.getWriter();


out.println("<html>" +
"<head><title>Cookie Information</title></head>" +
"<body bgcolor=\"#FFFFFF\">" +
"<h1>Cookie Information</h1><table>");
if (cookies != null) {
for(int i=0, n=cookies.length; i < n; i++) {
out.println ("<tr><td>" + cookies[i].getName() + "</td>");
out.println ("<td>" + cookies[i].getValue() + "</td></tr>");
}
}
out.println("</table></body></html>");
out.close();
}
}
See also How do I setup a cookie to expire after a certain time?

I am using WebSphere. Where exactly should I place my HTML files and


servlet class files and how do I access these files from the browser?
Location: http://www.jguru.com/faq/view.jsp?EID=124400
Created: Aug 10, 2000 Modified: 2000-08-11 12:46:51.413
Author: Taylor Goetz (http://www.jguru.com/guru/viewbio.jsp?EID=123153)
Question originally posed by Yogesh Beri
(http://www.jguru.com/guru/viewbio.jsp?EID=99548

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)

Your compiled servlet classes typically go in the "servlets" subdirectory of the


WebSphere installation directory. It is important to point out that this directory is
"reloadable", meaning any classes in this directory may be dynamically reloaded if
they are modified.

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.

Comments and alternative answers

how can I remove a cookie set by servlet


Author: Jan Kester (http://www.jguru.com/guru/viewbio.jsp?EID=410702), Apr 26,
2001
I tried to remove the cookie set by the servlet for sessionid by setting it's time to live
to 0 or by trying to overwrite it by another cookie with the same name. But still, any
next session call seems to see this cookie as the cookie that contains the session. How
can I get rid of this cookie? I want to start session by receiving session by URL, then
write my own cookie JSESSIONID with this URL received sessionid and then
continue with normal cookie session control.

Re: how can I remove a cookie set by servlet


Author: Ketan Kakkad (http://www.jguru.com/guru/viewbio.jsp?EID=439788),
Jun 15, 2001
We are experiencing similar problem and don't have an answer! Per my
understanding, there is no standard way of removing (or even modifying) a
JSESSIONID cookie set by the session. Is there any GURU out there who knows
some way of accomplishing this??

Re: Re: how can I remove a cookie set by servlet


Author: Jan Kester (http://www.jguru.com/guru/viewbio.jsp?EID=410702),
Jun 15, 2001
Managed to do it. Have some code to put cookie to null or date to 0. However,
you must add context path and server-name to Cookie to make it work. Send
me mail if you still need it (jan.kester@puntoseguro.com). Jan

Modifying/Removing JSESSIONID cookie.


Author: Ketan Kakkad (http://www.jguru.com/guru/viewbio.jsp?EID=439788), Jun
15, 2001
First to define the problem ...

Most servlet engines set a JSESSIONID cookies as per-session cookie (browser


memory only cookies) instead of persistent cookie (write to disk).

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!

Can I use the PageContext.forward() or RequestDispatcher.forward()


method to forward to a specific anchor (something like
"mypage.html#intro")?
Location: http://www.jguru.com/faq/view.jsp?EID=125063
Created: Aug 11, 2000 Modified: 2000-08-11 14:42:06.484
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Royer Kerwin
(http://www.jguru.com/guru/viewbio.jsp?EID=115906

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

The *browser* is what "goes to" an anchor...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Aug 13, 2000
The *browser* is what "goes to" an anchor inside a fully-generated page. Inside a
request, the browser has already asked the server to generate an entire page; the
"forward" or "include" results in the server generating such an entire page. In
returning such an entire page, the servlet engine can't also tell the browser to scroll to
a specific anchor inside the generated page.

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.

Every time I start Tomcat and do a ps -awx there appears to be around 35


different instances of Tomcat in memory at the same time. Is this normal?
Does it interfere with performance?
Location: http://www.jguru.com/faq/view.jsp?EID=125066
Created: Aug 11, 2000 Modified: 2000-08-11 14:43:39.01
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Jaymes Sorbel
(http://www.jguru.com/guru/viewbio.jsp?EID=116271

This is normal, and represents Linux's concept of threads. A thread in Linux is


implemented as a process. Even though it says each is using X amount of memory,
in reality, they're all sharing the same heap, so it's not taking up extra memory.

What is a three-tier architecture?


Location: http://www.jguru.com/faq/view.jsp?EID=125072
Created: Aug 11, 2000 Modified: 2000-08-11 14:55:10.431
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by joy choudhury
(http://www.jguru.com/guru/viewbio.jsp?EID=104345

A three-tier architecture is any system which enforces a general separation between


the following three parts:

1. Client Tier or user interface


2. Middle Tier or business logic
3. Data Storage Tier

Applied to web applications and distributed programming, the three logical tiers
usually correspond to the physical separation between three types of devices or
hosts:

1. Browser or GUI Application


2. Web Server or Application Server
3. Database Server (often an RDBMS or Relational Database)

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:

1. JSPs, Servlets, or Java client applications responsible for user interface


2. Session Beans or Entity Beans whose methods implement business logic
and business rules
3. Entity Beans whose fields represent data; these fields are "persisted"
(stored and retrieved) either by the EJB server (for container-managed
persistence) or by the Entity Beans themselves (for bean-managed
persistence)
As you can see, the precise definition of "tiers" can vary widely depending on the
particular needs and choices of an application designer. However, they all maintain
the general division of client-logic-storage.

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:

• What seperates one tier from another in the context of n-tiered


architecture?
• In distributed architecture (typical three tier consisting of thin client,
middleware & database) which type of JDBC driver should be used
and why?
• What is meant by the term "business logic"?
• Are the following schemes 3 tiered architecture?
• What is the recommended, "best" architecture for JSP applications?

Comments and alternative answers

NEED SOME HELP WITH THE FOLLOWING QUESTIONS


Author: hapz happy (http://www.jguru.com/guru/viewbio.jsp?EID=1239371), Apr 18,
2005
hi, just need some answers to some questions about XML coz i dont hav a clue. 1)
how to identify a website that is using XML? 2) in which way can you identify a
website is using XML and not xhtml? 3) what is server-side XML, what is client-side
XML? 4) how to identify a website that is using a Three-Tier Architecture

Re: NEED SOME HELP WITH THE FOLLOWING QUESTIONS


Author: hapz happy (http://www.jguru.com/guru/viewbio.jsp?EID=1239371), Apr
18, 2005
reply to h.mahil@herts.ac.uk thanx

Re[2]: NEED SOME HELP WITH THE FOLLOWING QUESTIONS


Author: Felix Zhu (http://www.jguru.com/guru/viewbio.jsp?EID=1241528),
Apr 28, 2005
You should think twice about your post on this website. There are many other
methods of gaining knowledge. See me in class. I can help.

Re[2]: NEED SOME HELP WITH THE FOLLOWING QUESTIONS


Author: Leonardo DaVinci
(http://www.jguru.com/guru/viewbio.jsp?EID=1245556), May 24, 2005
Meow :)

How do I configure IPlanet 4.0 (web server) to work with Tomcat?


Location: http://www.jguru.com/faq/view.jsp?EID=125278
Created: Aug 12, 2000 Modified: 2000-08-13 14:42:29.761
Author: Roger Sergeant (http://www.jguru.com/guru/viewbio.jsp?EID=125277)
Question originally posed by archana sahu
(http://www.jguru.com/guru/viewbio.jsp?EID=112286

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]

Comments and alternative answers

iPlanet does not support the whole 2.2 spec. Spec...


Author: Glen Stampoultzis (http://www.jguru.com/guru/viewbio.jsp?EID=234390),
Feb 15, 2001
iPlanet does not support the whole 2.2 spec. Specificaly it does not support web
applications.

Tomcat and iPlanet


Author: Jerry Birchler (http://www.jguru.com/guru/viewbio.jsp?EID=414720), May
3, 2001
Ok, Yet another reason to do this is that some application software does not work with
the iPlanet servlet engine. Take Vignette 5.6.1, for example, you can enable the servlet
engine in iPlanet, and it does work, but in order to enable JSP V/5 commands, you
must use the Tomcat servlet engine. So, this is a completely valid question that I hope
someone can answer, as I am having the same problem.

Re: Tomcat and iPlanet


Author: Frank O'Connell (http://www.jguru.com/guru/viewbio.jsp?EID=425184),
May 20, 2001
did you ever get your answer? We are faced with the same problem. DigiChat
httptunneling servlet has only been tested on Tomcat. I would also like to
configure Netscape to use tomcat as the servlet engine.

Re: Re: Tomcat and iPlanet


Author: Jerry Birchler (http://www.jguru.com/guru/viewbio.jsp?EID=414720),
May 20, 2001
In my case, it was not so much a matter of configuring Tomcat with iPlanet as
it was a matter of configuring Tomcat for Vignette on an iPlanet web server. I
was able to do this on a Windows 2000 Server platform. My biggest hurdle
was getting the right thin JDBC driver to work for my Oracle database running
on a Solaris Intel box. That required a special membership relationship with
Oracle to do the appropriate download. Even then, I had to keep guessing until
I got the right driver. Also, I had to hack the registry to keep iPlanet from
running out of pages for virtual memory and causing the blue screen of death.
So, in your case, I suppose you just want to replace the iPlanet Servlet engine
with Tomcat? I'm sure that has to be possible, but I haven't had a specific need
to do that just yet. I'd look into making changes to the files under
c:\netscape\server4\conf. You can configure things there like Classpath, JVM
and JRE library settings. Also, I'm running Tomcat as an NT service. This is
very convenient if you ever need to reboot the machine. You'll have to play
around with Tomcat *.properties files and download a couple of things to
make that happen. Eventually, I'll get around to replacing the iPlanet servlet
engine, if for no other reason but to prove it can be done. Until then, good luck
to you, and if you beat me to the solution, please let me know what you did.

Re: Tomcat and iPlanet


Author: Kristian Rickert
(http://www.jguru.com/guru/viewbio.jsp?EID=432617), Jun 1, 2001
Another reason: There are some configuration issues with iPlanet which
are very annoying. 1) If I want a new JAR file in Tomcat, I just add it to a
directory and bounce the server - can't do that with iPlanet 2) If I want to
configure the JVM, it's much easier with tomcat - because you can see
what tomcat does to run the JVM and change it's attributes. 3) iPlanet's
servlet enguine does not display the error message unless you do a println()
command. I want to use tomcat because it's better documented than iPlanet.
Yet iPlanet is kick ass at serving static HTML, and Tomcat is terrible at it.
SO YES!! THERE IS A REASON.

Re: Re: Tomcat and iPlanet


Author: sharon leibel
(http://www.jguru.com/guru/viewbio.jsp?EID=447088), Jun 28, 2001
Another reason has to do with iPlanet's memory limitation to the JVM
(500 MB)

Re[3]: Tomcat and iPlanet


Author: Adam boyet
(http://www.jguru.com/guru/viewbio.jsp?EID=870968), May 10, 2002
Have you been able to replace the iPlanet servlet engine with Tomcat?

SSL is another reason


Author: Stewart Elkin (http://www.jguru.com/guru/viewbio.jsp?EID=912723), Jun
14, 2002
Another reason iPlanet to Tomcat upgrades are hampered are that Tomcat uses a JSSE
keystore for it's server-SSL implementation, whereas iPlanet uses the proprietary
(now open source) NSS format. There is no satisfactory upgrade path for iPlanet
customers who have invested in SSL certs installed in iPlanet, and none at all where
they require client-auth as well.

So, running Tomcat within iPlanet resolves the cert upgrade problem.

Re: SSL is another reason


Author: Jerry Birchler (http://www.jguru.com/guru/viewbio.jsp?EID=978843),
Aug 7, 2002

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.

Check out these links:


1. http://www.mail-archive.com/tomcat-dev@jakarta.apache.org/maillist.html
2. http://www.mail-archive.com/tomcat-user%40jakarta.apache.org/

I document what I've done, so far, there.

If this is possible, I'm going to do it, but I'm going to need some help.

Please send me any updates to jrbirchler@attbi.com. I am planning on doing this


on both my Linux and Solaris sandboxes.

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).

Comments and alternative answers

Where, at the jakarta-tomcat site, are the mod_jk...


Author: Michael Bourdon (http://www.jguru.com/guru/viewbio.jsp?EID=260421),
Nov 22, 2000
Where, at the jakarta-tomcat site, are the mod_jk files located?

Can I use mod_jk + Tomcat and mod_jserv + JServ with...


Author: Marco Becchio (http://www.jguru.com/guru/viewbio.jsp?EID=278835), Dec
15, 2000
Can I use mod_jk + Tomcat and mod_jserv + JServ with the same Apache server?

A compiled mod_jk for linux can be found at http:/...


Author: Hans Gerwitz (http://www.jguru.com/guru/viewbio.jsp?EID=100248), Jan
30, 2001
A compiled mod_jk for linux can be found at http://jakarta.apache.org/builds/jakarta-
tomcat/release/v3.2.1/bin/linux/i386/ , documentation at
http://jakarta.apache.org/tomcat/jakarta-tomcat/src/doc/mod_jk-howto.html
No, mod_jk and mod_jserv are not compatible (cannot be installed in the same
instance of Apache). When transitioning, I've used mod_jserv for both Tomcat and
JServ instances with different ports.

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

Re: NOW WHAT?


Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727), Sep 5, 2002
Hi,
Maybe you can look at the AJP documentation

Re: NOW WHAT?


Author: James Bond (http://www.jguru.com/guru/viewbio.jsp?EID=1063566),
Mar 5, 2003
matt, thanks for providing the johnhunter link, it works like a charm on windows
xp.

How do I set a cookie from a servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=125813
Created: Aug 13, 2000 Modified: 2000-08-14 06:48:52.921
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

This is answered at How do I set a cookie within a JSP page?.

See also

• How do I access a cookie from a servlet?


• How do I setup a cookie to expire after a certain time?
• How can I delete a cookie from within a JSP page?
• How do you check for the existence of a cookie?
• and all questions in the topic Java:API:Servlets:Cookies, Sessions, and State
Management

How do I end (invalidate) a session?


Location: http://www.jguru.com/faq/view.jsp?EID=126094
Created: Aug 14, 2000 Modified: 2000-09-07 15:23:55.799
Author: Richard Raszka (http://www.jguru.com/guru/viewbio.jsp?EID=7963)
Question originally posed by Ramsey Nasr
(http://www.jguru.com/guru/viewbio.jsp?EID=4383

Sessions can be invalidated by calling the invalidate() method on the HttpSession


Object. In a Servlet this can be performed using the following code:

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class InvalidateSession extends HttpServlet


{
public void doGet(
HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();

// Get the current session


HttpSession session = req.getSession(true);

// Invalidate it for a particular reason


if (....)
{
session.invalidate();
}
// Continue processing
// - May need a session to be created to continue
processing

}
}

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

How do I end (invalidate) a session? - comments


Author: Allen S (http://www.jguru.com/guru/viewbio.jsp?EID=50829), May 3, 2001
Don't you think you need to obtain the session even before getting the PrintWriter
object?

How do I access a cookie from a servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=126109
Created: Aug 14, 2000 Modified: 2000-08-14 06:44:26.796
Author: Richard Raszka (http://www.jguru.com/guru/viewbio.jsp?EID=7963)
Question originally posed by Alex Chaffee PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=3

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.*;

public class PrintCookies extends HttpServlet


{
public void doGet(HttpServletRequest req,
HttpServletResponse res) throws ServletException,
IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();

// Get the Cookies


Cookie[] cookies = req.getCookies();

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]

How do I send a redirect from a servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=126245
Created: Aug 14, 2000 Modified: 2000-08-25 08:58:41.776
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

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.

The standard HttpResponse object has a method,


response.sendRedirect(String), that does the right thing with HTTP
headers to send an HTTP redirect to the browser. Check the JavaDoc for more
details. One important note: you must call sendRedirect() before (or better: instead
of) writing any data to the response output stream.

You can do the same thing yourself with response.setHeader("Location",


"http://foo.com/"); but sendRedirect() is preferred.

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 bgcolor="White" text="Navy">

You should be transferred automatically to the new page. If


not please <a href="http://foo.com/index.html">click this
link</a>.

</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().

See also How do I perform browser redirection from a JSP page?

Comments and alternative answers

Comment: 0-Second Redirection


Author: Josh B (http://www.jguru.com/guru/viewbio.jsp?EID=547221), Nov 14, 2001
True. There's not much of a point in specifying a zero-second wait for redirection for
the average user. However, the browser I use (Opera) allows me to turn redirection
off... so if a page is loaded that gives me a choice of continuing on, it's welcome.
FYI... some people get tired of programmers redirecting us willy-nilly on their sites.
=)

Re: Comment: 0-Second Redirection


Author: Kumar Nagarajan
(http://www.jguru.com/guru/viewbio.jsp?EID=1166919), Apr 29, 2004
Forward the request from the servlet to a JSP page and have all the parameters you
want to send as hidden parameters. In the JSP page, in the on-load event, submit
the form to the other servlet (in the other application). Hope this helps. Thanks.
Kumar.

How do you put a hidden parameter in the response.redirect()?


Author: Dave Lu (http://www.jguru.com/guru/viewbio.jsp?EID=585267), Mar 27,
2002
I'm trying to forward or redirect my servlet to another servlet from another
application. I want to send some parameters (or attributes) along with the redirection,
but the parameters needs to be hidden. What is the solution.

Re: How do you put a hidden parameter in the response.redirect()?


Author: Jay kumar (http://www.jguru.com/guru/viewbio.jsp?EID=716541), Jun 9,
2002
Dave, I also have some similar requirement. I need to call a servlet on a different
server and need to pass some parameter. Are you able to solve your problem,
please let me know. It would be very helpful for me.

Re[2]: How do you put a hidden parameter in the response.redirect()?


Author: Dave Lu (http://www.jguru.com/guru/viewbio.jsp?EID=585267), Jun
17, 2002
Hi Jay, Because my application was web base, my temporary solution was to
create a html which auto-forward to the other servlet. What I basically do is,
retreive the values from the request and create a small html (with the hidden
parameters) which re-submit to the other servlet when onload. If I find a better
solution I will let you know ;0)
Re[2]: How do you put a hidden parameter in the response.redirect()?
Author: peter eisert (http://www.jguru.com/guru/viewbio.jsp?EID=953342),
Jul 18, 2002
I have the same problems.
I want to redirect a html page with method=post and informations in hidden
fields.
response.setStatus(307);
response.setHeader("Location", url);
It works fine with MSIE.
But with the Netscape Navigator the body is always empty.
Is there any change to tell the Navigator to do what I want?
Best regards
peter

Re[3]: How do you put a hidden parameter in the response.redirect()?


Author: Ken Young
(http://www.jguru.com/guru/viewbio.jsp?EID=901514), Oct 12, 2002
Did you try putting the form tag around your hidden varibles? IE works
without the form tag, but Netscape doesn't like it when you have form
objects without the form tags around it.

How can I invoke an EJB from a servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=126254
Created: Aug 14, 2000 Modified: 2000-08-14 08:57:21.382
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by prakash patel
(http://www.jguru.com/guru/viewbio.jsp?EID=102421

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

first create the home object, then using home, access...


Author: raghavendra ghorpade (http://www.jguru.com/guru/viewbio.jsp?EID=344479),
Mar 5, 2001
first create the home object, then using home, access the method. for example:
try {
Context c=new InitialContext();
Object o=c.lookup("gor");
first.ABCHome
home=(first.ABCHome)PortableRemoteObject.narrow(o,first.ABCHome.class);
abc=home.create();
(abc.yourmethod(with paramaters)
}
catch(Exception ex) {
ex.printStackTrace();
}
Re: first create the home object, then using home, access...
Author: J C (http://www.jguru.com/guru/viewbio.jsp?EID=756527), Feb 12, 2002
This seems to be lots of details missing. When you run J2EE client with Sun's
J2EE reference implementation server, you use runclient command which sets a
number of properties. How do you set these within servlet/JSP? I guess that you
have to set these properties when starting web server (e.g., servlet), right?

Why do I get a "java.net.BindException:Address in use" error?


Location: http://www.jguru.com/faq/view.jsp?EID=126267
Created: Aug 14, 2000 Modified: 2001-09-07 09:37:42.354
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by anupama bapat
(http://www.jguru.com/guru/viewbio.jsp?EID=124529

Probably because the address is in use :-)

You're already running an instance of your servlet engine, or another service is


running on its port. Make sure the other service is fully stopped before launching
another one.

See also

• How do I fully shut down the server?


• Why doesn't Tomcat shut down when I run shutdown.bat (or shutdown.sh)?
• 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?

Comments and alternative answers

This happens when you stop Tomcat and then restart...


Author: d petersen (http://www.jguru.com/guru/viewbio.jsp?EID=140879), Sep 2,
2000
This happens when you stop Tomcat and then restart it... what you have to do is 'ps -a'
to find the pid for 'Java' and the 'kill -9 pid' to stop the process. Then you can start
Tomcat.

Address in use error when starting Tomcat


Author: Dan Desch (http://www.jguru.com/guru/viewbio.jsp?EID=827173), Apr 5,
2002
I had the same problem with Tomcat 4.0.3. I tried a dozen different port numbers in
server.xml to no avail--still got the same address already in use message except in
each case referencing the new port number I was trying.

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

Actually, servlets/JSPs and EJB are complementary, not competing technologies:


Servlets provide support for writing web based applications whereas EJBs provide
support for writing transactional objects. In larger web systems that require
scalability, servlet and JSP or XML/XSL technologies provide support for the front end
(UI, client) code, where EJB provides support for the back end (database connection
pooling, declaritive transactions, declaritive security, standardized
parameterization...)

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:

• Respond to http/https protocol requests.


• (With JSP) provide an easy way to format HTML output.
• Easily associate a web user with session information

Some of the things that EJBs enable you to do that servlets/JSPs do not are:

• Declaritively manage transactions. In EJB, you merely specify whether a


bean's methods require, disallow, or can be used in the context of a
transaction. The EJB container will manage your transaction boundaries
appropriately. In a purely servlet architecture, you'll have to write code to
manage the transaction, which is difficult if a logical transaction must access
multiple datasources.
• Declaritively manage security. The EJB model allows you to indicate a security
role that the user must be assigned to in order to invoke a method on a bean.
In Servlets/JSPs you must write code to do this. Note, however that the
security model in EJB is sufficient for only 90% to 95% of application code -
there are always security scenarios that require reference to values of an
entity, etc.

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.

all times are in seconds


Specified Actual session timeout period Actual session timeout period
session timeout for the server running on a for the server running on a
period Windows NT machine Solaris 5.6 machine
10 24 32
53 53
53 47
44 48
45 50
20 54 39
44 51
45 40
25 22
49 52
60 105 93
97 114
100 110
113 109
101 110
120 131 161
170 146
169 135
165 137
147 146

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:

• Assuming that a session was not previously created, the method



• HttpSession session = HttpServletRequest.getSession( true );

creates a new session between a client and a server.

• The timeout period of this session can be specified by invoking



• session.setMaxInactiveInterval( int interval );

The timeout period of a session is the maximum permissible time in seconds


between successive client accesses. If a client request is not received within
the specified timeout period, the session is invalidated and objects bound to it
are unbound.

• If an object wishes to receive notification of when it is bound to or unbound


from a session, the object must implement the HttpSessionBindingListener
interface.

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.*;

public class TestSessionTimeout extends HttpServlet {

private static final String TIMER_KEY = "session.timer";

public void doGet (HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException
{
HttpSession session = request.getSession(true);
session.setMaxInactiveInterval( 120 );
SessionTimer timer = (SessionTimer) session.getAttribute( TIMER_KEY
);

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();
}
}

class SessionTimer implements HttpSessionBindingListener {

private long createTime;

public SessionTimer( long ctime )


{
createTime = ctime;
}

public void valueBound( HttpSessionBindingEvent event ) {}

public void valueUnbound( HttpSessionBindingEvent event )


{
try {
long diffTimeInSecs = ( System.currentTimeMillis() - createTime )
/ 1000;
System.out.println( "The session duration in seconds: " +
diffTimeInSecs );
} catch( SecurityException e ) {}
}
}

Comments and alternative answers

Why you don't use the method "isNew" to ...


Author: Juan Ignacio (http://www.jguru.com/guru/viewbio.jsp?EID=324997), Feb 16,
2001
Why you don't use the method "isNew" to verify if the session was created.

Is it possible with Tomcat running in a standalone mode to obtain the usual


httpd logs (with the remote address, date/time of connection, pages, etc.?)
Location: http://www.jguru.com/faq/view.jsp?EID=127155
Created: Aug 15, 2000 Modified: 2001-07-19 15:47:30.626
Author: Ignacio J. Ortega (http://www.jguru.com/guru/viewbio.jsp?EID=98626)
Question originally posed by Daniel Le Berre
(http://www.jguru.com/guru/viewbio.jsp?EID=60379

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

I use the following code in my jsp pages to obtain...


Author: Daniel Le Berre (http://www.jguru.com/guru/viewbio.jsp?EID=60379), Aug
17, 2000
I use the following code in my jsp pages to obtain a similar behaviour:

<% application.log(request.getRemoteHost()+" "+(new


java.util.Date())+" "+request.getHeader("Referer")); %>

Here is a class that will do the trick.


Author: matt paduano (http://www.jguru.com/guru/viewbio.jsp?EID=491036),
Sep 5, 2001
I got a class file off the web that provided access logging as a plug in for tomcat. It
didn't work quite right, so I ran it through a decompiler and made a hack. It seems
to work now. If I could attach it via this interface, I would. But I can't. So drop me
a line and let me know where to send it and I'll send it to you with the server.xml
config info. mpaduano@modeln.com

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

[Does this work? Please submit feedback if so (or if not)... -Alex]

Comments and alternative answers

Well i need only the servlet operations so i think...


Author: Rafael Coutinho (http://www.jguru.com/guru/viewbio.jsp?EID=115513), Aug
17, 2000
Well i need only the servlet operations so i think that or its was already had compiled
or that is only used for JSC. But i appreciate your attention Thanx!

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 tomcat-dev@jakarta.apache.org, 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.)

What is a web application (or "webapp")?


Location: http://www.jguru.com/faq/view.jsp?EID=129328
Created: Aug 17, 2000 Modified: 2000-08-18 19:25:56.836
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

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 web application exists as a structured hierarchy of directories. The root of this


hierarchy serves as a document root for serving files that are part of this context. For
example, for a web application located at /catalog in a web server, the index.html file
located at the base of the web application hierarchy can be served to satisfy a
request to /catalog/index.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.

The contents of the WEB-INF directory are:

• /WEB-INF/web.xml deployment descriptor


• /WEB-INF/classes/* directory for servlet and utility classes. The classes in this
directory are used by the application class loader to load classes from.
• /WEB-INF/lib/*.jar area for Java ARchive files which contain servlets, beans,
and other utility classes useful to the web application. All such archive files
are used by the web application class loader to load classes from.

<h3>Sample Web Application Directory Structure</h3>

Illustrated here is a listing of all the files in a sample web application:

/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".

Accessing images and HTML files within a web app


Author: Thomas Sasala (http://www.jguru.com/guru/viewbio.jsp?EID=876089), Dec
5, 2002
Our general policy is to access all images and HTML files using absolute paths. Thus,
when the JSP or HTML file is moved to a different directory, the linked resource will
still work (assuming it has not been moved). How does one accomplish this with a
web app? The web application can be deployed to any context by the site
administrator, so there is no way to know before hand what the absolute path would
be during the coding phase. Does that mean images (and HTML files) have to be
accessed using relative paths? I suppose you could map a servlet to /image and use
the servlet to return the correct image, but that's not very efficient. -Tom

Re: Accessing images and HTML files within a web app


Author: Rama Sarma (http://www.jguru.com/guru/viewbio.jsp?EID=1222294),
Jan 20, 2005
Can you help me out with the following problem. It is, if I have to map images in
a JSP or HTML from a remote location dynamically, how should i proceed further.
I think i should go with a servlet in between. Can you explain the procedure of the
same. Hope, you got my question.
Thanks n Regards,
Ram

What is a WAR file and how do I create one?


Location: http://www.jguru.com/faq/view.jsp?EID=129333
Created: Aug 17, 2000 Modified: 2000-08-18 19:27:43.733
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

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 *

See also What is a web application (or "webapp")?

How are initialization parameters passed to a servlet under Servlet API


version 2.2?
Location: http://www.jguru.com/faq/view.jsp?EID=129378
Created: Aug 17, 2000 Modified: 2000-08-18 19:29:39.156
Author: Avi Kak (http://www.jguru.com/guru/viewbio.jsp?EID=26410)
Through the webapp deployment descriptor, which is the web.xml file in the directory
WEB-INF.

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"?>

<!DOCTYPE web-app SYSTEM


"http://java.sun.com/j2ee/dtds/web-app_2.2.dtd">

<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

Cannot get init-params to work


Author: Jeffrey Blaze (http://www.jguru.com/guru/viewbio.jsp?EID=529107), Oct 24,
2001
I tried exactly what was detailed in "How are initialization parameters passed to a
servlet under Servlet API version 2.2?" I got a 404 when trying to load
...../ServletParam1 or ServletParam2. That's one problem. I then added:;
<servlet>
<servlet-name>
servletParam;
</servlet-name>;
<servlet-class>;
ServletParam;
</servlet-class>;
<init-param>;
<param-name>parama</param-name>;
<param-value>valuea</param-value>;
</init-param>;
<init-param>;
<param-name>paramb</param-name>;
<param-value>valueb</param-value>;
</init-param>;
</servlet>;
to the web.xml file. Told browser to load ServerParam. It did, but no init-params were
displayed. Is there some higher-level setting somewhere, perhaps a security switch,
that determines whether init-params can be accessed? also, how exactly does the
<server-name> / <server-class> mapping work? The implication in the main topic is
that the <server-name> entry specifies an alias for the <server-class>, but this did not
work for me.

Re: Cannot get init-params to work


Author: juan carbajal (http://www.jguru.com/guru/viewbio.jsp?EID=1227809),
Feb 17, 2005
I have the same problem were you able to get through it?

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

You can use <jsp:forward page="/relativepath/YourServlet" /> or


response.sendRedirect("http://path/YourServlet").

Variables can be sent as:

<jsp:forward page=/relativepath/YourServlet>
<jsp:param name="name1" value="value1" />
<jsp:param name="name2" value="value2" />
</jsp:forward>

You may also pass parameters to your servlet by specifying


response.sendRedirect("http://path/YourServlet?param1=val1").

See also:

• What servlet code corresponds to the various "scope" values for the
<jsp:useBean> tag?

Comments and alternative answers

I follow this, but how can I use those parameters once...


Author: Jeff Sajor (http://www.jguru.com/guru/viewbio.jsp?EID=62983), Aug 18,
2000
I follow this, but how can I use those parameters once I get to the servlet? In ther
words, the first part is solved -- passing parameters from the JSP to the servlet. The
part I need to know is when I get inside my servlet, how do I retrieve the parameters
that I passed with the JSP?

You can also set variables in the request, session,...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Aug 18, 2000
You can also set variables in the request, session, or application; see above link for
details.

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

To get the parameter(s) that are passed from JSP page,


you can use the following snippet of code within your servlet:

String somename = request.getParameter("parametername");

You can access them using String varisble1 = req...


Author: Rahul kumar Gupta (http://www.jguru.com/guru/viewbio.jsp?EID=4809),
Aug 20, 2000
You can access them using
String varisble1 = request.getParameterValues("ParameterName")[0];
or
String variable1 = request.getParameter("ParameterName");
or if you're sending an array
String []variable1 = request.getParameterValues("ParameterName")[0];

The best way is to use Enumeration en = reques...


Author: manoj Tripathy (http://www.jguru.com/guru/viewbio.jsp?EID=133823), Aug
24, 2000
The best way is to use
Enumeration en = request.getParameterNames();
then loop thru the enumeration to get all the parameters/arguments that you passed

Passing Boolean Variables to an Included JSP?


Author: Ryan Bales (http://www.jguru.com/guru/viewbio.jsp?EID=922699), Jun 21,
2002
I am passing this boolean variable to the jsp below. How do I access in on the
sidebar.jsp

this code gives me errors:

boolean ridgidbliptag = request.getParmeterValues("ridgidbliptag");


Please help. Thanks Ryan

ridgidbliptag = true;

<jsp:include page="includes/menu/sidebar.jsp" flush="true">


<jsp:param name="BackGroundImage" value="bg_A.gif"/>
<jsp:param name="BackGroundColor" value="#663300"/>
<jsp:param name="LogoImage" value="logoA.gif"/>
<jsp:param name="ridgidbliptag" value="<%=ridgidbliptag%>" />
</jsp:include>

Can there be more than one instance of a servlet at one time ?


Location: http://www.jguru.com/faq/view.jsp?EID=129558
Created: Aug 17, 2000 Modified: 2000-08-18 20:32:59.181
Author: Avi Kak (http://www.jguru.com/guru/viewbio.jsp?EID=26410) Question
originally posed by francois lascelles
(http://www.jguru.com/guru/viewbio.jsp?EID=115425

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.

How can I implement HTTP keep-alive on the connection between my applet


and servlet?
Location: http://www.jguru.com/faq/view.jsp?EID=130219
Created: Aug 18, 2000 Modified: 2000-08-24 10:56:58.625
Author: Rajah Kalipatnapu (http://www.jguru.com/guru/viewbio.jsp?EID=116593)
Question originally posed by Venkatesan Lakshmi Narayanan
(http://www.jguru.com/guru/viewbio.jsp?EID=29154

You can use public void setRequestProperty(String key, String value)


method on URLConnection.

Description of the method from Java API:


Sets the general request property.
Parameters:
key - the keyword by which the request is known (e.g., "accept").
value - the value associated with it.

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.

public class TestConnectionKeepAlive


{
public static void main(String[] args)
{
try
{
java.net.URL url = new java.net.URL
("http://my.host.com/examples/servlet/Example");
java.net.URLConnection uc = url.openConnection();
uc.setRequestProperty("connection","Keep-Alive");
uc.connect();
java.io.BufferedReader br = new
java.io.BufferedReader(
new java.io.InputStreamReader(uc.getInputStream()));

String str = null;


while( true )
{
str = br.readLine();
if( str == null)
break;
System.out.println(str);
}
}catch(Exception e)
{
e.printStackTrace();
}
}

}
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

Yes, for Tomcat 3.1. No, for Tomcat 3.2 Beta.


But is very easy to secure Tomcat 3.1:

• 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.

But you can implement it yourself with a collection.

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.

for example if you are using JSP look at this code-

...

<jsp:useBean id="allsessions" scope="application"


class="java.util.HashTable"/>

...

<%
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

Maybe under Tomcat 3.1, but not Tomcat 3.2


Author: Roger Hand (http://www.jguru.com/guru/viewbio.jsp?EID=292314), May 8,
2001
I hacked a version of the above code that I was actually getting to work under Tomcat
3.1, but it doesn't work with Tomcat 3.2, which does some trickery with sessions
when you attempt to reference them from outside the request . . . rather than storing
an org.apache.tomcat.session.StandardSession as Tomcat 3.1 does, Tomcat 3.2
stores an org.apache.tomcat.facade.HttpSessionFacade, which appears to act as a
security shield for the real session, and only returns dummy values.

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:

• Extend the maximum timeout for the web page.


• Optimize the query to return the data faster.
• Reduce the amount of data you return.
• Increase the bandwidth to the database.
• Tune the transport protocol to carry more data per packet.
• Last and most importantly for remote access across a slow line: denormalize
the query. One query returning many rows will have a far faster throughput
than many queries returning a small number of rows. Differently put, the
submission and processing of a query itself can easily longer than the actual
retrieval of the rows.

Joe Sam Shirah adds:

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.

Comments and alternative answers

Preventing browser HTTP connection timeout


Author: Abu Daniel (http://www.jguru.com/guru/viewbio.jsp?EID=50542), Mar 5,
2003
You can send dummy tags to the browser, just to keep the connection alive. A patch-
code which I wrote for my JSPs was:
<%
///// dummy tags to the browser so that connection is maintained
/////////
final java.util.Vector vec = new java.util.Vector();
final java.io.PrintWriter writer = response.getWriter();
Runnable runnable = new Runnable() {
public void run() {
int count = 0;
while(vec.size() == 0) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
writer.write("<keepAlive id=\"" + count++ +
"\"/>\r\n");
writer.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
Thread transectionThread = new Thread(runnable);
transectionThread.start();
///////////// End New Code to send dummy tags to browser so
connection is maintained /////////
%>
After the last line of your bean call (or processing) write the following line:
<%
vec.addElement("test");
%>

How can I tell if a connection to my servlet is via a secure channel (i.e.,


HTTPS instead of HTTP)?
Location: http://www.jguru.com/faq/view.jsp?EID=134132
Created: Aug 24, 2000 Modified: 2000-08-24 16:05:55.974
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Use the servlet request's isSecure() or getAuthType() methods.

Where can I find the API documentation for Servlets?


Location: http://www.jguru.com/faq/view.jsp?EID=134133
Created: Aug 24, 2000 Modified: 2000-08-24 16:06:41.865
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

It's available from Sun's J2EE API documentation page.

How do I use servlet aliasing, so the URL


"http://foo.com/mywebapp/servlet/a.b.c.MyServlet" can become
"http://foo.com/mywebapp/Thingy"?
Location: http://www.jguru.com/faq/view.jsp?EID=134402
Created: Aug 24, 2000 Modified: 2000-08-24 19:08:46.694
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

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.

The <servlet-mapping> element defines a mapping from a URL pattern to a servlet.


This element contains two sub-elements, <servlet-name> and <url-pattern>.

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!

Comments and alternative answers

I guess in this answer, the dir "com\stinky&q...


Author: neal ravindran (http://www.jguru.com/guru/viewbio.jsp?EID=17737), Nov 5,
2000
I guess in this answer, the dir "com\stinky" is inside "WEB-INF\classes" dir (under
that particular webapp...servers\default\somewebApp\WEB-INF\classes) and contains
the "Helloworld.class"...is that right? [Yes. -Alex]

How can I do this aliasing in IBM Websphere?


Author: Farhat Kathawala (http://www.jguru.com/guru/viewbio.jsp?EID=238431),
Dec 18, 2000
How can I do this aliasing in IBM Websphere?
This works with jserv but what about mod_jk?
Author: javier Beringola (http://www.jguru.com/guru/viewbio.jsp?EID=345612), Jun
14, 2001
How do you do aliasing with mod_jk?

How can I map to http://foo.com/Thingy?


Author: Yeatts Jones (http://www.jguru.com/guru/viewbio.jsp?EID=541424), Nov 8,
2001
Can you map to somewhere outside the mywebapp directory?

servlet-name & url-pattern not working


Author: aftab mehmood (http://www.jguru.com/guru/viewbio.jsp?EID=737958), Jan
28, 2002
hello !
in my web application both tags are not working?
i am using tomcat 4.0?
what else can be done, in addition to adding tags in web.xml
here is my code
<servlet>
<servlet-name>H17</<servlet-name>
<servlet-class>Servlet17</<servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>H17</<servlet-name>
<url-pattern>/Go </url-pattern>
</servlet-mapping>
my web application is=web now,
a )http://localhost:8080/web/Go
b )http://localhost:8080/web/servlet/H17
c )http://localhost:8080/web/servlet/Servlet17
only " c " is working ok
thank you

Re: servlet-name & url-pattern not working


Author: aftab mehmood (http://www.jguru.com/guru/viewbio.jsp?EID=737958),
Jan 28, 2002
examples provided in web application of tomcat related to mapping (e.g
examples) are working fine

Servlet Mapping on a Sun Cobalt Server?


Author: Kit Reynolds (http://www.jguru.com/guru/viewbio.jsp?EID=821894), Apr 2,
2002
My question relates to servlet mapping on a Sun Cobalt server. I've successfully
deployed WAR files to the server and everything works fine, with a new context
created etc. However I haven't been able to successfully map files such as *.frm or
even *.htm across to servlets, the server just reports file not found. Everything maps
fine on my local Tomcat 3.2 and 4.0 setups. Any suggestions? or thoughts gratefully
received. (I'm working with an ISP's shared Sun Cobalt Server with JDK 1.3 installed
which provides Tomcat as a plug in to the web server.)

What'll happen to a servlet request (including the transactions that have


already been carried out) when: a) client's browser has been closed. b)
client's connection has been disconnected. c) client presses the stop button.

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

All of the above result in a "java.net.SocketException: Connection reset by peer:


socket write error" when you close() the PrintWriter in the response. If it is important
that the client see's the message then ideally you would want to catch the Exception
and rollback the transaction you were working on.

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.

Comments and alternative answers

Right, you have no choice in JSDK 2.0 but with JSDK...


Author: Thomas Nagel (http://www.jguru.com/guru/viewbio.jsp?EID=68546), Sep
21, 2000
Right, you have no choice in JSDK 2.0 but with JSDK 2.2 you have a
response.flushBuffer method which could be used for the following work around:

Example:

... Some Code ...

try{

for( int i=0; i<10000; i++ ){

out.println( "test\n" );
Thread.sleep( 2 );
response.flushBuffer();

} catch( Exception e ){
log( "---> Exception " + e.toString() );
}

... Some Code ...

Hitting the STOP Button in the browser results in something like this:

2000-09-21 02:10:16 - path="/testArea" :TestServlet: ---> Exception


java.io.IOException: Datenübergabe unterbrochen (broken pipe)

Hope this helps :-)


Bye

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

Sun has an good article (with sources) at:

Writing a Web Crawler in the Java Programming Language

Comments and alternative answers

Also, before you start to parse a possibly messy HTML...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Oct 9, 2000
Also, before you start to parse a possibly messy HTML file, you may want to clean it
up. HTMLTidy would help. Unfortunately, Andy decided not to keep maintaining the
Java version. See http://www3.sympatico.ca/ac.quick/

If I send an encoded URL to a servlet, do I have to decode it before using


the getParameter() method or is it automatically decoded by the service()
method of the servlet?
Location: http://www.jguru.com/faq/view.jsp?EID=135073
Created: Aug 25, 2000 Modified: 2000-08-25 20:34:46.982
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Richard Pilon
(http://www.jguru.com/guru/viewbio.jsp?EID=130873

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.*;

public class SimpleT3Client {

public static void main(String[] argv) throws Exception {

T3Client t3 = new T3Client("t3://localhost:7001");


t3.connect();
String prop = t3.services.config()
.getProperty("weblogic.httpd.documentRoot");
t3.disconnect();
}

Comments and alternative answers

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 class AccessMBeanForJGuru


{

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"?

I am not sure of the naming convention.

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)

Through the load-on-startup element of the webapp deployment descriptor file


web.xml.

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.

Comments and alternative answers

RE: <load-on-startup> at web.xml of Servlet 2.2 API


Author: simon ru (http://www.jguru.com/guru/viewbio.jsp?EID=400431), Apr 10,
2001
What if I am not using Servlet and web container but only the ejb container? Does the
app server provide something like that? I am using Borland App Server 4.5.

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)

Through the servlet-mapping element of the webapp deployment descriptor file


web.xml. The url-pattern sub-element of the servlet-mapping element must be
set to '/'.

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"?>

<!DOCTYPE web-app SYSTEM


+"http://java.sun.com/j2ee/dtds/web-app_2.2.dtd">

<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.

Tried it - but it seems to catch other requests as well


Author: Amos Shapira (http://www.jguru.com/guru/viewbio.jsp?EID=4346), Aug 30,
2001
I tried adding the following to my web.xml file:
<servlet>
<servlet-name>
start
</servlet-name>
<servlet-class>
StartController
</servlet-class>
</servlet>

<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.

I do have the standard mime-mapping in the web.xml file.

Can I do anything about this?

Thanks,

--Amos

Use welcome-file and get over with it


Author: Amos Shapira (http://www.jguru.com/guru/viewbio.jsp?EID=4346), Aug
30, 2001
I just got around the problem: instead of the Servlet stuff I created an index.jsp file
which reads like:
<% response.sendRedirect("login"); %>
And added the following to my web.xml file:
<welcome-file-list>
<welcome-file>
index.jsp
</welcome-file>
</welcome-file-list>
And now it works like a charm.

What is the difference between response.sendRedirect(),


RequestDispatcher.forward(), and PageContext.forward()?
Location: http://www.jguru.com/faq/view.jsp?EID=136035
Created: Aug 27, 2000 Modified: 2002-12-30 09:08:31.581
Author: Serge Knystautas (http://www.jguru.com/guru/viewbio.jsp?EID=100012)
Question originally posed by Priya Venkatesan
(http://www.jguru.com/guru/viewbio.jsp?EID=129496

In a nutshell, RequestDispatcher.forward() works on the server and


response.sendRedirect() works on the browser. When you invoke
RequestDispatcher.forward(), the servlet engine transfers control of this HTTP
request internally from your current servlet or JSP to another servlet or JSP or static
file. When you invoke response.sendRedirect(), this sends an HTTP response to the
browser to make another request at a different URL.

RequestDispatcher.forward() and PageContext.forward() are effectively the same.


PageContext.forward is a helper method that calls the RequestDispatcher method.

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()?

Comments and alternative answers

Hi Priya, I put up the same question in http://th...


Author: Kiran Sarvepalli (http://www.jguru.com/guru/viewbio.jsp?EID=17055), Oct
9, 2000
Hi Priya, I put up the same question in http://theserverside.com and I got the
following answer:

Well basically both method calls redirect you to new resource/page/servlet.

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.

I don't know about PageContext.forward().

Thanks,
Kiran

Is there a significant difference in handle time?


Author: Joost Schouten (http://www.jguru.com/guru/viewbio.jsp?EID=581960), Jun
30, 2003
All requests made to my app go through my controller servlet. Since I often use long
query strings I choose to use the response.sendRedirect("myJSPfile"), so the address
bar would always look clean. My servlet -> JSP's communication goes through the
session beans of the container.
But by the sound of things this is not the fastest option. I was just wondering if
anybody knows if this delay of the headers traveling to and from the client one more
time is significant? And is it worth to use the requestDispatcher.forward()?

Kind regards, Joost Schouten

How can I measure the file downloading time using servlets?


Location: http://www.jguru.com/faq/view.jsp?EID=136390
Created: Aug 28, 2000 Modified: 2001-07-23 09:16:32.622
Author: Serge Knystautas (http://www.jguru.com/guru/viewbio.jsp?EID=100012)
Question originally posed by JayaRam Raja Sekar
(http://www.jguru.com/guru/viewbio.jsp?EID=94956

[Note: this could mean servlet-as-client or servlet-as-server; we assume this is the


servlet-as-server interpretation]

First start by creating a FileServlet... a servlet that takes a dir/filename as a


parameter (either query string, post parameters, or extra path info). Get a File
object handle to the data you want to download. Before you start writing data,
capture the current time in a long primitive. Then write all data out, and at the end,
get the current time again. Take the difference, and that was your transfer time.
Here's some mockup code. note: do not implement this as it gives read access
to your entire web root (including source of JSPs... figure out where you
want to serve files from and change accordingly.

ServletOutputStream out = response.getOutputStream();


String filename =
getServletContext().getRealPath(request.getQueryString());
FileInputStream fin = new FileInputStream(filename);
long start = System.currentTimeMillis();
byte data[] = new byte[1024];
int len = 0;
while ((len = fin.read(data)) > 0) {
out.write(data, 0, len);
}
out.flush();
long stop = System.currentTimeMills();
log("took " + (stop - start) + "ms to download " + filename);
[N.B.: the above approach may not give the results you're looking for. It measures
the amount of time spent on the server; however, many other factors can determine
the perceived time spent by the client, including net lag and buffering. A more
accurate approach would use JavaScript to do the following:

1. Store the current time in a JavaScript variable


2. Output random data of a known size
3. At the end of that block, mark the time again and subtract as above
4. Divide by data size to get transfer rate

Check out MSN's Bandwidth Speed Test for inspiration.


-Alex]

How do I install Tomcat as servlet manager of Domino 5.x?


Location: http://www.jguru.com/faq/view.jsp?EID=136393
Created: Aug 28, 2000 Modified: 2000-08-30 12:54:10.19
Author: Serge Knystautas (http://www.jguru.com/guru/viewbio.jsp?EID=100012)
Question originally posed by Pablo Rodriguez
(http://www.jguru.com/guru/viewbio.jsp?EID=101122

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. :)

Comments and alternative answers

Oh yes there are...


Author: Andy Armstrong (http://www.jguru.com/guru/viewbio.jsp?EID=141392),
May 29, 2001
We've just released a Domino/Tomcat connector. Find it at
http://free.tagish.net/domino-tomcat/index.jsp.

Architecturally speaking, under what circumstances must I consider adding


EJB into the mix when building web-based applications using servlets and
JSP?
Location: http://www.jguru.com/faq/view.jsp?EID=137169
Created: Aug 28, 2000 Modified: 2000-08-28 21:39:26.129
Author: Govind Seshadri (http://www.jguru.com/guru/viewbio.jsp?EID=14)

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.

How can I read GET or POST parameters that were encoded in an


international character set? Also, when a user fills in an HTML Form using a
custom Input Method Editor for, say, Japanese, how can my servlet/JSP
know which encoding was used?
Location: http://www.jguru.com/faq/view.jsp?EID=137281
Created: Aug 28, 2000 Modified: 2001-01-06 06:48:12.443
Author: Jan Borchers (http://www.jguru.com/guru/viewbio.jsp?EID=48743)
Question originally posed by RAM SAM
(http://www.jguru.com/guru/viewbio.jsp?EID=127269

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.

public String getText(HttpServletRequest request)


{
String value = request.getParameter("mytext");

try{
value = new String(value.getBytes(),
request.getCharacterEncoding());
}catch(java.io.UnsupportedEncodingException ex){
System.err.println(ex);
}

return value;
}

See also

• Can JRun be configured so that it converts GET or POST parameters encoded


in UTF-8 correctly into Unicode for use in the Java servlet?
• If my servlet or JSP contains international characters (like "Ýðüö"), how do I
ensure they are displayed correctly?

Comments and alternative answers

But does this assume that there is some information...


Author: RAM SAM (http://www.jguru.com/guru/viewbio.jsp?EID=127269), Oct 2,
2000
But does this assume that there is some information about the charset is coming in
from the browser? I tried it but I always obtained ISO-8859-1 as the answer even
though I used shift-jis to input the characters.

I tried it on a machine that has a traditional chinese...


Author: Roop Goyal (http://www.jguru.com/guru/viewbio.jsp?EID=287466), Dec 27,
2000
I tried it on a machine that has a traditional chinese operating system. The value
returned by request.getCharacterEncoding() is null, although the html page that
contains the From has the following line in its HEAD.
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">.

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?

This doesn't work, anyone know how to make it work?


Author: Haitao Jiang (http://www.jguru.com/guru/viewbio.jsp?EID=414121), May 2,
2001
request.getCharacterEncoding() simply can not get the charset set by the client.
Anyone know how to set it in the JSP so that the servlet can get the encoding info?
Thanks jianghaitao@yahoo.com

Re: This doesn't work, anyone know how to make it work?


Author: maria baldassarri (http://www.jguru.com/guru/viewbio.jsp?EID=435002),
Jun 7, 2001
with tomcat 3 this workaround works:
value=new String(request.getParameter("Input").getBytes("ISO8859_1"),
"UTF8")
with tomcat 4 read the following article about a new method in the Java servlet
API 2.3 and Tomcat 4
http://developer.java.sun.com/developer/technicalArticles/Servlets/servletapi2.3
request.setCharacterEncoding can be used to tell the server the charset to use to
correctly parse the parameters and POST data. You have to call this before you
call getParameter.

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,

Would it not be possible to tell the servlet-container how to decode POSTed


Requests?

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?

If it would be possible, how can it be done and is that feasibility provided by


other Servlet-Container as JRun for example?

This works for me.


Author: Andrew Young (http://www.jguru.com/guru/viewbio.jsp?EID=879849), May
15, 2002
Here's what I did to make this work correctly. I'm entering Japanese in Win2k and it's
being encoded as UTF-8. getCharacterEncoding() returned null, so I assume it's UTF-
8. If it returns anything else I assume that it's whatever was returned.
String text = request.getParameter("text");
String encoding = request.getCharacterEncoding();
if (encoding == null) {
encoding = "UTF-8";
}
try {
text = new String(textParam.getBytes(), encoding);
} catch(Exception ex) {
System.err.println(ex);
ex.printStackTrace();
}

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

String self = req.getScheme() + "://" + req.getServerName() +


(port == 80 ? "" : ":"+port) + req.getServletPath();

by the following statements:

String webapp = null;


String realPath = getServletContext().getRealPath(
req.getServletPath() );
String fileSeparator = System.getProperty( "file.separator" );
StringTokenizer st = new StringTokenizer( realPath,
fileSeparator );
while ( st.hasMoreTokens() ) {
if ( st.nextToken().equals( "webapps" ) ) {
webapp = st.nextToken();
break;
}
}
String self = req.getScheme() + "://" + req.getServerName() +
(port == 80 ? "" : ":"+port) + "/" + webapp +
req.getServletPath();

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]

How can I JSP under Apache JServ?


Location: http://www.jguru.com/faq/view.jsp?EID=139446
Created: Aug 31, 2000 Modified: 2000-09-04 19:18:19.025
Author: Serge Knystautas (http://www.jguru.com/guru/viewbio.jsp?EID=100012)
Question originally posed by sreenivasa rao gaddam
(http://www.jguru.com/guru/viewbio.jsp?EID=136249

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).

You can however add GNUJSP at http://klomp.org/gnujsp/. It supports JSP 1.1 on


servlet 2.0 or 2.1 engines. In fact, in many ways it's a nicer environment to develop
than Tomcat or JRun or other current JSP systems (good debugging and
configurability). Unfortunately, the Servlet 2.2 features were too compelling and we
had to move away from JServ and GNUJSP.

Comments and alternative answers

Use tomcat3.1. It's the best solution to servlet and...


Author: luca valenti (http://www.jguru.com/guru/viewbio.jsp?EID=36876), Sep 5,
2000
Use tomcat3.1. It's the best solution to servlet and jsp, IMO, and it supports JSP 1.1
and servlets 2.2. See http://jakarta.apache.org for details.

What is inter-servlet communication?


Location: http://www.jguru.com/faq/view.jsp?EID=139489
Created: Aug 31, 2000 Modified: 2000-09-06 13:45:54.498
Author: shilpa Tiwari (http://www.jguru.com/guru/viewbio.jsp?EID=138841)
Question originally posed by joy choudhury
(http://www.jguru.com/guru/viewbio.jsp?EID=104345

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.

e.g. TestServlet test=


(TestServlet)getServletConfig().getServletContext().getServlet("OtherServlet");
otherServletDetails= Test.getServletDetails();

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.

Servlets could also invoke other servlets programmatically by sending an HTTP


request. This could be done by opening a URL connection to the desired Servlet.

Comments and alternative answers

interservlet communication between two dofferent web sevrs


Author: dhanasekar dhandapani
(http://www.jguru.com/guru/viewbio.jsp?EID=392865), Apr 30, 2001
Well u mentioned the different ways that servlets can communicate to generate a
respons, provided the servlets are running in the same server. how can two servlets
running in different server can communication? . The server may be running in the
same network (or) . different networks please answer my question

Re: interservlet communication between two dofferent web sevrs


Author: Gaurav Shukla (http://www.jguru.com/guru/viewbio.jsp?EID=932052),
Jul 16, 2002
When two different Servlets are residing on two different servers, there servlet
contexts are different. This would require careful consideration while playing with
the request dispatcher object. J2EE spec says that different Context
communication is not achievable.
How do I make servlet aliasing work with Apache+Tomcat?
Location: http://www.jguru.com/faq/view.jsp?EID=140877
Created: Sep 2, 2000 Modified: 2000-09-06 13:40:32.764
Author: Ken Kress (http://www.jguru.com/guru/viewbio.jsp?EID=43931)

[See How do I use servlet aliasing? for background.]

Chapter 13 of the Java Servlet Specification v2.2, gives an example of using a


"deployment descriptor" to add a new path to a servlet. The problem is the technique
shown fails when you integrate Tomcat with Apache.

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.

Comments and alternative answers

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.

Re[2]: Using mod_jk


Author: Mike Konikoff
(http://www.jguru.com/guru/viewbio.jsp?EID=700186), Dec 23, 2001
I tried this as well with no luck. Is there any alternative?

mod_jk doesn't read web.xml, does it?


Author: javier Beringola (http://www.jguru.com/guru/viewbio.jsp?EID=345612), Jun
14, 2001
so, how?...........and what about if my servlets are in this way:
dsds.gdfg.ere.fdffd.myServlet?

Is there any way to determine the number of concurrent connections my


servlet engine can handle?
Location: http://www.jguru.com/faq/view.jsp?EID=142244
Created: Sep 5, 2000 Modified: 2000-09-06 16:16:54.581
Author: Avi Kak (http://www.jguru.com/guru/viewbio.jsp?EID=26410) Question
originally posed by Manoj Tripathi
(http://www.jguru.com/guru/viewbio.jsp?EID=122726

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.

Comments and alternative answers

Here's a different, related, question: What is the...


Author: Roy Wilson (http://www.jguru.com/guru/viewbio.jsp?EID=53232), Sep 6,
2000
Here's a different, related, question: What is the maximum number of connections that
my servlet engine can accept and also meet service level agreements (like reaction
time, response time, throughput, not refusing more than a certain percentage of
connections attempted)? The answer to that, of course, depends on (at least) the rate at
which connections are requested and the resource demand per request.
I have a problem using HttpServletResponse.sendRedirect() with
microbrowsers (WML/HDML). Those browsers don't seem to understand
this and return an error. How do I send a redirect to a WAP device?
Location: http://www.jguru.com/faq/view.jsp?EID=201403
Created: Sep 8, 2000 Modified: 2000-09-11 09:22:40.326
Author: Matt Small (http://www.jguru.com/guru/viewbio.jsp?EID=92190) Question
originally posed by francois lascelles
(http://www.jguru.com/guru/viewbio.jsp?EID=115425

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]

Comments and alternative answers

In JSP you can use <jsp:forward> instead. This...


Author: Artur de Sousa Rocha (http://www.jguru.com/guru/viewbio.jsp?EID=70489),
Jan 5, 2001
In JSP you can use <jsp:forward> instead. This does the redirection server-side.
Drawback: browser-side the URL doesn't change. To do it from a "normal" servlet
you would have to call the other servlet and stream its response back to browser - not
very practical.

How do I set up Servlets on Linux?


Location: http://www.jguru.com/faq/view.jsp?EID=202543
Created: Sep 11, 2000 Modified: 2000-09-11 10:57:32.629
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by vivek tawde
(http://www.jguru.com/guru/viewbio.jsp?EID=133324

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).

The most popular products seem to be:

• Tomcat from Apache Jakarta


• JServ from Apache
• Resin from Caucho
• JRun from Allaire

See the individual products' web sites and README files for installation instructions.

Comments and alternative answers

Another good, free all-Java Web server and servlet...


Author: Nathan Meyers (http://www.jguru.com/guru/viewbio.jsp?EID=138686), Sep
15, 2000
Another good, free all-Java Web server and servlet engine is Jetty from Mort Bay
Consulting.

How do I use Tomcat with Netscape Server?


Location: http://www.jguru.com/faq/view.jsp?EID=206207
Created: Sep 14, 2000 Modified: 2000-09-14 19:17:00.746
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Look at the Tomcat Netscape How to file located at the address :


http://jakarta.apache.org/tomcat/jakarta-tomcat/src/doc/tomcat-netscape-
howto.html.

What is a request dispatcher and how does it work?


Location: http://www.jguru.com/faq/view.jsp?EID=206736
Created: Sep 14, 2000 Modified: 2000-09-17 14:16:11.941
Author: Avi Kak (http://www.jguru.com/guru/viewbio.jsp?EID=26410) Question
originally posed by Alex Chaffee PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=3

A RequestDispatcher object can forward a client's request to a resource or include


the resource itself in the response back to the client. A resource can be another
servlet, or an HTML file, or a JSP file, etc.

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.

For constructing a RequestDispatcher object, you can use either the


ServletRequest.getRequestDispatcher() method or the
ServletContext.getRequestDispatcher() method. They both do the same thing,
but impose slightly different constraints on the argument path. For the former, it
looks for the resource in the same webapp to which the invoking servlet belongs and
the pathname specified can be relative to invoking servlet. For the latter, the
pathname must begin with '/' and is interpreted relative to the root of the webapp.

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 dispatcher = getRequestDispatcher("Servlet_B");


dispatcher.forward( request, response );

where request, of type HttpServletRequest, is the first parameter of the enclosing


service method (or the doGet method) and response, of type
HttpServletResponse, the second. You could accomplish the same by
RequestDispatcher
dispatcher=getServletContext().getRequestDispatcher(
"/servlet/Servlet_B" );
dispatcher.forward( request, response );

Comments and alternative answers

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

Any Idea ? My code is:


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class chamado extends HttpServlet {
public void doGet (HttpServletRequest request, HttpServletResponse
response)
throws ServletException {
String param;
param = request.getParameter("param");
if (param.compareTo("method1")==0) {
try {
method1();
} catch (Exception ex) {}
}
}

public void method1() {


//Do something

}
}

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class chamador extends HttpServlet {


public void doPost (HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
RequestDispatcher RD =
getServletContext().getRequestDispatcher("/chamado?param=method1");
RD.forward(request, response);
}
}

Where is the log file (written by ServletContext.log()) for


JavaWebServer2.0?
Location: http://www.jguru.com/faq/view.jsp?EID=206818
Created: Sep 15, 2000 Modified: 2001-07-19 15:42:11.116
Author: Shirish Bathe (http://www.jguru.com/guru/viewbio.jsp?EID=206816)
Question originally posed by Hong Shi
(http://www.jguru.com/guru/viewbio.jsp?EID=9628

[Running on a WinNT4.0. Looked into the event_log but it's not there.] Hi,

Logs generated by ServletContext.log() or GenericServlet.log() are stored as event


either in a file or displayed.

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.

By default (for JavaWebServer2.0 running on a WinNT4.0) logs are stored in Rolling


file "event_log" with buffer of 8KB. As this option uses the file cache you can not find
your log entries in the file unless the cache is written to disk.

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).

Hope this will solve your query..

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.*;

public class commonServlet extends HttpServlet


{
/*the method of Convert transfer data in typeof String (String Input)
from one format(StandardFrom) to
another format(StandardTo)*/
public static String convert (String Input, String
StandardFrom, String StandardTo)
{
byte[] bytes;
String conResult = new String();
try
{
bytes = Input.getBytes(StandardFrom);
conResult = new String (bytes, StandardTo);
}

catch(Exception e)
{
//debugging begins here
System.out.println(e);
//debugging ends here
return("null");
}
return conResult;
}//method convert ends here

//Do nothing within methods doGet & doPost


public void doGet(HttpServletRequest req, HttpServletResponse
res)
{ }
public void doPost(HttpServletRequest req, HttpServletResponse
res)
{ }
}
swarraj kulkarni also contributed to this answer and adds:

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.

Comments and alternative answers

I have tried the above code. But the from standard...


Author: Dalia Reji (http://www.jguru.com/guru/viewbio.jsp?EID=62488), Oct 18,
2000
I have tried the above code. But the from standard (StandardFrom) always need to be
Cp1252 or 8859_1. The following is the scenario what I have tried,

I have an entry.jsp whose character encoding is set to Cp1256. In this jsp I am


entering an arabic character and submitting to another jsp display.jsp. Display.jsp also
uses the Cp1256 encoding. Since the JSP cannot understand the encoding of the
request, to get the actual string submitted, I have to do the following conversion.

String sName = request.getParameter("name");


bytes[] b = sName.getBytes("Cp1252");
String sActual = new String(b, "Cp1256");
I changed my system property file.encoding to CP1256, thinking that I don't need the
above conversion. But still, to get the correct string back I have to specify the source
encoding as Cp1252. (My default system file.encoding is Cp1252).

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

Does context.RequestDispatcher expect an absolute path to be relative to


the webapp root or the server root? What about response.sendRedirect()?
Location: http://www.jguru.com/faq/view.jsp?EID=208370
Created: Sep 17, 2000 Modified: 2000-09-21 11:01:33.779
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

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."

Thus, for a webapp (context) called "shopping", the URL

http://www.foo.com/shopping/service/support.html
is accessed with the call
context.getRequestDispatcher("/service/support.html")

However, the response.sendRedirect() method expects its path parameter to be


relative to the server root, not the webapp root. Thus, to send a redirect to the
above URL from a servlet running on www.foo.com, you must say

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

• A URL must begin with a protocol and hostname ("http://www.foo.com"), so


it's actually a path, not a URL.
• The path is not technically absolute, since it's sometimes relative to the
server root, as described above.

Comments and alternative answers

Perhaps the Servlet Specs should be more specific about...


Author: lee yeow leong (http://www.jguru.com/guru/viewbio.jsp?EID=3804), Dec 26,
2000
Perhaps the Servlet Specs should be more specific about relative URL. For
Websphere 3.5,
sendRedirect("/a.jsp")
would mean
http://<hostname>/<servlet context>/a.jsp
while in IAS6.0, it resolves to
http://<hostname>/a.jsp

How do I discover the size of an image file (GIF or JPEG) on disk?


Location: http://www.jguru.com/faq/view.jsp?EID=208401
Created: Sep 17, 2000 Modified: 2000-09-18 18:00:36.238
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Mohamed Abu Zur
(http://www.jguru.com/guru/viewbio.jsp?EID=103782

First, load the image. If you have Swing, you can use

ImageIcon icon = new ImageIcon(args[0]);


Image image = icon.getImage();
If you do not have Swing, you will need access to a toolkit, a component, and a
media tracker. See "How do I make sure an Image is loaded before I try to display
it?"http://www.jguru.com/jguru/faq/view.jsp?EID=20617

Once you have loaded the image, you can use its getHeight() and getWidth()
methods, which work as expected.

Comments and alternative answers

You can also do it by looking at the JPEG header. It...


Author: James Thrasher (http://www.jguru.com/guru/viewbio.jsp?EID=301019), Jan
12, 2001
You can also do it by looking at the JPEG header. It saves lots of time loading the
image. Here's source to a class that does that:
http://www.gjt.org/servlets/JCVSlet/list/gjt/org/gjt/jjt/jpeginfo

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().

What is a Servlet Context?


Location: http://www.jguru.com/faq/view.jsp?EID=208612
Created: Sep 17, 2000 Modified: 2000-09-18 08:57:21.158
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by navin kumar
(http://www.jguru.com/guru/viewbio.jsp?EID=202883

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.

Since Servlet spec 2.1, a servlet context is more-or-less equivalent to a web


application ("webapp").

Comments and alternative answers

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.

Re: a servlet container can have multiple Servlet Contexts


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Sep 7,
2001
Each context represents a separate application. So "application scope" variables
are stored as Servlet Context Attributes. That means that separate
contexts/applications do not share variables (unless you use an external method
like the database or file system).

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?

Does the RequestDispatcher expect a relative URL to be relative to the


originally-called servlet or to the current servlet (if different)?
Location: http://www.jguru.com/faq/view.jsp?EID=210214
Created: Sep 19, 2000 Modified: 2000-09-20 11:18:59.269
Author: swarraj kulkarni (http://www.jguru.com/guru/viewbio.jsp?EID=121306)
Question originally posed by Alex Chaffee PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=3
Since the RequestDispatcher will be passing the control (request object and response
object) from the current Servlet, the relative URL must be relative to the current
servlet.

The originally called servlet has passed the control to the current servlet, and now
current servlet is acting as controller to other resourses.

Comments and alternative answers

That's not clear enough


Author: Amos Shapira (http://www.jguru.com/guru/viewbio.jsp?EID=4346), Jun 6,
2001
I've read the same text in the Servlet 2.2 spec and arrived here after that because it
confuses me.

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.

Can someone clarify what is the defined behaviour to be expected?

Thanks.

What is the difference between in-process and out-of-process servlet


containers?
Location: http://www.jguru.com/faq/view.jsp?EID=211289
Created: Sep 20, 2000 Modified: 2000-09-21 10:13:32.784
Author: swarraj kulkarni (http://www.jguru.com/guru/viewbio.jsp?EID=121306)
Question originally posed by Mahesh Devendran
(http://www.jguru.com/guru/viewbio.jsp?EID=204413

For the best explaination of this question pl. see the apache site:

Information about servlet containers at Apache

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.

In addition to these types of containers, there is 3rd type which is stand-alone


servlet containers. These are an integral part of the web server.
Comments and alternative answers

Commerical examples of in & out process containers


Author: neal ravindran (http://www.jguru.com/guru/viewbio.jsp?EID=17737), Mar 2,
2002
Could you provide the commericial names of a few famous in & out process
containers?

In BEA Weblogic - Is it possible to load a Servlet, without mentioning an


alias name in the weblogic.properties file?
Location: http://www.jguru.com/faq/view.jsp?EID=212120
Created: Sep 21, 2000 Modified: 2000-09-21 10:40:07.487
Author: Igor Royzis (http://www.jguru.com/guru/viewbio.jsp?EID=212112) Question
originally posed by Nitin Baligar
(http://www.jguru.com/guru/viewbio.jsp?EID=207743

Yes. This is how:


http://www.weblogic.com/docs51/classdocs/API_servlet.html#134798
Comments and alternative answers

Answer Yes it is very much possible to do this. We...


Author: shilpa Tiwari (http://www.jguru.com/guru/viewbio.jsp?EID=138841), Sep 21,
2000
Answer
Yes it is very much possible to do this. Weblogic provides a ServletServlet which
could be used to call other servlets.
You need to register this servlet in the weblogic.properties file with an alias.
e.g. weblogic.httpd.register.servlet=weblogic.servlet.ServletServlet

You can now use ServletServlet to serve another servlet.


e.g.
http://localhost:7001/servlet/examples/servlets/HelloWorldServlet.
Here "servlet" ( in the above url) is the alias name of the ServletServlet servlet in the
properties file .
The rest of the url which is examples/servlets/HelloWorldServlet is understood by
ServletServlet as the
PATH_INFO as examples.servlets. HelloWorldServlet ( a "/" in the PATH_INFO is
understood as "." by the ServletServlet.)

This class examples.servlets.HelloWorldServlet is searched in the system


CLASSPATH of WebLogic or the servlet classpath.
A servlet called using the ServletServlet will behave like any other servlet in that the
init() method is executed the first time the servlet is called.
(Versions of WebLogic Server prior to version 5.1 re-initialized a servlet called from
the ServletServlet each time the servlet was called.
Also, once the servlet class is loaded, it is not loaded again when subsequent servlet
objects are instantiated. )

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.

You might want to refer to this link :


http://www.weblogic.com/docs51/classdocs/API_servlet.html#134798

How is SingleThreadModel implemented in Tomcat? In other containers? [I


would assume that Tomcat uses its connection thread pool, and creates a
new instance of the servlet for each connection thread, instead of sharing
one instance among all threads. Is that true?]
Location: http://www.jguru.com/faq/view.jsp?EID=212826
Created: Sep 21, 2000 Modified: 2000-09-28 19:24:28.15
Author: Avi Kak (http://www.jguru.com/guru/viewbio.jsp?EID=26410) Question
originally posed by Eric Armstrong
(http://www.jguru.com/guru/viewbio.jsp?EID=201746

The question mixes together two rather independent aspects of a servlet container:
"concurrency control" and "thread pooling".

Concurrency control, such as achieved by having a servlet implement the


SingleThreadModel interface, addresses the issue of thread safety. A servlet will be
thread-safe or thread-unsafe regardless of whether the servlet container used a
thread pool. Thread pooling merely eliminates the overhead associated with the
creation and destruction of threads as a servlet container tries to respond to multiple
requests received simultaneously. It is for this reason that the specification document
for Servlet 2.2 API is silent on the subject of thread pooling -- as it is merely an
implementation detail. However, the document does indeed address the issue of
thread safety and how and when to use SingleThreadModel servlets.

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.

Comments and alternative answers

"My experiments show that Tomcat 3.1 does indeed...


Author: Eric Armstrong (http://www.jguru.com/guru/viewbio.jsp?EID=201746), Oct
2, 2000
"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."

--thank you. That is the information I needed. Apparently, then, it *tries* to do


efficient processing, but only succeeds part of the time...

Which servlet containers have persistent session support? Specifically, does


Tomcat 3.1?
Location: http://www.jguru.com/faq/view.jsp?EID=212858
Created: Sep 21, 2000 Modified: 2000-09-28 19:28:27.817
Author: Avi Kak (http://www.jguru.com/guru/viewbio.jsp?EID=26410) Question
originally posed by Abhay Bhanushali
(http://www.jguru.com/guru/viewbio.jsp?EID=202848

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.

Comments and alternative answers

Thank you for a response I am more interested in ...


Author: Abhay Bhanushali (http://www.jguru.com/guru/viewbio.jsp?EID=202848),
Sep 28, 2000
Thank you for a response

I am more interested in persistant implementation of session supported by the


Application Server providers. WebSphere supports persistant session implementation.
This is required for to add scalability to App Servers. My investigation shows Tomcat
does not implement persistant session management.

Are there any freeware App Servers that support this feature?

Re: Thank you for a response I am more interested in ...


Author: zalla rouge (http://www.jguru.com/guru/viewbio.jsp?EID=1167200), Apr
29, 2004
I have tried to code persistency of the tomcat 4 sessions (only for client data) and I
made it work, but I have never tested it in a heavy load production envrironment.

Can I use JAAS as the authentication technology for servlets ?


Location: http://www.jguru.com/faq/view.jsp?EID=213499
Created: Sep 22, 2000 Modified: 2000-10-05 19:14:36.497
Author: reshma deshmukh (http://www.jguru.com/guru/viewbio.jsp?EID=132478)
Question originally posed by Lieven Trappeniers
(http://www.jguru.com/guru/viewbio.jsp?EID=111554

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

Can I use JAAS authorization part in a servlet without...


Author: Eric Touchard (http://www.jguru.com/guru/viewbio.jsp?EID=208811), Oct
16, 2000
Can I use JAAS authorization part in a servlet without its authentication part? (The
authentication is done via a web server or a servlet engine.)

Re: Can I use JAAS authorization part in a servlet without...


Author: tippu sultan (http://www.jguru.com/guru/viewbio.jsp?EID=417083), Jun
26, 2001
No , It is not at all possible to use JAAS with out authentication, With JAAS
authentication only we can do authorisation other wise you will get exeception say
trying to authorise unautenticated subject.

JAAS not implemented in J2EE containers


Author: martin smith (http://www.jguru.com/guru/viewbio.jsp?EID=260406), Mar 23,
2001
The best way to do security for most apps seems likely to be to rely on the security
services provided by J2EE containers (app servers.) However, my research so far
indicates that common J2EE containers have not implemented JAAS. E.g., Tomcat
and Allaire's JRun. I assume this is because they were developed before JAAS was
finalized, and I assume (hope) this will be corrected and standardized in future
releases of these products (and perhaps made mandatory for J2EE certification.)
Martin

How can I see/access the response headers? Request headers can be


accessed using request.getHeaderNames() but how to access the response
headers?
Location: http://www.jguru.com/faq/view.jsp?EID=213901
Created: Sep 23, 2000 Modified: 2000-09-28 19:32:44.797
Author: gopala krishna kakani
(http://www.jguru.com/guru/viewbio.jsp?EID=209882) Question originally posed by
nitin k (http://www.jguru.com/guru/viewbio.jsp?EID=137461

It is not (yet) possible to see response header information.

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.

Comments and alternative answers

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...

How does one do it in weblogic 5.1 without a web.xml file


Author: Shailesh Kumar (http://www.jguru.com/guru/viewbio.jsp?EID=874140),
Sep 16, 2002
How does one do it when there is no web.xml file.There is only a servlet
registered in the weblogic.properties file

Is it possible to write a servlet that acts as a FTP server?


Location: http://www.jguru.com/faq/view.jsp?EID=218390
Created: Sep 28, 2000 Modified: 2000-09-28 20:23:55.887
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by sharma MR (http://www.jguru.com/guru/viewbio.jsp?EID=4939

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.

Generally, extending servlets to protocols other than HTTP is a quixotic enterprise.


Just install a standalone FTP server and you'll be much happier.

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

[You could also try to parse your web.xml file... -Alex]

Comments and alternative answers

You can use the following statement to set in your...


Author: Balaji Thraksha (http://www.jguru.com/guru/viewbio.jsp?EID=222075), Oct
4, 2000
You can use the following statement to set in your response.

getServletContext().getMimeType(File2View)

where File2View is the name of the file. String Parameter.


Is there a way to disable a user's ability to double-click a submit
image/button (and therefore submitting duplicate data -- multiple
submits)? Is there a way to do this with Javascript?
Location: http://www.jguru.com/faq/view.jsp?EID=219433
Created: Sep 30, 2000 Modified: 2001-09-26 12:31:55.779
Author: Ken Beard (http://www.jguru.com/guru/viewbio.jsp?EID=219432) Question
originally posed by Gregory Grondin
(http://www.jguru.com/guru/viewbio.jsp?EID=211118

[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.

[That's fine, but... Got source? -Alex]

Comments and alternative answers

Disallowing Multiple Submits/Clicks.


Author: Prashant Rais (http://www.jguru.com/guru/viewbio.jsp?EID=484518), Jan
11, 2002
Is there a way to do it on the server side if I have the constraint of not using
javascript?

Re: Disallowing Multiple Submits/Clicks.


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jan 30,
2002
Yes, see Disabling Multiple Clicks

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.

What are the main differences between Servlets and ISAPI?


Location: http://www.jguru.com/faq/view.jsp?EID=221843
Created: Oct 3, 2000 Modified: 2000-10-04 11:57:03.041
Author: swarraj kulkarni (http://www.jguru.com/guru/viewbio.jsp?EID=121306)
Question originally posed by Bharadwaja Cheruvu
(http://www.jguru.com/guru/viewbio.jsp?EID=216253

The first difference is obviously that Servlets is the technology from Sun
Microsystems and ISAPI is from Microsoft.
Other Differences are:

Servlet is a simple .class file and ISAPI is a DLL


Servlets run in the Servlet containers and may be in-process or out of process.
ISAs run in the same address space as the HTTP server
Servlet container preprocesses and postprocesses the data communication
between the client and server. ISAPI Filters provide the capability of pre-processing
and post-processing of all data sent between the client and the server
Java is the only choice for writing Servlets, VC++/MFC is used to write ISAPI
code
Servlets works on most of the Web servers plus third party containers can be
integrated with other web servers to provide servlets on them. ISAPI works on only
ISAPI-compliant Web server (for example, Microsoft Internet Information Server)
Servlets can connect to the Databases through JDBC as well as jdbc-odbc
bridges. ISAPI can connect to Databases through only ODBC
Servlets have access to many server-side technologies like EJB and etc. ISAPI is
limited in scope
Multiple commands can be implemented in a servlet by using pathinfo. ISAPI
allows multiple commands in one DLL, implemented as member functions of the
CHttpServer object in the DLL.
Content generation and content presentation can be done seperately in Servlets
with the help of JSP. ISAPI code has to generate HTML code itself.

You can find more info here:


ISAPI Information
Servlets information

Is ASP's "response.redirect" equivalent to the Servlet API's


"response.sendRedirect"?
Location: http://www.jguru.com/faq/view.jsp?EID=222059
Created: Oct 4, 2000 Modified: 2000-10-04 11:59:57.426
Author: Rajakumar Makapur (http://www.jguru.com/guru/viewbio.jsp?EID=129728)
Question originally posed by Vinaykumar Nagubandi
(http://www.jguru.com/guru/viewbio.jsp?EID=116693

Yes it is.

response.sendRedirect(String url) is equivalent of ASP's response.redirect method.

Comments and alternative answers

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.

For instance, your JavaBean could have the following code:

private JspPage jspPage;

public JspPage getJspPage()


{
return jspPage;
}

public void setJspPage(JspPage jspPage)


{
this.jspPage = jspPage;
}

Then, from within your JSP page, you could invoke:

<jsp:useBean id="yourBean" class="your.package.YourBean" />


<% yourBean.setJspPage(this); %>

Now, your bean can access the implicit objects and methods of the calling JSP page.

How can I call C or C++ code from servlets?


Location: http://www.jguru.com/faq/view.jsp?EID=222735
Created: Oct 4, 2000 Modified: 2000-12-01 09:05:18.686
Author: Alexander Krapf (http://www.jguru.com/guru/viewbio.jsp?EID=221775)

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]

How do I invoke CORBA from a servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=223605
Created: Oct 6, 2000 Modified: 2000-10-06 13:03:48.628
Author: zhu jiang (http://www.jguru.com/guru/viewbio.jsp?EID=14031) Question
originally posed by Jiyong Jon (http://www.jguru.com/guru/viewbio.jsp?EID=88580

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.

Can I associate a servlet with a particular mime-type, so if the client


requests a file of that type, my servlet will be executed?
Location: http://www.jguru.com/faq/view.jsp?EID=223689
Created: Oct 6, 2000 Modified: 2000-10-06 13:02:44.867
Author: Wellington Silva (http://www.jguru.com/guru/viewbio.jsp?EID=223085)
Question originally posed by Dmitry Ryzhevich
(http://www.jguru.com/guru/viewbio.jsp?EID=208194

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.

How can I use Apache's http://xml.apache.org/fop software embedded into


a servlet to generate a PDF output file?
Location: http://www.jguru.com/faq/view.jsp?EID=223692
Created: Oct 6, 2000 Modified: 2000-10-06 14:01:17.777
Author: Wellington Silva (http://www.jguru.com/guru/viewbio.jsp?EID=223085)
Question originally posed by Shannon Wenzel
(http://www.jguru.com/guru/viewbio.jsp?EID=116219

Take a look on Cocoon demo apps. There's a demo for this in there.

[Does anyone have a URL for this demo? -Alex]

Comments and alternative answers

The Cocoon FAQ provides an answer at http://xml.ap...


Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Oct 7,
2000
The Cocoon FAQ provides an answer at http://xml.apache.org/cocoon/faqs.html#faq-
fopimages.

What are the different cases for using sendRedirect() vs.


getRequestDispatcher()?
Location: http://www.jguru.com/faq/view.jsp?EID=223732
Created: Oct 6, 2000 Modified: 2000-10-06 12:59:31.857
Author: Wellington Silva (http://www.jguru.com/guru/viewbio.jsp?EID=223085)
Question originally posed by Vinaykumar Nagubandi
(http://www.jguru.com/guru/viewbio.jsp?EID=116693

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.

If my servlet or JSP contains international characters (like "Ýðüö"), how do


I ensure they are displayed correctly?
Location: http://www.jguru.com/faq/view.jsp?EID=224631
Created: Oct 8, 2000 Modified: 2000-10-08 18:15:10.571
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Berrin Altuntas
(http://www.jguru.com/guru/viewbio.jsp?EID=216891

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
&#221;&#240;&#252;&#246;
or
&Yacute;&eth;&uuml;&ouml;

I have written a method, htmlescape(), that converts a Unicode string (one


containing two-byte Unicode characters) into the HTML-escaped equivalent. It is
available at http://www.purpletech.com/code/src/com/purpletech/util/Utils.java. (If
the site is currently unavailable, please send me email.)

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

[Short answer: put it in your CLASSPATH. -Alex]

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
(shirish.bathe@wipro.com)

Comments and alternative answers

Resource Bundle on Web Server


Author: Fintan Conway (http://www.jguru.com/guru/viewbio.jsp?EID=452521), Aug
20, 2001

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

How do I access the value of a cookie using JavaScript?


Location: http://www.jguru.com/faq/view.jsp?EID=225605
Created: Oct 10, 2000 Modified: 2000-10-15 12:58:18.458
Author: Shirish Bathe (http://www.jguru.com/guru/viewbio.jsp?EID=88588)
Question originally posed by Seshadri Venkatesh
(http://www.jguru.com/guru/viewbio.jsp?EID=121699

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";

And the following statement displays the property's value:

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 (shirish.bathe@wipro.com)

Comments and alternative answers

You should go to the cookies page at javascript.in...


Author: Melanie Munden (http://www.jguru.com/guru/viewbio.jsp?EID=138305),
Oct 16, 2000
You should go to the cookies page at javascript.internet.com. It has lots of free
examples: http://javascript.internet.com/cookies/

How do I convert my existing applets and/or CGI programs to servlets?


Location: http://www.jguru.com/faq/view.jsp?EID=227520
Created: Oct 12, 2000 Modified: 2000-10-15 12:55:10.277
Author: Ryan Breidenbach (http://www.jguru.com/guru/viewbio.jsp?EID=45212)
Question originally posed by Philip Ly
(http://www.jguru.com/guru/viewbio.jsp?EID=111844

This is really two different questions.

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.

Comments and alternative answers

See also What are the Servlet equivalents to all the...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Oct 15, 2000
See also What are the Servlet equivalents to all the CGI environment variables?

You cannot replace applets with servlets, however if...


Author: Andrew Howard (http://www.jguru.com/guru/viewbio.jsp?EID=225016), Oct
16, 2000
You cannot replace applets with servlets, however if your applet happens to connect
to a server using a specific port other than 80 you will realise that you can have
security issues with client's firewalls. This is where servlets come in. With servlets
you can create your own protocol within HTTP which is called HTTP Tunnelling
this allows the servlet to use the Serializable interface of ojects to copy the object
through the HTTP protocol and then the applet can use this object as it pleases.

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.

Is there a clean way to interface with CyberCash CashRegister service from


a java servlet or EJB?
Location: http://www.jguru.com/faq/view.jsp?EID=228899
Created: Oct 15, 2000 Modified: 2000-10-24 08:36:27.44
Author: Alexandros Kotsiras (http://www.jguru.com/guru/viewbio.jsp?EID=64209)
Question originally posed by Celia Jia
(http://www.jguru.com/guru/viewbio.jsp?EID=142900

I haven't been able to find a "clean" way to do this.

The way cybercach MCK works is the following :


You submit the order to directpaycredit.cgi which connects to the Cybercash Server
and from there to the Financial institution. The directpaycredit.cgi depending on the
success or failure of the transaction sends it's response to a success.tem file or a
failure.tem file. MCK provides a way to retrieve in those files inside hidden fields all
the values of the input fields (CC_Number, Customer_Name etc.) that the user
entered when he submitted the final form.

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.

I haven't been able to find a better way...


Thanks,
Alex.

How can we send a POST request when we call getRequestDispatcher()


functions ? It is easy to make a GET request but I don't know how for POST
one.
Location: http://www.jguru.com/faq/view.jsp?EID=231318
Created: Oct 18, 2000 Modified: 2000-10-24 10:33:52.192
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by APAN Cyril
(http://www.jguru.com/guru/viewbio.jsp?EID=211969

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

See also http://www.jguru.com/jguru/faq/view.jsp?EID=740

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.

[The JavaScript source code for doing this is:


<input type="button" onClick="window.print(0)" value="Print This Page">
-Alex]

How do I invoke the command-line Java interpreter from a web server or


servlet (assuming there is a java application on the machine where the
webserver is located)? Or, can I invoke Java with CGI?
Location: http://www.jguru.com/faq/view.jsp?EID=232370
Created: Oct 19, 2000 Modified: 2000-10-24 10:30:51.799
Author: Serge Knystautas (http://www.jguru.com/guru/viewbio.jsp?EID=100012)
Question originally posed by syahriar rizza
(http://www.jguru.com/guru/viewbio.jsp?EID=223435

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]

Comments and alternative answers

I run the java program in a separate JVM on WIN NT....


Author: Michael Wu (http://www.jguru.com/guru/viewbio.jsp?EID=141930), Jan 14,
2001
I run the java program in a separate JVM on WIN NT. A separate console window
always opens and then closes. How can I run the java program in the background or at
least hide the console window?

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.

One approach is to create a java.awt.Frame, and then use java.awt.Toolkit's


getPrintJob method to print that Frame to the printer. This will return a
java.awt.PrintJob object if it works.

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.

[See also http://www.jguru.com/jguru/faq/view.jsp?EID=98857]

How do I set up a virtual host? That is, I want http://www.foo.com/ to be


served off my own machine.
Location: http://www.jguru.com/faq/view.jsp?EID=234896
Created: Oct 24, 2000 Modified: 2000-10-24 11:03:35.284
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by venkata prasad earanti
(http://www.jguru.com/guru/viewbio.jsp?EID=210033

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.)

1. Name-based virtual host: Multiple hostnames mapped to the same static IP


address.
2. IP-based virtual host: Multple hostnames, each mapped to a different static IP
address, but one machine responding to all of those multiple IP addresses.
These are often called "IP aliases" or "multiple interfaces" (here "interface"
refers to the TCP/IP interface, not any of the other infinite definitions of
"interface").

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:

• Unix Split Personality: How to Virtual Host


• Linux IP-Alias mini-HOWTO
• Apache Virtual Host documentation
• Does anyone know how to do IP aliasing on Windows?
• How do I use servlet aliasing, so the URL
"http://foo.com/mywebapp/servlet/a.b.c.MyServlet" can become
"http://foo.com/mywebapp/Thingy"?
• Can I configure Tomcat so that the name of the webapp is not used in the
URL? E.g. http://localhost/servlet/HelloWorld, instead of
http://localhost/examples/servlet/HelloWorld
• How do I set up virtual hosting on Tomcat in standalone mode?
• How do I set up virtual hosting on Tomcat with Apache?
• How do I set up virtual hosting on Java Web Server?
• How do I set up virtual hosting on Allaire JRun?

How can I serve a "Linearized" PDF file from a servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=236545
Created: Oct 25, 2000 Modified: 2001-07-23 09:59:30.715
Author: Garth Somerville (http://www.jguru.com/guru/viewbio.jsp?EID=225821)
Question originally posed by Richard Williams
(http://www.jguru.com/guru/viewbio.jsp?EID=2390
[More question: I am using a servlet to stream out the bytes of a PDF file to a user's
browser. No problem there, it's just streaming out a file. The problem is in dealing
with what Acrobat refers to as "Linearized" files. When served by a Netscape
Enterprise server, these "linearized" files display the first page of the PDF file in the
Acrobat Reader while subsequent pages are still being loaded. When displayed using
my servlet as the file source, the entire document must download before I can see
the first page.]

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:

GET /example.pdf HTTP/1.1


Range: bytes=0-1023
Here, the client is asking for only the first 1K of the file.

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.

[Hmm, sounds a little dubious... Has anyone tried this? -Alex]

Comments and alternative answers

I tried to do this with IE5.0


Author: Colin Yates (http://www.jguru.com/guru/viewbio.jsp?EID=772727), Feb 26,
2002
Hi, I have tried to do this but I cannot get IE to request the byte ranges? It is using
http1.1 but I have checked all the headers, all the parameters etc. and it never asks for
the bytes. I have tried simply setting the status to 206, but it doesn't do anything. If
someone could figure out how to extract the byte range I will carry on. Cheers Colin
Yates

Re: I tried to do this with IE5.0


Author: Sylvainn Lesagee
(http://www.jguru.com/guru/viewbio.jsp?EID=1222412), Jan 20, 2005
Hi please forward the code, i am doing something similar work. Thanx

Re: I tried to do this with IE5.0


Author: Sylvainn Lesagee
(http://www.jguru.com/guru/viewbio.jsp?EID=1222412), Jan 20, 2005
Hi, please forward the code at: slesage "at" neuf.fr i am doing something similar
work. Thanx

I have done this


Author: Robert Wind (http://www.jguru.com/guru/viewbio.jsp?EID=418623), Mar
22, 2002
I've written a servlet that responds appropriatly to byte-range requests. If anyone's
interested, I'll post the code.

Re: I have done this


Author: Colin Yates (http://www.jguru.com/guru/viewbio.jsp?EID=772727), Mar
23, 2002
Please post, I am *very* interested! Could you please also email to
colin.yates@ntlworld.com Cheers

Re[2]: I have done this


Author: Robert Wind (http://www.jguru.com/guru/viewbio.jsp?EID=418623),
Mar 25, 2002
The code appears to be too large to post here, so I'll email it to you. If anyone
else is interested, email me at rwind@rochester.rr.com.

Re[3]: I have done this


Author: Sudheendra Galgali
(http://www.jguru.com/guru/viewbio.jsp?EID=868107), Jul 21, 2004
Hi, I am interested in this code too. Can you send it to me? Thanks, -SG

Re[2]: I have done this


Author: John Hayward
(http://www.jguru.com/guru/viewbio.jsp?EID=1195083), Aug 24, 2004
Did you get the source code for serving bytes from a servlet? I'm interested in
doing this myself. Could you email that source code to me also? I'm at
jhayward@boldtech.com thank you.

Re[3]: I have done this


Author: Jan Pelegrin
(http://www.jguru.com/guru/viewbio.jsp?EID=1243379), May 10, 2005
Is it possible to have the source code also. Mailto jan.pelegrin#4st.be
Thanks

Re[2]: I have done this


Author: Rajesh Boopalan
(http://www.jguru.com/guru/viewbio.jsp?EID=1206250), Oct 19, 2004
We also handling the similer one,could you please send the code to mail id.
rajpalan@yahoo.com Thanks in Advance, B.Rajesh.

Re: I have done this


Author: chatla prathap (http://www.jguru.com/guru/viewbio.jsp?EID=28780), Apr
7, 2004
please send me the code as iam interested in it. thanks in advance.

Re[2]: I have done this


Author: m k (http://www.jguru.com/guru/viewbio.jsp?EID=1174232), May 27,
2004
I'm looking to do the same thing with a servlet, is the code still available?
Thank you

please forward the code


Author: aarthi vad (http://www.jguru.com/guru/viewbio.jsp?EID=1195392),
Aug 25, 2004
please forward the code, i am doing something similar work.

Re: please forward the code


Author: Antony Lawrence
(http://www.jguru.com/guru/viewbio.jsp?EID=1199791), Sep 17, 2004
Can I have it too (antony.lawrence@wachovia.com).... Thanx

Re[2]: please forward the code


Author: Nitin Goyal
(http://www.jguru.com/guru/viewbio.jsp?EID=1204913), Oct 13, 2004
Can I have the code too? (nitingoyal_07@yahoo.com) Thanks.

Re[3]: please forward the code


Author: Nav Gupta
(http://www.jguru.com/guru/viewbio.jsp?EID=1208992), Nov 3,
2004
Could someone please send me (navgupta@yahoo.com) the code as
well?

Re: I have done this


Author: Nitin Goyal (http://www.jguru.com/guru/viewbio.jsp?EID=1204913), Oct
13, 2004
I have implemented it successfully for single byte-range requests but the browser
does nothing when it requests for multipart/byteranges. I have followed RFC2616
conventions to send the multipart/byteranges but browser does not seem to
respond to it. Do I have anything other than specified in RFC2626 for multipart?

Re: I have done this


Author: Cathy Hui (http://www.jguru.com/guru/viewbio.jsp?EID=1207626), Oct
27, 2004
Hi Robert, Could u pleaset post the code online for us to share please? Thanks!
Cathy

How can I serve a "Linearized" PDF file from a servlet?


Author: Murray Bob (http://www.jguru.com/guru/viewbio.jsp?EID=1209589),
Nov 6, 2004
Can I get the code as well

Re: I have done this


Author: lana shapiro (http://www.jguru.com/guru/viewbio.jsp?EID=1213053),
Nov 25, 2004
Hi Robert. Could you please e-mail me this code? My e-mail address is
lana.shapiro@comcast.net . Thank you very much.
« previous beginning next »

Could you show me an example of using doPut() method?


Location: http://www.jguru.com/faq/view.jsp?EID=236578
Created: Oct 25, 2000 Modified: 2001-07-15 22:49:41.473
Author: Garth Somerville (http://www.jguru.com/guru/viewbio.jsp?EID=225821)
Question originally posed by Daniel Mayor
(http://www.jguru.com/guru/viewbio.jsp?EID=66226

[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]

A simple example would be a source code repository application consisting of a Java


Applet on the client and a Servlet on the server -- it would be entirely appropriate to
upload new files into the system by having the applet send an HTTP PUT request,
which would be processed by the servlet's doPut() method.

I am guessing there is more to this question. It is important to understand that in


the HTTP 1.1 protocol, each request indicates a resource (the request path) and an
action (the method) to be taken. In HTTP/1.1 the methods supported are OPTIONS,
GET, POST, HEAD, PUT, DELETE, and TRACE. Each of these is clearly defined and
differentiated in the HTTP/1.1 RFC. In particular, POST and PUT do not mean the
same thing.

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:

->GET /file.dat HTTP/1.1

<-HTTP/1.1 404 Not Found

->PUT /file.dat HTTP/1.1


Content-Length: 6
Content-Type: text/plain

Hello!

<-HTTP/1.1 200 OK

->GET /file.dat HTTP/1.1

<-HTTP/1.1 200 OK
Content-Length: 6
Content-Type: text/plain

Hello!

The above exchange makes no sense if POST is used instead of PUT.

However, when it comes to servlet programming, the distinctions among HTTP


methods have been largely lost, in particular the difference between GET and POST.
When it comes to servlets, it is essentially up to the author to define what his
doPost() or doPut() means but it probably makes sense to keep in mind what these
mean in HTTP and try to use them accordingly.

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.

What does the exception "java.net.SocketException: Connection reset by


peer" mean? How can this be avoided?
Location: http://www.jguru.com/faq/view.jsp?EID=237557
Created: Oct 26, 2000 Modified: 2000-10-26 09:45:16.207
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Nivedita Dixit
(http://www.jguru.com/guru/viewbio.jsp?EID=224747
It usually happens when the connection was reset by the peer -- that is, when the
client unexpectedly closed the socket. This happens when the user clicks "stop", or
"reload", or "back", or enters a new URL, or closes his Internet connection, while a
resource is still being downloaded (before your server gets to close its socket). This
is normal behavior and you shouldn't worry about it.
Comments and alternative answers

But why does it happen only when I use Netscape as...


Author: Manish Bhatnagar (http://www.jguru.com/guru/viewbio.jsp?EID=12550),
Mar 1, 2001
But why does it happen only when I use Netscape as my browser ? My servlets work
very fine with Internet Explorer. They cry with this error only when I use Netscape as
my browser.

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 browser started a request and the user pressed STOP.


• The browser started an request in one frame and JavaScript on another frame
told it to go somewhere else (which has the same effect as a user pressing
STOP).
• You have a meta refresh reload someplace that is firing so fast that the
previous request hasn't had a chance to complete yet. The five second
periodicity makes me pretty suspicious of this.
• You have some network component in between (a router or proxy) that is
misbehaving.
• You have some completely separate connection attempts going on that are
disobeying the HTTP protocol (such as doing a telnet connection to port 8080
and then disconnecting).

Re: Craig says


Author: Xavier Haurie (http://www.jguru.com/guru/viewbio.jsp?EID=471764),
Aug 8, 2001
I had an interesting instance of Craig's second point: "The browser started an
request in one frame and JavaScript on another frame told it to go somewhere else
(which has the same effect as a user pressing STOP)."

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:

<input name="button" type="submit" onClick="location=URL; return


false;">

Re: Craig says


Author: sathish r (http://www.jguru.com/guru/viewbio.jsp?EID=1180043), Jun 19,
2004
I get this error when i do multi threading from client side. Client is a java app
which talks to a Directory server. I made the code to execute parallely, this is
causing this exception in tomcat servlet which is the client. I do not understand
how multithreading affects networking behaviour?

Another question on this....


Author: Michael Shelnutt (http://www.jguru.com/guru/viewbio.jsp?EID=483318),
Aug 24, 2001
Actually, does anyone know how I can catch this behavior in my servlet? If the user
submits a form which in turn starts a long query on my db, if the user clicks STOP or
BACK, I want to stop the query from processing. Any thoughts?

Re: Another question on this....


Author: Adam Flint (http://www.jguru.com/guru/viewbio.jsp?EID=477446), Aug
28, 2001
The approach I took was to get the servlet to set the response in the doPost method
and then go off and do its processing.

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

Re: Another question on this....


Author: Lee Johnson (http://www.jguru.com/guru/viewbio.jsp?EID=999672), Sep
16, 2002
Michael, Did you ever find a solution to this? We also need to catch this
exception. However, this exception does not appear to be catchable since jrun
handler already catches it ?

java.net.SocketException:Connection reset by peer


Author: pradnya korde (http://www.jguru.com/guru/viewbio.jsp?EID=1011016), Oct
11, 2002
hello, i am getting the same problem to be more elaborate i am trying to use the
concept of applet - servlet communitcation. an applet is connecting to a servlet using
URLConnection.. the applet is wrinting an object of type vector to the ouputstream
using hte writeObejct function of the Objectouptutstream class however the servlet is
not able to read it from the inputstream... at this time it throws the excption
java.net.SocketException:Connection reset by peer what can be the problem any
idea..? thank you so much in advance Pradnya

Re: java.net.SocketException:Connection reset by peer


Author: Jon Dean (http://www.jguru.com/guru/viewbio.jsp?EID=1161759), Apr 9,
2004
has anyone given an answer for this? i am communicating with a servlet using a
regualar java application. the app and servlet are communicating back and forth
just fine. the servlet in the end should send out an email but instead returns the
connection reset exception to the app. i'm running tomcat which seems to work
great for my other servlets. i'm kind of stumped as to what this means and
therefore can't really pinpoint the errors in my code and the component i'm writing
with this is due in a few days!

thanks:)

Re[2]: java.net.SocketException:Connection reset by peer


Author: Jon Dean (http://www.jguru.com/guru/viewbio.jsp?EID=1161759),
Apr 9, 2004
well nevermind i found the answer to my own question, although i didn't
realize this forum has been dead for well over a year anyway. in case anyone
happens to come across this the problem was that i was using a mal-formed
smtp server address (a stupid problem i had in searching an array list and
pulling out the wrong string). it seems that this exception will be thrown just
about any time an error causes the connection to be aborted (at least that's what
i gather from the problem i had).

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.

Is there a way to determine what cookies or headers are being sent in a


response? [I'm assuming the response was passed in from a request
dispatcher or something... -Alex]
Location: http://www.jguru.com/faq/view.jsp?EID=243705
Created: Nov 2, 2000 Modified: 2000-11-02 15:43:34.369
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Martin Hinds
(http://www.jguru.com/guru/viewbio.jsp?EID=137914

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.

See also http://www.jguru.com/jguru/faq/view.jsp?EID=213901

Comments and alternative answers

You can use the containsHeader() method of HttpSer...


Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Nov 3,
2000
You can use the containsHeader() method of HttpServletResponse to see if a response
is there, just not get its value.

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

You can't. That's a security feature. See What is a cookie?.

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]

Comments and alternative answers

Session cookies and the cookie domain...


Author: Daniel Leong (http://www.jguru.com/guru/viewbio.jsp?EID=796580), Mar
14, 2002
I'm not sure your answer is 100% true. As I understand it, the JSP session is usually
maintained in a cookie (expcet for URL rewriting). Cookies that are expected to work
for SSL sites too probably need to specify a cookie domain. This gets mentioned
briefly in this article here, in context of Weblogic. I know Websphere can do the
same, but I'm not sure about Tomcat.

Re: how do I share sessions between two server instances...


Author: alberto rosa (http://www.jguru.com/guru/viewbio.jsp?EID=351649), May 8,
2002
I think the point is sharing session data between 2 instances. As the servlet spec says,
session scope is web application (=servlet context) domain. So, there is no garanty to
share session data between 2 web applications, neither so between 2 instances. But,
this depends on the vendor's implementation (see vendor's session manager details for
more information). For example, Websphere 3.5 is not compliant with servlet spec, so
you can share session data between 2 web applications in the same instance. Hope
this makes sense for you... Regards, Alberto.

Re[2]: how do I share sessions between two server instances...


Author: m lar (http://www.jguru.com/guru/viewbio.jsp?EID=918866), Jun 19,
2002
Could you give me a more deeper explanation about sharing session between 2
web applications? I work with Websphere 4.0.3 Thanks in advance, Marta

Re[3]: how do I share sessions between two server instances...


Author: alberto rosa (http://www.jguru.com/guru/viewbio.jsp?EID=351649),
Jun 19, 2002
Marta:

Websphere 4 is already servlet 2.2 compliant, so the concept of web


application is added in that version. In previous versions, web applications
session domain was not isolated from others, but this is no longer running on
WAS 4.x.

Hope this is clearer for you.

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...


Author: Niclas Meier (http://www.jguru.com/guru/viewbio.jsp?EID=245132), Nov 7,
2000

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]

How can I output audio or video from a servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=245939
Created: Nov 5, 2000 Modified: 2001-07-23 09:18:07.365
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by sathish baboo
(http://www.jguru.com/guru/viewbio.jsp?EID=203430

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).

Comments and alternative answers

Actually, it is possible (and not that hard) to send...


Author: Ivar Vasara (http://www.jguru.com/guru/viewbio.jsp?EID=262588), Nov 25,
2000

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.

Note: don't forget to set the correct MIME type.

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]

Still unclear to me how to play output video from a servlet to a browser


Author: Amit Rosner (http://www.jguru.com/guru/viewbio.jsp?EID=433821), Jun 5,
2001
I would like to send video to a servlet to the browser (ie5) , so that the video will play
within the browser itself. Currently, following the suggestions here, I used the
"sendRedirect" to send the MPG to the browser but it opened it with "Windows
Media Player". How can I play in within the browswer itself? Can anyone send me a
sample code that does that? Amit.

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");

Re: HTML suggestion


Author: Marta Santana (http://www.jguru.com/guru/viewbio.jsp?EID=873616),
May 10, 2002
Hi evreybody, I have another question related to this, How can I embed video
when that video is a query result. I make it on the fly!! Can anyone help me!!
Thanks a lot marta

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

In ServletAPI 2.1 a new method is added which is: HttpSession


HttpServletRequest.getSession() With which you can get Session object. See
http://java.sun.com/products/servlet/2.1/changes.html .

In jsdk 2.1 there are two methods for getting session

1) HttpSession getSession(boolean create) Gets the current valid session associated


with this request, if create is false or, if necessary, creates a new session for the
request, if create is true.

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]

Comments and alternative answers

Home-rolled session IDs and using the HttpSession object.


Author: Richard Robinson (http://www.jguru.com/guru/viewbio.jsp?EID=395750),
Apr 7, 2001
I have a similar question. I have a servlet application that has been in existence for 2
years now. I rolled it using my own session IDs, which I pass in the URL or hidden
fields on POSTs. There are quite a few methods that depend on the format of the
Session ID as it is. And I will lose all that if I go to the Java HTTPSession object's
creation of sessions. Is there no way I can enjoy all the benefits of HttpSession object
-- WHILE using my same session IDs (and their baggage logic/format)?

Re: Home-rolled session IDs and using the HttpSession object.


Author: M. washu (http://www.jguru.com/guru/viewbio.jsp?EID=1217388), Dec
21, 2004
I'm interested to know if there is an alternative to this question ?

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.

How do I set up virtual hosting on Allaire JRun?


Location: http://www.jguru.com/faq/view.jsp?EID=246903
Created: Nov 6, 2000 Modified: 2000-12-07 20:23:40.845
Author: reshma deshmukh (http://www.jguru.com/guru/viewbio.jsp?EID=132478)
Question originally posed by Alex Chaffee PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=3

Refer Alliare knowledgebase:


http://www.allaire.com/support/KnowledgeBase/search.cfm

My applet is sending a request to a servlet (using tomcat 3.1 + Apache). I


cannot know upfront how long the processing will take (from 10 seconds to
10 hours).

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.

Comments and alternative answers

Thanks all for your answers. Here is what I had im...


Author: Nicolas Cohen (http://www.jguru.com/guru/viewbio.jsp?EID=235112), Dec
8, 2000
Thanks all for your answers. Here is what I had implemented right after asking the
question: the applet sends the initial request. Then it just sends a ping message from
time to time. The backend server processes the request and the servlet stores the
answer in the session. On the next ping from the applet, the answer is then transferred
to the applet. It works quite well, the GET call is only 59 bytes. This is the same idea
as Jens' solution except I don't store any thread, but Jens couldn't know I had sockets
between middleware and backend too ;)

facing the same problem !!!


Author: hacene khellaf (http://www.jguru.com/guru/viewbio.jsp?EID=454113),
Sep 14, 2001
i'm facing the same problem, i created a thread to keep the servlet alive and i send
to the applet a wait message
the problem is that the stream is closed as soon as i start the thread, is there any
special meaning of " store the thread in the session" ?

thanks for any help

How do you do servlet aliasing with Apache and Tomcat?


Location: http://www.jguru.com/faq/view.jsp?EID=250363
Created: Nov 9, 2000 Modified: 2000-11-21 03:04:34.094
Author: Serge Knystautas (http://www.jguru.com/guru/viewbio.jsp?EID=100012)
Question originally posed by Felix Wong
(http://www.jguru.com/guru/viewbio.jsp?EID=102927
Servlet aliasing is a two part process with Apache and Tomcat. First, you must map
the request in Apache to Tomcat with the ApJServMount directive, e.g.,

ApJServMount /myservlet /ROOT

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

Hi, I have tried doing what you have suggested, but...


Author: Alex Korneyev (http://www.jguru.com/guru/viewbio.jsp?EID=326128), Feb
11, 2001
Hi, I have tried doing what you have suggested, but it is not working. this is what i
have in web.xml

<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

What about with mod_jk?


Author: javier Beringola (http://www.jguru.com/guru/viewbio.jsp?EID=345612), Jun
14, 2001
This works perfect with jserv but do you know how to do it with mod_jk?

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

Re: Servlet Aliasing


Author: Nancy Roberts
(http://www.jguru.com/guru/viewbio.jsp?EID=739557), Jan 30, 2002
Hi, Thanks man,that was a very tricky and cool way of solving it.i tried it and
working fine.we were badly looking for a solution .this works well with Jserv
also. Nancy

Re: Servlet Aliasing


Author: Dave Peter (http://www.jguru.com/guru/viewbio.jsp?EID=739566),
Jan 30, 2002
Hi Premjith, Superb way of changing the context root of tomcat,working fine
.Thanks and can u try this with Jserv. Dave

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

I think this code will help U


Author: srinivas kandagatla (http://www.jguru.com/guru/viewbio.jsp?EID=1150943),
Mar 2, 2004
HttpSession session = request.getSession(false); boolean takeToLogin = false;
if(session == null) takeToLogin = true; if(takeToLogin) { forward(request, response,
"Login.jsp"); return; }

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 HTTP/1.1 specs at: ftp://ftp.isi.edu/in-notes/rfc2616.txt

See also How do I download a (binary, text, executable) file from a servlet or JSP?
(especially the feedback)

Comments and alternative answers

I want to download XML File with IE5.5SP1. But IE don't...


Author: Tiara Milk (http://www.jguru.com/guru/viewbio.jsp?EID=304749), Jan 17,
2001
I want to download XML File with IE5.5SP1. But IE don't open save as dialog. IE
open XML File,alose DTD File. Please let me know to download XML file with save
as dialog. My code as follows:
--
res.setContentType("application/download");
res.setHeader("Content-Disposition", "inline;filename=myFile.txt");
res.setContentLength((int)file.length());
---
I tried to write [attachment] word. But I got a download.htm. Why?

Try use [extension-token] (see rfc2183)


Author: Evgeny Dementiev (http://www.jguru.com/guru/viewbio.jsp?EID=312081),
Jan 25, 2001
Try use [extension-token] (see rfc2183)

In my servlet I am trying to let the user download...


Author: Mike Jewson (http://www.jguru.com/guru/viewbio.jsp?EID=313341), Jan 26,
2001
In my servlet I am trying to let the user download a file using the following code:
response.setHeader("Content-Disposition","attachment;filename=myFile.txt"); Works
fine in Netscape, but when trying to do this in IE the filename is the name of the
servlet. Is there anyway to fix this?

Re: In my servlet I am trying to let the user download...


Author: seema bhatnagar (http://www.jguru.com/guru/viewbio.jsp?EID=429391),
May 28, 2001
Have u found the solution for this problem.I too am facing the same problem.In
the save as dialog box it displays servlet name.Another starnge problem is that if i
don't provide space in the word "content- disposition" the hour glass waits forever
but gives the correct file name in IE.But in NS it works fine in all the conditions.
Please suggest something.

Re: Re: In my servlet I am trying to let the user download...


Author: david peter (http://www.jguru.com/guru/viewbio.jsp?EID=471669),
Aug 21, 2001
Remove the attachment keyword from the response.setHeader statement. It
then downloads which ever file name you give Thanks

Re: In my servlet I am trying to let the user download...


Author: Surya Rani (http://www.jguru.com/guru/viewbio.jsp?EID=212310), Aug
30, 2001
Hey I used the same code But, it works fine with IE4.7,5.0,5.5SP2 It is not
working in NS. In NS the file name is servlet name. Can you help me in this.

In response to what I had just previously wrote. I...


Author: Mike Jewson (http://www.jguru.com/guru/viewbio.jsp?EID=313341), Jan 26,
2001
In response to what I had just previously wrote. I found that IE does not like a fully
qualified path for the filename like :
filePath = "c:\temp\file.txt";
Make sure that it is just the filename and no directory information. Then it will work
in both Netscape and IE. Thanks.

Re: In response to what I had just previously wrote. I...


Author: Markus Jon Nagel
(http://www.jguru.com/guru/viewbio.jsp?EID=429404), May 28, 2001
According to the RFC mentioned above, absolute filenames such as
"C:\foodir\foofile.txt" are not allowed, supported, you got to hell for it, etc... ;-)
You MUST specify a filename WITHOUT any reference to a directory.
So it seems IE is more standard - compliant that NS is (funny enough).

What happened in NS anyway (just curious)?

Best regards, Markus J. Nagel

it could not be done


Author: durgesh patel (http://www.jguru.com/guru/viewbio.jsp?EID=1218492),
Dec 28, 2004
hi. it could not be done

I have too this problem. Even if a put file path =...


Author: Alexander Mazurok (http://www.jguru.com/guru/viewbio.jsp?EID=313062),
Jan 30, 2001
I have too this problem.
Even if a put file path = only file.
Can anybody help me? please, send comments to amazurok@ukr.net

Thanks. I' sorry. I mistake a file name in this source....


Author: Tiara Milk (http://www.jguru.com/guru/viewbio.jsp?EID=304749), Feb 3,
2001
Thanks. I' sorry. I mistake a file name in this source. I want to download a XML file
with XML extension at the save-dialog.
--
res.setContentType("application/download");
res.setHeader("Content-Disposition", "inline;filename=myFile.xml");
res.setContentLength((int)file.length());
---
I tried to use the extension-token, for example, x-force-download ,and so on. But
IE5.5SP1 think maybe only the file extension. I tried to use the no full Path. But it
worked same thing. My research result is following: IE5.01 is OK.( can open save-
dialog ) IE5.5SP1 is NG.( open the file at the Browser). Is it IE5.5Sp1 BUG? Thaks.

Second posting - I didn't see the first so I am re...


Author: Scott Rolfson (http://www.jguru.com/guru/viewbio.jsp?EID=341761), Mar 1, 2001
Second posting - I didn't see the first so I am resending. I apologize if this is a duplicate.

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.

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 25, 2001
I must just be blind or something, but I couldn't find ANYTHING on MS support
about obtaining this file. I followed the link from the MS Bug Page that you
provided and tried to get some "web based support" from them, but I had to sign
up for a Passport account. I tried that, it said my email was already in use. When I
tried to log in using my email, it said that account didn't exist. Arghh!! I searched
everywhere else on that site, to no avail.

Can you point me in the right direction to find this simple little thing?? Thanks!

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 25, 2001
Update your BIO with an email address or post it here and I will send you the
files.

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 srolfson@yahoo.com 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......

apocalypse29_99@yahoo.com

I want give an option to download several files..


Author: Ramesh Juluru (http://www.jguru.com/guru/viewbio.jsp?EID=434906), Jul 4,
2001
How can i give an option to download several files as alex told for
one file.
Awaited reply.
regards,
ramesh

saving text file...


Author: Chris Chan (http://www.jguru.com/guru/viewbio.jsp?EID=1150403), Mar 1,
2004
I'm trying to write the text file based on the result set form the command. The thing is,
I don't want the file saved on the server, rather have the file saved on the client
machine. Is there a way to attach this text file when it technically hasn't been created?
I tried the execCommand to use the saveAs dialog, but it defaults everything to
unicode, even though I clearly state it is "text/plain". thanks in advance.

file download dialog on IE browser


Author: ramaa Davanagere
(http://www.jguru.com/guru/viewbio.jsp?EID=1184629), Jul 8, 2004
This article is very useful for me but I want to find out if we can take this a step
further. What I mean by this is, can we find out if the user clicked "Open" or
"Save" or "Cancel" buttons on the file download dialog? Is there a handle that I
returned with the what the user clicked. I'm more inter ested to know if the user
clicked cancel button. I need to take specific actions when the user clicks cancel
button or the save button. Please help me. Thanks a ton. If you know the answer
(or any ideas) Thanks. Ramaa
« previous beginning next »

Can Tomcat be configured to interpret all, or selected, .html files within a


given context as JSP? Or, do JSP files have to end with a .jsp extension?
Location: http://www.jguru.com/faq/view.jsp?EID=254460
Created: Nov 15, 2000 Modified: 2000-12-07 19:59:03.193
Author: swarraj kulkarni (http://www.jguru.com/guru/viewbio.jsp?EID=121306)
Question originally posed by Tom Boyd
(http://www.jguru.com/guru/viewbio.jsp?EID=230240

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>

And comment out the following block

<mime-mapping>
<extension>
html
</extension>
<mime-type>
text/html
</mime-type>
</mime-mapping>

What is the difference between request attributes, session attributes, and


ServletContext attributes?
Location: http://www.jguru.com/faq/view.jsp?EID=255157
Created: Nov 16, 2000 Modified: 2000-12-01 13:12:10.11
Author: Wellington Silva (http://www.jguru.com/guru/viewbio.jsp?EID=223085)
Question originally posed by Bhalinder Singh
(http://www.jguru.com/guru/viewbio.jsp?EID=205994

A ServletContext attribute is an object bound into a context through


ServletContext.setAttribute() method and which is available to ALL servlets (thus
JSP) in that context, or to other contexts via the getContext() method. By definition
a context attribute exists locally in the VM where they were defined. So, they're
unavailable on distributed applications.

Session attributes are bound to a session, as a mean to provide state to a set of


related HTTP requests. Session attributes are available ONLY to those servlets which
join the session. They're also unavailable to different JVMs in distributed scenarios.
Objects can be notified when they're bound/unbound to the session implementing
the HttpSessionBindingListener interface.

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]

Are singleton/static objects shared between servlet contexts?


Location: http://www.jguru.com/faq/view.jsp?EID=256911
Created: Nov 17, 2000 Modified: 2000-12-07 21:20:21.071
Author: kedar choudhary (http://www.jguru.com/guru/viewbio.jsp?EID=99914)
Question originally posed by kurt kessel
(http://www.jguru.com/guru/viewbio.jsp?EID=237344

[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?]

It depends on from where the class is loaded.

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.

When building web applications, what are some areas where


synchronization problems arrise?
Location: http://www.jguru.com/faq/view.jsp?EID=259083
Created: Nov 21, 2000 Modified: 2000-12-07 21:24:13.745
Author: Brian O'Byrne (http://www.jguru.com/guru/viewbio.jsp?EID=38567)
Question originally posed by rob g
(http://www.jguru.com/guru/viewbio.jsp?EID=47931

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.

Typical examples include:

• Connections to external servers, especially if you have any sort of pooling.


• Anything which you include in a HttpSession. (Your user could open many
browser windows and make many simultaneous requests within the one
session.)
• Log destinations, if you do your own logging from your servlets.

How do I identify the device (browser) the request is coming from?


Location: http://www.jguru.com/faq/view.jsp?EID=259332
Created: Nov 21, 2000 Modified: 2000-12-07 23:56:27.149
Author: Michael Szlapa (http://www.jguru.com/guru/viewbio.jsp?EID=241392)
Question originally posed by Pankaj Mishra
(http://www.jguru.com/guru/viewbio.jsp?EID=238618

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:

Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 4.0)

To read it you can do something like this:

request.getHeader("User-Agent");

See also servlet examples coming with the Jakarta-Tomcat.

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

There are several tools available on the internet for this.


The most effective one that I've found is
Net Mechanic -
http://www.netmechanic.com
They have an image optimizing utility, as well as utilities to tell you about anything
else that may be wrong with your HTML code.

TROY

ASP provides an Ad Rotator component for using banners on a web site. Is


there an equivalent way to rotate ad banners in Servlets?
Location: http://www.jguru.com/faq/view.jsp?EID=259608
Created: Nov 21, 2000 Modified: 2000-12-13 10:03:05.992
Author: Troy Niven (http://www.jguru.com/guru/viewbio.jsp?EID=219893) Question
originally posed by Avinash Kapoor
(http://www.jguru.com/guru/viewbio.jsp?EID=239024

None that I know of.


There is such thing as a Javascript that will do it though.
Here's an example.
The script is free to use, and easily customized.
TROY

How can I explicitly load a servlet ?


Location: http://www.jguru.com/faq/view.jsp?EID=260178
Created: Nov 22, 2000 Modified: 2000-12-07 20:02:47.939
Author: Omar Khan (http://www.jguru.com/guru/viewbio.jsp?EID=232689) Question
originally posed by Rajesh Ajmera
(http://www.jguru.com/guru/viewbio.jsp?EID=47656

Servlets can be loaded automatically when a servlet engine starts, using


configuration parameters. They depend on which servlet engine you are using. For
instance, JRun 2.2 has a configuration parameter that is called Pre-Load.

See also http://www.jguru.com/jguru/faq/view.jsp?EID=218109

Comments and alternative answers

Java Web Server does not automatically load the se...


Author: prajakt samant (http://www.jguru.com/guru/viewbio.jsp?EID=272793), Dec
11, 2000
Java Web Server does not automatically load the servlet. You need to do :
Class.forname("servletclass");
to load the Servlet

How do I identify the device (browser) the request is coming from?


Location: http://www.jguru.com/faq/view.jsp?EID=262330
Created: Nov 25, 2000 Modified: 2000-11-29 11:18:23.363
Author: Russell Quong (http://www.jguru.com/guru/viewbio.jsp?EID=262328)
Question originally posed by Pankaj Mishra
(http://www.jguru.com/guru/viewbio.jsp?EID=238618

public void doGet (HttpServletRequest req, HttpServletResponse resp) .... {


String browser = req.getHeader("User-Agent");
...
}
On Linux I get something like:
Mozilla/4.73 [en] (X11; U; Linux 2.2.17 i686)

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.)

You may view the code at my home page


(http://www.geocities.com/perry_tew/jsp_code/refreshservlet/). There are three
source files: a bean, a servlet, and a web.xml file. If you have any questions, let me
know.

Comments and alternative answers

Here's a stripped down version of the code. It uses...


Author: Perry Tew (http://www.jguru.com/guru/viewbio.jsp?EID=60814), Dec 1,
2000
Here's a stripped down version of the code. It uses two classes: LongTaskBean and
LongTaskServlet. Note: I'm not threading expert, so if someone sees room for
improvement, please post about it. Thanks!
=============================================

//LongTaskServlet.java

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class LongTaskServlet extends HttpServlet{

LongTaskBean longTask = null;

public void init() throws ServletException {

longTask = new LongTaskBean();

public void doPost( HttpServletRequest request,

HttpServletResponse response)

throws

ServletException, IOException{

doGet( request, response );

/**

* Handle the HTTP GET method by building a simple web page.

*/
public void doGet ( HttpServletRequest request,

HttpServletResponse response)

throws

ServletException, IOException{

PrintWriter

out;

// set content type and other response header fields first

response.setContentType("text/html");

// then write the data of the response

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"

+ " <h1>Long Task

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

page will automatically refresh every 10 seconds.</i>");

} else {

out.println(

"<b>No

refresh is taking place. Click the button to begin.</b>");

out.println(

"</td></tr></table>" + "\n");

if ( !longTask.isDoingTask() ) {

out.println(

"

<center>" + "\n"

+ "

<form name=\"form1\"

method=\"POST\">" + "\n"
+ "

<input

type=\"hidden\" name=\"doTask\" "

"value=\"yes\">"

+ "\n"

+ "

<input

type=\"submit\" value=\"Do Task\">"

+ "\n"

+ "

</form>" + "\n"

+ "

</center>" + "\n"

);

out.println(

"</body></html>");

out.close();

//===========================================
//LongTaskBean.java

public class LongTaskBean{

private boolean inLongTask = false;

private String status = "No Status Available";

private String lastErrorMsg = "NONE";

public LongTaskBean(){}

public boolean isDoingTask(){

return inLongTask;

private void setTaskFlag( boolean flag ){

inLongTask = flag;

public String getLastError(){

return lastErrorMsg;

private void setLastError(String msg){

lastErrorMsg = msg;

}
public String getStatus(){

return status;

private void setStatus( String s ){

status = s;

public void doLongTask(){

if( !isDoingTask() ){

setTaskFlag(true);

new LongTaskThread(

"Refresh Part Master" ).start();

return;

private class LongTaskThread extends Thread{

public LongTaskThread( String str ){

super( str );

private void exitWithError( String error ){

// not using sync


method to prevent possible lock

lastErrorMsg = error;

inLongTask = false;

public void run(){

/* reset the

lastErrorMsg */

setLastError("NONE

(Beginning Long Task)");

//======= DO TASK HERE

================//

for ( int i = 0; i <

10; i++ ){

setStatus("I'm

sleeping #" + i + ". Check back later");

try

{ sleep( 5000 ); } catch (InterruptedException e){}

setLastError("NONE:

Completed Successfully");

setTaskFlag(false);
}

Re: Here's a stripped down version of the code. It uses...


Author: Seema K (http://www.jguru.com/guru/viewbio.jsp?EID=380850), Mar 29,
2001
Hi Perry, The code has has been put in very well but I faced a small problem while
running the servlet. Internet Explorer gives me the following error "This page
cannot be refreshed without resending the information" Click on Retry or Cancel.
We need to keep clicking on Retry if the servlet has to proceed. Can you suggest a
way out for this ?

As far as I am concerned, this arises a new question:...


Author: Thanos Varias (http://www.jguru.com/guru/viewbio.jsp?EID=44391), Dec 3,
2000
As far as I am concerned, this arises a new question: Many web appservers I have
used get really angry when you start opening and closing threads in their execute
threads context. Can anybody think of a way to deliver the same result avoiding
threads?
Thanks,
Thanos Varias

Another solution is to display the text "Loading,...


Author: shahbaz chaudhary (http://www.jguru.com/guru/viewbio.jsp?EID=268763),
Dec 7, 2000
Another solution is to display the text "Loading, please wait..." using java script at the
top of the page (before executing the query) and hide the text after the query is done.

Re: Another solution is to display the text "Loading,...


Author: Padma Killi (http://www.jguru.com/guru/viewbio.jsp?EID=479480), Aug
19, 2001
Can I have the Javascript code for displaying an intermediate html page like "Wait
Please"..while a jsp page executing the java bean. Your quick assistance would be
appreciated.

Thanos - EJB Servers forbid threads; however, servlet...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Dec 8, 2000
Thanos - EJB Servers forbid threads; however, servlet engines allow them. You just
have to be careful using "distributed" servlets (running on more than one load-
balanced server) that you know what you're doing.

IMHO, all previous answers in this page are wrong ...


Author: Stephane Boisson (http://www.jguru.com/guru/viewbio.jsp?EID=1512), Dec
14, 2000

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...

Here is a short example:

public void service(HttpServletRequest req, HttpServletResponse res)


throws ServletException, IOException
{
res.setContentType("multipart/x-mixed-
replace;boundary=\"boundary\"");
ServletOutputStream out = res.getOutputStream();

// Here is the first part


out.print("\n\r--boundary\n\r");
out.print("Content-Type: text/html\n\r\n\r");

out.println("<H1>Waiting...</H1>");
out.flush();

// Here is the long work (here, a sleep)


try {
Thread.sleep(3000);
}
catch (Exception e) {
// ignore
}

// Here is the second part


out.print("\n\r--boundary\n\r");
out.print("Content-Type: text/html\n\r\n\r");

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");

Don't forget to close the tags at the end of the document.


Now this should work!

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 {

public void init() throws ServletException {

public void service(HttpServletRequest req, HttpServletResponse


res)
throws ServletException, IOException
{
res.setContentType("multipart/x-mixed-
replace;boundary=\"boundary\"");
ServletOutputStream out = res.getOutputStream();

// Here is the first part


out.print("\n\r--boundary\n\r");
//out.print("Content-Type: text/html\n\r\n\r");
res.setContentType("text/html");
out.println("<HTML><head><title>Wait
page</title></head>");
out.println("<body>");
out.println("<H1>Waiting...</H1>");
out.println("</body>");
out.println("</HTML>");
out.flush();

// Here is the long work (here, a sleep)


try {
Thread.sleep(3000);
}
catch (Exception e) {
// ignore
}

// Here is the second part


out.print("\n\r--boundary\n\r");
//out.print("Content-Type: text/html\n\r\n\r");
res.setContentType("text/html");
out.println("<HTML><head><title>Done
page</title></head>");
out.println("<body>");

out.println("<H1>Done</H1>");

out.print("\n\r--boundary--\n\r");
out.println("</body>");
out.println("</html>");
out.flush();
}

public void destroy(){

}
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)

Stephane, Thanks for the post! I'm still learning...


Author: Perry Tew (http://www.jguru.com/guru/viewbio.jsp?EID=60814), Feb 2,
2001
Stephane,
Thanks for the post! I'm still learning html, so I really enjoyed your comments.

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

Re: Stephane, Thanks for the post! I'm still learning...


Author: Vanathi Manivannan
(http://www.jguru.com/guru/viewbio.jsp?EID=460199), Jul 23, 2001
Any update on this? I'm now facing the similar issue. Did you get any solution for
this

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 )

throws ServletException, IOException


{
res.setContentType( "text/html" );

HttpSession session = req.getSession( true );


PrintWriter out = res.getWriter();

if ( session.getValue( "WAIT" ) == null )


{
session.putValue( "WAIT", "" );

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 to implement Waiting message.....in <iframe>


Author: Java Boy
(http://www.jguru.com/guru/viewbio.jsp?EID=282622), Feb 12, 2002
This solution is very good but in my JSP page i have differnt iframe
which contains differnt jsps and that take time to load . The main jsp
contains 4 iframes even if i write the above code in each jsp user can't
see it because jsps are down in the page and user has to scroll down the
page. So pl. help me How to display waiting message in this case.
Thanks in adv.

Re: How to implement Waiting message.....in <iframe>


Author: Bill Allen
(http://www.jguru.com/guru/viewbio.jsp?EID=764191), Feb 19,
2002
use a little ballen script!

Re[2]: How to implement Waiting message.....in <iframe>


Author: Java Boy
(http://www.jguru.com/guru/viewbio.jsp?EID=282622), Feb 20,
2002
What do u mean by that? I don't understand.
« previous beginning next »

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.

// Grant to code in foobar directory


grant codeBase "file:/foobar/-"
{
permission java.io.FilePermission "${/}bin${/}myapplication",
"read,exec";
}

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!

What is the difference between apache webserver, java webserver and


tomcat server?
Location: http://www.jguru.com/faq/view.jsp?EID=265204
Created: Nov 29, 2000 Modified: 2000-11-29 11:05:01.175
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by SREEDHAR REDDY
(http://www.jguru.com/guru/viewbio.jsp?EID=111571

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

Comments and alternative answers

I thought Tomcat could be used as a http server for non-production purposes?


Author: Emm R (http://www.jguru.com/guru/viewbio.jsp?EID=1154361), Mar 15,
2004
I thought Tomcat could be used as a http server for non-production purposes?

.. 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

Re[3]: .. therfore there is no difference in their over all purpose except


the languages used to write them. ( ? )
Author: Richa Ai (http://www.jguru.com/guru/viewbio.jsp?EID=1255954),
Aug 1, 2005
Yes Tomcat alone is good enuf

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...

How can I call a servlet from a CGI script (written in Perl)?


Location: http://www.jguru.com/faq/view.jsp?EID=266269
Created: Nov 30, 2000 Modified: 2000-12-13 10:14:08.683
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by devabhaktuni mahendra
(http://www.jguru.com/guru/viewbio.jsp?EID=243752

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....

[There are two other options:

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 try to install and not working


Author: Frans Thamura (http://www.jguru.com/guru/viewbio.jsp?EID=384571), Mar
21, 2001
I install mysql in my PC, install tomcat 3.2.1, and copy the mysql_comp.jar to
c:\tomcat\lib, but still have an error cannot attempt to access. error: at
Class.forName("org.gjt.mm.mysql.Driver"); Regards, Frams

Re: I try to install and not working


Author: Vasant Kumar (http://www.jguru.com/guru/viewbio.jsp?EID=53644),
May 16, 2001
Hi unzip the jar file and copy the 'org...' dircetory structure to 'web-inf\classes'
directory. I had the same problem... I put it in classpath...and everywhere. I m
using Win 2K Adv server. Thanks Vasant

Re[2]: I try to install and not working


Author: Eric Deandrea
(http://www.jguru.com/guru/viewbio.jsp?EID=899305), May 31, 2002
I am having the exact same problem under tomcat 3.3. Has anyone got this
working?

Tomcat 3.3 use of JDBC mm.mysql-2.0.6 driver


Author: Paul Shields (http://www.jguru.com/guru/viewbio.jsp?EID=464686), Jul 30,
2001
I am using Tomcat 3.3 on Solaris 2.6 and had to place the mm.mysql-2.0.6.jar file in
the $TOMCAT_HOME/lib/common directory and restart the Tomcat server to get the
jsp engine to find the driver. I had originally placed the jar file in
$TOMCAT_HOME/lib directory as directed by the Tomcat installation instructions,
but this resulted in a class not found exception on org.gjt.mm.mysql.Driver

Re: Tomcat 3.3 use of JDBC mm.mysql-2.0.6 driver


Author: grant8411 grant8411
(http://www.jguru.com/guru/viewbio.jsp?EID=1038095), Dec 15, 2002
put the jar file inside c:\jdkXXXX\jre\lib\ext folder

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.

Joe Sam Shirah adds:

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.

Comments and alternative answers

Some code that may help you.


Author: Paul Hunnisett (http://www.jguru.com/guru/viewbio.jsp?EID=504117), Sep
27, 2001
The following code will do what you want once you have got hold of your file as a
file.

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

What is the difference between an Application Server and a Web Server?


Location: http://www.jguru.com/faq/view.jsp?EID=282323
Created: Dec 19, 2000 Modified: 2000-12-20 10:05:22.308
Author: sharad chaudhary (http://www.jguru.com/guru/viewbio.jsp?EID=62937)

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) ]

Comments and alternative answers

Web servers do offer caches, clustering and load b...


Author: Dan Christopherson (http://www.jguru.com/guru/viewbio.jsp?EID=39644),
Dec 21, 2000
Web servers do offer caches, clustering and load balancing - in fact, these are far
easier to implement for web servers than application servers, because web servers are
far simpler.

Also, HTTP is an application layer protocol that runs over TCP/IP.

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)

Now, given Apache's module APIs, is it a web server or an application server?

Re: Web servers do offer caches, clustering and load b...


Author: Balaji Sundararajan
(http://www.jguru.com/guru/viewbio.jsp?EID=439659), Jun 15, 2001

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.)

Re[2]: Web servers do offer caches, clustering and load b...


Author: Barath Ganesan
(http://www.jguru.com/guru/viewbio.jsp?EID=1212633), Nov 23, 2004
In my context,a web server is just a publishing server.whereas an application
server provides some services like security, and as said before clustering and
caches on its own.we jus have to configure in order to use these services.in
case of a web server it is the burdon of the programmer to do all these. A web
server provides services only to web clients whereas an application server
provides services to any application which is running in a distributed
environment.

Re: Web servers do offer caches, clustering and load b...


Author: Matt Rokenbrod (http://www.jguru.com/guru/viewbio.jsp?EID=955561),
Jul 18, 2002
Can multiple Application Servers Run on the same webserver on the same
computer?

Re: Web servers do offer caches, clustering and load b...


Author: Krupakar Jonnalagadda
(http://www.jguru.com/guru/viewbio.jsp?EID=1204169), Oct 8, 2004
Apache's module apis is an application server.

WebServer just serves HTTP Request, while Application...


Author: Anurag Goel (http://www.jguru.com/guru/viewbio.jsp?EID=285633), Dec 25,
2000
WebServer just serves HTTP Request, while Application Server consist of Servlet
Engine, and serve WebServer. WebServer contains only HTML files and send only
HTML file any other file requested which has to be compiled dynamically based on
the request, Webserver will get it from Application Server. Application Server consist
of Servlet Engine,JVM and other parsers which interpret the required class files and
send it to Webserver.

It should also be noted that while many AppServers...


Author: Alex Varanese (http://www.jguru.com/guru/viewbio.jsp?EID=334606), Feb
20, 2001
It should also be noted that while many AppServers (such as BEA's WebLogic) are
indeed a superset of web server functionality, they aren't generally used that way.
WebLogic is often used for it's enterprise capabilities and then augmneted by allowing
Apache to handle the strictly HTTP-related side of things.

Re: It should also be noted that while many AppServers...


Author: Sanjay Kumar Gupta
(http://www.jguru.com/guru/viewbio.jsp?EID=1083738), May 12, 2003
Summary: A normal web server can handle Http request means it can provide
static web pages, images, css etc. For generating dynamic web contents it requires
support for JSP, Servlets etc in Java & ASp in Microsoft respectively. So A java-
enabled webserver means it has JVM & servlet engine which can run java servlets
or JSp if it has JSP container. In such a case, the web server on receiving http
request which can be handled by a servlet, passes it on to servlet which will
handle it & may generate an HTML page which web server delivers to
webbrowser. An application server can provide services based on various
protocols including HTTP, meaning web service can be inbuilt or can be
configured with it. Application servers serve application code to application
clients. It provides several services like transaction processing, resource pooling
i.e. database connection pooling, Security features, clustering etc.

Re[2]: It should also be noted that while many AppServers...


Author: prasenjit biswas
(http://www.jguru.com/guru/viewbio.jsp?EID=1228123), Apr 8, 2005
You can't run EJB or any business logic in Javawebserver.An application
server should have the capability to run business logic in it.That's why we can't
say that JWserver a application server.

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....

Re: Application vs Webserver


Author: rahul bose (http://www.jguru.com/guru/viewbio.jsp?EID=219615), Sep 4,
2001
can a web server exists by itself without any appserver Thanks, rahul

Re: Re: Application vs Webserver


Author: praveen Kumar Nagunoori
(http://www.jguru.com/guru/viewbio.jsp?EID=542975), Nov 13, 2001
Yes Webserver can exists by itself as it supports all the basic facilties to serve
the purpose of a simple webhosting

How can you embed a JavaScript within servlets / JSP pages?


Location: http://www.jguru.com/faq/view.jsp?EID=284607
Created: Dec 22, 2000 Modified: 2000-12-22 12:27:24.197
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by ashok GS (http://www.jguru.com/guru/viewbio.jsp?EID=284597

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.

Comments and alternative answers

You can include JavaScript inside JSP code in two ...


Author: vijay kumar (http://www.jguru.com/guru/viewbio.jsp?EID=286766), Dec 27,
2000
You can include JavaScript inside JSP code in two manner:
<head>
<script language="javascript" src = "pagename.js">
</script>
</head>
or At any point of time in between JSP code,
<script language ="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.

How can I make a POST request through response.sendRedirect() or


response.setStatus() and response.setHeader() methods?
Location: http://www.jguru.com/faq/view.jsp?EID=285822
Created: Dec 26, 2000 Modified: 2000-12-26 06:02:05.853
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Hemant Desai
(http://www.jguru.com/guru/viewbio.jsp?EID=250843

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

• Use GET instead


• Make the POST from your servlet, not from the client
• Store data in cookies instead of passing it via GET/POST

Search the FAQ for questions relating to the above.

I have synchronized doGet() and doPost() methods in my servlets. Will this


create any problem? Should i use the single thread model instead?
Location: http://www.jguru.com/faq/view.jsp?EID=285904
Created: Dec 26, 2000 Modified: 2000-12-28 09:46:07.137
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Parvez Kapadia
(http://www.jguru.com/guru/viewbio.jsp?EID=263972

This question is answered in the main Servlets/Threading question,


http://www.jguru.com/jguru/faq/view.jsp?EID=150, especially point 4.

Don't use SingleThreadModel either, since there are many pitfalls.

Unfortunately, there's no shortcut to thread safety. Just learn the techniques,


synchronize access to shared data only, and you'll be OK.

My servlet's destroy() method is never called. Is this a bug in WebSphere,


or am I doing something wrong?
Location: http://www.jguru.com/faq/view.jsp?EID=286603
Created: Dec 26, 2000 Modified: 2000-12-27 08:16:42.353
Author: Kris Srikanth (http://www.jguru.com/guru/viewbio.jsp?EID=283258)
Question originally posed by Ken Xu
(http://www.jguru.com/guru/viewbio.jsp?EID=285652

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]

Comments and alternative answers

I have this problem while using Websphere 3.0.2 for...


Author: Ken Xu (http://www.jguru.com/guru/viewbio.jsp?EID=285652), Dec 27,
2000
I have this problem while using Websphere 3.0.2 for NT. After I install the patch for
Websphere, the problem is solved. Now my servlet's destroy() method is called when
the servlet is unloaded. [Yay! So it *was* a bug in WebSphere! -Alex]

What is a better way of writing servlets 1. A Single servlet which uses


something like command pattern. i.e same servlet based on incomming
paramter does different things. Or 2. Different servlet for different
operations. Like Login Servlet, Logout Servlet, Preferences Servlet etc.

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

I think the 2nd option is best, becauase

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.

4. Easy to mentain the code if it is broken by functionality.

I hope this helps you. --Badri

Comments and alternative answers


I prefer the 1-servlet solution. Especially when...
Author: Alexander Jesse (http://www.jguru.com/guru/viewbio.jsp?EID=293364), Jan
4, 2001
I prefer the 1-servlet solution.

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).

At the end it will depend on personal likings.


-- Alexander

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.

I open my servlet database (JDBC-ODBC) connection in the init() method. I


close it in the destroy() method. My database is configured to close the
connection automatically after 10 minutes of idle time. This creates
problems since the servlet does not call the destroy() method and the init()
method remains in the memory. within that time and after 10 minutes if a
user requests that servlet it throws an exception saying : not logged on.
why is this happening and if you can provide a solution to this problem by
giving a sample code?
Location: http://www.jguru.com/faq/view.jsp?EID=287341
Created: Dec 27, 2000 Modified: 2001-01-04 05:48:02.297
Author: Jorge Jordão (http://www.jguru.com/guru/viewbio.jsp?EID=275762)
Question originally posed by Parvez Kapadia
(http://www.jguru.com/guru/viewbio.jsp?EID=263972

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.*;

public class DBServlet extends HttpServlet {

private static final String DB_DRIVER =


"sun.jdbc.odbc.JdbcOdbcDriver";
private static final String DB_URL = "jdbc:odbc:Northwind";
private static final String DB_USER = "";
private static final String DB_PASSWORD = "";

public void init(ServletConfig config) throws ServletException {


try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException ex) {
throw new UnavailableException("JDBC Driver " + DB_DRIVER +
" not found.");
}
}

public void doPost(HttpServletRequest request, HttpServletResponse


response)
throws IOException, ServletException {
try {
Connection conn =
DriverManager.getConnection(DB_URL,DB_USER,DB_PASSWORD);
// execute statements (and process results)
conn.close();
} catch (SQLException ex) {
// handle exception
}
}

If you find this approach too slow, consider using a connection pool.

Comments and alternative answers

Can't you reconfigure your database so it doesn't time...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jan 4, 2001
Can't you reconfigure your database so it doesn't time out connections?

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).

Comments and alternative answers

You can also generate reports using Excel,by setting...


Author: Priya Venkatesan (http://www.jguru.com/guru/viewbio.jsp?EID=129496), Jan
2, 2001
You can also generate reports using Excel,by setting the
response.setContentType("application/vnd.ms-excel") in a JSP page. Doing so,you
will be able to view the report(lets say you created one using <table></table> in
html.)If you set this contentType, you will be able to see the generated report in
Excel.

Re: You can also generate reports using Excel,by setting...


Author: Nandakumar Adikesavan
(http://www.jguru.com/guru/viewbio.jsp?EID=585789), Jan 10, 2002
Hai, i am using Apache tomcat 4.0. I tried 2 ways: (1) <%@ page
contentType="application/vnd.ms-excel" %> (2)
response.setContentType("application/vnd.ms-excel"); i didn't get any proper o/p.
If u have to know, pls reply me.

Re[2]: You can also generate reports using Excel,by setting...


Author: Javier Ramos Saralegui
(http://www.jguru.com/guru/viewbio.jsp?EID=782130), Mar 5, 2002
You should atke a look a the POI project at apache.org there is a full API to
manage Excel files.

Can I rename the name of the output file?


Author: Raul Cosio (http://www.jguru.com/guru/viewbio.jsp?EID=531530), Jan
18, 2002
I have created an example using response.setContentType(...) and
<table>...</table> It works fine but before displaying the result a dialog box
appears asking if I want to view the result in the page or save to disk. Is it possible
to avoid this dialog?. If not, is it possible to make the dialog have another file
name like report.xls instead of report.jsp ? Thanks

Re: Can I rename the name of the output file?


Author: Suren Raj (http://www.jguru.com/guru/viewbio.jsp?EID=814033),
Mar 27, 2002
Hi Raul, iam using weblogic server 6.1. Iam trying to open/save an excel file
on the click of hyper link. But it opens in a normal text instead opening an
excel window. Whats the problem in the following code. Or if u have some
sample pl. email to surenraj@indiatimes.com Thanx in advance Test.jsp:
<HTML> <HEAD> <TITLE></TITLE> <%
response.setContentType("application/vnd.ms-excel"); %> </HEAD> <BODY
onload=""> <form method="post" name ='test' action=''> test </form>
</BODY> </HTML> Regards Suren

Re: Can I rename the name of the output file?


Author: Raul Cosio (http://www.jguru.com/guru/viewbio.jsp?EID=531530),
Mar 31, 2002
Maybe the problem is you are calling response.setContentType() after
<HTML><HEAD>... and content type is already written to the client. In my
code I'm using a table because each cell will be displayed in your Excel
spreadsheet. The table doesn't include any header tags...

<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>

Hope this helps

Re[2]: Can I rename the name of the output file?


Author: Mark Mac
(http://www.jguru.com/guru/viewbio.jsp?EID=1157650), Mar 25, 2004
Raul, I tried to implement your scripts above, but it won't display in Excel,
it would appear as a normal page in my browser. Can you please give me
some light on this? Are there any configuration/setting needed to be check?

Re: You can also generate reports using Excel,by setting...


Author: anu doddapuneni
(http://www.jguru.com/guru/viewbio.jsp?EID=1159013), Apr 2, 2004
Can some one tell me how to generate and save excel by clicking on a link.. I am
using hssf framework to create a excel file. By default it saves on server side, but i
want a dialogbox to open to give an option to user to save or open.. I appriciate ur
help.. This is what i am doing.. HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet <-- code to create rows and cells and cell data
here--> String fileName = "test.xls"; FileOutputStream fileOut = new
FileOutputStream(fileName); response.setContentType("application/vnd.ms-
excel"); response.setHeader("Content-Disposition", "inline;
filename="+fileName); wb.write(fileOut); fileOut.close();

What if the conditions are as follows: 1. the webserver...


Author: Joanna Chua (http://www.jguru.com/guru/viewbio.jsp?EID=349162), Mar
11, 2001
What if the conditions are as follows:
1. the webserver should be platform-independent.
2. it doesn't require IIS or for the web client to be using windows platform. (that
means linux-based platform user/web clients should be to access this also, as to how
please tell me so.)

So based on the above conditions, the use of COM Excel object or any of the
Windows stuff are out of the question.

JSP Excel, easy...


Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), May 21,
2001
Just set the appropriate content type and provide a tab delimited file for the output and
you've generated yourself an Excel spreadsheet.
<%@ page contentType="application/vnd.ms-excel" %>
This is a test
1 2 3 4
5 6 7 8

Re: JSP Excel, easy...


Author: Jennifer Hunt (http://www.jguru.com/guru/viewbio.jsp?EID=434241),
Jun 5, 2001
I'm quite new to JSP. I have created a .jsp file based on the example provided. The
output to the browser is: This is a test 12345678 - not in excel. Please tell me what
I'm doing wrong....

Re: JSP Excel, easy...


Author: Anand Sundarraman
(http://www.jguru.com/guru/viewbio.jsp?EID=477083), Aug 14, 2001
I am using this for technique for creating excel files from Java servlets. Now what
I want to do is create multiple sheets with specific names. Is this possible? If so
pls let me know.

Re: Re: JSP Excel, easy...


Author: Anil Passi (http://www.jguru.com/guru/viewbio.jsp?EID=494831),
Sep 12, 2001
Anand can u send me the code u r having. I too need it and will it run on sun
solaris machine with iplanet webserver installed ........ My requirement is to
create an Excel sheet without using odbc ... any windows tool ... I have to do it
on sun solaris iplanet machine ..... Any advice on this will be of big help to
me... mail me at anilk_7@yahoo.com regards anil

Re[2]: JSP Excel, easy...


Author: ambudu ambudu
(http://www.jguru.com/guru/viewbio.jsp?EID=851513), Apr 23, 2002
Hi Anand could you pls send me the code u use to create excel file from a
servlet Thanks Siva

Re: JSP Excel, easy...


Author: Nandakumar Adikesavan
(http://www.jguru.com/guru/viewbio.jsp?EID=585789), Jan 10, 2002
hai, John I would like to know, where i want to specify my ".xls" files ???? how to
open Excel ???? Pls, reply me..!!! Thanks..

Re: JSP Excel, easy...


Author: Mark Mac (http://www.jguru.com/guru/viewbio.jsp?EID=1157650), Mar
25, 2004
John, I tried to implement your script but I wasn't successful in running it on my
PC. What are the possible reasons why it will open as a normal JSP Page instead
of Excel. Im running at Windows 2000, Service Pack 4, Internet Explorer 6.0.
Thanks ahead.

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

Re: see also


Author: avish Khode (http://www.jguru.com/guru/viewbio.jsp?EID=1262142),
Sep 13, 2005
Hi , I have a from with some Text Boxes in which user fills the data (Date range
etc) Once user Press a Submit button i am Calling javaScript which will submit
the Data to the another Url whih will generate the .xls file as Response . But My
problem i that My file opens in same Browser window for which i have
sumbmited the from , I want .xls file to be opened in some other Window . Plz tell
me How can i o this. Plz mail me if anyBody Knows Solution My email id
mail2avish@yahoo.com

How can I automatically invoke a servlet periodically at specified time


intervals, like cron?
Location: http://www.jguru.com/faq/view.jsp?EID=293013
Created: Jan 4, 2001 Modified: 2001-09-07 09:35:17.145
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Ram Prasad.K
(http://www.jguru.com/guru/viewbio.jsp?EID=108201

You can do this using Java Threads.

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?

2. In this servlet's init() method, spawn a thread.

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).

The java.util.Timer class can help a lot. See

• How do I schedule a task to run at a certain time?


• How do I schedule a task to run repeatedly?

See also How can I automatically invoke a servlet at regular time intervals using
Resin?
Comments and alternative answers

See "run-at" parameter in servlet config...


Author: Pavel Bernshtam (http://www.jguru.com/guru/viewbio.jsp?EID=274236), Jan
4, 2001
See "run-at" parameter in servlet configuration for Resin (www.caucho.com) Servlet
Engine

spawned thread does not always get destroyed


Author: Doug Straka (http://www.jguru.com/guru/viewbio.jsp?EID=499147), Sep 18,
2001
This works great, although I have noticed that the spawned thread (infinite loop) does
not always get destroyed when I bring down the application server. Any ideas on how
to prevent this from happening?

Re: spawned thread does not always get destroyed


Author: John Mark Mark (http://www.jguru.com/guru/viewbio.jsp?EID=579145),
Dec 10, 2001
Try setting setting the damon to true then if the thread that opened it is killed .. the
spawned thread should die as well.

How do I pass a request object of one servlet as a request object to another


servlet?
Location: http://www.jguru.com/faq/view.jsp?EID=293386
Created: Jan 4, 2001 Modified: 2001-01-05 06:12:50.287
Author: chris lambrou (http://www.jguru.com/guru/viewbio.jsp?EID=293366)
Question originally posed by Lalit Choudhary
(http://www.jguru.com/guru/viewbio.jsp?EID=257176

Use a Request Dispatcher. Please look at


http://java.sun.com/docs/books/tutorial/servlets/communication/request-
dispatcher.html. [Also the other FAQs in the topic Servlets:Message Passing -Alex]

Is there anything available in the HttpServletRequest which would tell me


whether the request came through HTTP or WAP originally, letting me set
my content type on the response accordingly? I want something a bit more
reliable than the user-agent in the header.
Location: http://www.jguru.com/faq/view.jsp?EID=293952
Created: Jan 5, 2001 Modified: 2001-01-05 05:40:21.901
Author: Edward Williams (http://www.jguru.com/guru/viewbio.jsp?EID=241100)
Question originally posed by Edward Williams
(http://www.jguru.com/guru/viewbio.jsp?EID=241100

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";

/** Content type string for WML */


public static final String CONTENT_TYPE_WML = "text/vnd.wap.wml";

/** The header which contains the available content types. */


public static final String HEADER_ACCEPT = "accept";

/** Returns a content type based on the requesting content type


* @param request Servlet request object
* @return The content type
*/
public static String getContentType( HttpServletRequest request ) {

String retval = CONTENT_TYPE_HTML; // Default return.

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

The problem with relying on the User-Agent header is...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jan 5, 2001
The problem with relying on the User-Agent header is that new user agents
(browsers) are released all the time, and you don't have any way of knowing what
they can or can't do. However, current browsers are actually pretty good at sending
*unique* User-Agent headers. What's needed is an up-to-date database describing the
capabilites of each User-Agent. You can then find out, not only whether it supports
WML, but also other markup languages (e.g. CHTML or HDML), what image types
(JPG, BMP, etc.), screen size, color, etc.

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
:-) ]

How can I set a System property in a servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=294938
Created: Jan 6, 2001 Modified: 2001-01-07 16:57:23.424
Author: Chandra Patni (http://www.jguru.com/guru/viewbio.jsp?EID=33585)
Question originally posed by Ankit Doshi
(http://www.jguru.com/guru/viewbio.jsp?EID=255153

You can simply use System.setProperty("propertyKey", "PropertyValue")


method in a servlet.

What is the basic need to use servlets?


Location: http://www.jguru.com/faq/view.jsp?EID=295100
Created: Jan 6, 2001 Modified: 2001-01-15 08:43:05.66
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Anupama Mohan
(http://www.jguru.com/guru/viewbio.jsp?EID=207040

Everyone needs a servlet!


That's right, it filets, it chops, it dices, slices,
Never stops, lasts a lifetime!

It mows your lawn


It picks up the kids from school
It gets rid of unwanted facial hair, it gets rid of embarrassing age spots,
It delivers a pizza,
It lengthens, it strengthens
It entertains visiting relatives,
It turns a sandwich into a banquet
It gets rid of your gambling debts,
it quits smoking

It's a friend, it's a companion.


It's the only product you will ever need

It gives you dandruff, and it finds you a job,


It is a job

(Apologies to Tom Waits)

See also What is a servlet?

Comments and alternative answers

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

Another thing you can do is just redirect to the r...


Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Jan 7, 2001
Another thing you can do is just redirect to the referer of the referer of the page, if
you don't want to hardcode the page. [Can you give a code example? -A]

String callingPage = request.getHeader("Refe...


Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Jan 8, 2001

String callingPage = request.getHeader("Referer");


response.sendRedirect(callingPage);
should do the trick

I suppose you can also use request.getRequestURI()...


Author: Harikrishna Neerkaje (http://www.jguru.com/guru/viewbio.jsp?EID=69829),
Jan 13, 2001
I suppose you can also use request.getRequestURI() to get the address of the jsp page.

request.getRequestURI() gives this request's URI, not...


Author: Rajah Kalipatnapu (http://www.jguru.com/guru/viewbio.jsp?EID=116593),
Mar 7, 2001
request.getRequestURI() gives this request's URI, not the Referer's URI.

Re: request.getRequestURI() gives this request's URI, not...


Author: Clarence Tan (http://www.jguru.com/guru/viewbio.jsp?EID=815644),
Mar 31, 2002
how come when compiled, the reponse object is not found? this is the eRRoR
regis.java:138: cannot resolve symbol symbol : variable response location: class
regis response.sendRedirect(path); ^ 1 error

Re[2]: request.getRequestURI() gives this request's URI, not...


Author: Garrett Smith (http://www.jguru.com/guru/viewbio.jsp?EID=733867),
Aug 16, 2002
In the jsp:
<input type='hidden' name='location' value='<%=
request.getRequestURI() %>' />
In the action servlet:
String location = request.getParameter("location");
;

What is the ServletConfig object, and why is it useful?


Location: http://www.jguru.com/faq/view.jsp?EID=295514
Created: Jan 7, 2001 Modified: 2001-01-08 08:01:45.047
Author: Troy Niven (http://www.jguru.com/guru/viewbio.jsp?EID=219893) Question
originally posed by Dhiraj Asrani
(http://www.jguru.com/guru/viewbio.jsp?EID=276883

The ServletConfig object is an interface. It contains the methods


getInitParameter
getInitParameterNames
getServletContext
getServletName
You can use the methods to determine the Servlet's initialization parameters, the
name of the servlets instance, and a reference to the Servlet Context the servlet is
running in.

getServletContext is the most valuable method, as it allows you to share information


accross an application (context).

There is more information in the Javadoc documentation that is provided.

See also http://www.jguru.com/jguru/faq/view.jsp?EID=35085 and


http://www.jguru.com/jguru/faq/view.jsp?EID=208612

Would response.sendRedirect work for an https: URL on a secured server


(SSL)? For example, would
response.sendRedirect("https://www.host.com/page.html") work?
Location: http://www.jguru.com/faq/view.jsp?EID=295807
Created: Jan 7, 2001 Modified: 2001-01-08 07:53:04.272
Author: wee yap ng (http://www.jguru.com/guru/viewbio.jsp?EID=35233) Question
originally posed by wee yap ng
(http://www.jguru.com/guru/viewbio.jsp?EID=35233

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]

Comments and alternative answers

I had previously work with a early release of JRUN...


Author: wee yap ng (http://www.jguru.com/guru/viewbio.jsp?EID=35233), Jan 8,
2001
I had previously work with a early release of JRUN with Netscape Enterprise Server.

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

Short answer: you can't :-( See


http://www.jguru.com/jguru/faq/view.jsp?EID=11422

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

Comments and alternative answers

Slightly longer answer...


Author: Jim Chrystal (http://www.jguru.com/guru/viewbio.jsp?EID=382923), Mar 20,
2001
One way of doing it would be through JNI, I believe. You could write your own
native application to perform this function. Performance would take a hit, however.
Your best bet would probably be to store your environment information in properties
file. Happy computing, Jim

Where can I learn techniques for building Internet applications using


servlet and JSP technology?
Location: http://www.jguru.com/faq/view.jsp?EID=296763
Created: Jan 8, 2001 Modified: 2001-01-15 08:03:46.903
Author: Frank Carlos (http://www.jguru.com/guru/viewbio.jsp?EID=296761)

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.

Does RequestDispatcher.forward() return to the caller ?


Location: http://www.jguru.com/faq/view.jsp?EID=297164
Created: Jan 8, 2001 Modified: 2001-01-15 08:07:51.31
Author: sampreet kaur chawla
(http://www.jguru.com/guru/viewbio.jsp?EID=296185) Question originally posed by
phil brackel (http://www.jguru.com/guru/viewbio.jsp?EID=260432

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]

How do I create a formatted Microsoft Word document from Java?


Location: http://www.jguru.com/faq/view.jsp?EID=299081
Created: Jan 10, 2001 Modified: 2001-03-02 07:28:41.274
Author: Stephen Silber (http://www.jguru.com/guru/viewbio.jsp?EID=10161)
Question originally posed by Vijay kumar
(http://www.jguru.com/guru/viewbio.jsp?EID=294344

[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.

The RTF spec is at


http://msdn.microsoft.com/library/default.asp?PP=/library/toc/specs/specs10.xml&t
ocPath=specs10&URL=/library/specs/rtfspec.htm

[See also http://www.jguru.com/jguru/faq/view.jsp?EID=3696]

Comments and alternative answers

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 ?

Can i generate the Word document using java class.There...


Author: Sumit Gangrade (http://www.jguru.com/guru/viewbio.jsp?EID=36802), Feb
27, 2001
Can i generate the Word document using java class.There is an API for PDF
generation com.lowagie which generates PDF file using java class. Is there any API
for MS Word document generation?

Is it possible to do load balancing from one web server to multiple Tomcat


servers?
Location: http://www.jguru.com/faq/view.jsp?EID=299385
Created: Jan 10, 2001 Modified: 2001-01-15 08:04:26.868
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by John Smith
(http://www.jguru.com/guru/viewbio.jsp?EID=110025

Tomcat 3.x supports load balancing through Apache (mod_jserv). Tomcat 4.x
supports it natively.
Comments and alternative answers

load balancing thru' mod_jserv


Author: randall phillips (http://www.jguru.com/guru/viewbio.jsp?EID=410389), Apr
26, 2001
how about thru' mod_jk?

Re: load balancing thru' mod_jserv


Author: Michael Erdely (http://www.jguru.com/guru/viewbio.jsp?EID=726279),
Jan 18, 2002
I know tomcat 3.x can load balance with mod_jk.

Catalina and Load Balancing


Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727), Jan 30, 2002
John,
Actually, I think that Tomcat 4.0.1 does not support Load Balancing natively, but
version 4.0.2 (at this time still in beta) it will.

Re: Catalina and Load Balancing


Author: Venkatesh Sangam
(http://www.jguru.com/guru/viewbio.jsp?EID=424561), Mar 12, 2002
I dint actually understand what do you mean by Load balaning. If there is only one
webserver, then it alone will handle all the requests. what does load balancing
mean in this case. ??

Re[2]: Catalina and Load Balancing


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Mar
13, 2002
Load balancing is for when there's more than one server. It balances the load,
so one (Tomcat) server gets half the requests, and the other server gets the
other half.

Re[3]: Catalina and Load Balancing


Author: hee lee (http://www.jguru.com/guru/viewbio.jsp?EID=1035338),
Dec 7, 2002
hello,

Can anybody tell me how to achieve


Load balancing in Tomcat..???

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 hope i may be wrong, if so, please


suggest me what is Load balancing and
how could we acheive it.

What does "request-timeout" parameter in Resin configuration mean?


Location: http://www.jguru.com/faq/view.jsp?EID=299567
Created: Jan 11, 2001 Modified: 2001-01-15 08:52:05.695
Author: Praveen Singh (http://www.jguru.com/guru/viewbio.jsp?EID=299541)
Question originally posed by Pavel Bernshtam
(http://www.jguru.com/guru/viewbio.jsp?EID=274236

Hi Pavel, I'm Praveen.

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.

my mail address is:praveens@cybage.com

Comments and alternative answers

Unfortunatly it is not work in this way :( I make...


Author: Pavel Bernshtam (http://www.jguru.com/guru/viewbio.jsp?EID=274236), Jan
15, 2001
Unfortunatly it is not work in this way :(

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

I can think of three options:

1. Use the JavaScript to built the tree in the browser.


Various JavaScript trees are available on the internet, including free
implementations. JavaScript will usually offer the highest performance.
Unfortunatelly due to the differences in JavaScript support in various browsers I
would only recommend it for intranet solution where you can standarize browser
settings and version.

[Does anyone have links to these JavaScript trees? -A]

2. Build an applet and place it on the JSP page.

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.

[Does anyone have links to these Applet trees? -A]

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

Comments and alternative answers

There's a nice JavaScript tree component at http:/...


Author: Jorge Jordão (http://www.jguru.com/guru/viewbio.jsp?EID=275762), Jan 15,
2001

There's a nice JavaScript tree component at http://www.treemenu.com.

Hello. CoolServlets.com also has a tree bean for free...


Author: Perry Tew (http://www.jguru.com/guru/viewbio.jsp?EID=60814), Jan 17,
2001
Hello. CoolServlets.com also has a tree bean for free use. See
http://coolservlets.com/CSTreeBean/.
Best of luck,
Perry Tew

In option 3, is there a way to remember the states....


Author: Vaidhy Kumar (http://www.jguru.com/guru/viewbio.jsp?EID=26604), Feb 5,
2001
In option 3, is there a way to remember the states. For examples let's say I show a list
of items a,b,c,d in a browser and I first expand b and later d. Is it possible to show b
and d in the expanded state?

I've heard concerns that applets using Swing trees...


Author: Pratap Das (http://www.jguru.com/guru/viewbio.jsp?EID=129542), Mar 5,
2001
I've heard concerns that applets using Swing trees (which must use plug-ins on the
browser side) have some portability issues - i.e works on some browsers & not on
others. Could someone comment on how this would affect a design choice between
Javascript trees & Applet trees?

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

What will happen is an unforeseeable event.


The best way to establish a default occurrence (the servlet handles a request at a
time) is to synchronize the access to the global variable or alternatively to create a
servlet that implements the SingleThreadModel interface.

[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]

Comments and alternative answers

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

Another good one


Author: Sean Foley (http://www.jguru.com/guru/viewbio.jsp?EID=499258), Sep 18,
2001
In most of the API javadocs they like to call it "non-deterministic" behavior.

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

Just as an <INPUT TYPE="text"> component only allows you to specify a single


(text) value, an <INPUT TYPE="file"> component only specifies one file.

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.

[See also How do I upload a file to my servlet? ]

[Does anyone have a more elegant solution? -Alex]

Comments and alternative answers

I've found only one other (non-applet) solution: upload...


Author: Joe Humphreys (http://www.jguru.com/guru/viewbio.jsp?EID=40248), Jan
17, 2001

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.

how to upload a file (HTML,BMP,Gif,..) using servlets?


Author: Arunachalam P (http://www.jguru.com/guru/viewbio.jsp?EID=90631),
May 1, 2001
hi friends, well. sorry for the question posted here. I have to get the answer, I hope
u people know the answer for" uploading the file". Pls suggest me to upload a file
using servlets. I have finished the client-side using <input type="file"...........> Pls
show me the way to proceed.. Thanx a lot to the accessors

Re: how to upload a file (HTML,BMP,Gif,..) using servlets?


Author: durgababu koka
(http://www.jguru.com/guru/viewbio.jsp?EID=434371), Aug 22, 2001
the best and easy way to upload the file(in my view) using MultipartRequest
class provided by orielly. just go to the orielly.com then download the
MultipartRequest class and import into ur servlet. in ur form(in which ur "file"
type is mentioned) just include this line like <FORM name="anyname"
ACTION="ur action" METHOD="POST" enctype="multipart/form-data">
then in ur servlet method. just include this code.. MultipartRequest multi =
new MultipartRequest(req,directory,filesize) so it will upload ur file what ever
u choosen. i hope u stand. thanks..

Re: I've found only one other (non-applet) solution: upload...


Author: Jasmin Mehta (http://www.jguru.com/guru/viewbio.jsp?EID=726950),
Jan 21, 2002
Hi Joe, Can you please send me the code of this technique for multiple file upload.
I'm looking for exactly same thing in my website. Pls send me code on
jasmine_mehta@yahoo.com Thx Jasmin

Try Zip files


Author: Carl Jabido (http://www.jguru.com/guru/viewbio.jsp?EID=416360), May 6,
2001
One method I'm playing around with right now is using Zip files to receive a single
archive of multiple files. Look through java.util.zip for info. Basically you can read
the Zip file, and get multiple ZipEntry objects which represent the individual files,
which you can manipulate with at will.

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.

Another brick in the wall :p


Author: Asim Ali (http://www.jguru.com/guru/viewbio.jsp?EID=474093), Aug 11,
2001
You can also try using the file list . You can browse several times and keep on adding
the fiiles to a list and then upload the list of files one by one .
Can you recommend some good books on servlets?
Location: http://www.jguru.com/faq/view.jsp?EID=303632
Created: Jan 16, 2001 Modified: 2001-01-19 14:18:19.009
Author: Jorge Jordão (http://www.jguru.com/guru/viewbio.jsp?EID=275762)
Question originally posed by preeti loomba
(http://www.jguru.com/guru/viewbio.jsp?EID=266963

If you like the (very nice) tutorial at http://www.apl.jhu.edu/~hall/java/Servlet-


Tutorial you should like the Sun Press book it inspired.

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.

Comments and alternative answers

good starting book


Author: Bert Guzenski (http://www.jguru.com/guru/viewbio.jsp?EID=415329), May
4, 2001
I'd recommend "Java - Servlet Programming" from O'Reilly Press.

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?

Can you recommend some good books on servlets?


Location: http://www.jguru.com/faq/view.jsp?EID=303778
Created: Jan 16, 2001 Modified: 2001-01-16 15:15:45.281
Author: Dominik Hasek (http://www.jguru.com/guru/viewbio.jsp?EID=297336)
Question originally posed by preeti loomba
(http://www.jguru.com/guru/viewbio.jsp?EID=266963

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

There is a comparative review of Servlet books at ...


Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Jan 16,
2001
There is a comparative review of Servlet books at JavaWorld that I wrote: Java servlet
books: A comparative review. Since that came out in March 2000, one decent book
should be added. It is reviewed at Which JSP book serves up the best lesson?. THe
new one is Core Servlets from Marty Hall. One other thing worth mentioning is the
Wrox book liked in the first review is out in a second edition: Professional Java
Server Programming, J2EE Edition

Does the session mechanism use cookies by default?


Location: http://www.jguru.com/faq/view.jsp?EID=304626
Created: Jan 17, 2001 Modified: 2001-01-19 14:04:59.079
Author: Jorge Jordão (http://www.jguru.com/guru/viewbio.jsp?EID=275762)
Question originally posed by mohan kumar
(http://www.jguru.com/guru/viewbio.jsp?EID=31319

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.

Comments and alternative answers

Cookies in Session Mechanism


Author: Vikram Sharma (http://www.jguru.com/guru/viewbio.jsp?EID=846457), Apr
19, 2002
HTTP by inception is stateless, hence any session tracking mechanism makes it
imperative to have an identifier for each session created. Cookies happnes to be the
most effective way of mainatining sessions, as they supply this uniques Id for each
request to the server. Web server on its end compares the session id with its stored
session ids. Per session cookies (not downloaded or set on client browser)
communicates with the web server. This cookies is set by default. Please correct me if
i'm off target. hope this info helps

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

You'll have to create a (new) similar cookie on server 2.

Have a ReadCookieServlet running on server1 that

• Reads the cookie, using request.getCookies()


• Redirects to WriteCookieServlet running on server2, passing the cookie
name, value and expiration date as request parameters, using
response.sendRedirect().

Have a WriteCookieServlet running on server2 that

• Reads the cookie name, value and expiration date request parameters, using
request.getParameter().
• Creates a similar cookie, using response.addCookie().

Comments and alternative answers

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.

When will WebSphere support WAR files?


Location: http://www.jguru.com/faq/view.jsp?EID=308027
Created: Jan 20, 2001 Modified: 2001-01-27 04:26:32.246
Author: Robert Castaneda (http://www.jguru.com/guru/viewbio.jsp?EID=4362)
Question originally posed by Sven Resch
(http://www.jguru.com/guru/viewbio.jsp?EID=251030

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.

My servlet application has been uploaded on a website with JRun support.


We access our servlets from behind a proxy. When two or more persons
from behind the proxy try and access the same sevlets netscape gives an
error to one saying "No Data found" and the other gets the data which the
first one had requested. What should I do to prevent this?
Location: http://www.jguru.com/faq/view.jsp?EID=310114
Created: Jan 23, 2001 Modified: 2001-01-27 04:36:34.974
Author: Joe Morse (http://www.jguru.com/guru/viewbio.jsp?EID=310104) Question
originally posed by Parvez Kapadia
(http://www.jguru.com/guru/viewbio.jsp?EID=263972

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:

1. Store the information you want to share in a persistant format, such as in a


file system or database. That way, any servlet that is running in a JVM that
can "see" these resources can get to this information.
2. If persisting this information is not an option, you can bind this information to
a context that is accessible to all servlet contexts, such as the application
server's context. This way, you can keep the data you want to share in
memory.
3. Use the old fashion way of passing information to a servlet - HTTP. One
servlet could foward a request to another servlet and include the data that
needs to be shared as parameters in the request.

Hope this helps!

[See also http://www.jguru.com/jguru/faq/view.jsp?EID=50791]

Comments and alternative answers

Pleeeeeeeease exapnd on 2. How do you use and access...


Author: john grimes (http://www.jguru.com/guru/viewbio.jsp?EID=323228), Feb 7,
2001
Pleeeeeeeease exapnd on 2. How do you use and access the servers application
context?

[Answer: Read the docs on Servlet.getServletContext() and


ServletContext.setAttribute() and ServletContext.getAttribute(). -Alex]

Also
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Oct 25, 2001
This question is also answered at:

• Is there a simple way to share a single Session object across multiple


ServletContexts?
• How can I share data between two different web applications?
• How can I pass data from a servlet running in one context (webapp) to a
servlet running in another context?
• Can two web applications (servlet contexts) share the same session object?

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>

where FooException is a subclass of ServletException.

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.

[See also How can I debug my servlet?]

Comments and alternative answers

error-page element documentation


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jul 16, 2001
Alessandro A. Garbagnati adds:

You should check the dtd of the Web Application Descriptor (web.xml). There is an
element that it's just for that:

<!ELEMENT error-page ((error-code | exception-type), location)>


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-code (#PCDATA)>


The error-code contains an HTTP error code, ex: 404

<!ELEMENT exception-type (#PCDATA)>


The exception type contains a fully qualified class name of a Java
exception type.

<!ELEMENT location (#PCDATA)>


The location element contains the location of the resource in the web
application

Re: error-page element documentation


Author: Tommy Chan (http://www.jguru.com/guru/viewbio.jsp?EID=493508),
Sep 10, 2001
Would someone teach me how to customize the Error Message of Error500 in
TOMCAT? I've tried to add the <error-page> tag in the web.xml file, but it doesn't
work. I've uploaded a copy of my web.xml file in
http://www.geocities.com/hkust2000/web.xml for reference. Can anyone tell me
what's wrong with my settings (I haven't changed anything, all are by default)?
Will there be other places apart from web.xml file which can affect the setting of
customizing the Error500 page?

Re[2]: error-page element documentation


Author: Garrett Smith (http://www.jguru.com/guru/viewbio.jsp?EID=745187),
Mar 23, 2002
Has anyone (besides Alex) gotten this to work?

Re[3]: error-page element documentation


Author: Ron R (http://www.jguru.com/guru/viewbio.jsp?EID=907416),
Jun 7, 2002
Yes. I used the following syntax:

<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.

Re[4]: error-page element documentation


Author: Garrett Smith
(http://www.jguru.com/guru/viewbio.jsp?EID=733867), Jun 8, 2002
Yeah, it definitely works. I forgot to include the DTD. This obviously
caused a problem.

Re[5]: error-page element documentation


Author: jim michael
(http://www.jguru.com/guru/viewbio.jsp?EID=930383), Jun 27,
2002
I'm still lost on this... I looked at every message in this thread, and
still can't figure out how to get it working. Obviously, the <error-
page> tag needs to go in web.xml, but whats this about the DTD?
I tried to analyze what the above message with all the <!Element>
stuff is doing, but I just don't get it.

What *exactly* do I need to put in web.xml to trap a 404?

Re[6]: error-page element documentation


Author: Garrett Smith
(http://www.jguru.com/guru/viewbio.jsp?EID=745187), Jun 27,
2002
You don't need to understand the DTD semantics completely to
write the document, but it would definitely help!

Here is the document I am using. It works for me:


<?xml version="1.0"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web
Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<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!

Re[7]: error-page element documentation


Author: jim michael
(http://www.jguru.com/guru/viewbio.jsp?EID=930383), Jun
27, 2002
Ok, thanks! Got that working now. Now I have an even
harder question: What about trapping 500 errors, such as:
"HTTP Status 500: No context configured to process this
request."

Since there *is* not context configured in this case, <error-


page> can't go in a deployment descriptor of a web app. So, I
thought perhaps I could put <error-page> in the server's
main web.xml. The server doesn't complain about it being
there, but it doesn't work, either. This does not seem to work:

<error-page>
<error-code>500</error-code>
<location>/error500.html</location>
</error-page>

Is it impossible to trap such an error? My ultimate goal is to


have a web site that doesn't throw *any* "ugly" errors no
matter how bad a user might mess with the URL, etc. Am I
dreaming?

Re[8]: error-page element documentation


Author: Garrett Smith
(http://www.jguru.com/guru/viewbio.jsp?EID=745187),
Jun 27, 2002
To answer your question, Error handlers are for runtime
errors, not configuration errors.

A context error...

I have never had that problem, so I don't know how much


I can help out here.

Usually you don't have to add a context. You can just go


to http://hostname.com/webappname/ and Tomcat finds
it.

Look in $CATALINA_HOME/conf/server.xml. You can


add a context by copying another context and changing
it. the examples context looks like this:
<!-- Tomcat Examples Context -->
<Context path="/examples"
docBase="examples" debug="0"
reloadable="true"
crossContext="true">

You can add a new context by copying and changing the


examples context. If this is hosted, it should be done by
the host. Users should probably not have access to this
unless tomcat is shared among users (via tomcat
manager).

A good (yet somewhat advanced) example is on IBM


Devworks. You can download and run the filter example:

http://www-106.ibm.com/developerworks/java/library/j-
tomcat/?open&l=101,t=grj,p=TomcatTricks

It explains how to add a context for the filter example. If


you are too impatient for all of that, copy and change the
examples context. Here is an example of a webapp
context that I made:
<!-- Advanced JSP Context -->
<Context path="/advanced"
docBase="advanced"
debug="3" reloadable="true"
crossContext="true"/>

Note that these changes will not take be applied until you
restart Tomcat. The same is true with web.xml.

[ I am using this for the examples in David Geary's


'Advanced JavaServer Pages.' ]

Re[9]: error-page element documentation


Author: jim michael
(http://www.jguru.com/guru/viewbio.jsp?EID=930383),
Jul 1, 2002
Thanks. I understand contexts, etc. Here's the scenario I
was trying to avoid. Say I have an app on my web page
that you get to via http://myserver.com/mywebapp.
Now imagine that someone bookmarks the app and they
get to it via that bookmark for years. Now imagine
someday during a site redesign I move the app to
http://myserver.com/mynewwebapp If the person tries
their bookmark, it will throw the "500 No context
configured" because "mywebapp" no longer exists. I
was hoping for a way to trap these sorts of errors so that
if such a thing happened the user would see a nice error
message instead of the scary Tomcat one <g>.

Re[10]: error-page element documentation


Author: Peter O'Brien
(http://www.jguru.com/guru/viewbio.jsp?EID=1045105),
Jul 28, 2003
One solution would be to have a single page in a web
app that redirects to mynewwebapp and register the
former web app at mywebapp. So when the browser
bookmark is used, the browser gets redirected to the new
URL. Or the page could display an appropriate message
to ask the user to update their bookmarks.

Re[7]: error-page element documentation


Author: Fabio Moratti
(http://www.jguru.com/guru/viewbio.jsp?EID=63024), Sep
11, 2003
Hi, I used the confiugration described for a 404 error and
works just fine: the error page I specified (404.jsp) is indeed
invoked.

The problem I am experiencing is that Explorer refuses to


show my error page and shows his.
I thied with different browsers (Mozilla, Konqueror) and the
output of the 404.jsp page is nicely shwn.
The thing I do not understand is that the "Tomcat" error page
is correctly shown: I used a sniffer to compare the HTTP
sent by Tomcat with his error page and by the 404.jsp and
the headers are identical.
Any pointers? This problem is driving me mad... :(
I am using Tomcat 4.1.24 and jdk 1.4.1.

Thanks in advance, Fabio

Re[8]: error-page element documentation


Author: Balázs Csepregi-Horváth
(http://www.jguru.com/guru/viewbio.jsp?EID=1170494),
May 13, 2004
Explorer catches the HTTP message code 404 and
replaces all the content with its own error page.
To switch this feature off go to: Tools -> Internet
Options... -> Advanced.
Then look for "Show friendly HTTP error messages" and
uncheck it. Click OK.

Re[9]: error-page element documentation


Author: Fabio Moratti
(http://www.jguru.com/guru/viewbio.jsp?EID=63024),
May 27, 2004
Hi, I further researched and experimented with the
behaviour of Explorer and error pages.
The custom error pages are catched and replaced if
they are "too small".
Looks like that Explorer thinks your "small" page is
too ugly and so decides to show his.
If the page weights a few Kb then it is shown: so you
can either create a nice looking page or you can add
some extra spaces to you page to meet the Explorer's
expectations.

Of course the advice of Balázs works ok, but


sometimes it is not possible to customize the client's
behaviour.

Fabio

Re[9]: error-page element documentation


Author: Michael Witherspoon
(http://www.jguru.com/guru/viewbio.jsp?EID=1236233),
Apr 2, 2005
Wow. Those sneaky dogs! I've been working on this
problem for more than 2 hours only to find out that I had
been doing it correctly from the first try. But, since
Microsoft thinks they own the whole world, they have
their own default settings that defeat the J2EE standards!

What a bunch of losers! Anyway, thank you so much for


posting the secret hint about the browser settings. I can't
see why they call their crappy replacement for my "very
friendly error page" a "friendly error message". There
was nothing friendly at all about the browser overriding
my error page.

At least I have it working now.

Spoon

Error page element


Author: Jeni Richards (http://www.jguru.com/guru/viewbio.jsp?EID=1014062), Feb
20, 2003
I am sucessfully using error-code element and it works great for links within the web
app. Is there any way of testing a link to ensure the page is there when the link is
outside the web app?
Deployment Descriptor excerpts need context
Author: Michael Witherspoon
(http://www.jguru.com/guru/viewbio.jsp?EID=1236233), Apr 2, 2005
It is very, very important when providing answers that include excerpts from
deployment descriptors to include enough skeleton descriptor so that the excerpt has
enough context so that someone using the answer knows where it goes. For example,
including

<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.

Instead, an excerpt with context might look like this:

<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

How can I maintain the session-specific Transport / Store objects across


multiple HTTP requests, Sun's implementations aren't serializable?
Location: http://www.jguru.com/faq/view.jsp?EID=319276
Created: Feb 2, 2001 Modified: 2001-02-02 10:21:42.184
Author: Dieter Wimberger (http://www.jguru.com/guru/viewbio.jsp?EID=25708)
Question originally posed by Mark K
(http://www.jguru.com/guru/viewbio.jsp?EID=302688

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.

For an example implementation you might want to take a look at:


http://www.sourceforge.net/projects/jwebmail and/or
http://www.sourceforge.net/projects/jwma

Both are open source webmail solutions written in Java.

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

encodeURL() is now encodeUrl() and encodeRedirectURL is now encodeRedirectUrl().


You can get the entire list by looking at the specs for the servlet APIs on the java
site. There is usually a section in the specs that is "What's New in the API".

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.

How do I port from Cold Fusion (CFM) to servlets?


Location: http://www.jguru.com/faq/view.jsp?EID=322789
Created: Feb 7, 2001 Modified: 2001-02-11 11:10:44.047
Author: philip chittoor (http://www.jguru.com/guru/viewbio.jsp?EID=313112)
Question originally posed by Rajith Raghu
(http://www.jguru.com/guru/viewbio.jsp?EID=246237

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

Comments and alternative answers

ColdFusion and Java


Author: Mike Viens (http://www.jguru.com/guru/viewbio.jsp?EID=420102), May 11,
2001
Check out www.tagservlet.com. They have a servlet that will parse ColdFusion pages
without the need for ColdFusion server.

Re: ColdFusion and Java


Author: adam butler (http://www.jguru.com/guru/viewbio.jsp?EID=885134), May
20, 2002
check out the new version of coldfusion from macromedia. Coldfusion has been
rewritten as a set of j2ee custom tags, retaining all the functionality and ease use
of cfml with the benefits of j2ee. The Coldfusion mx server comes in two
versions, a stand alone version based on a cut down version of jrun or a full j2ee
version which can be plugged into other j2ee application servers currently jrun4,
sun one and ibm websphere for full details go here
http://www.macromedia.com/software/coldfusion/

I have a Web Application, that works perfect on Netscape Navigator, but


when I use the method "POST" in a JSP, and use Internet Explorer as
Browser, then the application stops working, I already done an analysis of
the problem, and I discover that IExplorer, just "cuts" part of the
information that the servlet target needs to do its job, so. How can I solve
this problem?? (I have to work with the "POST" method) Example: The
Object Request have 2912 characters(using Netscape), but using IExplorer,
it reduces to 2362!!, and then the servlets stops working because of the lost
of information.
Location: http://www.jguru.com/faq/view.jsp?EID=326002
Created: Feb 11, 2001 Modified: 2001-02-11 11:12:19.104
Author: Dieter Wimberger (http://www.jguru.com/guru/viewbio.jsp?EID=25708)
Question originally posed by Andres Rojas
(http://www.jguru.com/guru/viewbio.jsp?EID=130022

I have encountered the same problem when submitting multipart/formdata via


POST to a secure webserver (i.e. https). I verified this on Server side, with different
CGI's and a test servlet, and submitted a Bug report. However, the bad news is that
nobody cared, and there is nothing that can be done about it, despite checking the
Microsoft Knowledge Base and waiting for updates to MSIE.

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.

Comments and alternative answers


This problem with multipart/form-data with POST on IE still persists...Is there a
workaround???
Author: Chidambaram Ganapathi
(http://www.jguru.com/guru/viewbio.jsp?EID=138126), Sep 11, 2001
I'm encountering the same problem as you guys have mentioned even now. Have you
guys figured out any work-arounds.

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.

Re: This problem with multipart/form-data with POST on IE still persists...Is


there a workaround???
Author: Joe Smith (http://www.jguru.com/guru/viewbio.jsp?EID=535122), Oct
31, 2001
The problem has to do with not having enough memory allocated on your app
server. trying upping it substantially and it should work.

Re[2]: This problem with multipart/form-data with POST on IE still


persists...Is there a workaround???
Author: KARTHIK JAYABALAN
(http://www.jguru.com/guru/viewbio.jsp?EID=1149210), Feb 26, 2004
Did this problem ever solved? I'm still having problems with this. If you have
solution, please let me know. Thanks.

Using JServ, even if a request is coming from the same browser, I am


getting a new session each time. I am using
request.getSession(true).getId() to find out session Id and it's different for
every request. What's going wrong ?
Location: http://www.jguru.com/faq/view.jsp?EID=330061
Created: Feb 15, 2001 Modified: 2001-02-15 13:40:50.354
Author: Vikram Lele (http://www.jguru.com/guru/viewbio.jsp?EID=251314)
Question originally posed by satish A
(http://www.jguru.com/guru/viewbio.jsp?EID=222556

request.getSession(true) will always return a new session.

You need to use request.getSession(false). If there is no session, it will return a null,


in which case you need to create a new session.

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.

If you don't have a login, you can do this:


thisSession = request.getSession(false);
if(thisSession == null)
thisSession = request.getSession(true);
To make sure the session is properly maintained, you must call this method at least
once before you write any output to the response.

regards,
- Vikram

Comments and alternative answers

as per JSDK API, getSession(true) returns a new session...


Author: satish A (http://www.jguru.com/guru/viewbio.jsp?EID=222556), Feb 15,
2001
as per JSDK API, getSession(true) returns a new session only if its not created yet. I
am referring JSDK 2.1

rgds, satish

Even though you specify request.getSession(true), until...


Author: vijay somagudam (http://www.jguru.com/guru/viewbio.jsp?EID=306348),
Feb 15, 2001
Even though you specify request.getSession(true), until u disable the cookies and
persession cookies option in the browsers internet options u can't get the same session
id! these options are there in internet options security tab inside this click on custom
level and disable the cookies and persession cookies!! now u can get the same session
id!!!

Re: Even though you specify request.getSession(true), until...


Author: M Hunt (http://www.jguru.com/guru/viewbio.jsp?EID=1099025), Jul 3,
2003
I've been having a 'mare with new sessions being created for each request, but
have fixed it now!

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.

request.getSession(true) will not always return a new...


Author: Koodal Kumaran Sailappan
(http://www.jguru.com/guru/viewbio.jsp?EID=300552), Feb 15, 2001
request.getSession(true) will not always return a new session. If a session is already
present, it returns a reference to it otherwise a new session is created.
Hey guys check the API ... !! If you refer to the...
Author: Niclas Meier (http://www.jguru.com/guru/viewbio.jsp?EID=245132), Feb 16,
2001

Hey guys check the API ... !!

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

It might be that netscape has cookies disabled. It...


Author: Hans Halim (http://www.jguru.com/guru/viewbio.jsp?EID=116548), Feb 19,
2001
It might be that netscape has cookies disabled. It seems that Tomcat remembers
session by cookies. Try setting netscape to accept cookies in Edit->Preferences under
Advanced category

Yes.. getSession(true) returns a new session only when...


Author: ashok chindam (http://www.jguru.com/guru/viewbio.jsp?EID=83479), Feb
22, 2001
Yes.. getSession(true) returns a new session only when it is not created yet. You might
have turned off cookies on ur browser. If so u have to encode the url to get the old
session.
Ashok.

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.

How can I set timeout for servlet response?


Location: http://www.jguru.com/faq/view.jsp?EID=330644
Created: Feb 15, 2001 Modified: 2001-02-16 15:07:26.829
Author: reshma deshmukh (http://www.jguru.com/guru/viewbio.jsp?EID=132478)
Question originally posed by Pavel Bernshtam
(http://www.jguru.com/guru/viewbio.jsp?EID=274236

[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]

How can I write/read files using servlets, without getting


java.io.FileNotFoundException: file_name(Permission denied).
Location: http://www.jguru.com/faq/view.jsp?EID=333861
Created: Feb 20, 2001 Modified: 2001-02-25 17:44:38.071
Author: Darren Hobbs (http://www.jguru.com/guru/viewbio.jsp?EID=15939)
Question originally posed by Sanjiv Mani Tripathi
(http://www.jguru.com/guru/viewbio.jsp?EID=252168
First, remember that servlets run on the server-side, and therefore only have access
to the file-system of the server. They cannot directly interact with clients, except
through HTTP request/response.

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.

Comments and alternative answers

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...

Where should configuration files be stored in a web application?


Location: http://www.jguru.com/faq/view.jsp?EID=338339
Created: Feb 25, 2001 Modified: 2001-02-25 17:32:51.684
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Guillaume Bilodeau
(http://www.jguru.com/guru/viewbio.jsp?EID=283171

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

Updating Config files


Author: Jason Rumney (http://www.jguru.com/guru/viewbio.jsp?EID=549612), Nov
16, 2001
Recommending the use of WEB-INF and getResourceAsStream() for storing config
files is all very well, but increasingly servers are running web applications straight out
of war files, so if you need to update the configuration dynamically, the code to do so
becomes messy and unportable. So is there a portable way to update config files in
2.3, or do I have to invent my own?

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.

Comments and alternative answers

To communicate with your servlet/jsp, your applet ...


Author: Sylvain Colomer (http://www.jguru.com/guru/viewbio.jsp?EID=320970),
Feb 26, 2001
To communicate with your servlet/jsp, your applet simply has to establish a HTTP
connection to the servlet which answers with the list of users (in plain text or XML
for example).

What is the difference between ServletContext and ServletConfig?


Location: http://www.jguru.com/faq/view.jsp?EID=339337
Created: Feb 26, 2001 Modified: 2001-03-02 07:17:03.47
Author: Ryan Breidenbach (http://www.jguru.com/guru/viewbio.jsp?EID=45212)
Question originally posed by vishal gupta
(http://www.jguru.com/guru/viewbio.jsp?EID=44954

A ServletContext represents the context in a servlet container of a servlet instance


operates. A servlet container can have several contexts (or web applications) at one
time. Each servlet instance is running in one of these contexts. All servlets instances
running in the same context are part of the same web application and, therefore,
share common resources. A servlet accesses these shared resource (such as a
RequestDispatcher and application properties) through the ServletContext object.

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.

See also What is a Servlet Context?.

Comments and alternative answers

Both are interfaces. The ServletConfig interface is...


Author: P Manchanda (http://www.jguru.com/guru/viewbio.jsp?EID=344357), Mar 5,
2001
Both are interfaces.

The ServletConfig interface is implemeneted by the servlet engine in order to pass


configuration information to a servlet. The server passes an object that implements the
ServletConfig interface to the servlet's init() method.

The ServletContext interface provides informaion to servlets regarding the


enviornment in which they are running. It also provides standard way for servlets to
write events to a log file.

Re: Both are interfaces. The ServletConfig interface is...


Author: suresh durai (http://www.jguru.com/guru/viewbio.jsp?EID=1207057), Oct
25, 2004
As u mentioned that both are interfaces.if interface means how can we create the
object for this interface.

How can you use Servlet Session Tracking with WAP?


Location: http://www.jguru.com/faq/view.jsp?EID=340156
Created: Feb 27, 2001 Modified: 2001-03-02 07:19:08.339
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Luke Studley
(http://www.jguru.com/guru/viewbio.jsp?EID=10174

[More question: I am trying to implement a simple access - login - re-direct


mechanism using WAP / WML, however the WAP browser does not seem to support
normal session tracking. Do I have to explicitly (and dynamically) place the sessionid
in the login form?]

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.

See also How do I send a redirect to a WAP device?

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

• 300 total cookies


• 4 kilobytes per cookie (including name)
• 20 cookies per server or domain

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.

Under what circumstances will a servlet be reloaded?


Location: http://www.jguru.com/faq/view.jsp?EID=343098
Created: Mar 2, 2001 Modified: 2001-03-03 11:26:56.965
Author: swarraj kulkarni (http://www.jguru.com/guru/viewbio.jsp?EID=121306)
Question originally posed by Narugopal Sahu
(http://www.jguru.com/guru/viewbio.jsp?EID=303532

That depends on the Servlet container.

Most of the Servlet containers reload the servlet only it detects the code change in
the Servlet, not in the referenced classes.

In Tomcat's server.xml deployment descriptor, if you have mentioned

<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

Comments and alternative answers

Servlets get reloaded in Ajache/Jserv whenever the...


Author: Harpreet Singh (http://www.jguru.com/guru/viewbio.jsp?EID=106255), Mar
12, 2001
Servlets get reloaded in Ajache/Jserv whenever the timestamp on the servlet code
changes. If any of the other objects that the servlet references change, the classes do
not get reloaded because servlet run in a different container and knows nothing about
the change in other classes. A quick fix for this is to just 'touch' the servlet whenever
your supporting objects change.

What is a Servlet Filter? (see Servlet Spec 2.3)


Location: http://www.jguru.com/faq/view.jsp?EID=344253
Created: Mar 4, 2001 Modified: 2001-03-05 16:01:34.401
Author: Allen Fogleson (http://www.jguru.com/guru/viewbio.jsp?EID=344251)
Question originally posed by Saravanan Jayachandran
(http://www.jguru.com/guru/viewbio.jsp?EID=91462

A filter is basically a component that is invoked whenever a resource is invoked for


which the filter is mapped. The resource can be something like a servlet, or a URL
pattern. A filter normally works on the request, response, or header attributes, and
does not itself send a response to the client.

[That's great, but a little brief -- anyone want to elaborate with more details, code
samples, etc.? -Alex]

Comments and alternative answers

see Jason Hunter's excellent article on Servlet 2.3:...


Author: Stefan Hoehn (http://www.jguru.com/guru/viewbio.jsp?EID=284266), Mar
15, 2001
see Jason Hunter's excellent article on Servlet 2.3: New Features exposed under
http://www.javaworld.com/jw-01-2001/jw-0126-servletapi.html

I am using the RequestDispatcher's forward() method to redirect to a JSP.


The problem is that the jsp's url is now relative to the servlet's url and all
my url's in the jsp such as <img src="pic.gif"> will be corrupt. How do I
solve this problem?
Location: http://www.jguru.com/faq/view.jsp?EID=344412
Created: Mar 5, 2001 Modified: 2001-03-07 13:27:52.885
Author: Dmitry Ivlev (http://www.jguru.com/guru/viewbio.jsp?EID=341551)
Question originally posed by Tobias Åkeblom
(http://www.jguru.com/guru/viewbio.jsp?EID=76237

You can use absolute urls like:


<BODY>
<% String base = request.getContextPath(); %>
<IMG src="<%=base%>/img/pic.gif">
</BODY>
or write out a BASE tag like:
<% String base = request.getContextPath(); %>
<HEAD>
<BASE HREF="<%=base%>">
</HEAD>

<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/").

In the JSP use the getAttribute:


e.g:
String stringSource = (String)request.getAttribute("mySourceDir").

So, now you have a variable to handle.


But be sure, this variable MUST END with a '/', without you need to add it in your
'img src'-tag. With this, you also can now use a html-dev.tool (like dreamveawer
ultradev) without having problems in showing and binding your gifs.

The img src shows:


e.g.:
src="/src/package/gfx/transp.gif"
with JSP Tag:
src="<%=stringSource%>gfx/transp.gif"

regards
J.Staebler

Re: Another solution:


Author: alejandro avila (http://www.jguru.com/guru/viewbio.jsp?EID=409805),
May 31, 2001
if you follow the J2EE WAR specification format you don't have to worry about,
absolute paths, becuase everything is going to be in the document root.

How can I pass language specific characters through a query string to a


servlet thats running on Tomcat 3.1 / Apache / mod_jserv?
Location: http://www.jguru.com/faq/view.jsp?EID=347167
Created: Mar 8, 2001 Modified: 2001-03-12 11:36:32.476
Author: Luigi Viggiano (http://www.jguru.com/guru/viewbio.jsp?EID=101985)
Question originally posed by Mikael Lichtenstein
(http://www.jguru.com/guru/viewbio.jsp?EID=222454

[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]

Comments and alternative answers

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.

Free Forte Community Edition


Author: Michael Murphy (http://www.jguru.com/guru/viewbio.jsp?EID=385872),
Mar 23, 2001
I use Forte and I love it. It fairly scaled back from a 'not-free' IDE, but you can
configure it pretty easily and 2.0 version has servlet support. I set mine up with
Oracle jars, Mysql jars and my own customer jars and it manages my projects pretty
well. However it is a serious hog so I suggest a fair amount of RAM >=128Mb. I use
256Mb, but I do so much other stuff (Oracle Apps) at the same time as well. the
Community Edition is great as is free go to java.sun.com

NetBeans IDE 3.1


Author: Jazci Nijjar (http://www.jguru.com/guru/viewbio.jsp?EID=408880), Apr 24,
2001
I currently use NetBeans IDE 3.1 which is very similar to Forte and its also free!!!

Forte for Java, Internet Edition


Author: Juergen Hoeller (http://www.jguru.com/guru/viewbio.jsp?EID=236151), Apr
30, 2001
My team uses Forte 2.0 Internet Edition for JSP and servlet development, and we
really appreciate it. IMHO Forte IE is the best environment for developing Java web
applications, especially if you want to write portable applications that do not rely on
some proprietary server features. In this case, Forte is the far better choice than any
IDE that is associated with some particular application server vendor. And if you do
not use EJB, it easily beats JBuilder 4 in terms of web application support, JSP
debugging facilities and - important too - price.
BTW, NetBeans is the open source project behind Sun's branded Forte product line.
And watch out for the upcoming Forte for Java 3.0, I expect some new useful features
introduced there!

Editor for Servlet


Author: ramanujam ragavan
(http://www.jguru.com/guru/viewbio.jsp?EID=429317), Sep 10, 2001
There is a superb editor for creating srevlets . It gives you a million options to play
with and there is no limit to customizing servlets. It is got the simplest interface
you can ever imagine. With one menu bar , a tool bar and a popup menu to add to
the editor panel, you can cut copy and paste and also select all and word wrap.
You can also print from it. you can save and open files --- So many facilities you
will adore for the rest of your life.... IT IS CALLED NOTEPAD ! ALL THE
BEST

Which servlet engines support HTTPS (SSL) connections?


Location: http://www.jguru.com/faq/view.jsp?EID=352812
Created: Mar 16, 2001 Modified: 2001-03-16 09:55:38.966
Author: Richard Raszka (http://www.jguru.com/guru/viewbio.jsp?EID=7963)
Question originally posed by Angel Sierra
(http://www.jguru.com/guru/viewbio.jsp?EID=346227

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.

Comments and alternative answers

SSL via built-in web server


Author: Juergen Hoeller (http://www.jguru.com/guru/viewbio.jsp?EID=236151), Apr
30, 2001
The servlet engine "Resin" by Caucho (http://www.caucho.com/products/resin)
supports SSL via its built-in web server, and it works perfectly.

answer
Author: John Smith (http://www.jguru.com/guru/viewbio.jsp?EID=431592), May 31,
2001
Think and read documentation

What is the maximum length of a URL, including GET parameters?


Location: http://www.jguru.com/faq/view.jsp?EID=384627
Created: Mar 21, 2001
Author: Manish Parmar (http://www.jguru.com/guru/viewbio.jsp?EID=288849)
Question originally posed by Adolfo Aladro
(http://www.jguru.com/guru/viewbio.jsp?EID=288038

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

Comments and alternative answers

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

Try this: Assume that you have tomcat location like:


c:\tomcat
at the command promt type:
set classpath=c:\tomcat\lib\servlet.jar
Comments and alternative answers

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.

Here's one way to be sure your classpath is correct: run


javap -classpath my;class;path javax.servlet.Servlet

If javap can't find it, then your classpath is wrong.

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.

See also How do I set my CLASSPATH for Servlets?

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

and I was setting CLASSPATH as follows:

CLASSPATH=.;C:\PROGRA~1\TOMCAT~1.3\LIB\SERVLET.JAR

(the ".;" bit placed at the start as recommended at


http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/index.html) I was using DOS
filenames because I *thought* that was the safest thing to do whenever programs
like Tomcat that involve DOS are involved. But then I finally tried setting the path
as:

CLASSPATH=.;C:\PROGRA~1\TOMCAT~1.3\lib\servlet.jar

and that solved the problem.

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

Consistent errors using javap -classpath my;class;path javax.servlet.Servlet


Author: David T (http://www.jguru.com/guru/viewbio.jsp?EID=1221377), Jan 15,
2005

This javap command consistly produced the following error in my windows


2000/tomcat 5.x configuration: "ERROR:Could not find javax.servlet.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\

Does TOMCAT provide JDBC Connection Pooling ?


Location: http://www.jguru.com/faq/view.jsp?EID=415490
Created: May 4, 2001 Modified: 2001-07-16 15:05:15.13
Author: Nicola Ken Barozzi (http://www.jguru.com/guru/viewbio.jsp?EID=39153)
Question originally posed by venu gopalan
(http://www.jguru.com/guru/viewbio.jsp?EID=394235

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.

[Also, http://www.javaexchange.com hosts a fine implementation of a JDBC


Connection Pool. -Alex]

Comments and alternative answers


Another connection pool
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jul 16, 2001
Also, see http://www.codestudio.com/ for the poolman connection pool library.

Re: Another connection pool


Author: Sasha Maksimenko
(http://www.jguru.com/guru/viewbio.jsp?EID=851934), Apr 24, 2002
From site codestudio.com: PoolMan is no longer available or supported through
this site. It did exceedingly well during its lifetime, and I appreciate the important
role it played in so many distributed applications over the past three years. If you
are looking for connection and object pooling mechanisms, they can now be found
in application servers such as JRun, Tomcat and the Jakarta Project, and other
J2EE products and servers.

Re[2]: Another connection pool


Author: Shane Word (http://www.jguru.com/guru/viewbio.jsp?EID=68418),
Jul 1, 2002
Or, if you don't want to use a J2EE or Servlet setup as part of your connection
pooling, you could just use one of the many other freely available DB
Connection pools, like the Open Source one at:
http://sourceforge.net/projects/esw/

Tomcat 4.x and Tyrex


Author: Mike Barlotta (http://www.jguru.com/guru/viewbio.jsp?EID=869607), May
23, 2002
Tomcat 4.x comes with Tyrex (another open source project from ExoLabs) which
allows it to support JDBC connection pooling and JNDI naming contexts.
Cool stuff

-Mike

Re: Tomcat 4.x and Tyrex


Author: Denny Dedhiya (http://www.jguru.com/guru/viewbio.jsp?EID=1030707),
Nov 28, 2002

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.

I have implemented the database connection pooling mechanism of struts using


commons-dbcp package and I want to use transaction management using Tomcat.

Can you please give me a running sample application which uses transcation
mgmt?
Many many thanks in advance

Denny Dedhiya

Re: Tomcat 4.x and Tyrex


Author: prathap chandran
(http://www.jguru.com/guru/viewbio.jsp?EID=1010464), Dec 10, 2002
does tomcat4.0.3 support dbcp connection pool? Thanks Prathap

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.

Comments and alternative answers


Further question...
Author: Anthony Lew (http://www.jguru.com/guru/viewbio.jsp?EID=415782), May
5, 2001
Thanks, Andre. My page is working correctly now. But just one more query. Can I
change something in the page that I sendRedirect to? Say, for example, I have a login
page and I want to display the name of the user on the page that I redirect... I know
that HTMLs are just static pages. So, just want to know whether there are any
technologies that can handle this...

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.]
-----------------

After getting the session, check to see if it is new:

HttpSession session = request.getSession();


if (!session.isNew()) {
//do something which requires the session to exist
}
else {
//new session was created - send new login page
}
[And see http://www.jguru.com/faq/view.jsp?EID=415883 for how to send a redirect
to a static login page. -Alex]
Comments and alternative answers

HttpSession class comes in handy for such requirements


Author: Koodal Kumaran Sailappan
(http://www.jguru.com/guru/viewbio.jsp?EID=300552), May 15, 2001
The idea is, Once the user has logged in, a new session is created. Typically, the Login
page has the following code
HttpSession session = request.getSession(true);
This does not gaurantee a new session always. If any Session is already active, then a
reference to it, is returned. To inactivate any session that is already present and to
have a new session,then the code is
HttpSession session = request.getSession(false);

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.

Re: HttpSession class comes in handy for such requirements


Author: phillip gibb (http://www.jguru.com/guru/viewbio.jsp?EID=748715), Feb
28, 2002
Hi
what I do now is have a bean in application scope that handles all the sessions.
It stores logins in a hash table and has a thread to check for inactivity.
The on the pages themselves I have a piece of javascript that starts up a method
after a certain time - that method opens up a little window with a countdown and a
"do you want to continue" question.
Its works great.
The only question is do I really have to store all users in an object(hashtable is
what I use), or can I just use the HttpSession object and add an attribute to indicate
whether a user has logged in or not.
Phill

Re[2]: HttpSession class comes in handy for such requirements


Author: Koodal Kumaran Sailappan
(http://www.jguru.com/guru/viewbio.jsp?EID=300552), Feb 28, 2002
The purpose is to alarm the user when his/her inactive time is nearing the
session timeout, if I had understood it correctly.

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.

If the hashtable approach is follwed, then application has the burden of


adding/removing the login into/from hashtable when user logs-in/logs-out.
Use a logon filter
Author: Rick DeBay (http://www.jguru.com/guru/viewbio.jsp?EID=1182519), Jun
29, 2004
A simple logon filter will send the user to a logon page when their session is invalid,
and forward them back to the page they were originally trying to access. This keeps
you from putting any session management code in the JSP. If you require a warning
that the session will expire soon, write a simple JSP tag which will write out an
HTML meta refresh tag, which will forward to the warning page based on the session
timeout. For browsers that don't support meta refresh or have it turned off, the tag
should also generate a simple javascript timer to do the forward.

How can I add or remove parameters from a request instance, before


sending it to the RequestDispatcher?
Location: http://www.jguru.com/faq/view.jsp?EID=415981
Created: May 5, 2001 Modified: 2001-09-26 12:39:50.595
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Antonio Hernandez
(http://www.jguru.com/guru/viewbio.jsp?EID=2783

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.

The mechanism in 2.3 is to use the "HttpServletRequestWrapper" class. See the


JavaDoc API.

Comments and alternative answers

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

Does anyone know of any detailed architectural design patterns for


organizing a web application with multiple servlets (and optionally, JSPs)?
Location: http://www.jguru.com/faq/view.jsp?EID=415984
Created: May 5, 2001
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
Barry Wythoff (http://www.jguru.com/guru/viewbio.jsp?EID=222348

[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. ]

What is the difference between static variables and instance variables in a


servlet?
Location: http://www.jguru.com/faq/view.jsp?EID=416009
Created: May 5, 2001 Modified: 2001-07-02 20:13:53.756
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Krishna Reddy
(http://www.jguru.com/guru/viewbio.jsp?EID=399043

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.

According to the Servlet specification, a servlet that does not declare


SingleThreadModel usually has one and only one instance, shared among all
concurrent requests hitting that servlet.

That means that, in servlets (and other multithreaded applications), an instance


variable behaves very much like a static variable, since it is shared among all
threads. You have to be very careful about synchronizing access to shared data.

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:

• Local variables - for loop iterators, result sets, and so forth


• Request attributes - for data that must be passed to other servlets invoked
with the RequestDispatcher
• Session attributes - persists for all future requests from the current user
only
• Instance variables - for data that persists for the life of the servlet, shared
with all concurrent users
• Static variables - for data that persists for the life of the application, shared
with all concurrent users -- including any other servlet instances that were
instantiated with different init parameters
• Context attributes - for data that must persist for the life of the application,
and be shared with all other servlets

(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.)

See How do I ensure that my servlet is thread-safe? for more detail.

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.

You can get it from Sun's Java Servlet download page.

Can multiple names be assigned to the domain of a cookie?


Location: http://www.jguru.com/faq/view.jsp?EID=416038
Created: May 5, 2001 Modified: 2001-10-24 07:24:43.329
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
Shilpa Kulkarni (http://www.jguru.com/guru/viewbio.jsp?EID=322579

[I am setting domain as '.abc.com' for a cookie. I want the same cookie to be


accessible to '.abc.net'. How can this be achieved by using a single cookie?]

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.

Comments and alternative answers

Use the URL


Author: Jeff Williams (http://www.jguru.com/guru/viewbio.jsp?EID=231946), May 7,
2001
You can't do it with a cookie, but you might be able to accomplish what you want by
using something else that the user sends in the HTTP request. Like the URL for
instance...try adding "?user=foobar" to the URLs for that user. Then you'll know who
it came from when they come back -- even to your different domain. Caveat -- this is
very insecure for a number of reasons. You might look at the 'one-time logon'
products like Securant and Netegrity to see how they do this.

How can I share data between two different web applications?


Location: http://www.jguru.com/faq/view.jsp?EID=416043
Created: May 5, 2001
Author: Wayne Xin (http://www.jguru.com/guru/viewbio.jsp?EID=49940) Question
originally posed by jean kunz
(http://www.jguru.com/guru/viewbio.jsp?EID=384644

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]

Comments and alternative answers

Also
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Oct 25, 2001
This question is also answered at:

• Is there a simple way to share a single Session object across multiple


ServletContexts?
• How can I share data between two different web applications?
• How can I pass data from a servlet running in one context (webapp) to a
servlet running in another context?
• Can two web applications (servlet contexts) share the same session object?

How can I write to a log file from a servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=416048
Created: May 5, 2001 Modified: 2001-07-19 15:45:47.964
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by chenxiaoli chenxiaoli
(http://www.jguru.com/guru/viewbio.jsp?EID=384584

Look for the method ServletContext.log(String) or GenericServlet.log(String). These


will write to a servlet log file maintained by your servlet container.

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:

• Where does the output of System.out and System.err go in a servlet?


• Can I get at the OutputStream that is buried underneath
ServletContext.log()?

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]

Comments and alternative answers

if is cookie is disabled on server


Author: raj kapse (http://www.jguru.com/guru/viewbio.jsp?EID=714303), Jan 9, 2002
use encodeURL() method for all the URLs

Re: if is cookie is disabled on browser


Author: raj kapse (http://www.jguru.com/guru/viewbio.jsp?EID=714303), Jan 9,
2002
use encodeURL() for all the URLs

I want to redirect to a particular page, but before that, I want to display a


different HTML page containing a message.
Location: http://www.jguru.com/faq/view.jsp?EID=416059
Created: May 5, 2001
Author: Troy Niven (http://www.jguru.com/guru/viewbio.jsp?EID=219893) Question
originally posed by Avinash N
(http://www.jguru.com/guru/viewbio.jsp?EID=346964
The User not validated and the Error Message doesn't get displayed at all . I first
want it to be displayed , and then after 10 seconds , I want to redirect the servlet to
my OpeningPage

How is that possible ???]

Try something like this instead then.

res.setHeader("refresh","10; URL=http://"
+req.getServerName()+"/Openingpage.html");

out.println(" User not Validated");

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.,

InputStream in = new FileInputStream(????);

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

Reading file from WEB-INF


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jun 17, 2001
Theoretically, this works for getting a file from the WEB-INF directory as well.

getRealPathgetServletContext().getRealPath("/WEB-
INF/myconfig.xml")
(may not work on some servlet containers, but it's supposed to).

Re: Reading file from WEB-INF


Author: drit . (http://www.jguru.com/guru/viewbio.jsp?EID=454295), Aug 5, 2001
Partly true. It depends on the container - BEA for example, requires that you have
to set the applicaton correctly in config.xml.

I would probably use getResource() instead...


Author: Chang Zhao (http://www.jguru.com/guru/viewbio.jsp?EID=466741), Aug 1,
2001

My specs might not be up to date, but it says


<snip>
... This method returns null if the servlet container cannot translate the virtual path to
a real path for any reason (such as when the content is being made available from a
.war archive).
</snip>
so instead, maybe you can try getResource("/WEB-INF/whatever.xml"), get the url,
and get it that way...
just my $.02

What about writing a file within the context path?


Author: nick orbit (http://www.jguru.com/guru/viewbio.jsp?EID=964690), Jul 25,
2002
So, now I know how to read a file from within my webapp root directory. What to
I have to do in order to write a file. In my application is an XML file that is loaded
on startup. It contains categories on three levels that could be edited. When edited
the file including the modifications has to be stored on the servers hard disk in the
same directory where it first has been read.

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

Re: I would probably use getResource() instead...


Author: Travis Capener (http://www.jguru.com/guru/viewbio.jsp?EID=1099562),
Jul 7, 2003

This worked for me.

Here is a more complete code fragment from a JSP file. I put my


test.properties file in the root of my context (i.e. where the JSP and HTML
files are).

URL myURL=application.getResource("/test.properties");
InputStream in = myURL.openStream();
Properties p = new Properties();
p.load( in );
out.println( p.getProperty("message") );

Thanks for the help.

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.

How do I pass a parameter from a servlet to a JSP?


Location: http://www.jguru.com/faq/view.jsp?EID=416164
Created: May 6, 2001
Author: JIA Java Italian Association
(http://www.jguru.com/guru/viewbio.jsp?EID=414973) Question originally posed by
prashanth vaidyaraj (http://www.jguru.com/guru/viewbio.jsp?EID=415076

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? .

Comments and alternative answers

Yes, but parameter != attribute


Author: Roger Hand (http://www.jguru.com/guru/viewbio.jsp?EID=292314), May 7,
2001
The above answer is true enough, and frankly it's almost always the best method to
use, but the original questioner asked about passing a parameter, not an attribute.

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.)

Re: Yes, but parameter != attribute


Author: Amos Shapira (http://www.jguru.com/guru/viewbio.jsp?EID=4346), May
12, 2001
We use such parameter passing (servlet forwarding the request to a JSP page) and
it's very simple - use requestDispatcher and add "&param=value" to the url passed
from the servlet to the jsp.

Re: Re: Yes, but parameter != attribute


Author: susan borgrink
(http://www.jguru.com/guru/viewbio.jsp?EID=441060), Jun 18, 2001
I am trying to do something simillar to what you have mentionned. But I am
having problems getting it to work. Could you send me an example?

Re: Re: Re: Yes, but parameter != attribute


Author: Amos Shapira
(http://www.jguru.com/guru/viewbio.jsp?EID=4346), Jun 18, 2001
It's really stright-forward, as the spec says:
RequestDispatcher rd =
request.getRequestDispatch("url?newparam=newvalue");
rd.forward(request, response);

As simple as that.

Re: Yes, but parameter != attribute


Author: Mayur Agrawal (http://www.jguru.com/guru/viewbio.jsp?EID=428828),
May 25, 2001
Please send me the utility file , I wanna have a look at it! regards! Mayur
magrawal@ebisinessdesign.com

Re: Yes, but parameter != attribute


Author: lakshmiramana bulusu
(http://www.jguru.com/guru/viewbio.jsp?EID=461459), Jul 25, 2001
please upload your sample code,
to pass a parameter from a servlet to a jsp page .

same problem but with struts action classes


Author: jn dl (http://www.jguru.com/guru/viewbio.jsp?EID=466056), Aug 1, 2001
I'm having the same problem, but using struts : how can I pass request parameters
from an ActionClass to a JSP ? the problem is, I can't use the requestDispatcher, I
must return an ActionForward at the end of the perform method of the ActionClass.

What is the meaning of foo?


Location: http://www.jguru.com/faq/view.jsp?EID=416167
Created: May 6, 2001
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by BoonNam Goh
(http://www.jguru.com/guru/viewbio.jsp?EID=409183

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."

As to the origin of the term...

From The Jargon File:

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.

From Foo Fighters FAQ:

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

How can I reference an external CSS file from a Servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=416168
Created: May 6, 2001
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
Ruhsar Soganci (http://www.jguru.com/guru/viewbio.jsp?EID=407801

[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]

Comments and alternative answers

Including Stylesheet on a JSP page


Author: Girish Kshirsagar (http://www.jguru.com/guru/viewbio.jsp?EID=568296),
Dec 6, 2001
Since browser must read the "<link .. for a quickfix you cah hardcode the path to the
CSS. This method is not preferred, but will get you going fast.

Re: Including Stylesheet on a JSP page


Author: Girish Kshirsagar
(http://www.jguru.com/guru/viewbio.jsp?EID=568296), Dec 6, 2001
If you want to avoid hardcoding the path, you can use the following code <LINK
REL="StyleSheet" HREF="<%=request.getContextPath()%>/Style.css"
TYPE="text/css">
Now, make sure that your css (Style.css) is in the root of the context (e.g.
webapp\examples) in case of Tomcat.

Re[2]: Including Stylesheet on a JSP page


Author: Girish Kshirsagar
(http://www.jguru.com/guru/viewbio.jsp?EID=568296), Dec 6, 2001
In case you want to have it relative to the context path you can also write
LINK as

<LINK REL="StyleSheet"
HREF="<%=request.getContextPath()%>/util/CSS/Style.css"
TYPE="text/css">

Where, /util/CSS is a folder underneath your context path (e.g.


/webapp/examples in case of a typical Tomcat set up).

However, you must make sure that the entire path is accurately typed (i.e. is
case sensitive).

Hope this additional clarification helps.


What is an Application Event? (see Servlet Spec 2.3)
Location: http://www.jguru.com/faq/view.jsp?EID=416170
Created: May 6, 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

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.

Comments and alternative answers

Java:API:Servlets:Cookies, Sessions, and State Management,


Tools:AppServer:WebServer:Tomcat
Author: joerg hartmann (http://www.jguru.com/guru/viewbio.jsp?EID=429981), May
29, 2001
Hi, you can't change this ID. The ID is hard-coded in the cource code
org.apache.tomcat.request.package.SessionInterceptor.java and other classes. There
are also constants defined in package org.apache.tomcat.core.Constants public static
final String SESSION_COOKIE_NAME = "JSESSIONID"; public static final String
SESSION_PARAMETER_NAME = "jsessionid"; but the constant is only used in the
Class SessionUtil... joerg

How does Tomcat distribute servlet/JSP processing to the 20+ Java


processes it creates?
Location: http://www.jguru.com/faq/view.jsp?EID=416234
Created: May 6, 2001
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
Daniel Yawitz (http://www.jguru.com/guru/viewbio.jsp?EID=241695

[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) pool behaviour instructed by it is:

Upper bound for concurrency of 50 threads.


When the pool has more then 25 threads standing idle it will start to kill them.
The pool will start 10 threads on creation, and it will try to keep 10 vacant threads
(as long as the upper bound is kept).

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.[...]

How do you pass parameters to servlets with web.xml?


Location: http://www.jguru.com/faq/view.jsp?EID=416236
Created: May 6, 2001
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
Craig Navin (http://www.jguru.com/guru/viewbio.jsp?EID=407103

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>
...

[These are accessible from Java by calling ...? -A]

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]

See also How do I set init parameters in the servlet engine?

Comments and alternative answers

Setting init params in web.xml


Author: Kamran Dianat (http://www.jguru.com/guru/viewbio.jsp?EID=419421), May
10, 2001
My servlets do not "see" the web.xml file at all. Now I know it is being processed by
Tomcat, since I get all these xml parse errors if the syntax is wrong. web.xml is under
WEB-INF directory, and the syntax is correct. Any one can shed any light on this
mystery. Thanks, Kamran.

Still not work after changing web.xml


Author: sa wa (http://www.jguru.com/guru/viewbio.jsp?EID=464624), Sep 27, 2001
Hi, I am really a beginner. Thanks for your answer there. At least I know where I
should put my web.xml. I renamed original /conf/web.xml, then create my own
web.xml in conf/, but once I started the Tomcat(4.0), it showed that :

-----------------
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
------------------

Can you give me any hints? What is it?


Here is my web.xml for a single TestServlet.java:
-------------------
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application
2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<servlet>
<servlet-name>test</servlet-name>
<servlet-class>com.stardeveloper.servlets.TestServlet</servlet-class>
<init-param>
<param-name>Name</param-name>
<param-value>sa wa </param-value>
</init-param>
</servlet>
</web-app>
----------------
Thanks in advance!

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.

Another good way, is to do it statistically: if it contains 85% (for example) of


alphanumerical chars, probably it's a text file. You can take statistics on the first
buffer read from the file to speed up checking.

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?.

Comments and alternative answers

I think this is not i18n


Author: Carfield Yim (http://www.jguru.com/guru/viewbio.jsp?EID=4648), May 6, 2001
If have to check for a i18n document, e.g.: Chinese, this method can't success. I think that we can
use the method isDefine() in Character to see if the file contain defined character.
http://www.javasoft.com/products/jdk/1.2/docs/api/java/lang/Character.html#isDefined(char)
Actually I have never write some code for testing, may be isLetterOrDigit() is a better choice
http://www.javasoft.com/products/jdk/1.2/docs/api/java/lang/Character.html#isLetterOrDigit(char)

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]

Comments and alternative answers

Nice tips Alex.


Author: Luigi Viggiano (http://www.jguru.com/guru/viewbio.jsp?EID=101985), May
6, 2001
Thanks for the notes Alex, I've learned a new thing.

Still problems when the servlets are in jar files.


Author: JIA Java Italian Association
(http://www.jguru.com/guru/viewbio.jsp?EID=414973), May 6, 2001
I still getting a "null" result when the servlets are located in jar files. As I've
mentioned, Some of my servlets are in a jar files in the common location
<tomcat.home>/lib and some are in jar files under <context>/WEB-INF/lib.
Regards.

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());

always get NULL


Author: Börries Ludwig (http://www.jguru.com/guru/viewbio.jsp?EID=741941), Jun
12, 2002
Hi together,

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"));

How to retrieve the IP address or the hostname of the client which is


accessing a servlet?
Location: http://www.jguru.com/faq/view.jsp?EID=417475
Created: May 8, 2001
Author: JIA Java Italian Association
(http://www.jguru.com/guru/viewbio.jsp?EID=414973) Question originally posed by
Arunachalam P PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=90631

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? ]

I converted an applet that displays a graphics to a servlet using the Acme


Gif encoder. Why do the graphics look so poor now?
Location: http://www.jguru.com/faq/view.jsp?EID=417520
Created: May 8, 2001
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
Lukas Mueller (http://www.jguru.com/guru/viewbio.jsp?EID=407035

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.

[See also http://www.jguru.com/faq/view.jsp?EID=159 -Alex]

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

How do I create an alias in Java Web Server?


Location: http://www.jguru.com/faq/view.jsp?EID=417546
Created: May 8, 2001
Author: sree mam (http://www.jguru.com/guru/viewbio.jsp?EID=31208) Question
originally posed by Puneet Sachdeva
(http://www.jguru.com/guru/viewbio.jsp?EID=28785

In javawebserver documentation you can find how to create alias.Here i am giving


the same from Documentation.

To Add a Servlet Alias:

• 1.In the Administration Tool, go to the Service->Manage->Setup->Servlet


Aliases panel.
• 2.Click Add.
• 3.In the Alias field, type the URL path name you want to use to invoke the
servlet.
• 4.In the Serlvet Invoked field, type the name of the servlet that will be run in
response to the alias.

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.)

To specify a servlet chain, type the name of each servlet, separated by


commas but no spaces (for example: finger,snoop,date). A servlet chain is
two or more servlets linked together so that each servlet in the chain is called
in succession by the previous servlet. All of the servlets in a servlet chain can
be aliased to one alias name. When a request arrives for that alias, all the
servlets in the chain will be invoked.

• 5.Enter the name of the servlet.


• 6.Click Save.

To Delete a Servlet Alias:

1.In the Administration Tool, go to the Service->Manage->Setup->Servlet Aliases


panel.
2.Select the alias from the list.
3.Click Remove.
4.Click Save.

To Edit a Servlet Alias:

1.In the Administration Tool, go to the Service->Manage->Setup->Servlet Aliases


panel.
2.Select an alias from the list.
3.Click Modify.
4.Remove the existing text and type new text, or append text to the existing
information.
5.Press Return.
6.Click Save.

Note: To move to a new field, click that field.

Is there a common way (not servlet-container dependant) to precompile a


jsp file without waiting for the first hit?
Location: http://www.jguru.com/faq/view.jsp?EID=425278
Created: May 20, 2001 Modified: 2001-10-29 10:48:02.387
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
Alessandro A. Garbagnati PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=32727
Yes, there is a common solution that it's defined in the JSP specification and it has to
be implemented by any container that claim to be compliant.
JSP 1.1 Specification paragraph 3.4.2 states:
A request to a JSP page that has a request parameter with name "jsp_precompile" is
a precompilation request. The "jsp_precompile" parameter may have no value, or
may have values "true" or "false". In all cases, the request should not be delivered to
the JSP page.
The intention of the precompilation request is that of a hint to the JSP container to
precompile the JSP page into its JSP page implementation class. The hint is conveyed
by given the parameter the value "true" or no value, but note that the request can
be just ignored in all cases.
Moved to paragraph 8.4.2 in JSP 1.2 PDF 2 Specification

So, to precompile 'myPage.jsp' it's enough to use 'myPage.jsp?jsp_precompile'.


This feature is extremely interesting even for verifying the code inside a page that
requires parameters, or that contains code like sql insert or delete queries, etc.

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

You can also use load-on-startup


Author: Amos Shapira (http://www.jguru.com/guru/viewbio.jsp?EID=4346), May 27,
2001
You can also ask the page to be loaded when the server starts. This is done via the
web.xml file, like this:
<servlet>
<servlet-name>login</servlet-name>
<jsp-file>/login.jsp</jsp-file>
<load-on-startup>1</load-on-startup>
</servlet>

Re: You can also use load-on-startup


Author: sari Pula (http://www.jguru.com/guru/viewbio.jsp?EID=435408), Jun 7,
2001
can u please specify steps to perform for precompiling JSP files,like which xml
file has to be changed and where actually .class file generatedby jspc compiler has
to be placed.

Re[2]: You can also use load-on-startup


Author: Kevin Weslowski
(http://www.jguru.com/guru/viewbio.jsp?EID=921400), Jun 20, 2002
Hello, I'm also wondering about the steps to getting this working...I was
wondering if you had any luck with this? Thanks, Kevin

Common way to precompile jsp pages


Author: jeff hancock (http://www.jguru.com/guru/viewbio.jsp?EID=1157795), Mar
26, 2004
Just an fyi... Using Tomcat 5 with Windows. Tomcat will NOT compile JSP pages on
startup or with the ?Precompile commandline or using any other method. You can
delete the class file and it still does not compile JSP pages. The only means is to use
JSPC/JAVAC to compile JSP pages.

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.)

For instance, to pass in a PrintWriter from the doGet method of a Servlet:

public MyThread extends Thread {


private PrintWriter myWriter;
public MyThread(PrintWriter writer)
{
myWriter = writer;
}
public void run()
{
...
myWriter.print(...);
...
}
}

public void doGet(...)


{
...
MyThread mt = new MyThread(response.getWriter());
mt.start();
mt.join();
...
}
This is a very dangerous technique, however, since the doGet() method may return
before the thread finishes. So watch out. That's why you need the join() call -- it
waits until the thread is finished.
Comments and alternative answers
Re : How do I pass a variable into a thread that can be accessed from the run()
method?
Author: Venugopal V.V. (http://www.jguru.com/guru/viewbio.jsp?EID=467584), Aug
6, 2001

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{

// the variables passed from the A.jsp


private String stD;
private String endD;
private int uId;
private int aId;
private int orgId;
private int empId;

public MyThread(String s,String e,int u,int a,int o,int e){


Bean a = new Bean();
stD = s;
endD = e;
uId = u;
aId = a;
orgId = o;
empId = e;
}
public void run(){
a.methodInBean (stD,endD,uId,aId,orgId,empId);

} // end of run()

} // end of MyThread()

*** end of code


a.methodInBean takes all the 6 parameters and finish its task. This is what i want.
Will the above code suffice what i wanted? Let me know if you have any comments..

- 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

How to make a cookie secure ? Are secure cookies encrypted ?


Location: http://www.jguru.com/faq/view.jsp?EID=425611
Created: May 21, 2001 Modified: 2001-10-24 07:25:29.328
Author: Luigi Viggiano (http://www.jguru.com/guru/viewbio.jsp?EID=101985)
Question originally posed by vishal ganjoo
(http://www.jguru.com/guru/viewbio.jsp?EID=382910

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

How to make cookies secure... really...


Author: Stansilav Illiogovich
(http://www.jguru.com/guru/viewbio.jsp?EID=1188926), Jul 27, 2004
In addition to delivering the cookies over HTTPS (SSL), and encrypting the contents
such that they cannot be manipulated via Man in the Middle attacks, there is an
additional requirement. The cookie must also be marked as 'secure' per RFC2109 as
in...
//snip
Set-Cookie:JSESSIONID:893ihewwydkq2764@&@09;Path=/;secure
//snip

Marking the cookies this way ensures they cannot be delivered over an unencrypted
session such as http.

Using these three methods together makes a cookie reasonably 'SECURE'

In what order are objects unbound when a session expires?


Location: http://www.jguru.com/faq/view.jsp?EID=425613
Created: May 21, 2001
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
joy stalnecker (http://www.jguru.com/guru/viewbio.jsp?EID=385118

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.

Comments and alternative answers

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 the first scenario we can be assured all objects are present.

In this second scenario, we cannot be sure which object leaves the session first. (Elvis
object has just left the session)

I don't know the answer, but I'm looking....

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]

How can I enable SSI (server-side includes) under Tomcat/Apache?


Location: http://www.jguru.com/faq/view.jsp?EID=425625
Created: May 21, 2001
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
Maxim Senin (http://www.jguru.com/guru/viewbio.jsp?EID=21992

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

Is that the output of a servlet to be included in the output of another one?


Author: Koodal Kumaran Sailappan
(http://www.jguru.com/guru/viewbio.jsp?EID=300552), Jun 21, 2001
Earlier, Servlet API has SERVLET tag that can be used in html files of extension
.shtml.With Servlet API 2.2 and above RequestDispatcher's include method can be
used.
getServletContext().getRequestDispatcher().include("/servlet/...")
refer the book for method signature.

SSI, Tomcat and Apache


Author: Richard Robinson (http://www.jguru.com/guru/viewbio.jsp?EID=395750),
Jul 29, 2001

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.

The workaround for me was to copy tomcat-apache.conf to tomcat.conf (or whatever


name you choose), and then to modify httpd.conf to include IT.

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)

How can I enable SSI (server-side includes) under Tomcat/Apache?


Author: Börries Ludwig (http://www.jguru.com/guru/viewbio.jsp?EID=514317), Oct
26, 2001
Hi,

I am using ordinary SSI like <!--#include virtual="/infonetIniFiles/footer.ini" -->

I created my own context in server.xml

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>

The isVirtualWebappRelative had problems until version 24102001

... and it works.

Hope that helps


Boeries

Re: How can I enable SSI (server-side includes) under Tomcat/Apache?


Author: Stephen Morad (http://www.jguru.com/guru/viewbio.jsp?EID=852710),
May 31, 2002
I'm using Tomcat 4.0.3 In order to use
org.apache.catalina.servlets.SsiInvokerServlet, I had to rename
CATALINA_HOME/server/lib/servlets-ssi.renametojar to
CATLINA_HOME/server/lib/servlets-ssi.jar and restart Tomcat.

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?

Created the following files/directories:


CATALINA_BASE/webapps/ssi
CATALINA_BASE/webapps/ssi/WEB-INF/web.xml
CATALINA_BASE/webapps/ssi/index.jsp
CATALINA_BASE/webapps/ssi/index.html
CATALINA_BASE/webapps/ssi/index.shtml
CATALINA_BASE/webapps/ssi/header.html
CATALINA_BASE/webapps/ssi/footer.html

I added this line to web.xml:


<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>

index.* are all identical and look like this:


<html>
<body>
Include header: <!--#include virtual="header.html"-->

Include footer: <!--#include virtual="footer.html"-->


</body>
</html>

When I connect to http://servername/ssi/index.*, the header.html and footer.html


files are not included.
Thanks for your help!

--Steve Morad

Re[2]: How can I enable SSI (server-side includes) under Tomcat/Apache?

Author: Holger Schulz


(http://www.jguru.com/guru/viewbio.jsp?EID=426304), Jun 20, 2002
Hello Stephen!

Maybe this is missing in your web.xml:

<servlet-mapping>
<servlet-name>ssi</servlet-name>
<url-pattern>*.shtml</url-pattern>
</servlet-mapping>

Greetings from Germany

Holger

Re[3]: How can I enable SSI (server-side includes) under


Tomcat/Apache?
Author: Stephen Morad
(http://www.jguru.com/guru/viewbio.jsp?EID=852710), Jun 20, 2002
Yep, that was it. Thanks a lot!

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

Rename Apache Tomcat-installation-directory/server/lib/servlets-ssi.renametojar


to Tomcat--installation-directory/server/lib/servlets-ssi.jar.

Remove the XML comments from around the SSI servlet and servlet-mapping
configuration in Apache Tomcat-installation-directory/conf/web.xml.

Re[2]: How can I enable SSI (server-side includes) under Tomcat/Apache?

Author: rambabu v (http://www.jguru.com/guru/viewbio.jsp?EID=1213098),


Nov 25, 2004
I have faced the same problem. even after uncommenting the required things
in web.xml and renaming the servlet-ssi.renametojar to servlet-ssi.jar and
restarting the server also i am not able to run ssi in tomcat5. Pl. do the needful.
Thks in Advance.

Re[3]: How can I enable SSI (server-side includes) under


Tomcat/Apache?
Author: Ricardo Fernandes
(http://www.jguru.com/guru/viewbio.jsp?EID=1232117), Mar 11, 2005
same problem here, after uncomment the lines in the web.xml and the
renametojar my apache tomcat still ignores the includes

How can I force the web browser to cache my images?


Location: http://www.jguru.com/faq/view.jsp?EID=428820
Created: May 25, 2001
Author: Salman Khan (http://www.jguru.com/guru/viewbio.jsp?EID=303261)
Question originally posed by Eike Hirsch
(http://www.jguru.com/guru/viewbio.jsp?EID=44417

In JavaScript, do
var image1 = new Image();
image1.src = "xyz.gif";
And then use image1.src wherever you were using the xyz.gif

This will cache the image.

See also http://www.jguru.com/faq/view.jsp?EID=377

[Note: there seems to be a bug in IE 5.5 preventing this from working. See the
forum thread for details. -A]

Comments and alternative answers


RE: How can I force the web browser to cache my images?
Author: Daniel Hooker (http://www.jguru.com/guru/viewbio.jsp?EID=1203506), Oct
5, 2004
Is there anyway of doing this server side only (e.g. no client script) Dan.

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

There is a good article at O'Reilly's OnJava.com portal demonstrating the use of


Servlet Filters at
http://www.onjava.com/pub/a/onjava/2001/05/10/servlet_filters.html
Comments and alternative answers

Writing Servlet 2.3 Filters


Author: Luigi Viggiano (http://www.jguru.com/guru/viewbio.jsp?EID=101985), May
30, 2001
Also check Writing Servlet 2.3 Filters

Re: Writing Servlet 2.3 Filters


Author: Luigi Viggiano (http://www.jguru.com/guru/viewbio.jsp?EID=101985),
May 30, 2001
sorry it's the same.

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 Applets?


Location: http://www.jguru.com/faq/view.jsp?EID=431179
Created: May 30, 2001
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the jGuru Applets FAQ.

Where can I learn (more) about Application Servers?


Location: http://www.jguru.com/faq/view.jsp?EID=431183
Created: May 30, 2001
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the jGuru AppServer FAQ.


Where can I learn (more) about Java's suport for internationalization
(I18N)?
Location: http://www.jguru.com/faq/view.jsp?EID=431191
Created: May 30, 2001 Modified: 2001-08-18 19:04:05.76
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the jGuru I18N FAQ.

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)

Check out the jGuru IO FAQ.

Where can I learn (more) about Java's reusable software components,


JavaBeans?
Location: http://www.jguru.com/faq/view.jsp?EID=431197
Created: May 30, 2001 Modified: 2001-06-16 16:04:06.477
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the jGuru JavaBeans FAQ.

Comments and alternative answers

Advanced Java Programming


Author: Naveen Madenhalli (http://www.jguru.com/guru/viewbio.jsp?EID=1253053),
Jul 13, 2005
If a applet client wants to send a request to a server, what are the various steps to be
followed?

Where can I learn (more) about the JavaScript scripting language?


Location: http://www.jguru.com/faq/view.jsp?EID=431204
Created: May 30, 2001
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the jGuru JavaScript FAQ.

Where can I learn (more) about JDBC, Java's Database Connectivity


solution?
Location: http://www.jguru.com/faq/view.jsp?EID=431206
Created: May 30, 2001 Modified: 2001-07-24 09:55:24.202
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the jGuru JDBC FAQ.

Where can I learn (more) about Java JSP (JavaServer Pages)?


Location: http://www.jguru.com/faq/view.jsp?EID=431214
Created: May 30, 2001
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)
Check out the jGuru JSP FAQ.

Comments and alternative answers

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.

Re: JSP Tutorial


Author: D.Narasimham Dhurjati
(http://www.jguru.com/guru/viewbio.jsp?EID=460448), Jul 24, 2001
Yes. I need jsp tutorial

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)

Check out the jGuru Threads FAQ.

Where can I learn (more) about Apache's Java-based server, Tomcat?


Location: http://www.jguru.com/faq/view.jsp?EID=431251
Created: May 30, 2001
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the jGuru Tomcat FAQ.

Comments and alternative answers

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)

Check out the Project JXTA site.

How do I configure JAAS for use with servlets?


Location: http://www.jguru.com/faq/view.jsp?EID=432434
Created: Jun 1, 2001
Author: tippu sultan (http://www.jguru.com/guru/viewbio.jsp?EID=417083)
Question originally posed by manish sharan
(http://www.jguru.com/guru/viewbio.jsp?EID=142288

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

Are there any monitoring tools in JRun?


Location: http://www.jguru.com/faq/view.jsp?EID=433241
Created: Jun 3, 2001
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
venu gopalan (http://www.jguru.com/guru/viewbio.jsp?EID=394235

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.

I personally use OptimizeIt! (www.optimizeit.com) with Tomcat and Resin. The


other one mentioned is JProbe (www.jprobe.com)

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.

When using com.oreilly.servlet.MultipartRequest to upload files, I get a


java.io.UnsupportedEncodingException: ISO-8859-1 -- What's up?
Location: http://www.jguru.com/faq/view.jsp?EID=433243
Created: Jun 3, 2001 Modified: 2001-07-23 10:26:33.745
Author: tansel halic (http://www.jguru.com/guru/viewbio.jsp?EID=403072) Question
originally posed by tansel halic
(http://www.jguru.com/guru/viewbio.jsp?EID=403072

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.

Comments and alternative answers

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 page cannot be displayed

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:

<form method="post" enctype="multipart/form-data" action="upl.jsp"> <input


type="file" name="file_name">
<input type="submit" name="Submit" value="Submit"> </form>

Re: Upload problem


Author: Alex Skrypnik
(http://www.jguru.com/guru/viewbio.jsp?EID=388047), Jul 31, 2001
I checked Opera 512 browser - all is ok. I used MS IE 5.5 before.

Re: Oreilly Package


Author: Neil Hornbeck (http://www.jguru.com/guru/viewbio.jsp?EID=708152),
Jan 7, 2002
We use the Oreilly package, and only experience this problem from certain
machines using IE 5.5. I did a dump of the header, and found that certain values
for headers were duplicated.

(example: CONTENT_TYPE = multipart/form-data;


boundary=---------------------------7d2dc1180a50, multipart/form-data;
boundary=---------------------------7d2dc1180a50)
This confuses the Oreilly parser, which looks for the boundary to parse the data,
and picks up the whole string after the first 'boundary='.

How can I create a protected, "restricted" website? I.e., where someone


can only access the site by e.g., entering a password.
Location: http://www.jguru.com/faq/view.jsp?EID=439953
Created: Jun 15, 2001 Modified: 2001-06-17 14:04:04.509
Author: JIA Java Italian Association
(http://www.jguru.com/guru/viewbio.jsp?EID=414973) Question originally posed by
hendra winata (http://www.jguru.com/guru/viewbio.jsp?EID=425301

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.

Comments and alternative answers

Look for FORM-BASED AUTHENTICATION


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jun 17, 2001
See What is FORM based login and how do I use it? Also, what servlet containers
support it?

Why does my Servlet request lose UTF-8 encoding in passed-in attributes?


Location: http://www.jguru.com/faq/view.jsp?EID=440403
Created: Jun 17, 2001
Author: Rahul kumar Gupta (http://www.jguru.com/guru/viewbio.jsp?EID=4809)
Question originally posed by Satish Murthy
(http://www.jguru.com/guru/viewbio.jsp?EID=322353

[I use setAttributes() in the HttpServletRequest object to pass UTF-8 strings to a


servlet. On the receiving servlet, I receive only '?' for each unicode character. What
should I do?]

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.

You can set the content type like this

String contentType= "text/html;charset=UTF-8";


response.setContentType(contentType);

How do I display a page to the user when basic authorization fails or is


cancelled?
Location: http://www.jguru.com/faq/view.jsp?EID=440418
Created: Jun 17, 2001
Author: Nicolai Bartkowiak (http://www.jguru.com/guru/viewbio.jsp?EID=76332)
Question originally posed by Nicolai Bartkowiak
(http://www.jguru.com/guru/viewbio.jsp?EID=76332

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.

Comments and alternative answers

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.

Cut and paste this in an html file and open it...

<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

Simple encoding routine of the previous example


Author: Luigi Viggiano (http://www.jguru.com/guru/viewbio.jsp?EID=101985), Jun
24, 2001
<SCRIPT LANGUAGE="JavaScript1.2">
<!--
function encode(s,k) {
var sl=s.length;
var kl=k.length;
for(encoded='',i=0; i<sl; i++) {
var encodedChar=s.charCodeAt(i)^k.charCodeAt(i%kl);
encoded += String.fromCharCode((encodedChar & 0x0F) + 97) +
String.fromCharCode((encodedChar >> 4) + 97);
}
return encoded;
}
//-->
</SCRIPT>

Re: Simple encoding routine of the previous example


Author: Dan McTaggart (http://www.jguru.com/guru/viewbio.jsp?EID=1186345),
Jul 15, 2004
How do you use the encoder?

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.

if you write your code like this:

<script>

//<!--

document.write(unescape("<here you type your HTMLcode or secret


stuff>"));

//-->

</script>

then the page will be blank.

you can of course write more code under the </script> tag.

Why doesn't Tomcat find classes in jars in the WEB-INF/lib directory?


Location: http://www.jguru.com/faq/view.jsp?EID=444337
Created: Jun 24, 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

According to the Servlet 2.2 specifications:


9.4: Directory Structure

A web application exists as a structured hierarchy of directories. The root of this


hierarchy serves as a document root for serving files that are part of this context. For
example, for a web application located at /catalog in a web server, the index.html file
located at the base of the web application hierarchy can be served to satisfy a
request to /catalog/index.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.

The contents of the WEB-INF directory are:

• /WEB-INF/web.xml deployment descriptor


• /WEB-INF/classes/* directory for servlet and utility classes. The classes in this
directory are used by the application class loader to load classes from.
• - /WEB-INF/lib/*.jar area for Java ARchive files which contain servlets, beans,
and other utility classes useful to the web application. All such archive files
are used by the web application class loader to load classes from.
I've never had this problem with either Tomcat and Resin, unless the file was not a
jar but a zip (It happened with Oracle's drivers that are packaged ina file called
classes12.zip).
Comments and alternative answers

Make sure the jar file has the correct path


Author: Newman Shee (http://www.jguru.com/guru/viewbio.jsp?EID=445216), Jun
25, 2001
Hi, I ran into the exact same problem today with TomCat cannot find the classes in
the jar file. After debugging through, it turns out that the problem is the jar file has the
wrong path to the java class in it. After re-jar the java classes with the correct path,
everything worked. Newman Shee

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.

I would suggest you do the following:

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.

For me, this post was helpful.

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

Assume your WEB-INF\web.xml deployment descriptor is correct.

Then place your classes in the directory...

C:\Java\com\mycompany\mypackage

Create your jar file, in the C:\Java directory, via

jar cvf myclasses.jar com\mycompany\mypackage\*.class

Place myclasses.jar in WEB-INF\lib (you no longer need WEB-


INF\classes\*).

Stop and restart Tomcat.

Now Tomcat will find your com.mycompany.mypackage.*.class classes.

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.

Personally I consider cleaner the first solution.

However, if you want to get clever, read on ... -Alex]

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>

<input type="hidden" name="ddtext" value="">


</select>
</form>

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

Is there a freeware or shareware Web forum application written in Servlet


or JSP?
Location: http://www.jguru.com/faq/view.jsp?EID=444360
Created: Jun 24, 2001
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
James Chen (http://www.jguru.com/guru/viewbio.jsp?EID=441020

Check out Jive.

From the site:

Jive is forum software that allows threaded discussions on websites. It features


excellent performance, user-defined "skins" to completely change the look, feel, and
function of forums, and a plugin API that can provide advanced features such as on-
the-fly translation, content filters, or almost anything else. Even better, Jive is Open
Source. That means that it's completely free to use on your own site, and more
importantly, has a dedicated community that continually improves the software.
Comments and alternative answers

Need to know more about Jive


Author: kvt kvt (http://www.jguru.com/guru/viewbio.jsp?EID=317336), Jun 25, 2001
What is the website of jive. Have you ever used the Jive Skin concept. I am really
interested in the skin concept.

Re: Need to know more about Jive


Author: Jeff Judge (http://www.jguru.com/guru/viewbio.jsp?EID=447777), Jun
29, 2001
You can find jive at http://jivesoftware.com. I've set it up a few times, and I have
to admit that it is very easy to setup and administer. Enjoy..

Re: Need to know more about Jive


Author: Ritu kumar (http://www.jguru.com/guru/viewbio.jsp?EID=314981), Dec
11, 2001
I want to know more about applying skins to the jive forum. Do you know of any
examples showing how to go about it ? Thanks, Ritu

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

Re: Another Alternative


Author: Michael Sun (http://www.jguru.com/guru/viewbio.jsp?EID=943802), Jul
10, 2002
Where can I find it ?
Jive is nolonger an open project, is there any other alternative?

Re[2]: Another Alternative


Author: Sandy Canfield
(http://www.jguru.com/guru/viewbio.jsp?EID=999432), Sep 15, 2002
Try:
http://yazd.yasna.com/
Can somebody tell me the advantages/disadvantages of Allaire JRun versus
Apache Tomcat?
Location: http://www.jguru.com/faq/view.jsp?EID=444367
Created: Jun 24, 2001
Author: Nick Makris (http://www.jguru.com/guru/viewbio.jsp?EID=250647) Question
originally posed by Anandanath Banerji
(http://www.jguru.com/guru/viewbio.jsp?EID=440091

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)

Comments and alternative answers

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.

Re: Allaire JRun


Author: Ajay Prabhakaran
(http://www.jguru.com/guru/viewbio.jsp?EID=481380), Oct 2, 2001
Do i have JDBC Connection Pooling support in Tomcat. This i beleive is available
in JRun.

Thanks in advance

Re: Re: Allaire JRun


Author: Ajay Prabhakaran
(http://www.jguru.com/guru/viewbio.jsp?EID=481380), Oct 2, 2001
Does Tomcat support JDBC Connection Pooling.. This i beleive is available in
JRun.

Thanks in advance

Re: Re: Re: Allaire JRun


Author: Dev Ramachandren
(http://www.jguru.com/guru/viewbio.jsp?EID=518866), Oct 12, 2001
No. Tomcat does not support JDBC Connection pooling. U will need a 3rd
party 100% JDBC driver which implements all JDBC 2.0 and preferably
3.0 to do that for you. You could use other drivers but a 100% JDBC driver
is better.
I have more questions/thoughts to pros/cons of Tomcat over JRun.
Author: Ravi Mittal (http://www.jguru.com/guru/viewbio.jsp?EID=1134303), Jul 20,
2004
We have live JRun production server. Can I run JRun on port 80? I tried but it crashes
very often.

Is JRun 4 Updater 2 a stable patch to use?

Can Tomcat work efficiently on dual/multi processor server than JRun?

What is more advisable to use for production machine JRun/Tomcat?

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.

Where do I get source code for an Internet search engine?


Location: http://www.jguru.com/faq/view.jsp?EID=445901
Created: Jun 26, 2001
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by dhrutiman mishra
(http://www.jguru.com/guru/viewbio.jsp?EID=440184

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?

Inside a JSP, how to represent private methods and call them?


Location: http://www.jguru.com/faq/view.jsp?EID=445904
Created: Jun 26, 2001
Author: Luigi Viggiano (http://www.jguru.com/guru/viewbio.jsp?EID=101985)
Question originally posed by Amit Rosner
(http://www.jguru.com/guru/viewbio.jsp?EID=433821

[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? ]

Use a declaration scriptlet:

<%!
private void foo() {
System.out.println("foo");
}
%>

<%
foo();
%>

Comments and alternative answers

Two possible ways


Author: Krishna Krishna (http://www.jguru.com/guru/viewbio.jsp?EID=440479), Jun
28, 2001
you can either place the methods enclosed within JSP tags <% ..... %> with in a JSP
page directly OR you can convert the servlet into a Java Program with whatever
methods and functionality u need and then use 'Bean' tag in the JSP page to invoke
methods u need to access. This should help, Good Luck.

The catch is that ....


Author: drit . (http://www.jguru.com/guru/viewbio.jsp?EID=454295), Aug 1, 2001
The catch is that in private methods, you cannot split your htmls and java code! This
is what I encountered with tomcat v3.2. I have worked around with <%@ include ...
tag> but that is still ugly. I am interested to listen to any other workarounds.

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

Another approach if separate form doesn't work...


Author: Carol Lietz (http://www.jguru.com/guru/viewbio.jsp?EID=446419), Jun 27,
2001
If you can't wrap the href in it's own form, then you could call Javascript to do the
submit. In this example, the action on the form (when user clicks the submit button) is
to go to java.sun.com. But if the user follows the "go to www.ugs.com" link, then they
would be directed there via post by the javascript.

Servlet would output ...


<form name=MyForm action="http://java.sun.com">
<input type=submit name="whatever" value="go to java web site">
<a href=javascript:this.submitMe();>go to www.ugs.com</a>
</form>

JS:
function submitMe()
{
document.MyForm.action="http://www.ugs.com/";
document.MyForm.target="targetName";
document.MyForm.submit();
return;
}

HTTP GET request


Author: zong zhang (http://www.jguru.com/guru/viewbio.jsp?EID=491205), Sep 23,
2001
I am using the answer to GET html file from a servlet.
I modified the code like this:
<form name="submitForm" method="GET" action="/servlet/ServletName"> Click
Me </form>
But When I click the "Click Me", I got the message:"bad gateway, DNS error". Where
am I wrong? Please Help. Thanks Zong

Re: HTTP GET request


Author: Sharat N (http://www.jguru.com/guru/viewbio.jsp?EID=502507), Sep 26,
2001
Check it doGet Method is defined in your servlet..

How do I assign the user's role without using a login form?


Location: http://www.jguru.com/faq/view.jsp?EID=445915
Created: Jun 26, 2001
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
Victor Serrato (http://www.jguru.com/guru/viewbio.jsp?EID=440450

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.

For Tomcat 3.2.x there is an interesting example of a JDBC Realm.


For additional info, I strongly suggest to read Chapter 11 (Security) and Chapter 13
(Deployment Descriptor) of the Servlet 2.2 specifications that you can download from
Sun.

[In Servlet 2.3 spec, the Security chapter is now 12.

Also - There's no way to programmatically set the user (e.g.


request.setRemoteUser), but if you need to, you can just use a session variable to let
yourself know that this user is "ok."

-Alex]

Comments and alternative answers

But then ...


Author: Christian Burger (http://www.jguru.com/guru/viewbio.jsp?EID=750308), Feb
7, 2002
... I can not use the standard security features of the web container to protect some
realms in accordance with the user group the user is belonging to ...

Why doesn't Response.sendRedirect() work after the binding of Tomcat


with Apache server?
Location: http://www.jguru.com/faq/view.jsp?EID=445939
Created: Jun 26, 2001
Author: Oren Deri (http://www.jguru.com/guru/viewbio.jsp?EID=63019) Question
originally posed by Tan HN (http://www.jguru.com/guru/viewbio.jsp?EID=40344

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.

Try the following:

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

%> <script type="text/javascript">location=url</script> <%

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 {

String ctxPath = req.getContextPath();


...

}
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

Quite serious issue


Author: David Tunkrans (http://www.jguru.com/guru/viewbio.jsp?EID=728671), Jan
21, 2002
There seems to be very few ways to query for deployment information from the
runtime environment. eg
-> ask the servlet which application or context it belongs to.

If anyone knows how to do this (or a "fix"), please let me know.

(david.tunkrans@servando.se)

Re: Quite serious issue


Author: Niko Schmuck (http://www.jguru.com/guru/viewbio.jsp?EID=408882),
Mar 1, 2002
The only possibility i see at the moment is to use an ugly hack with the help of
javax.servlet.ServletContext .getRealPath(java.lang.String path)
(and use empty string for path). From the returned file path subtract the root path
(if you have one at hand) or just use the last fragment (directory) as the name of
the web application context.

I'm sorry, i know that this is far from optimal, but ...
Niko

Context path in init()


Author: Mihai Iancu (http://www.jguru.com/guru/viewbio.jsp?EID=837190), Apr 13,
2002
The java servlet api does not have a method for getting the context path of an
application other than for getContextPath() on a HttpServletRequest object.
This can be too late for some applications.
One can try to use the ServletConfig (actually the vendor specific implementation) to
achieve this goal. But this means that the portability of your code is limited (but from
my experience, developers will have a limited range of web/app server
implementations anyways).
The (ServletConfig) implementation for WebSphere 4.x is
com.ibm.servlet.engine.webapp.WebApp and for WebLogic 6.x
weblogic.servlet.internal.WebAppServletContext.

Use for WebSphere 4.x:

WebApp ibmWebApp = (WebApp)servletContext;


String contextPath = ibmWebApp.getRootURI();

Use for WebLogic 6.x:

WebAppServletContext beaWebApp =
(WebAppServletContext)servletContext;
String contextPath = beaWebApp.getContextPath();

For other implementations, one should consult the web/app server documentation.

Re: Errata Context path in init()


Author: Mihai Iancu (http://www.jguru.com/guru/viewbio.jsp?EID=837190), Apr
13, 2002
I meant vendor specific ServletContext implementation... and not ServletConfig.

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:

String refererPage = request.getHeader("referer");


[Tim Delesio adds:
You can also create a hidden field in the form and then use a if statement to check
and route accordingly.
Or, if the parameter you've added is called 'original',
response.sendRedirect( request.getParameter("original") );
-Alex]
Comments and alternative answers

Referer isn't reliable


Author: Frank Steidinger (http://www.jguru.com/guru/viewbio.jsp?EID=34216), Jun
28, 2001
I'd recommend you use the hidden field. While it is certainly more of a hassle it is
also more reliable.
The referer field can be stripped from the HTTP header by a proxy. In fact the
browser isn't required to send the referer field in the header at all.

Re: Referer isn't reliable


Author: Thomas Andreas Schwob
(http://www.jguru.com/guru/viewbio.jsp?EID=335784), Dec 3, 2001
Hidden field is very limiting, because it just can provide the name of the web page
all the rest of the URL cannot be provided because its dynamic, therefore

How do you want to store in a hidden field a URL context?

This in certain cases must be provided because of cross-application links where


the two applications reside in different URL contexts, or even worse on different
machines (host). In such a case one absolutely needs a fully-qualified URL.

Actually it is a lack in the specification of HTTP. 'referer' should not be a header


data but be sent mandatory in the request and therefore should be a
HttpServletRequest API in the interface like 'getReferer' or 'getReferringURL'.
This way a proxy has no chance to cut such data, which I think is not admissible
anyway.

Actually in regard to complex web applications implementing complex data


workflow (let's assume a complex web-based production control system) it is
every day more apparent to me that HTTP is not any more uptodate to the
requirements of such applications and needs urgently a revision.

I won't regard alternatives like integration to CORBA via IIOP, because this would
lead too far here.

Re[2]: Referer isn't reliable


Author: Frank Steidinger
(http://www.jguru.com/guru/viewbio.jsp?EID=34216), Dec 4, 2001
I'd fill the hidden field on the server using the request.getRequestURI()
method if the path is sufficient or reconstruct the full URL with the
HttpUtils.getRequestURL(request) if necessary. In my opinion that's still
better than relying on data that may be missing. And it is not just a problem of
proxies removing the referer field as there are other circumstances where the
browser doesn't provide it. Some browsers even allow the user to disable
referer logging (e.g. Opera).
That HTTP isn't the best choice for complex application from a technical
viewpoint goes without saying. Changing the HTTP specification wouldn't
solve the problem for quite some time as you'd still have to support older
browsers.

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

You should be able to include a name in the image tag

<....NAME ="your name"...>.

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.

Comments and alternative answers

multi submit html forms


Author: Steve Ryan (http://www.jguru.com/guru/viewbio.jsp?EID=277716), Jun 29,
2001
This is OK until you want to replace the buttons by images. I've spent many painful
hours trying to do this with javascript in both browsers. Dont bother. An easy example
is ......

<form> <input type='image' name='a1' src='button.gif' value='submit'> <input


type='image' name='a2' src='button.gif' value='submit'> <form>
result
<% if (request.getParameter("a1.x")!=null) out.println("b1 pressed"); if
(request.getParameter("a2.x")!=null) out.println("b2 pressed"); %>

Re: multi submit html forms


Author: Charmaine Farrugia
(http://www.jguru.com/guru/viewbio.jsp?EID=1072763), Apr 3, 2003
hi i am kind of new to this stuff and was wondering whether you could help me
out with a few problems regarding an image button i am trying to use for a map.
THE image buttin is on a JSP page and I want the image button to return the
coordinates to a servlet however everytime i try reading the parameters from the
servlet it keeps giving me null ..

the code im using is as follows :


in JSP :
<form action="../servlet1?" method="GET"> <div align="center"> <input
type="image" src="images/comp.gif" name="image" width="400" height="300">
</div>
and in servlet:
if ((reqParam = request.getParameter("image.x"))!=null) { xStr = new
Double(reqParam); System.out.print(xStr); } else System.out.print("empty x co-
ordinate");

and it always returns empty x-co-ordiante

Am i missing out on something??

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"?

Your help would be GREATLY appreciated


Lost in java :(
Charmaine

Tried this - didn't work


Author: Laurie Mecham (http://www.jguru.com/guru/viewbio.jsp?EID=1149931),
Apr 30, 2004
I had already tried your solution prior to reading this. It isn't working for me and from
reading other sites, I'd say I'm not the only one. I noticed in your reply you said you
were using an html page (you didn't say you were going from a JSP to a servlet). Was
that a slip? Do you have that code working for a JSP? Thanks, Hamilton

Re: Tried this - didn't work


Author: Laurie Mecham (http://www.jguru.com/guru/viewbio.jsp?EID=1149931),
Apr 30, 2004
Oops, my message should have been to Nick

How can I prevent Microsoft's so-called "SmartTags" from manipulating my


web content?
Location: http://www.jguru.com/faq/view.jsp?EID=446724
Created: Jun 27, 2001
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

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: Re: self.close()!!


Author: Sriram Narasimhan
(http://www.jguru.com/guru/viewbio.jsp?EID=105242), Jun 28, 2001
Does that mean there are no solutions available at present to stop the dialog
box when u close a window using self.close() ?

Re: Re: Re: self.close()!!


Author: Kevin Dorff
(http://www.jguru.com/guru/viewbio.jsp?EID=445138), Jun 28, 2001
I don't see what this has to do with Start Tags, BUT, the answer is that
self.close() has a warning (question) when you attempt to close a main
browser window. If you pop-up a child window you can self.close() it
without a problem or a question. This is a "security feature".

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."

Did you try ?

Re: Re: self.close()!!


Author: Sriram Narasimhan
(http://www.jguru.com/guru/viewbio.jsp?EID=105242), Jul 3, 2001
yeah ! But still the same problem.

Re: Re: Re: self.close()!!


Author: Stevens Gestin
(http://www.jguru.com/guru/viewbio.jsp?EID=458859), Aug 24, 2001
This is a Javascript security problem ! Not Smart Tag. The only way our
Self.close window won't show a warning dialog bax is if the current
window was opened with a JavaScript function like window.open.

Hope it could help

This just in!


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jun 28, 2001
Microsoft has just announced it will drop Smart Tags from Windows XP.
"At this time we just don't believe it's going to be ready when (Windows XP) ships in
October," Microsoft spokesman Jim Cullinan said late Wednesday. "External
feedback" was one of the factors that led the company to remove the feature, although
he indicated it could be resurrected in later versions.

How can one Servlet Stop (and Re-Start) another Servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=448698
Created: Jul 2, 2001
Author: Ryan Breidenbach (http://www.jguru.com/guru/viewbio.jsp?EID=45212)
Question originally posed by John Maring
(http://www.jguru.com/guru/viewbio.jsp?EID=12155

[I am using JRun's JrunScheduler, but I need to re-start it whenever I modify it's


Event.ini file. Any ideas?]

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.

Hope this helps.

Comments and alternative answers

Servlet accepts commands like "Refresh"


Author: Mahendra Goyal (http://www.jguru.com/guru/viewbio.jsp?EID=331192), Jul
7, 2001
I dont know if this is of help to you but i really do not like the idea of restarting the
tomcat or servlet.What i have done is my servlet accepts commands like "Refresh"
using getPathInfo().so the command would be like /servlet/MyServlet/Refresh.The
sevlet then will ask for admin username and password and if authenticated and
authorised it would refresh the content ,cache etc.Within init there wouldbe a call to
an updating method and on receiving refresh command the servlet will again call the
same method.

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]

Comments and alternative answers

Is this a proxy setting or can I use a servlet?


Author: neal ravindran (http://www.jguru.com/guru/viewbio.jsp?EID=17737), Nov 1,
2002
I have a webapp that needs to get the IP address of the client. I have not been
successful so far. Is this a proxy setting you have here?

Why do we somtimes encounter a "400 GET not supported" message?


Location: http://www.jguru.com/faq/view.jsp?EID=448704
Created: Jul 2, 2001
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Danisment Gazi Unal
(http://www.jguru.com/guru/viewbio.jsp?EID=404238

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.

Aron Tunzi adds:

Insert into you servlet the following code:

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
doPost(request,response);
}

public void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
//insert your code hier.
}
Comments and alternative answers

400 GET not supported


Author: Danisment Gazi Unal
(http://www.jguru.com/guru/viewbio.jsp?EID=404238), Jul 5, 2001
Hello,

This my test application. I don't send GET to my servlet, I send


POST. But, I saw
a GET in web servlet log as below:

217.131.15.19 - - [30/Jun/2001:04:22:30 -0500] "GET


/servlet/itrprof.itrprof HTTP/1.0" 400 163 "-" "Mozilla/4.77 [en]
(Win98; U)"

my question: how is this GET produced ?

thanks...

Re: 400 GET not supported


Author: Lalitha Sivaraman
(http://www.jguru.com/guru/viewbio.jsp?EID=403897), Aug 17, 2001
Hi, We too have faced the same problem under Weblogic. The reason for our
problem was - there is a file called web.xml which contains the list of all servlets,
their class name etc. When we tried to call the servlet without including the details
in web.xml we got the same error. Probably there will an equivalent file in ur
server also - Checkout
Using VisualAge for Java, the servlet engine starts but while accessing it
from the browser it is giving an error 503.
Location: http://www.jguru.com/faq/view.jsp?EID=448722
Created: Jul 2, 2001
Author: Aron Tunzi (http://www.jguru.com/guru/viewbio.jsp?EID=446077) Question
originally posed by Navnit Singh Mathur
(http://www.jguru.com/guru/viewbio.jsp?EID=446821

[
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.

What you need to do is:

Click the "Edit Class Path..." button.


Check all needed projects.
Start the servlet engine
In the brower edit: localhost:8080/servlet/xxx.yyy where xxx ist the package's
name (eg my.java.test) and yyy the name of the class (eg TestServlet); now the full
path is:http://localhost:8080/servlet/my.java.test.TestServlet
Comments and alternative answers

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

Re: WTE/Servlet Engine


Author: Diego Mansilla (http://www.jguru.com/guru/viewbio.jsp?EID=746347),
Feb 4, 2002

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?
Location: http://www.jguru.com/faq/view.jsp?EID=452687
Created: Jul 10, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Josep Grifell
(http://www.jguru.com/guru/viewbio.jsp?EID=451431

On your URLConnection, add


conn.setRequestProperty("Content-type", "java-internal/" +
hash.getClass().getName());
The getClass().getName() is the general way to specify the class, you can hard code
the value, like the following....
conn.setRequestProperty("Content-type", "java-
internal/java.util.Hashtable");
Comments and alternative answers

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");

This seems to work fine for me

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.

How do I process FDF files created by the Acrobat Forms plug-in?


Location: http://www.jguru.com/faq/view.jsp?EID=455199
Created: Jul 15, 2001
Author: Arun Bharathan (http://www.jguru.com/guru/viewbio.jsp?EID=106958)
Question originally posed by Christine Hutcheson
(http://www.jguru.com/guru/viewbio.jsp?EID=452670

[ The files are uploaded with content type = application/vnd.fdf ]

To update/complete or recover data from a FDF you need adobe java classes which
are JNI for Adobe DLLs.

I think it is available in Abobe's site

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.

Comments and alternative answers

Problems with current versions of FDF toolkit


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jul 15, 2001
FDF Toolkit Version 4.05 works with JDK 1.1 and below. There is no Java support in
version 5 yet. :-(

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.

Why do I sometimes get the error "ODBC Driver Manager ...function


Sequence Error"?
Location: http://www.jguru.com/faq/view.jsp?EID=455201
Created: Jul 15, 2001
Author: Pramod Vuppalapanchu
(http://www.jguru.com/guru/viewbio.jsp?EID=453652) Question originally posed by
Hema latha (http://www.jguru.com/guru/viewbio.jsp?EID=405076

We had the same problem and we found that

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.

Comments and alternative answers

Sun JDBC-ODBC Bridge (JRE 1.2.2) Bug work-around


Author: Darrell Teague (http://www.jguru.com/guru/viewbio.jsp?EID=517558), Oct
11, 2001
We ran into this same problem with the same symptoms (i.e. random Function
Sequence Errors). As ugly as this is, it is possibly the only sure-fire work-around if
you cannot change your JRE (such as when integrating with another company's
product that ships with and will not change their JRE from 1.2.3. to 1.3.x):

Close the statement and re-create it between each call:

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

Re: Sun JDBC-ODBC Bridge (JRE 1.2.2) Bug work-around


Author: Rahul Pawar (http://www.jguru.com/guru/viewbio.jsp?EID=520149), Oct
14, 2001
Hi Darrell,
The work around you have suggested is not quite working for me.
Instead of Statement object we are using the CallableStatement object in combi
with stored procedures of MS SQL Server.
I m doing exactly as suggested by you but then its not working. Pls try to delve
into the problem.

Thanks,
Rahul

Re: Re: Sun JDBC-ODBC Bridge (JRE 1.2.2) Bug work-around


Author: Darrell Teague
(http://www.jguru.com/guru/viewbio.jsp?EID=517558), Oct 15, 2001
Yours sounds like a slightly different situation (CallableStatement Interface
and stored procedures on MS SQLServer). However, if you will post a code
snippet with all of the relavent pieces (creation of the CallableStatement,
stored procedure execution calls, creation of ResultSets, closing of ResultSets,
closing of Statement, etc), I (and perhaps others) will be glad to take a look at
it.
Re: Re: Re: Sun JDBC-ODBC Bridge (JRE 1.2.2) Bug work-around
Author: Rahul Pawar
(http://www.jguru.com/guru/viewbio.jsp?EID=520149), Oct 15, 2001

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 rp_jguru@yahoo.com. 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

You can just put a link like this


<a href="/serverpath/runme.bat">execute runme</a>
When client clicks on it it will be asked to open the file (and execute it) or just to
download it. This is general way to handle this (think about .exe installers... always
you need to push on ok after choosing to execute the file instead of just download it)

[But see How to copy the file from Server side into Client ... for words of warning
about security... -A]

What is a session and why is it required?


Location: http://www.jguru.com/faq/view.jsp?EID=455205
Created: Jul 15, 2001
Author: Bozidar Dangubic (http://www.jguru.com/guru/viewbio.jsp?EID=433955)
Question originally posed by aruna rani
(http://www.jguru.com/guru/viewbio.jsp?EID=405045

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.

See Topic Java:API:Servlets:Cookies, Sessions, and State Management

How can I generate an output in CSV format from a database query?


Location: http://www.jguru.com/faq/view.jsp?EID=455207
Created: Jul 15, 2001
Author: Luigi Viggiano (http://www.jguru.com/guru/viewbio.jsp?EID=101985)
Question originally posed by Ritu kumar
(http://www.jguru.com/guru/viewbio.jsp?EID=314981

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.

It's very common to put as first line the names of fields.

Comments and alternative answers

There are libraries to help


Author: Stephen Ostermiller (http://www.jguru.com/guru/viewbio.jsp?EID=576685),
Jan 28, 2002
Comma Separated Values (CSV) in Java is an available library to help. It supports
reading and writing the files.

Re: There are libraries to help


Author: Namita Prakash (http://www.jguru.com/guru/viewbio.jsp?EID=1024031),
Nov 11, 2002
Hi, I need to convert MS Access files into CSV format.i cannot use the export
function of MS Access coz it will require me to manually export a lot of files.how
do i do it using JDBC-ODBC bridge. thaanks, namita

Re[2]: There are libraries to help


Author: Richard Rodger
(http://www.jguru.com/guru/viewbio.jsp?EID=1220174), Jan 7, 2005
Use the ODBC Data Sources administration applet to define a DSN (data
source name) for the CSV file. More details here:
http://java.sun.com/j2se/1.3/docs/guide/jdbc/getstart/bridge.doc.html

Can I spawn a background thread from my servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=455215
Created: Jul 15, 2001
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Michael O Connor
(http://www.jguru.com/guru/viewbio.jsp?EID=412596

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.

public class DaemonStarter extends HttpServlet {


public void init() {
TimerDaemon d = new TimerDaemon();
d.start();
getServletContext().setAttribute("daemon", d);
}
}

public class MyDaemon extends Thread {


long secs = 0;
public void run() {
while (true) {
Thread.sleep(1000);
secs++;
}
}
public long getSecs() {
return secs;
}
}

public class PrintSecs extends HttpServlet {


public class doGet(...) {
TimerDaemon d =
(TimerDaemon)getServletContext().getAttribute("daemon");
response.getWriter().println( d.getSecs() );
}
}

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.

Comments and alternative answers

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;
}
}
}

public class PrintSecs extends HttpServlet {


public class doGet(...) {
TimerDaemon d =
(TimerDaemon)getServletContext().getAttribute("daemon");
response.getWriter().println( d.getSecs() );
}
}

While forwarding from one page to another by using RequestDispatcher,


how do I avoid the error " OutputStream is already being used for this
request" ?
Location: http://www.jguru.com/faq/view.jsp?EID=455248
Created: Jul 15, 2001
Author: thomas dietrich (http://www.jguru.com/guru/viewbio.jsp?EID=413665)
Question originally posed by kodandapani a
(http://www.jguru.com/guru/viewbio.jsp?EID=415257

Just a few pointers:

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.

Comments and alternative answers

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!!!

Re: RequestDispatcher Forwarding....


Author: Mark Lesk (http://www.jguru.com/guru/viewbio.jsp?EID=440839), Aug 29,
2001
Actually, it is still an error to call response.getOuputStream() at anytime after a call to
request.getWriter() is made. This is true whether it is before, after, or during a
request.getRequestDispatcher().include() call.

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();

How do I prevent users from viewing the contents of my WEB-INF


directory?
Location: http://www.jguru.com/faq/view.jsp?EID=455249
Created: Jul 15, 2001
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
Danisment Gazi Unal (http://www.jguru.com/guru/viewbio.jsp?EID=404238

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.

What is the difference between ServletContext.getInitParameter() and


HttpServlet.getInitParameter() ?
Location: http://www.jguru.com/faq/view.jsp?EID=455711
Created: Jul 16, 2001
Author: André Wolf (http://www.jguru.com/guru/viewbio.jsp?EID=310274) Question
originally posed by Rama krishna Maddipati
(http://www.jguru.com/guru/viewbio.jsp?EID=433173

[Original Question:

I am using Tomcat Web server.I am passing parameter in Web.xml using

<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>

To retrieve this parameter you just call getInitParameter() in your servlet.

Comments and alternative answers

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 ...

Is there a way in Tomcat to set up zones for servlets like in jserv?


Location: http://www.jguru.com/faq/view.jsp?EID=455766
Created: Jul 16, 2001
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by ryan wexler
(http://www.jguru.com/guru/viewbio.jsp?EID=433624
Not really. Tomcat 4 has somewhat better management of classpaths and contexts
and virtual hosts -- you might want to check it out.

Why do I get "java.lang.NoClassDefFoundError: sun/tools/javac/Main" ?


Location: http://www.jguru.com/faq/view.jsp?EID=455768
Created: Jul 16, 2001
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Sean K (http://www.jguru.com/guru/viewbio.jsp?EID=429709

java.lang.NoClassDefFoundError: sun/tools/javac/Main means that your


classpath is not set correctly. Make sure your JAVA_HOME is set up right before you
run the tomcat or startup scripts. If that doesn't do it, see these FAQs:

• How do I set my CLASSPATH for servlets?


• When starting Tomcat l get "java.lang.NoClass...
• java.lang.NoClassDefFoundError in unix

Comments and alternative answers

Search Comment On FAQ Entry Why do I get


"java.lang.NoClassDefFoundError: sun/tools/javac/Main" ?
Author: marion schwarz (http://www.jguru.com/guru/viewbio.jsp?EID=462656), Jul
26, 2001
Sometimes the installation of jdk does not include the tools.jar in the
JAVA_HOME\lib directory. tools.jar contains the requested Main.class file. Copying
the .jar into the \lib directory solves this problem.

Re: Search Comment On FAQ Entry Why do I get


"java.lang.NoClassDefFoundError: sun/tools/javac/Main" ?
Author: Taswell Jeffries (http://www.jguru.com/guru/viewbio.jsp?EID=716794),
Jan 11, 2002
Hi Marion, I am experiencing the same problem. I have a windows 2000 SP2
Server with IIS loaded. I have installed Tomcat 3.3. I have also installed j2re-
1_3_1_01-win. I cannot find any tools.jar on my filesystem. Should I juust get a
copy of tools.jar and copy it into the library directory? Many thanx Taswell
Jeffries

Re[2]: Search Comment On FAQ Entry Why do I get


"java.lang.NoClassDefFoundError: sun/tools/javac/Main" ?
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727), Jan 11, 2002
I think you have to install the full J2SE, not just the Runtime Edition (J2RE).

Re[2]: Search Comment On FAQ Entry Why do I get


"java.lang.NoClassDefFoundError: sun/tools/javac/Main" ?
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727), Jan 11, 2002
I think you have to install the full J2SE, not just the Runtime Edition (J2RE).

Re: Search Comment On FAQ Entry Why do I get


"java.lang.NoClassDefFoundError: sun/tools/javac/Main" ?
Author: JOSE LUIS KUHLMANN
(http://www.jguru.com/guru/viewbio.jsp?EID=1219050), Jan 2, 2005
I solve the problem of the following way: I have put initially(originally) of my
program the name of the file .java of the following way, package Name of the file;

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

Re: Re: Tomcat-NoClassDefFoundError:.....


Author: suomi hasler (http://www.jguru.com/guru/viewbio.jsp?EID=517403),
Oct 11, 2001
Hi every (body or not)

I solved this problem this morning:


with the previous installation on tomcat-4.0, I had been able to run servlets but
not JSP, where I always got the error msg you mention above.

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.

good luck. suomi

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

How do I implement a hit counter in Servlets or JSP?


Location: http://www.jguru.com/faq/view.jsp?EID=456418
Created: Jul 17, 2001 Modified: 2002-12-04 21:51:15.09
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Hema latha
(http://www.jguru.com/guru/viewbio.jsp?EID=405076

When implementing a hit counter, there are many decisions to make.

1. Are you sure you want to write it yourself?

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:

o How can I add a counter applet to my web page?


o http://www.theCounter.com
o http://www.jcount.com
o http://counter.bloke.com
2. What do you want to count?

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.

3. Where do you want to save the data?

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

o How can I access or create a file or folder in the...


o Is there a standard place to write temporary files...
o How do I access a database from my servlet?
Aron Tunzi posted some great code for writing to a file in the forum thread for
this question, at How do I implement a hit counter in Servlets or JSP

4. How do you want to display the results?

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.

How to build an image-based counter

To build an image-based counter, write a servlet -- let's say /myapp/counter -- that


works as follows:

public void doGet(...) {


incrementCount();
Image i = getImage();
writeImage(response);
}
Of course, you still have to write the incrementCount, getImage, and writeImage
methods :-) See the AWT FAQ and the Servlets: Images topic for help on creating
and sending images from a Servlet.

In your client pages, output the following HTML:

<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.

Comments and alternative answers

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?

Re: Bean Example


Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Jul 18,
2001
Read #3.

How do I trap a 404 error inside my servlet if my servlet does a


RequestDispatcher to a non-existent page ?
Location: http://www.jguru.com/faq/view.jsp?EID=457102
Created: Jul 18, 2001
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
Tim Owen (http://www.jguru.com/guru/viewbio.jsp?EID=455434

[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.

This is the extract of the web.xml DTD:

<!-- 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)>

Comments and alternative answers


What a moronic answer!
Author: jack david (http://www.jguru.com/guru/viewbio.jsp?EID=462745), Jul 26,
2001
Everybody knows that. Copy and pasted the dtd. Atleast an example fragment of
XML showing how to actualy use it would have been useful.

Re: What a moronic answer!


Author: Axel Stahlhut (http://www.jguru.com/guru/viewbio.jsp?EID=965487),
Nov 18, 2004
What a moronic comment!

Include the following in your deployment descriptor file (web.xml)


Author: Ravindra Peddireddy (http://www.jguru.com/guru/viewbio.jsp?EID=510262),
Oct 3, 2001

<error-page>
<error-code>404</error-code>
<location>/ErrorPage.jsp</location>
</error-page>

When there is a 404 error it automatically redirects to "ErrorPage.jsp" in which you


will typically display your custom error message.

You may also trap exceptions by including the following :-

<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.

Re: Include the following in your deployment descriptor file (web.xml)


Author: Mojmir Hanes (http://www.jguru.com/guru/viewbio.jsp?EID=730375),
Jan 22, 2002
Hi, I have a problem redirecting error 500. Here is my web.xml
<web-app>
<error-page>
<error-code>404</error-code>
<location>/errorPages/404.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/errorPages/500.jsp</location>
</error-page>
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/errorPages/exception.jsp</location>
</error-page>
</web-app>
I try to write page with syntax error
<% str = Strin; %>
but without redirecting java.lang.exception in web.xml I see default Tomcat error
page. I would like to see errorPages/500.jsp page.

I use Apache 1.3.22 and Tomcat 4.01

Thank you very much :-)


Miuek
(sorry for my english :-) )

Re[2]: Include the following in your deployment descriptor file (web.xml)


Author: Vijay Dogra (http://www.jguru.com/guru/viewbio.jsp?EID=1149724),
Feb 27, 2004
I have same problem in customizing tomcat eror pages.I have added <error-
page> <error-code>500</error-code> <location>/error.jsp</location> </error-
page> in my web.xml file but still it doesnt work. I have tomcat 5.0.16 and
jdk1.4.2 on XP machine. Kindly help me

Re[3]: Include the following in your deployment descriptor file


(web.xml)
Author: Tim Hannaford
(http://www.jguru.com/guru/viewbio.jsp?EID=1179663), Jun 17, 2004
Your problem could be as simple as not refreshing a cached paged when
the error occurs. Or perhaps you have another runtime error in your
error.jsp page. That was a problem I had, which made my exception
handling appear not to work. I replaced the jsp with a static html as a test
and it worked out for me. I hope that helps.

Re[4]: Include the following in your deployment descriptor file


(web.xml)
Author: Vijay Dogra
(http://www.jguru.com/guru/viewbio.jsp?EID=1149724), Jun 28, 2004
Yes thanks for the answer it was actually i was not flushing the buffer.
Thanks!!!!!

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

You can configure Resin to run servlets at regular intervals.

In /ref/servlet-config.xtp in the Resin docs, have a look at the run-at


specification for resin.conf.

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>

Comments and alternative answers

Interested to know more about this....


Author: Karen Ng (http://www.jguru.com/guru/viewbio.jsp?EID=462255), Dec 19,
2001
Where can I get more info about the solution above?

How do I download several files at the same time?


Location: http://www.jguru.com/faq/view.jsp?EID=460087
Created: Jul 23, 2001
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Donatello Parigino
(http://www.jguru.com/guru/viewbio.jsp?EID=451493

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]

Comments and alternative answers

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 ?

Re: Multidownload by Javascript


Author: Rick Tossavainen
(http://www.jguru.com/guru/viewbio.jsp?EID=1153085), Mar 10, 2004
Was an answer to this ever determined as we have need to download multiple files
via a browser with the click of one "download button"?

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

You must set the Content-length HTTP header.

You can use the following code:

response.setHeader("Content-disposition", "attachment;filename=name");
response.setIntHeader("Content-length", filelength);
ServletOutputStream sos = response.getOutputStream();
...
Comments and alternative answers

Problem with JSP's


Author: Rémi Vannier (http://www.jguru.com/guru/viewbio.jsp?EID=480640), Aug
30, 2001
I have a related problem... What if you forward a JSP page, and you don't know the
content-length by advance ???

Re: Problem with JSP's


Author: Jatinder Thind (http://www.jguru.com/guru/viewbio.jsp?EID=488511),
Sep 8, 2001
When u forward a JSP page,the page is not
actualy sent to the client.Its
executed by the servlet container
on the server side only.So the question of
making the file length known to the client does not arise.

Reaction to this answer


Author: Rémi Vannier (http://www.jguru.com/guru/viewbio.jsp?EID=480640), Sep 8,
2001
I found the answer to my question myself. It is true that I don't have to set the content-
length of the request. In fact, I think it is not possible unless you can access the code
of the JSP interpreter Since the JSP interpreter cannot know by advance the content
length, it uses a different transfer format : the Chunked transfer Encoding, used since
HTTP 1.1. In the case of the chunked transfer encoding, the data is sent by chunks,
whose length is specified in the first line of the chunk in hexadecimal format. U can
deal with that by 2 ways : Either U use the w3c class 'ChunkedInputStream', which
decodes the Chunked data... (package org.w3c.www.http) Either U code it yourself,
since it is very simple... Here is the algorithm in pseudo language If transfer-encoding
equals chunked { read Chunksize (use BufferedReader.readLine() in Java) while
chunksize>0 { totalsize += chunksize read 'chunksize' bytes } } add the content length
header with the value 'totalsize'. Bye all.

Why do Frames suck?


Location: http://www.jguru.com/faq/view.jsp?EID=460110
Created: Jul 23, 2001
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

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.

Comments and alternative answers

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:

• Not possible to bookmark


• Print problems
• Authoring problems (others steeling your content by displaying it in their own
frameset)
• Search engine problems

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.

How can I display bar codes in my Java program?


Location: http://www.jguru.com/faq/view.jsp?EID=462245
Created: Jul 25, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

IDAutomation has a set of commercial beans, applets, and servlets for dynamic bar
code generation.
Comments and alternative answers

Where can I find free barcode generator in java and javascript?


Author: Philippe Corbes (http://www.jguru.com/guru/viewbio.jsp?EID=1238298),
Apr 13, 2005
For a free java barcode generator visit:
http://sourceforge.net/projects/barbecue

for a free javascript barcode generator and free codes visite:


http://philippe.corbes.free.fr/codebarre/jsbarcode/index.html (in french)
or
http://philippe.corbes.free.fr/codebarre/jsbarcode/index_en.html (in english)
How do I pass query parameters when I use Request Dispatcher?
Location: http://www.jguru.com/faq/view.jsp?EID=472606
Created: Aug 9, 2001
Author: JIA Java Italian Association
(http://www.jguru.com/guru/viewbio.jsp?EID=414973) Question originally posed by
Preedesh Menon (http://www.jguru.com/guru/viewbio.jsp?EID=277934

[I am using:

reqDisp =
servletContext.getRequestDispatcher("/applicationsecurity/RedirectLogin
.jsp")
reqDisp.forward(req,res);
]

Since you're working with a request, nstead of using the getRequestDispatcher()


method of the ServletContext, you should use the getRequestDispatcher of the
HttpServletRequest object.

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:

org/apache/struts/action/ActionServlet.java line 1751:

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.

Two: All request details are not passed when using


ServletConfig.getRequestDispatcher. May be it is the query string parameters for the
current page that does not reach the page where request is forwarded. (don't
remember exactly..surf it out)

Is there a recommended way to validate form data entered by the user?


Should I do it on the client or the server?
Location: http://www.jguru.com/faq/view.jsp?EID=473818
Created: Aug 10, 2001 Modified: 2001-09-26 12:17:44.267
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Ignacio Coloma
(http://www.jguru.com/guru/viewbio.jsp?EID=466626

[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.

Is there a (more or less) standard way to achieve this?

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.]

> Is there a (more or less) standard way to achieve 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).

public void doGet(...) {


String error = validate(req);
if (error != null) {
printError(resp, error);
return;
}
// continue on with processing form
...
}

(Alternately, you could throw a ValidationException whose getMessage() field


contains the error. My personal style is to avoid exceptions except in truly
exceptional cases, and since you expect the user to enter bogus data at least some
of the time, this doesn't qualify.)

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.

Check Refactoring by Martin Fowler for inspiration on this sort of incremental


programming. It's a lot more rewarding and efficient than trying to solve the whole
problem all at once.

Also, check Jakarta Regexp package if you're going to be validating string contents.

Please see the forum threads:

• Good idea - more simple than mine


• how to check whether the data entered is a number ...

for some more discussion of this problem.


Comments and alternative answers

A comment from Leonard Grove


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Nov 11, 2001
use a pattern matching function in the ezVerify (http://www.ezverify.com) server-side
validation tag library.

Is there a simple example of how to use web application security in


WebLogic?
Location: http://www.jguru.com/faq/view.jsp?EID=479768
Created: Aug 20, 2001
Author: CustomWare Asia Pacific
(http://www.jguru.com/guru/viewbio.jsp?EID=139414) Question originally posed by
CustomWare Asia Pacific PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=139414

Following is an example for WebLogic 6.x that protects all URLs that begin with
/secure:

WEB-INF/web.xml - Define a constraint and a role

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web


Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<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>

WEB-INF/weblogic.xml - Map the admin role to the system user in WebLogic.

<!DOCTYPE weblogic-web-app PUBLIC "-//BEA Systems, Inc.//DTD Web


Application 6.0//EN" "http://www.bea.com/servers/wls600/dtd/weblogic-
web-jar.dtd">

<weblogic-web-app>
<security-role-assignment>
<role-name>admin</role-name>
<principal-name>system</principal-name>
</security-role-assignment>

</weblogic-web-app>

Why do I get the error java.lang.IllegalStateException: Header already


sent ?
Location: http://www.jguru.com/faq/view.jsp?EID=480147
Created: Aug 20, 2001
Author: Nils Kulk (http://www.jguru.com/guru/viewbio.jsp?EID=337581) Question
originally posed by Dave Brown
(http://www.jguru.com/guru/viewbio.jsp?EID=459504

Hi, sounds like you're trying to set a header after you've written something to the
response output stream.

An HTTP repsonse message is composed as follows: an HTTP reponse code


(something like "HTTP/1.1 200 OK") followed by zero or more headers (something
like "ContentType: text/html") followed by the repsonse contents.

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.

So the wrong way is:

OutputStream out =
response.getOutputStream();
out.writeln("Hello...");
out.flush();
response.setContentType("text/html");

The right way is:

response.setContentType("text/html");
OutputStream out =
response.getOutputStream();
out.writeln("Hello...");
out.flush();
Comments and alternative answers

the same error in jsp


Author: johnson johney (http://www.jguru.com/guru/viewbio.jsp?EID=527416), Oct
22, 2001
Hi,
What does this mean if the same error happens in jsp, I am not using the forward tag
or requestdispatcher anywhere in the jsp

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.

Is it possible to set the user name and password on an HTAccess certificate


directly from my code rather than have the user do it from the HTAccess
prompt?
Location: http://www.jguru.com/faq/view.jsp?EID=492801
Created: Sep 7, 2001
Author: Bogdan Sheptunov (http://www.jguru.com/guru/viewbio.jsp?EID=310126)
Question originally posed by Tim Smiser
(http://www.jguru.com/guru/viewbio.jsp?EID=351009

Yes. This is the code for BASIC http authorization:


// use this to encode the username/password
private String encodeAuthorization String username, String password)
{
String authorization = username + ":" + password;
sun.misc.BASE64Encoder enCoder = new sun.misc.BASE64Encoder();
return "Basic " + enCoder.encode(authorization.getBytes());
}

// insert this piece into setting the connection properties, where


encodedAuthorization is a result of the function given above:
connection.setRequestProperty("Authorization", encodedAuthorization);
Comments and alternative answers

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());
}
}

How do I use a RequestDispatcher to call one servlet from another servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=492819
Created: Sep 7, 2001
Author: André Wolf (http://www.jguru.com/guru/viewbio.jsp?EID=310274) Question
originally posed by Irene Espadas
(http://www.jguru.com/guru/viewbio.jsp?EID=481137

To call another servlet you have to use a request dispatcher:


RequestDispatcher rd =
this.getServletConfig()
.getServletContext()
.getRequestDispatcher("/path-to-servlet");
rd.forward();
or
rd.include();
See J2EE-API documentation for more information.

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".

Comments and alternative answers

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

Re: DoPost to DoGet???


Author: Eduardo Garcia (http://www.jguru.com/guru/viewbio.jsp?EID=1145466),
Feb 11, 2004
Hi Irene.
Just make a call to doGet method inside the doPost method,
like this:

public void doPost (HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException
{
doGet(request,response).
}
Hope that can be helpful :).

how to forward from doPost


Author: Satish Rapalli (http://www.jguru.com/guru/viewbio.jsp?EID=1233969), Mar
21, 2005
Hi, I'm unable to forward or include from doPost method,which i am successfull with
doGet. Actually, i'm catching the information from a form whose method is post into a
servlet class which has only doPost and then i'm trying to forward the request to
another servlet class. The code inside the doPost method is: RequestDispatcher rd =
request.getRequestDispatcher("/math"); rd.forward(request,response); The error when
form is submitted : type Status report message HTTP method POST is not supported
by this URL description The specified HTTP method is not allowed for the requested
resource (HTTP method POST is not supported by this URL).

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.

How do I parse hex integer Color codes passed as parameters to my


servlet?
Location: http://www.jguru.com/faq/view.jsp?EID=492831
Created: Sep 7, 2001
Author: Bogdan Sheptunov (http://www.jguru.com/guru/viewbio.jsp?EID=310126)
Question originally posed by Allan Kamau
(http://www.jguru.com/guru/viewbio.jsp?EID=484440

[ I am trying to pass Color values like 0xeeeeee or 0xEEEEEE as values to


parameters from a get post (in the header). However I am unable to process the
value into an integer value which is a requirement for the Color(int) constructor I will
use to create the new color based on this passed value, I have tried

int
colorvalue=Integer.parseInt(req.getParameterValue("ColorParameter"));

It is throwing an NumberFormatException which I am printing displaying the actual


value of the parameter e.g

<output> NumberFormatException : 0xEEEEEE </output>

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. ]

The keyword for you is Integer.decode(). Here is some sample code:

String hexValue = "0x11";


Integer decodedInt = null;
int result = 0;
try
{
decodedInt = Integer.decode(hexValue);
}
catch (NumberFormatException e)
{
System.out.println("Cannot convert '" + hexValue + "': " +
e.getMessage());
}
if (decodedInt != null)
{
result = decodedInt.intValue();
}
System.out.println(result); // prints out 17

Comments and alternative answers


Search Comment On FAQ Entry RE: How do I parse hex integer Color codes
passed as parameters to my servlet?
Author: Garrett Smith (http://www.jguru.com/guru/viewbio.jsp?EID=733867), May
20, 2002
Well, I don't think he wants the whole hex as a number, rather it would make sense to
have a number each for red, green, and blue.
String colorParameter;
int r;

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!

So what are you going to do with this?

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

You have to go to Project-Option-Server. In the button option "Manage Deployment


Target" you have to configure the server, putting the password, server name and
domain. You can do this in enviroment options for all the projects Run the servlet. It
has to generate a web.xml and weblogic.xml file. I think you have to make a
directory named classes in
\config\mydomain\applications\DefaultWebApp_myserver\WEB-INF\classes. Make
sure the xml files it generates have been put in
\config\mydomain\applications\DefaultWebApp_myserver\WEB-INF\

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.

(I prefer using browser redirects (sendRedirect()) over RequestDispatcher since it


keeps bookmarks and Reload/Refresh logic clean.)

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:

public void doGet(HttpServletRequest req, HttpServletResponse res) {


doPost(req.res);
}

You should also read the Forum Thread on this subject for many other good
comments.

Comments and alternative answers

One servlet or several servlets


Author: Subrahmanyam Allamaraju
(http://www.jguru.com/guru/viewbio.jsp?EID=265492), Sep 15, 2001

I've a few comments on Alex Chaffee's answer:

• Whether a servlet (typically a subclass javax.servlet.http.HttpServlet) chooses


to support one or several HTTP methods, it inherits default behavior from the
abstract super class. Given this, it is perfectly valid to support more than one
method in a given servlet. For instance, a servlet may implement doGet,
doPost and doHead.

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.

How do I load a file from inside a WAR file?


Location: http://www.jguru.com/faq/view.jsp?EID=497268
Created: Sep 14, 2001
Author: Bozidar Dangubic (http://www.jguru.com/guru/viewbio.jsp?EID=433955)
Question originally posed by Dean Sheppard
(http://www.jguru.com/guru/viewbio.jsp?EID=14227

[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]

I have done the same thing many times using ctx.getResourceAsStream("/rel-


path/filename") and it always works fine. I am not sure what is the problem in your
case. try to access the file using getResourceAsStream() and see if that works.

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.

Comments and alternative answers

Check out
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Sep 27, 2001
Dmitry Namiot, Aug 20, 2001 writes:

Check out cache taglib on http://www.servletsuite.com/jsp.htm for example.

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.

It is pretty fast and provides functionality you outlined above.

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.

Comments and alternative answers

why cant you cache ResultSet and just use it as a cursor


Author: sam pitroda (http://www.jguru.com/guru/viewbio.jsp?EID=476938), Nov 15,
2001
I am assuming that there is no problem in caching resultset in servlet which you can
get back from session id.
Can anyone tell me the advantages and disadvantages between Tomcat,
JRun, and JServ for Apache Web Server?
Location: http://www.jguru.com/faq/view.jsp?EID=497500
Created: Sep 15, 2001
Author: Christopher Schultz (http://www.jguru.com/guru/viewbio.jsp?EID=138382)
Question originally posed by Terry Kroukamp
(http://www.jguru.com/guru/viewbio.jsp?EID=495999

Here's some quick-n-dirty facts:


Product Pros Cons
Tomcat • Free as in both beer and • Not the fastest implementation on the
speech planet
• Active open-source
development effort • You're on your own for support

• Very current in terms of


servlet API compliance
JRun • Free as in beer for • Costs money for production use
developers • Versions that I've used (pre-3.0) had
• Relatively speedy lots of configuration headaches

• Supported by Allaire • Slightly behind the times with


(Macromedia) updates (compared to open source
projects)
Apache Free as in both beer and speech • No longer in active development
JServ (Tomcat inherited this effort)
• Has some thread-leaking issues, in
my experience
• Only supports servlet API 2.0 (not
later)

• You're on your own for support

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.

Configuration management is fully documented, as is installation and troubleshooting


for all of these products, online.

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

What about Resin?


Author: Kai Mysliwiec (http://www.jguru.com/guru/viewbio.jsp?EID=506836), Sep
29, 2001
Has anyone experince with Resin?

Re: What about Resin?


Author: Marc Schneider (http://www.jguru.com/guru/viewbio.jsp?EID=707299),
Jan 2, 2002
Yes, Resin is similar to Tomcat, but:

a) It's much much faster

b) It's (slightly) easier to configure, and you have more options

c) It's expensive in an Production environment ($500 per server, $4500 for a pack
of 10)

Hope that helps...

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.

Has Tomcat covered all functions of JServ?


Author: amq zhang (http://www.jguru.com/guru/viewbio.jsp?EID=761045), Feb 16,
2002
I was trying to do some testing following doc http://java.apache.org/jserv/howto.load-
balancing.html
I am not sure how different Tomcat is, will there still have got same functions? or I'd
better just set up JServ, make life bit easier?

Re: Has Tomcat covered all functions of JServ?


Author: Kevin CHEUNG
(http://www.jguru.com/guru/viewbio.jsp?EID=1061154), Feb 27, 2003
How about Orion AS? I've tested it and compared to Tomcat 4.x, Orion is even
easier to configure but I guess the tradeoff is scalability as Tomcat is pretty
scalable. I didn't have the Orion in production usage and the runtime performance
against Tomcat 4.x is thus known. Is there experience sharing on the relative
runtime performance?

How do I load an applet from a servlet or JSP? Where do I place my applet


class files?
Location: http://www.jguru.com/faq/view.jsp?EID=499425
Created: Sep 18, 2001 Modified: 2003-01-05 05:53:08.134
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Chris Klumpp
(http://www.jguru.com/guru/viewbio.jsp?EID=496701

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("&amp;lt;APPLET CODE='MyApplet.class' WIDTH=50 HEIGHT=50
CODEBASE='/applets'&amp;gt;"&amp;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?

Comments and alternative answers

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.")

Class Not Found


Author: JASPER TAPIA (http://www.jguru.com/guru/viewbio.jsp?EID=1052495),
Jan 31, 2003
I set up the directory structure like you said
/usr/local/catalina/webapps/ESI/applets/HelloWorldApplet.class
/usr/local/catalina/webapps/ESI/applet.html I just want to call a basic applet from a
html page. [ESI]# less applet.html <HTML> <HEAD> <TITLE>Hello World
Applet</TITLE> </HEAD> <BODY BGCOLOR="#FFFFFF">
<H1>Hello World Applet</H1>
<APPLET code="HelloWorldApplet.class" width=350 height=120
codebase='/applets'> </BODY> </HTML> [applets]# less HelloWorldApplet.java
import java.applet.*; import java.awt.*; public class HelloWorldApplet extends
Applet { static final String message = "Hello World"; private Font font; public void
init() { setBackground(Color.white) ; font = new Font("SansSerif", Font.BOLD,
48); } public void paint(Graphics g) { g.setColor(Color.pink); g.fillOval(10, 10, 330,
100); g.setColor(Color.red); g.drawOval(10,10, 330, 100); g.drawOval(9, 9, 332,
102); g.drawOval(8, 8, 334, 104); g.drawOval(7, 7, 336, 106);
g.setColor(Color.black); g.setFont(font); g.drawString(message, 40, 75); } } When I
opened the html page I just got a grey box. When I scolled over it I saw load: class
HelloWorldApplet not found in the bottom bar of my browser. Do I have to point to
the class file in my web.xml file or set a CLASSPATH? Thanks in advance

Re: Class Not Found


Author: Ryan Swanson (http://www.jguru.com/guru/viewbio.jsp?EID=1246596),
May 31, 2005
ok so i have a .jar file how would i load that? i have a specific class file inside the
jar file i need to load. ne hlp plz.

How do I pass params like -D to the JServ JVM?


Location: http://www.jguru.com/faq/view.jsp?EID=500047
Created: Sep 19, 2001
Author: drit . (http://www.jguru.com/guru/viewbio.jsp?EID=454295) Question
originally posed by sam pitroda
(http://www.jguru.com/guru/viewbio.jsp?EID=476938

[I want to pass this parameters to JVM that runs my servlet. E.g. -Djava.
naming.factory.initial = com.sun.jndi.cosnaming.CNCtxFactory]

There is a file in apache/JServ known as "jserv.properties". Set your param in this


wrapper.bin.parameters key.

How do I use servlets to return dynamically generated PDF documents?


Location: http://www.jguru.com/faq/view.jsp?EID=500656
Created: Sep 20, 2001
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

[Thanks to Greg Perkins, Aug 27, 2001:]

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

We have a similar situation where we wanted a generic approach and decent


separation of view/logic. XSL allows you to transform any XML document to many
types of visual documents such as PDF and HTML. Thus your servlet can generate
the data as XML and simply pass it through the processor.

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.

Re: Try XSL-FO


Author: Dev eloper (http://www.jguru.com/guru/viewbio.jsp?EID=1183562), Jul
3, 2004
If you do not want to have to program your application to handle conversion from
html to pdf, then you can look at a web service offered by Gilgamesh Solutions at
http://gilgamesh-solutions.com/webservices.cfm. Using this service you will be
able to send a URL to an html page you build on the fly on your server, and the
service will actually crawl over your URL and convert your page to pdf! You can
control many options including footers, headers, page breaks, page orientation
(landscape vs. portrait), include high quality images (png, jpg, gif). The beauty
about this service is that you are able to control the format of your generated pdf
using html tags! If you have a coldfusion server, then you can actually buy the
product for around $60 I believe. But you might want to go with the service option
if you do not want to deal with installation, setting up your application, worrying
about changing your application when you upgrade, if you use different languages
and you want an application that is platform and web server independent. Give it a
try, I believe that they have test environments on their web site where you can try
their products live for free.

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

Re: Try xml.apache.org/fop


Author: Santanu Sen (http://www.jguru.com/guru/viewbio.jsp?EID=524215), Oct
18, 2001
I am a real beginner on Java. I am trying to compile a Servlet that we got from
Software AG- an xml to pdf Servlet that will convert xml document to pdf on the
fly. It is not compiling. Do you think you can share your Servlet source code with
me ? Looks like yours one is doing the same job. Thanks

Try XMLPDF also


Author: James Childers (http://www.jguru.com/guru/viewbio.jsp?EID=761785), Feb
17, 2002
I have had some success with XMLPDF, as well. You can use it to generate a PDF
from and XML template and data that has been stored in an XML file (or an in
memory representation of an XML file.) Has worked great for me.

How do I get a session object to perform a task before it is invalidated?


Location: http://www.jguru.com/faq/view.jsp?EID=500657
Created: Sep 20, 2001
Author: Denis Navarre (http://www.jguru.com/guru/viewbio.jsp?EID=495283)
Question originally posed by Tony Fagan
(http://www.jguru.com/guru/viewbio.jsp?EID=226421

Hi Tony,

You must implement the javax.servlet.http.HttpSessionBindingListener


interface in your object stored in session.

Two methods must be added to your object when you implement this interface:

public void valueBound(HttpSessionBindingEvent arg1)


and
public void valueUnbound(HttpSessionBindingEvent arg1)

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.

I use this interface to delete temporary files and it works fine.

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.

Why do I get the error "IllegalStateException" when using the


RequestDispatcher?
Location: http://www.jguru.com/faq/view.jsp?EID=501393
Created: Sep 21, 2001
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Mark Gorenstein
(http://www.jguru.com/guru/viewbio.jsp?EID=492823

When you use RequestDispatcher.forward or RequestDispatcher.include to call


another servlet, you must pay very close attention to a fairly tricky detail of the
servlet "chain of command."

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.

Two common variants of this exception are "java.lang.IllegalStateException:


Header already sent" and "java.lang.IllegalStateException: Cannot forward
as Output Stream or Writer has already been obtained".

"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().

This is due to the semantics of RequestDispatcher.forward() -- it's intended to be


called only by servlets that do literally nothing to the response before forwarding
(since the "forwardee" is supposed to be the master servlet). Unfortunately, this
means that you can't do things that you might naturally expect, like forwarding from
one servlet or JSP to another, where each one adds a little bit of data to the
response. Also unfortunately, there are some scenarios where you *can* do exactly
that, so when you encounter a scenario where the exception is thrown, it seems to
come from out of the blue.

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.

RequestDispatcher.include() is probably a safer method than


RequestDispatcher.forward() for other reasons, since it leaves the request
parameters alone (forward() changes the path etc. to be relative to the target
servlet, not the original 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:

• Why do I get the error java.lang.IllegalStateExcep...


• While forwarding from one page to another by using...
• RequestDispatcher class: IllegalStateException ra...
• RequestDispatcher FAQ Topic
• If the output stream was not buffered at the time ...
• Using Tomcat and Xalan, why do I get the exception...

Comments and alternative answers

You should also explore


Author: Phillip Morelock (http://www.jguru.com/guru/viewbio.jsp?EID=523143), Oct
17, 2001
at least on the output end, i use JavaBeans and custom Tags to do most of this work
(like when the author of this answer described making the navbar with one
component, the content with another, etc....).

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

You have no control how the browser decides to print a page.

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.

Comments and alternative answers

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.

Re: FDF Merge


Author: Archana Goud (http://www.jguru.com/guru/viewbio.jsp?EID=544525),
Nov 30, 2001
How To Go About it can u be more detail. i generated a report in jsp. i need to take
printout of it and the adress is been printed on top i want to eliminate it by using
pdf how can i ? can u please help me out thank u

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.

What is the difference between using getSession(true) and


getSession(false) methods?
Location: http://www.jguru.com/faq/view.jsp?EID=502938
Created: Sep 24, 2001 Modified: 2001-09-26 08:27:49.151
Author: sanjay pai (http://www.jguru.com/guru/viewbio.jsp?EID=385708) Question
originally posed by arun vis (http://www.jguru.com/guru/viewbio.jsp?EID=474858

The difference is as follows:

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'.

Do objects stored in a HTTP Session need to be serializable? Or can it store


any object?
Location: http://www.jguru.com/faq/view.jsp?EID=504834
Created: Sep 26, 2001
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Dean Sheppard
(http://www.jguru.com/guru/viewbio.jsp?EID=14227

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.

How can I send a POST request from a Servlet or JSP?


Location: http://www.jguru.com/faq/view.jsp?EID=504839
Created: Sep 26, 2001
Author: Luigi Viggiano (http://www.jguru.com/guru/viewbio.jsp?EID=101985)
Question originally posed by Juergen Havermann
(http://www.jguru.com/guru/viewbio.jsp?EID=482830
There's nothing in the servlet API that let you to use the POST method for submitting
data to any URL; but your servlet can enstablish a URL connection to the php page,
send the parameters you need as HTTP body and print out the response in its body.

See also the following FAQs:

• How can I make a POST request through response.sen...


• How can we send a POST request when we call getReq...
• How do I upload a file using a Java client (not a ...
• How do I call one servlet from another servlet?
• When you communicate with a servlet from an Applet...
• How do I capture a request and dispatch the exact...
• Can I call a CGI script from a servlet?
• How can an applet or application pass data to and ...
• How can my applet communicate with my servlet?

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.*;

public class Source extends HttpServlet {


private static final String CONTENT_TYPE = "text/html";

public void doGet(HttpServletRequest request,


HttpServletResponse response) throws
ServletException,
IOException {
response.setContentType(CONTENT_TYPE);

URL url;
URLConnection urlConn;
DataOutputStream cgiInput;

// URL of target page script.


url = new URL("http://localhost:8086/servlet/Target");
urlConn = url.openConnection();

urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setUseCaches(false);
urlConn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");

// Send POST output.


cgiInput = new DataOutputStream(urlConn.getOutputStream());

String content = "param1=" + URLEncoder.encode("first


parameter")
+ "&param2="
+ URLEncoder.encode("the second one...");

cgiInput.writeBytes(content);
cgiInput.flush();
cgiInput.close();

// reads the CGI response and print it inside the servlet


content
BufferedReader cgiOutput =
new BufferedReader(new
InputStreamReader(urlConn.getInputStream()));
PrintWriter servletOutput = response.getWriter();
servletOutput.print("<html><body><h1>This is the Source
Servlet</h1><p />");
String line = null;
while (null != (line = cgiOutput.readLine())){
servletOutput.println(line);
}
cgiOutput.close();
servletOutput.print("</body></html>");
servletOutput.close();
}
}

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class Target extends HttpServlet {


private static final String CONTENT_TYPE = "text/html";

public void doPost(HttpServletRequest request,


HttpServletResponse response) throws
ServletException,
IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
out.print("<h2>Target's output</h2><p /><pre><code>");

Enumeration enum = request.getParameterNames();


while (enum.hasMoreElements()){
String param = (String) enum.nextElement();
String value = request.getParameter(param);
out.println("param=" + param + " value=" + value);
}
out.print("</code></pre>");
}
}
If the user uploads a file with the same name as a previously uploaded one,
how to overcome the overwriting of the first file?
Location: http://www.jguru.com/faq/view.jsp?EID=504842
Created: Sep 26, 2001
Author: George Koras (http://www.jguru.com/guru/viewbio.jsp?EID=77493)
Question originally posed by krishna kumar
(http://www.jguru.com/guru/viewbio.jsp?EID=473175

[Hi! I am using com.oreilly.servlet.MultipartRequest up = new


com.oreilly.servlet.MultipartRequest(request,"c:/test",10*1024) to upload
a file into server.Can anyone help me in solving the prevention of overwriting of
existing uploaded file? For example if i upload "paint.bmp",then this will be stored as
"paint.bmp" in the server. Again if i upload a different picture under the same file
name "paint.bmp" , the previous one is overwritten by the new one.This shouldnt
happen.If the file "paint.bmp" already exists, some new filename should be
generated for the new uploaded file and saved.can any one pass me source code for
this problem.Thank you in advance... ]

Did you try using the exists() method of the File object? e.g.:

String pathname = "c:/test";


// I guess you meant "c:\\test"!

File f = new File(pathname);


if (f.exists())
{
out.write("File already exists!\n");
}
else
{
MultipartRequest up =
new MultipartRequest
(request, pathname,10*1024);
}
Comments and alternative answers

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.

Re: Download manually:Runs successfully on windows


Author: nidhi tewari (http://www.jguru.com/guru/viewbio.jsp?EID=581714), Dec
13, 2001
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.io.IOException;
import java.io.PrintStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Hashtable;
public class Download extends HttpServlet {
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException {
String strFileName = "";
ServletContext serContext = this.getServletContext();
ServletOutputStream sos = res.getOutputStream();
//UNC Path
String dirName = "\\\\Gladiator\\eFM_API_CommonTestArea\\temp.txt";
String strContentType = getServletContext().getMimeType(dirName);
res.setContentType(strContentType);
File sFile = new File(dirName);
String fileName=sFile.getName();
long lFileLength=sFile.length();
/* Read the file into a byte array */
byte[] FileinBytes = new byte[(int)lFileLength];
FileInputStream fis = new FileInputStream(dirName);
/* Read the bytesarray into file input stream */
long lByteRead = fis.read(FileinBytes,0,(int)lFileLength);
//ServletOutputStream sos = null;
PrintStream ps = null;
String header_info = req.getHeader("USER-AGENT");
if (header_info.indexOf("MSIE") != -1) {
res.setHeader("Content-Disposition","attachment;fileName = " + fileName);
}
else { res.setHeader("Content-Disposition","attachment;fileName=\"" + fileName
+ "\";");
} sos = res.getOutputStream();
ps = new PrintStream(sos);
ps.write(FileinBytes, 0, (int)lFileLength);
ps.flush();
}
}

Re[2]: Download manually:Runs successfully on windows


Author: Juan Carlos Erazo Montoya
(http://www.jguru.com/guru/viewbio.jsp?EID=897670), Jul 30, 2002
Yo can use defaultrenamepolicy(). Something like: mpreq = new
MultipartRequest(request, tempFileDir, 20*1024, new
defaultFileRenamePolicy());

How do I load a properties file from WEB-INF/classes?


Location: http://www.jguru.com/faq/view.jsp?EID=506416
Created: Sep 28, 2001
Author: George McKinney (http://www.jguru.com/guru/viewbio.jsp?EID=21278)
Question originally posed by Craig McDaniel
(http://www.jguru.com/guru/viewbio.jsp?EID=443037

We use a number of properties files, both from the classes directory and from sub
directories without any problem.

For files directly in the classes directory, our code is like:

Properties dbProps = new Properties();

//The forward slash "/" in front of in_filename will ensure that


//no package names are prepended to the filename when the
Classloader
//search for the file in the classpath
InputStream is =
getClass().getResourceAsStream("/"+in_filename);
if(null == is)
{
throw new ConfigException("Can't locate file:"
+in_filename);
}
try
{
dbProps.load(is);//this may throw IOException
return dbProps;
}
catch (IOException ioe)
{
System.err.println("Properties loading failed in
AppConfig");
throw new ConfigException(ioe,"Can't locate file:"
+in_filename);
}
Comments and alternative answers

Can I load a property file even if don't have WEB-INF dir?


Author: Saurabh Bhargava (http://www.jguru.com/guru/viewbio.jsp?EID=526712),
Oct 23, 2001

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

don't forget the "/" before the props filename

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.

How do I write a tunneling HTTP proxy in Java?


Location: http://www.jguru.com/faq/view.jsp?EID=506464
Created: Sep 28, 2001
Author: Martin Erren (http://www.jguru.com/guru/viewbio.jsp?EID=446238)
Question originally posed by Alexandre Torres
(http://www.jguru.com/guru/viewbio.jsp?EID=480684

[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.*;

class ProxyConnection extends Thread {

Socket fromClient;
String host;
int port;
long timeout;

ProxyConnection(Socket s, String host, int port, long timeout) {


fromClient=s;
this.host = host;
this.port = port;
this.timeout=timeout;
}

public void run() {


InputStream clientIn = null;
OutputStream clientOut = null;
InputStream serverIn = null;
OutputStream serverOut = null;
Socket toServer = null;
int r0=-1,r1=-1,ch=-1,i=-1;
long time0 = new Date().getTime();
long time1 = new Date().getTime();
try {
toServer = new Socket(host,port);
Proxy.display("open connection to:"+toServer+"(timeout="+timeout+" ms)");
clientIn = fromClient.getInputStream();
clientOut = new BufferedOutputStream(fromClient.getOutputStream());
serverIn = toServer.getInputStream();
serverOut = new BufferedOutputStream(toServer.getOutputStream());
while(r0!=0 || r1!=0 || (time1-time0)<=timeout) {
while((r0=clientIn.available())>0) {
Proxy.println(""); Proxy.println("<<<"+r0+" bytes from client");
Proxy.display(""); Proxy.display("<<<"+r0+" bytes from client");
for(i=0; i<r0; i++) {
ch = clientIn.read();
if(ch!=-1) {
serverOut.write(ch);
Proxy.print(ch);
} else {
Proxy.display("client stream closed");
}
}
time0=new Date().getTime();
serverOut.flush();
}
while((r1=serverIn.available())>0) {
Proxy.println(""); Proxy.println(">>>"+r1+" bytes from server");
Proxy.display(""); Proxy.display(">>>"+r1+" bytes from server");
for(i=0; i<r1; i++) {
ch = serverIn.read();
if(ch!=-1) {
clientOut.write(ch);
Proxy.print(ch);
} else {
Proxy.display("server stream closed");
}
}
time0=new Date().getTime();
clientOut.flush();
}
if(r0==0 && r1==0) {
time1 = new Date().getTime();
Thread.sleep(100);
//Proxy.display("waiting:"+(time1-time0)+" ms");
}
}
} catch(Throwable t) {
Proxy.display("i="+i+" ch="+ch);
t.printStackTrace(System.err);
} finally {
try {
clientIn.close();
clientOut.close();
serverIn.close();
serverOut.close();
fromClient.close();
toServer.close();
Proxy.quit(time1-time0);
} catch(Exception e) {
e.printStackTrace(System.err);
}
}
}
}

public class Proxy {

public static final String usageArgs =" <localport> <host> <port> <timeout_ms>";

static int clientCount;

public static synchronized void print(int i) {


System.out.print((char) i);
}

public static synchronized void println(String s) {


System.out.println(s);
}

public static synchronized void display(String s) {


System.err.println(s);
}

public static synchronized void quit(long t) {


display("...quit after waiting "+t+" ms");
clientCount--;
}

public void run(int localport, String host, int port,long timeout) {


try {
ServerSocket sSocket = new ServerSocket(localport);
while(true) {
Socket cSocket=null;
try {
display("listening...");
cSocket = sSocket.accept();
if(cSocket!=null) {
clientCount++;
display("accepted as #"+clientCount+":"+cSocket);
ProxyConnection c = new ProxyConnection(cSocket,host,port,timeout);
c.run();
}
} catch(Exception e) {
e.printStackTrace(System.err);
}
try {
cSocket.close();
} catch(Exception e) {
//fall thru
}
}
} catch(Throwable t) {
t.printStackTrace(System.err);
}
}

public static void main(String[] argv) {


Proxy self = new Proxy();

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

Comments and alternative answers

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):

ProxyConnection c = new ProxyConnection(cSocket,host,port,timeout);


c.start(); ///!!!

instead of

ProxyConnection c = new ProxyConnection(cSocket,host,port,timeout);


c.run();

Note that java.net.Socket and java.net.ServerSocket allows setting a timeout


by:

void setSoTimeout(int timeout);

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!

Re: Multiple Clients


Author: Ole Sandum (http://www.jguru.com/guru/viewbio.jsp?EID=1184326), Jul
7, 2004
I believe the client socket is getting close()'d in two different places: 1) as
fromClient.close() near the bottom of ProxyConnection and also 2) as
cSocket.close() in Proxy. The last one, I believe, is a mistake. Once you start
spawning threads, the client sockets will be closed (by the parent thread) before
the worker thread gets any work done. Hope this helps.

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

You need to escape the character with a \, like the following:


out.println("var themessage = \"message: \";");
Comments and alternative answers

Client side JS includes and JSP


Author: Alan Johnson (http://www.jguru.com/guru/viewbio.jsp?EID=241283), Oct 8,
2001
If you have much JS code that you can't include client side with the script tag (<script
scr="filename.js" />) then you should consider JSP as an alternative to using the
escape charater.
How do I retrieve parameters in the exact order in which they appeared on
the HTML form? The method getParameterNames() does not preserve the
order.
Location: http://www.jguru.com/faq/view.jsp?EID=508859
Created: Oct 2, 2001 Modified: 2001-10-02 10:35:07.229
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Roger Hom
(http://www.jguru.com/guru/viewbio.jsp?EID=486599

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

• How do I get the name of the currently executing servlet?


• What is the difference between URL encoding, URL r...

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.

Comments and alternative answers

getting parameter names from query string


Author: Roger Hom (http://www.jguru.com/guru/viewbio.jsp?EID=486599), Oct 2,
2001
Am I still able to use the request.getQueryString() if the form is being sent using the
post method?

Re: getting parameter names from query string


Author: Subrahmanyam Allamaraju
(http://www.jguru.com/guru/viewbio.jsp?EID=265492), Oct 2, 2001

No. You can't do it for extracting parameters from the post request.

Why is it required to depend on the order of parameters?. To make the application


fail-safe, it is better to reconsider the approach and change it to not depend on the
order of parameters.

Re: Re: getting parameter names from query string


Author: Roger Hom (http://www.jguru.com/guru/viewbio.jsp?EID=486599),
Oct 4, 2001
I am writing a generic form handler that needs to process any type of html
form and output the results to an email message or written to a file on a server.
The users would like the data to be in the same order as it was defined in their
form. That is why I need the correct order of the parameters from the form.

Re: Re: Re: getting parameter names from query string


Author: Amos Shapira
(http://www.jguru.com/guru/viewbio.jsp?EID=4346), Oct 6, 2001
Then consider ways like attaching an index to the parameter names, or
some other way to associate order with them (e.g. extra index parameter
which holds the index of each "form" parameter).

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

Here is an example of a formmailer I wrote some time ago that


implements Amos Shapira's suggestion.
http://alan.datdec.com/formmailer.zip

Feel free to use it but don't think there is any warrentee, expressed or
implied, etc. Notice the FMCFormat Parameter.

Here is another example of html calling to the mailer:


http://www.finowen.com/contact.jsp

Re: Re: Re: Re: Re: getting parameter names from query string

Author: Roger Hom


(http://www.jguru.com/guru/viewbio.jsp?EID=486599), Oct 15,
2001
Thanks for the suggestions and code Amos and Alan, ... pretty cool

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

By default, the session object is context-specific. Although a few servlet containers


(Tomcat, Resin) may allow web applications to share session contexts by means of
the "crosscontext" setting within the deployment descriptor, by default, that should
not be allowed for security purposes and must be used cautiously only for admin-
type applications.

[For example:

<Context path="/myapp" docBase="/home/web/myapp'" crossContext="true"


debug="0" reloadable="false" trusted="false" />
-Alex]
Comments and alternative answers

Also
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Oct 25, 2001
This question is also answered at:

• Is there a simple way to share a single Session object across multiple


ServletContexts?
• How can I share data between two different web applications?
• How can I pass data from a servlet running in one context (webapp) to a
servlet running in another context?
• Can two web applications (servlet contexts) share the same session object?

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:

• It looks like "crossContext" allows you to get the ServletContext. According


to the servlet docs, "There is one context per 'web application' per Java Virtual
Machine." This would appear to be a server-wide piece of information, not
tied to the particular browser's session.
• If this does have anything to do with the browser's session, I don't understand
why this should be disabled for "security purposes." What's insecure about
two web applications on my own server, both of which I wrote, accessing the
same user session information?

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.

SESSION ISOLATION is very important, since the person developing WEBAPP-


TWO doesnt necessarily know what variable names WEBAPP-ONE is using.

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

Use JspISAPI for it


Author: Akash Kava (http://www.jguru.com/guru/viewbio.jsp?EID=1135160), Jan 2,
2004
Well the solution is here...

http://jspisapi.neurospeech.com , we had similar problem and trying to find solution


but too complex method of tomcat's documentation lead us to develop our own
solution called JspISAPI. The details of installation is given in the website.

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

How to return a value from a servlet to a JSP?


Location: http://www.jguru.com/faq/view.jsp?EID=524336
Created: Oct 18, 2001
Author: Shahram Khorsand (http://www.jguru.com/guru/viewbio.jsp?EID=3357)
Question originally posed by hassan hassan
(http://www.jguru.com/guru/viewbio.jsp?EID=519522

There are couple of ways to do this.

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

How to return a value from a servlet to a JSP?


Author: Lee Jeffrey (http://www.jguru.com/guru/viewbio.jsp?EID=563988), Nov 27,
2001
Hi, I tried the methods you wrote but I am always returned with the following error:
1. ......: Cannot resolve symbol
symbol :method getServletContext()
location: class.mips.Report.Ui.ReportAction
RequestDispatcher rd = getServletContext().getRequestDispatcher("/test1.jsp")

Re: How to return a value from a servlet to a JSP?


Author: Sergi Pérez (http://www.jguru.com/guru/viewbio.jsp?EID=724738), Jan
20, 2002
You must use the JSDK2.1 or higher. If you must use the 2.0 try to use the
method:
resp.sendRedirect("page.jsp");

When using URLConnection to upload an object from applet to servlet, the


servlet's doGet method is never executed. Why?
Location: http://www.jguru.com/faq/view.jsp?EID=524345
Created: Oct 18, 2001
Author: Ana Narvaez (http://www.jguru.com/guru/viewbio.jsp?EID=231092)
Question originally posed by leo lee
(http://www.jguru.com/guru/viewbio.jsp?EID=477092
URL url=new URL("http://localhost:8080/servlet/ServerServlet?Action=3");
URLConnection servletConnection=url.openConnection();
servletConnection.setDoInput(true);
servletConnection.setDoOutput(true);
servletConnection.setUseCaches (false);
servletConnection.setDefaultUseCaches (false);
servletConnection.setRequestProperty ("Content-Type", "application/octet-stream");
ObjectOutputStream outputToServlet = new
ObjectOutputStream(servletConnection.getOutputStream());
outputToServlet.writeObject("asdfa");
outputToServlet.flush();
outputToServlet.close();
I had the same problem and I resolved it reading the response from the servlet. You
can do:
.....

outputToServlet.writeObject("asdfa");

outputToServlet.flush();

outputToServlet.close();

//and now read from the servlet

int code = servletConnection.getResponseCode();

//or you can read the header.

String header = servletConnection.getHeaderField(0);

//or you can obtain de inputstream

InputStream in = servletConnection.getInputStream();

I Hope this helps you


Comments and alternative answers

Don't reinvent the wheel.


Author: Christopher Bowland
(http://www.jguru.com/guru/viewbio.jsp?EID=217833), Oct 18, 2001
You might want to take a look at the work that Jason Hunter did at
http://www.servlets.com/cos/index.html. The HttpMessage class provides exactly
what you are seeking and I know from personal experience that servlets handling its
request will process the doGet() or doPost() as appropriate.
When using URLConnection to upload an object from first servlet to second
servlet, the doGet method of second Servlet is never executed. Why
Author: Rajagopalan Subramanian
(http://www.jguru.com/guru/viewbio.jsp?EID=989686), Aug 29, 2002
We have implemented the same code u have specified. But the actual scenario is
Reading an object ( may be a plain document , XML Document...) in First Servlet
which is in First Webserver and pass it to Second servlet which is in Second
WebServer. And how this object is to be accepted in Second servlet ( may be in doGet
method) and display it in its original format. We are getting the same problem of
doget() of the second servlet not getting executed. And what should be the coding for
reading the passed object from first servlet.

After HttpSession.invalidate() is called I expect the next getSession call


should return a new session with a different session id. However, it returns
the same sessionid ???
Location: http://www.jguru.com/faq/view.jsp?EID=524347
Created: Oct 18, 2001
Author: Luigi Viggiano (http://www.jguru.com/guru/viewbio.jsp?EID=101985)
Question originally posed by Prabodh Navare
(http://www.jguru.com/guru/viewbio.jsp?EID=440669

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.

Comments and alternative answers

serving static pdf files with tomcat


Author: Hartmut Bernecker (http://www.jguru.com/guru/viewbio.jsp?EID=424953),
Apr 10, 2002
I have the same problem when sending a PDF that I don't generate.
If I do the same with IIS 5 the PDF is actually displayed. When having a look to the
HTTP headers You will see that:
HTTP/1.1 200 OK
Server: Microsoft-IIS/5.0
Connection: close
Date: Wed, 10 Apr 2002 20:20:57 GMT
Content-Type: application/pdf
Accept-Ranges: bytes
Last-Modified: Tue, 05 Sep 2000 10:51:39 GMT
ETag: "802fb1442717c01:d91"
Content-Length: 91853

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.

Below is my 'playSound' class.

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;

static private final Log logSound = new Log ("logSound");

AudioClip onceClip, loopClip;


URL codeBase;

boolean looping = false;

public playSound() {
startLoadingSounds();
}

void startLoadingSounds() {
//Start asynchronous sound loading.
try {
codeBase = new URL("file:\\mifc\\res\\") ;

} catch (MalformedURLException e) {
logSound.out(e.getMessage());
}

soundList = new SoundList(codeBase);


soundList.startLoading(login);
soundList.startLoading(ready);
soundList.startLoading(unknown);

}
public void stop() {
onceClip.stop(); //Cut short the one-time sound.
if (looping) {
loopClip.stop(); //Stop the sound loop.
}
}

public void start() {


if (looping) {
loopClip.loop(); //Restart the sound loop.
}
}

public void play( String what) {

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;

else if( what.equalsIgnoreCase("ready") )


{
onceClip = soundList.getClip("systemReady.wav");

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;

class SoundList extends java.util.Hashtable {


JApplet applet;
URL baseURL, completeURL;

public SoundList(URL baseURL) {


super(5); //Initialize Hashtable with capacity of 5 entries.
logSound.out( "baseURL*******"+baseURL);

this.baseURL = baseURL;
}

public void startLoading(String relativeURL) {

/* uncomment this only if soundLoader class doesn't work...


try {
completeURL = new URL(baseURL, relativeURL);
logSound.out( "completeURL*******"+completeURL);
} catch (MalformedURLException e){
logSound.out("SoundLoader:"+e.getMessage());
}

AudioClip audioClip = Applet.newAudioClip(completeURL);


soundList.putClip(audioClip, relativeURL);
**/

new SoundLoader(this, baseURL, relativeURL);


}

public AudioClip getClip(String relativeURL) {


logSound.out( "relativeURL*******"+relativeURL);

return (AudioClip)get(relativeURL);
}

public void putClip(AudioClip clip, String relativeURL) {


put(relativeURL, clip);
}
}

//This guy doesn't work if my servlet does NOT implement


interface 'SingleThreadModel'
class SoundLoader extends Thread {
SoundList soundList;
URL completeURL;
String relativeURL;
public SoundLoader(SoundList soundList,URL baseURL, String
relativeURL)
{
this.soundList = soundList;
try {
completeURL = new URL(baseURL, relativeURL);
} catch (MalformedURLException e){
}
this.relativeURL = relativeURL;
setPriority(MIN_PRIORITY);
this.start();
}
public void run() {
AudioClip audioClip = Applet.newAudioClip(completeURL);
soundList.putClip(audioClip, relativeURL);
}

How can I call a servlet from a regular Java application?


Location: http://www.jguru.com/faq/view.jsp?EID=524479
Created: Oct 18, 2001
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Annar Innad
(http://www.jguru.com/guru/viewbio.jsp?EID=522486

See How can my applet communicate with my servlet?


Comments and alternative answers

Applet Servlet communication


Author: Stuart Woodward (http://www.jguru.com/guru/viewbio.jsp?EID=129604),
Oct 21, 2001
You could subclass your servlet from HttpServlet and POST to it. You might also
want to look at an RPC protocol like SOAP before reinventing the wheel.
Alternatively, you could also develop your own Socket based protocol to
communicate with the servlet.

Can we capture clickstreams using servlets?


Location: http://www.jguru.com/faq/view.jsp?EID=524483
Created: Oct 18, 2001
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Raj Kumar
(http://www.jguru.com/guru/viewbio.jsp?EID=454402

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/

How do I set session timeouts of greater than 30 minutes?


Location: http://www.jguru.com/faq/view.jsp?EID=525564
Created: Oct 19, 2001
Author: Janko Harej (http://www.jguru.com/guru/viewbio.jsp?EID=280966)
Question originally posed by Joji Daniel
(http://www.jguru.com/guru/viewbio.jsp?EID=503188

Tomcat session keeps expiring in spite of entries in web.xml to the effect of


<session-config>
<session-timeout>60</session-timeout> <!-- 30 minutes -->
</session-config>
(where the number indicates the time in minutes)

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:

I've included this in my JSP page:

session.setMaxInactiveInterval(600);

Comments and alternative answers

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.

Re: session timeouts


Author: fresh guy (http://www.jguru.com/guru/viewbio.jsp?EID=1032778), May
9, 2003

hai friends,

Iam working on email system for which

iam using

1. tomcat4.0.4

2. Javamail api

3. servlets

I need the sessiontimeout for 4 hours.

I already set in my servlets as

session.setMaxInactiveInterval(14400);

as well as in web.xml file as

<session-config>

<session-timeout>240</session-timeout>

</session-config>

Eventhough i set in both ways my session is

expiring after 30 mins(the default sessiontimeout for tomcat)


Please, let me know how i could achieve

4 hours for my sessiontimeout.

I'll will be thankful to them who responds me

quickly as this is too urgent.

thanks.

How can I modify a Request object before passing it to another servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=528234
Created: Oct 23, 2001
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Patrick Timmins
(http://www.jguru.com/guru/viewbio.jsp?EID=427817

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!

You can do something like this in Servlets 2.3 by subclassing HttpRequestWrapper.


See the Servlet 2.3 spec for more details.
Comments and alternative answers

Modifying http parameters in request.


Author: Roger Hand (http://www.jguru.com/guru/viewbio.jsp?EID=292314), Oct 24,
2001
This may not fit exactly into what you're trying to do, but thought it might help . . .
If manipulating http headers and parameters at the http stream level would work for
you, then see my comment Here's a servlet wrapper that makes it easy in the topic
Can I call a CGI script from a servlet?.

What is a session? What is the difference between session and cookie?


Location: http://www.jguru.com/faq/view.jsp?EID=528741
Created: Oct 24, 2001
Author: Bozidar Dangubic (http://www.jguru.com/guru/viewbio.jsp?EID=433955)
Question originally posed by sabu vs PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=476248

[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.

the difference between session and a cookie is two-fold.


1) session should work regardless of the settings on the client browser. even if users
decide to forbid the cookie (through browser settings) session still works. there is no
way to disable sessions from the client browser.
2) session and cookies differ in type and amount of information they are capable of
storing. javax.servlet.http.Cookie class has a setValue() method that accepts Strings.
javax.servlet.http.HttpSession has a setAttribute() method which takes a String to
denote the name and java.lang.Object which means that HttpSession is capable of
storing any java object. Cookie can only store String objects.

Comments and alternative answers

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?

Do I have to synchronize read-only access to a text file?


Location: http://www.jguru.com/faq/view.jsp?EID=531243
Created: Oct 26, 2001 Modified: 2001-10-27 08:18:32.688
Author: Bozidar Dangubic (http://www.jguru.com/guru/viewbio.jsp?EID=433955)
Question originally posed by Tony Fagan
(http://www.jguru.com/guru/viewbio.jsp?EID=226421

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

Do I have to synchronize read-only access to a text file?


Author: Serge Borodai (http://www.jguru.com/guru/viewbio.jsp?EID=1135393), Dec
22, 2003
So, I have to synchronize read-only access to a text file?

Can I place my classes somewhere other than inside WEB-INF?


Location: http://www.jguru.com/faq/view.jsp?EID=536258
Created: Nov 1, 2001 Modified: 2002-04-19 05:36:14.822
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by S
R (http://www.jguru.com/guru/viewbio.jsp?EID=530361

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]

Comments and alternative answers

Classes outside WEB-INF\classes


Author: Subrahmanyam Allamaraju
(http://www.jguru.com/guru/viewbio.jsp?EID=265492), Nov 1, 2001

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.

Re: Classes outside WEB-INF\classes


Author: Maheedhar Pullakhandam
(http://www.jguru.com/guru/viewbio.jsp?EID=544002), Nov 9, 2001
There is certain overhead in keeping the classes in WEB-INF\Classes. Container
verifies any change made to the concerned class file, before passing every request
to a servlet, which may amount to certain lag in response time.

If the efficiency is so concerned, classes should be added to WEB-INF\Classes


during development and to CLASSPATH while shipping the product.

Re: Re: Classes outside WEB-INF\classes


Author: Subrahmanyam Allamaraju
(http://www.jguru.com/guru/viewbio.jsp?EID=265492), Nov 10, 2001

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

classes outside WEB-INF


Author: Martin Ober (http://www.jguru.com/guru/viewbio.jsp?EID=120947), Mar 26,
2002
I have an application that runs standalone and on multiple webapps with separate
databases.
I also have different versions of the application running on my server, so the setting of
the CLASSPATH doesn't work at all.

Using WebappClassLoader.addRepository() could be a solution ???

Another very simple way:


write a little class that copies the jars and resources from a specified source to your
WEB-INF directory and call it on initializing your context.
NOT FINE BUT WORKS ;-)

Use a Manfifest for the jars with Version-Infos.

bye

Re: classes outside WEB-INF


Author: Todd Stark (http://www.jguru.com/guru/viewbio.jsp?EID=1056632), Feb
14, 2003
Hi, I am trying to reference jar files and classes outside the WEB-INF. I would
like to add my CLASSPATH so that when the JSP page is compiled the necessary
jars are available. Do you have some sample code and steps of how to use
WebappClassLoader.addRepository() or have you found a better way of doing
this? Thanks

CLASSPATH and Tomcat 3.3.1


Author: simmo uk (http://www.jguru.com/guru/viewbio.jsp?EID=845358), Apr 19,
2002
There is a particular problem when for example you are using ZIP files, or when the
CLASSPATH is used to store other resources (eg. properties files) not loaded by the
class loaders. I can't seem to get system properties
org.apache.tomcat.apps.classpath or org.apache.tomcat.common.classpath
to work either...

Is it a good idea to declare your connection object globally, open the


connection in init and close it on destroy? Or is it better to just open and
close it all in a doGet or doPost each time a thread request the servlet?
Location: http://www.jguru.com/faq/view.jsp?EID=538678
Created: Nov 4, 2001
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by brett haas
(http://www.jguru.com/guru/viewbio.jsp?EID=538610

Globally. Definitely. It can take upwards of 10 seconds or even several minutes to


open a DB connection (depending on your sever and drivers).

See How do I access a database from my servlet or JSP?... and the topic
Servlets:Databases

Comments and alternative answers

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

Here is the correct approach:

• Get the connection when required and close it immediately after use. Do this
within the doXXX() methods.
• Configure your J2EE container for connection pooling.

Why? Here are the reasons.

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.

Re: Connection handling


Author: brett haas (http://www.jguru.com/guru/viewbio.jsp?EID=538610), Nov 6,
2001
I ran 4 separate test today, using two different schools of thought on using a
connection object. I created two servlets, and created 25 near simultaneous threads
to each servlet. Each servlet made a call to a database to display 198 records using
the stored procedure which is at the very bottom of this message.
The first one was declaring the connection object inside of a doGet() method and
closing it before the end of the method. The avg load of each page was: 13519 ms
(local connection)

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.

CREATE Procedure sp_GetAllArticles

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

Re: Re: Connection handling


Author: Subrahmanyam Allamaraju
(http://www.jguru.com/guru/viewbio.jsp?EID=265492), Nov 6, 2001

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:

• T1 does D1 (the transaction begins here).


• T1 does D2.
• T2 does D1.
• T2 roles back
• T2 ends
• T1 does D3
• T1 ends.

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.

For performance sake, you SHOULD consider pooling. It is unrealistic to test


without pooling.

Re: Re: Re: Connection handling


Author: brett haas (http://www.jguru.com/guru/viewbio.jsp?EID=538610),
Nov 7, 2001
I DEFINITELY believe you. You should also use a form of connection
pooling. I was just giving some information on a simple test I performed,
which only had one database interaction.

I have a quick question for you, which is not directly related to this topic.

I am displaying results from a database, one of the fields is a "Text"; field


which contains content that was written in Microsoft word. When it is
displayed to the clients browser any ‘ or “ is converted into a question
mark. I know Java uses Unicode(utf-16), is there a what to change the code
to different set just for this servlet? Of course there is always the brute
force way, and do a char replacement on that content, but that is not such
an elegant solution. Thanks in advance for your help.

Alternative - Connection Pool in Tomcat


Author: Norman Hanson (http://www.jguru.com/guru/viewbio.jsp?EID=462048), Dec 7, 2001
Not every has or wants a J2EE Server. You may want to consider using a connection pool created on
startup, then just grabbing a connection from the pool in your jsps.
I found a nice simple pool package from ww.bitmechanic.com then wrote a servlet with just an init
method, load-on-startup in the web.xml and viola, connection pooling with tomcat.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import com.bitmechanic.sql.*;
import java.sql.*;

public class StartupConnectionPoolServlet extends HttpServlet {

private static String ALIAS = "alias";


private static String URL = "jdbc.url";
private static String DRIVER = "jdbc.driver";
private static String USERNAME = "jdbc.username";
private static String PASSWORD = "jdbc.password";
private static String MAXCONN = "jdbc.max.connections";
private static String IDLE = "jdbc.idle.timeout";
private static String CHECKOUT = "jdbc.checkout.timeout";
private static String DEBUG = "debug";

private String dbAlias;


private String dbDriver;
private String dbUrl;
private String dbUsername;
private String dbPassword;
private int dbMaxConnections;
private int dbIdleTimeout;
private int dbCheckoutTimeout;
private boolean debug = true;

public void init()


throws ServletException
{
try
{
ConnectionPoolManager poolMgr = null;
// see if the application already has a connection pool
manager attached to it
if
( getServletContext().getAttribute("connectionPoolManager") != null)
{
poolMgr =
(ConnectionPoolManager)(getServletContext().getAttribute("connectionPoolManager"));
}
else
{
poolMgr = new ConnectionPoolManager(120);
}

ConnectionPool pool= null;


if (getConnectionInfo() )
{
//DriverManager.registerDriver((Driver)(Class.forNa
me(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);
}
getServletContext().setAttribute( "connectionPoolManager",
poolMgr );
if (debug) System.out.println("****** end
StartupConnectionPoolServlet - debug true ******");
}
catch (Exception e)
{
e.printStackTrace();
throw new ServletException(e);
}

}
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

Re: Alternative - Connection Pool in Tomcat


Author: Joost Schouten (http://www.jguru.com/guru/viewbio.jsp?EID=581960),
Feb 1, 2002
Hi, I'm not sure if this thread is still alive, but I'll give it a try anyway.

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

Re[2]: Alternative - Connection Pool in Tomcat


Author: Norman Hanson
(http://www.jguru.com/guru/viewbio.jsp?EID=462048), Feb 1, 2002
they are not. the if debug is a oneliner, look closely, no {}. --norm

Re[3]: Alternative - Connection Pool in Tomcat


Author: Joost Schouten
(http://www.jguru.com/guru/viewbio.jsp?EID=581960), Feb 1, 2002
Oops! sorry for bugging you. But now I relize that the problem lies
somewhere else. Thanks for your reply,

Joost

Re: Alternative - Connection Pool in Tomcat


Author: Joost Schouten (http://www.jguru.com/guru/viewbio.jsp?EID=581960), Feb 2, 2002
Hi, I think I'm really close to making my pool work. However. From my dbConnect Bean I call the fo
method:
pool =
(ConnectionPool)StartupConnectionPoolServlet.getServletContext().getAttribute("rbd

And during compilation I'm presented with the following error:

non-static method getServletContext() cannot be referenced from a static context

If I only knew what it meant? What am I doing wrong?

Thanks,
Joost

Re[2]: Alternative - Connection Pool in Tomcat


Author: Norman Hanson (http://www.jguru.com/guru/viewbio.jsp?EID=462048),
Feb 3, 2002
you are really making this harder than it ought be. the servlet code i posted will
compile.
then as a stated before simply define the db pool paramaters in the web.xml for a
<servlet> hmmm, maybe like this.
<servlet>
<!-- for each connection pool you want copy this servlet
change the servlet-name, alias, and increment the load-on-
startup for su
re -->
<servlet-name>startConnectionPoolForMyDb</servlet-name>
<servlet-
class>com.path.to.my.servlet.StartupConnectionPoolServlet</servlet-
class>
<init-param>
<param-name>debug</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>alias</param-name>
<param-value>mydbpool</param-value>
</init-param>
<init-param>
<param-name>jdbc.driver</param-name>
<param-
value>com.sybase.jdbc2.jdbc.SybDriver</param-value>
</init-param>
<init-param>
<param-name>jdbc.url</param-name>
<param-
value>jdbc:sybase:Tds:myhost:myport/mydatabase</param-value>
</init-param>
<init-param>
<param-name>jdbc.username</param-name>
<param-value>myusername</param-value>
</init-param>
<init-param>
<param-name>jdbc.password</param-name>
<param-value>mypassword</param-value>
</init-param>
<init-param>
<param-name>jdbc.max.connections</param-name>
<param-value>10</param-value>
</init-param>
<init-param>
<param-name>jdbc.idle.timeout</param-name>
<param-value>120</param-value>
</init-param>
<init-param>
<param-name>jdbc.checkout.timeout</param-name>
<param-value>120</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

Re[3]: Alternative - Connection Pool in Tomcat


Author: Norman Hanson (http://www.jguru.com/guru/viewbio.jsp?EID=462048), Feb 3,
2002
then to get a connection from the pool...
<%@ page import="com.bitmechanic.sql.*, java.sql.*,java.util.*" %>
<%
ConnectionPool pool=
(ConnectionPool)getServletContext().getAttribute("whatevermyalaiswas");
Connection conn = pool.getConnection();
/* use your connection for this or that
then for completness... */
/* return the connection to the pool */
pool.returnConnection((PooledConnection)conn);
%>

why create a new bean? you can put any Object in the servlet context.

Re[4]: Alternative - Connection Pool in Tomcat


Author: Joost Schouten
(http://www.jguru.com/guru/viewbio.jsp?EID=581960), Feb 4, 2002
Thanks for your help. By looking at your code I found out that I should
ommit the servletname when using the getServletContext() method. It's
all working fine now.

I'm using this one bean to communicate with my database. Just so I


keep my JSP pages clean.

Cheers,
Joost

Re[5]: Alternative - Connection Pool in Tomcat


Author: MAHABOOB PASHA
(http://www.jguru.com/guru/viewbio.jsp?EID=740395), Jun 3, 2002
Hi Joost Schouten, I am also using the JSP page and bean id "cargo"
is using for the Database connection(This is Corba Connection not
JDBC). Please could you advise me how can go about this. I am
also using the Tomcat4.0.1 with apache server. Please could you
send me the sample changes in Tomcat/Servlet/JSP. My email id is
rubypasha2002@yahoo.com. Thanks again. <jsp:useBean
id="cargo" class="Track.TrackTransaction" scope="session" />
Regards, Mahaboob Pasha

Re[6]: Alternative - Connection Pool in Tomcat


Author: Joost Schouten
(http://www.jguru.com/guru/viewbio.jsp?EID=581960), Jun 4,
2002
Hi,

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.

Re[3]: Alternative - Connection Pool in Tomcat


Author: ad joyce (http://www.jguru.com/guru/viewbio.jsp?EID=921197),
Jul 22, 2002
I have placed the parameters into web.xml but when i try to make a
connection it cannot find the class so i wondering where should
project.StartupConnectionPoolServlet be located <servlet-
Class>project.StartupConnectionPoolServlet</servlet-class> any help
would be appreciated

Re[4]: Alternative - Connection Pool in Tomcat


Author: Norman Hanson
(http://www.jguru.com/guru/viewbio.jsp?EID=462048), Jul 22, 2002
if you don't know where to put servlets you need to back up and start
with a simpler example, but i'll answer anyway. given...
<servlet-class> com.mypackage.servlet.BlahServlet </servlet-class>
your class (.class file) should be compiled into
mywebapp/WEB-
INF/classes/com/mypackage/servlet/BlahServlet.class
if its jarred up the the jar file should be in WEB-INF/lib
--norm

Re: Alternative - Connection Pool in Tomcat


Author: MAHABOOB PASHA
(http://www.jguru.com/guru/viewbio.jsp?EID=740395), May 31, 2002
Hi Norman Hanson, Thanks for your ver good information for connection pooling
in tomcat. I am using a JSP with bean name like <jsp:useBean id="cargo"
scope="session" class="Track.Tracking" /> The bean cargo will take care all the
connection using the corba object conection. In this case how can I implement
your code in my application. How can I define Alise,URL, DRIVER, USER
NAME, PASSWORD, MAX CONNECTION, IDLE, CHECK OUT, DEBUG.
Please advise me. Everybody suggesting to go for J2EE BUT I need to do it only
in tomcat. Thanks again. Regards, Mahaboob Pasha

Re[2]: Alternative - Connection Pool in Tomcat


Author: Norman Hanson
(http://www.jguru.com/guru/viewbio.jsp?EID=462048), Jun 1, 2002
look up in the thread to my posting on
Norman Hanson, Feb 3, 2002
the params are defined in the web.xml. hope this helps
--norm
« previous beginning next »

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.

How to get the values of the variables in a different session?


Location: http://www.jguru.com/faq/view.jsp?EID=559280
Created: Nov 23, 2001
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by rakesh sa (http://www.jguru.com/guru/viewbio.jsp?EID=545976

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?

Is access to ServletContext and Session attributes thread safe?


Location: http://www.jguru.com/faq/view.jsp?EID=567276
Created: Nov 29, 2001
Author: Ryan Breidenbach (http://www.jguru.com/guru/viewbio.jsp?EID=45212)
Question originally posed by Tal Golan
(http://www.jguru.com/guru/viewbio.jsp?EID=512887

For example, is the following code thread safe?

public void setServletAttr( String theAttr, String theValue ) {


getServletContext().setAttribute( theAttr, theValue );
}

public void setSessionAttr( HttpServletRequest request, String theAttr, String


theValue ) {
request.getSession().setAttribute( theAttr, theValue );
}

Thanks. This has been killing me!

----------------------------------------

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.

BTW, it appears that both of these implementation in Tomcat 3.2.2 have no


sychronization.

Hope this helps.

Comments and alternative answers

Is access to ServletContext and Session attributes thread safe?


Author: Mark Kauffman (http://www.jguru.com/guru/viewbio.jsp?EID=1007647),
Oct 3, 2002
So how is it typically implemented? I want to use the ServletContext for caching data
I get from a backend DB. This means the named object (a data bean) will change
during run-time and the code reading the data bean should not be interrupted by some
code setting the data bean.

How can administrator invalidate sessions other than his own?


Location: http://www.jguru.com/faq/view.jsp?EID=567278
Created: Nov 29, 2001
Author: Kevin Schaaf (http://www.jguru.com/guru/viewbio.jsp?EID=466729)
Question originally posed by Betsy Zelinger
(http://www.jguru.com/guru/viewbio.jsp?EID=432122

I know that HttpSessionContext is deprecated with no replacement, but is there a


work-around if an administrator wants to be able to delete sessions? I can get him a
list of the sessions open, but can't find a way to invalidate them... cannot find any
way to get a handle on a session other than the getSession method of HttpRequest,
which of couse will be the administrator's own... is this just impossible now?

--------------------------------

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.

Starting service Tomcat-Standalone


Apache Tomcat/4.0.1
Starting service Tomcat-Apache
Apache Tomcat/4.0.1
java.lang.NoSuchMethodError
at
org.apache.catalina.connector.ResponseStream.flush(ResponseStream.java:
244)
at java.io.OutputStreamWriter.flush(OutputStreamWriter.java:245)
at java.io.PrintWriter.flush(PrintWriter.java:120)
at
org.apache.catalina.connector.ResponseWriter.flush(ResponseWriter.java:
125)
at
org.apache.catalina.connector.ResponseBase.finishResponse(ResponseBase.
java:481)
at
org.apache.catalina.connector.HttpResponseBase.finishResponse(HttpRespo
nseBase.java:229)
at
org.apache.catalina.connector.http.HttpResponseImpl.finishResponse(Http
ResponseImpl.java:288)
at
org.apache.catalina.connector.http.HttpProcessor.process(HttpProcessor.
java:1038)
at
org.apache.catalina.connector.http.HttpProcessor.run(HttpProcessor.java
:1106)
at java.lang.Thread.run(Thread.java:484)

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!).

Comments and alternative answers

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

Re: How to prevent display in the url.


Author: Rommel Sharma (http://www.jguru.com/guru/viewbio.jsp?EID=234085),
Dec 22, 2001
One easy solution is use HttpSession object to maintain the values in a session. Do
not use the GET method. Use POST. The advantage of taking the values in a
session is that you dont have to set and unset the values each time while going
from one page to another. All values stored in the session will persist for the entire
browsing session.

To create the session:


HttpSession session = request.getSession(true);
session.putValue("PASWD", password);

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");

For other things ...


Author: Gary Bisaga (http://www.jguru.com/guru/viewbio.jsp?EID=757704), Feb 13,
2002
For things other than passwords, it may not be practical to use HTTP POST fields.
For example, some piece of page display state that is not a field on the form.

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

1. Create a folder with any name of ur choice (say MyAssignment).

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).

5. Place the web.xml and weblogic.xml files in the WEB-INF folder.

6. Edit web.xml to read as:


<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web
Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
<display-name>My Web Assignment</display-name>
<servlet>
<servlet-name>CounterServlet</servlet-name>
<servlet-class>CounterServlet</servlet-class>
</servlet>

<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.

8. Deploy the web-app (see docs).

9. You can now access the servlet as:


http://127.0.0.1:7001/MyAssignment/CounterServlet"

[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

Deploying a simple servlet in weblogic 7.0


Author: puneet jain (http://www.jguru.com/guru/viewbio.jsp?EID=1088585), May 27, 2003
hi i have followed the directory structure and put my application named "WebApp" in the application dire
domain . i am accessing succes.. the static files that is html but i am not able to access the srvlet inside the
directory. every time i access it it thros the following error stating that the classes not founnd in the classp
classes is the server talking about thouhg i havesset the classpath ?? THE ERROR IT THROWS IS THIS
********************************* <May 28, 2003 12:09:54 PM IST> <Error> <HTTP> <101250>
<[ServletContext(id=1642082,name=WebApp,context-path=)]: Servlet class myclasses.Gservlet for servl
not be loaded because a class on which it depends was not found in t he classpath
D:\bea\user_projects\Applicationdomain\applications\WebApp;D:\bea\user_projects\Applicationdomain\a
ons\WebApp\WEB-INF\classes. java.lang.NoClassDefFoundError: myclasses/Gservlet (wrong name: Gs
28, 2003 12:09:54 PM IST> <Error> <HTTP> <101018> <[ServletContext(id=1642082,name=WebApp,
Servlet f ailed with ServletException javax.servlet.ServletException:
[ServletContext(id=1642082,name=WebApp,context-path=)]: Servlet class myclasses.Gservlet for servlet
not be loaded because a class on which it depends was not found in the classpath D:\bea\user
_projects\Applicationdomain\applications\WebApp;D:\bea\user_projects\Applicationdomain\applications
INF\class es. java.lang.NoClassDefFoundError: myclasses/Gservlet (wrong name: Gservlet) at
weblogic.servlet.internal.ServletStubImpl.prepareServlet(ServletStubImpl.java:791) at
weblogic.servlet.internal.ServletStubImpl.getServlet(ServletStubImpl.java:517) at
weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:351) at
weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:306) at
weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.ja
weblogic.security.service.SecurityServiceManager.runAs(SecurityServiceManager.java:744) at
weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppServletContext.java:3086) at
weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestImpl.java:2544) at
weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:153) at
weblogic.kernel.ExecuteThread.run(ExecuteThread.java:134) > ****************** please help me pu
In some web.xml I find DOCTYPE reference of "web-app_2_2.dtd",(in
Weblogic 5.1 example) in others, of "web-app_2.2.dtd" (in java pet store).
What is the difference between the two DTDs?
Location: http://www.jguru.com/faq/view.jsp?EID=586710
Created: Dec 17, 2001
Author: Luigi Viggiano (http://www.jguru.com/guru/viewbio.jsp?EID=101985)
Question originally posed by vikrant jain
(http://www.jguru.com/guru/viewbio.jsp?EID=502452

I believe that web-app_2.2.dtd is misspelled and you can verify it at this page:
J2EETM — DTDs.

Both are aivable at Sun' site:

• 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.

HttpUtils.parseQueryString is deprecated. What should we use instead ?


Location: http://www.jguru.com/faq/view.jsp?EID=587251
Created: Dec 17, 2001
Author: Bozidar Dangubic (http://www.jguru.com/guru/viewbio.jsp?EID=433955)
Question originally posed by sam pitroda
(http://www.jguru.com/guru/viewbio.jsp?EID=476938

Use getParameterMap() in HttpServletRequest.


Comments and alternative answers

seems wrong
Author: shan fu (http://www.jguru.com/guru/viewbio.jsp?EID=241378), Apr 9, 2002
show refer to HttpServletRequestWrapper

Re: seems wrong


Author: Garp Garp (http://www.jguru.com/guru/viewbio.jsp?EID=1071362), Apr
12, 2003
This does not handle case where request has nothing to do with string being
parsed. What should we do in these cases?

How do i find out whether a request to a particular servlet is coming from


another servlet or, if it is coming from a user request?
Location: http://www.jguru.com/faq/view.jsp?EID=594117
Created: Dec 22, 2001
Author: Christopher Schultz (http://www.jguru.com/guru/viewbio.jsp?EID=138382)
Question originally posed by jayashree viswanathan
(http://www.jguru.com/guru/viewbio.jsp?EID=589873
[While it is tempting to use request.getRemoteHost, this will not work.] The
getRemoteHost should always return a foreign IP address. The only reason you might
get the local host as your IP from getRemoteHost is if your servlet actually made an
HTTP request to another servlet.

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.

// in first servlet doGet...


HttpSession session = request.getSession();
session.setAttribute(dataBeanId, dataBean );
...
RequestDispatcher rd = request.getRequestDispatcher("servlet2uri");
rd.forward(request, response);

// in the second servlet doGet...


HttpSession session = request.getSession();
dataBean = (DataBean)session.getAttribute( dataBeanId );

Is it better to have lots of methods to my servlet, or to keep the code inside


the doGet or doPost method?
Location: http://www.jguru.com/faq/view.jsp?EID=594560
Created: Dec 23, 2001
Author: Ryan Breidenbach (http://www.jguru.com/guru/viewbio.jsp?EID=45212)
Question originally posed by Stephen Ward
(http://www.jguru.com/guru/viewbio.jsp?EID=560878

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:

• Your application is very extensible. To add another piece of functionality,


you simply create a class to encapsulates this fucntionality - your servlet code
remains unchanged.
• Single point of entry to your site. Since all requests go throught the same
servlet, you have one place for error-handling, logging, etc.
• Decouples application code from web interface. Since classes
independant of your servlet our handling the processing, they can be reused
by other non-web components.

For more on this pattern and other J2EE patterns, go to Sun's J2EE Patterns Catalog.

Hope this helps.

[Make sure to also read the forum thread where this question was posed for more
advice. -Alex]

Comments and alternative answers

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

Re: Is it better to have lots of methods to my servlet, or to keep the code


inside the doGet or doPost method?
Author: Sushil Srivastava (http://www.jguru.com/guru/viewbio.jsp?EID=744298),
Feb 21, 2002
I would recommend logically splitting your servlet class into methods rather than
putting everyting within one method. Putting everyting in one method smells of
structural programming.For e.g not much point in adding database related
connection into doPost.

How do I set a System Property and access it from a Servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=594561
Created: Dec 23, 2001
Author: Dane Foster (http://www.jguru.com/guru/viewbio.jsp?EID=224441)
Question originally posed by Muhammad Asif
(http://www.jguru.com/guru/viewbio.jsp?EID=301509

I am using JAXP for parsing xml documents.


With JAXP we specify the parser to use in system property named
"javax.xml.parsers.SAXParserFactory". The related function createXMLReader()
automatically takes this value from system.

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]

Comments and alternative answers

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:

1) It uses the value of the system property (e.g.


javax.xml.parsers.SAXParserFactory)
2) It looks in the JRE/lib/jaxp.properties file
3) It uses a JAR file service provider to look in a file called META-
INF/services/javax.xml.parsers.SAXParserFactory
4) It uses the default instance.

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.

Re: Alternative solution


Author: Leos Literak (http://www.jguru.com/guru/viewbio.jsp?EID=910037), Oct
1, 2004
And do you have generic solution? E.g. when I want to setup custom log4j for
each context? Or to have my own system property to be set for each context? If I
set it in container startup script, it will be shared across all contexts. But I want to
have different value in each context :-( Is it achievable via System.properties? Do
servlet containers support such use case?

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.

2. What happens when a filter throws an exception other than UnavailableException.


Does the container continue to go on. I mean is my only choice to have a catch block
and not do a doFilter in it or does an exception automatically halt the processing
down the filter chain and the servlet.

3. I have an authentication filter and I want to do a mapping to /* so that all


requests pass thro' authentication. However I need to add some extra filters to
servlets by name. Is this possible.?

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

Try these links:


http://java.sun.com/products/jimi/
http://rsb.info.nih.gov/ij/
Java Advanced Imaging

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.

Comments and alternative answers

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

See http://cscene.org/CS4/CS4-04.html for a JNI tutorial with source code which


verifies a user's password.
Comments and alternative answers

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

Is it possible to make calls to C or C++ methods from a servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=594580
Created: Dec 23, 2001
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by David Leonard
(http://www.jguru.com/guru/viewbio.jsp?EID=555596

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

Then How if i wanna call some java methods from a C or C++???


Author: Jia Li (http://www.jguru.com/guru/viewbio.jsp?EID=581971), Jul 9, 2002
Thanx!

Calling java Methods


Author: Madhan Iyer Vasudevan
(http://www.jguru.com/guru/viewbio.jsp?EID=985437), Aug 19, 2002
U CAN USE JNI TO CALL METHODS AND FIELDS IN JAVA. REFER SUN
DOCUMETATION ON JNI_>METHOD AND FIELS ACCESSORS

How do I pass some servlet variable to javascript?


Location: http://www.jguru.com/faq/view.jsp?EID=715231
Created: Jan 9, 2002
Author: Shirish Bathe (http://www.jguru.com/guru/viewbio.jsp?EID=550801)
Question originally posed by Dewi Sumatra
(http://www.jguru.com/guru/viewbio.jsp?EID=712005

I embedded the javascript code in the servlet such as:

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

for(int i=0; i<strAlpha.length;i++){


letterArray[i]=strAlpha[i];
}
Servlets are executed at server while javascript is executed at client browser.

The following code is actually creating javascript code which is then executed at
client browser.

out.print("var letterArray = new Array(");


Boolean isFirst = true;
//Iterator through Array
for (int i=0; i < strAlpha.length; i++){
if (!isFirst){
out.print(","); <== Semi colon added
}
isFirst = false;
out.print("'" + strAlpha[i] + "'"); <== Single quote and Semi
colon added
}
out.println(");");
If you see HTML source code, you will see following lines :
var letterArray = new Array('A','B','C','D','E','F','G','H','I');
Shirish

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/

You can pass references or method calls on to another servlet.


Author: A W (http://www.jguru.com/guru/viewbio.jsp?EID=821893), Apr 2, 2002
This method of passing requests is vital for pass through servlets that sit in DMZ's
that are not secure. The request is passed to a back-end servlet through the passing
servlet to avoid outside access to a secure resource.

How can I store international / Unicode characters into a cookie?


Location: http://www.jguru.com/faq/view.jsp?EID=722908
Created: Jan 16, 2002
Author: Sajith Kumar (http://www.jguru.com/guru/viewbio.jsp?EID=486201)
Question originally posed by Joao Pedro
(http://www.jguru.com/guru/viewbio.jsp?EID=498354

Example:

I would like to put this String: "até" The problem is when I get the cookie value I
receive "at".

----------------------

One way is that before storing the cookie URLEncode it.

URLEnocder.encoder(str);

And use URLDecoder.decode(str) when you get the stored cookie.

Comments and alternative answers

How can I store international / Unicode characters into a cookie?


Author: Callum Bir (http://www.jguru.com/guru/viewbio.jsp?EID=1084713), Jun 16,
2003
I have the same problem, and the above solution does not work. When a Javascript
writes a cookie which contains say Chinese characters, when we retrieve it, it looks
fine. When JSP sends the cookie, (gets the value from the parameter), the cookie
appears as rubbish. The JSP page is setting the encoding to utf-8, which is the same as
the input HTML form. The key problem now is really setting and retrieving say
Chinese characters (or anything non english) from Java Cookie in JSP/Servlet. As
long as the data is not coming through the cookie, I can get the data correctly coming
through the JSP and displayed correctly in any Java Swing component. But as soon as
the data comes in through the cookie, things stops working. Anything I am missing?

Encode with base64.


Author: Simon Xenitellis (http://www.jguru.com/guru/viewbio.jsp?EID=1222719),
Jan 22, 2005
You can encode the text in base64 before storing as a cookie.

What is the difference between request.getAttribute() and


request.getParameter()?
Location: http://www.jguru.com/faq/view.jsp?EID=724724
Created: Jan 17, 2002
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
Ashish Goradia (http://www.jguru.com/guru/viewbio.jsp?EID=452036

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.

Comments and alternative answers

difference between request.getAttribute() and request.getParameter()


Author: partha saha (http://www.jguru.com/guru/viewbio.jsp?EID=719123), Apr 25,
2002
Please post a more elaborated answer with examples if possible

Re: difference between request.getAttribute() and request.getParameter()


Author: Shashank Dixit (http://www.jguru.com/guru/viewbio.jsp?EID=1042366),
Jan 2, 2003
Hi, If you want to send some objects to another resource you can set it thr
request.setAttribute(string e.g "key", object e.g "Obj"). In the next page you can
get those attributes but passing the string "key" int request.getAttribute(). As
against this the one can use getParameter() to get the form paramters which is
submitted on client request.
Since session.getValue("name") has been deprecated, what method do I
call instead?
Location: http://www.jguru.com/faq/view.jsp?EID=724725
Created: Jan 17, 2002
Author: Erik Runia (http://www.jguru.com/guru/viewbio.jsp?EID=585265) Question
originally posed by nagaraju nookala
(http://www.jguru.com/guru/viewbio.jsp?EID=542427

Use session.getAttribute("name").toString() to accomplish the same thing as the


deprecated getValue method.

How can I prevent the expiration of a Session?

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.

1. To change one or more session (but on a per-session basis), use the


setMaxInactiveInterval(int interval) method of the
javax.servlet.http.HttpSession interface, passing any value in seconds. If you
use a negative value, the session will never expire.
2. To change all the sessions, use the web application descriptor (web.xml):
...
<session-config>
<session-timeout>[MINUTES]</session-timeout>
</session-config>
...
If you want the container to never timeout a session, use a [MINUTES] value
0 or less.

Why do I get the error org.xml.sax.SAXParseException : Element type "web-


app" must be declared when starting my web application? It has a web-app
element already!
Location: http://www.jguru.com/faq/view.jsp?EID=740497
Created: Jan 30, 2002
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
Steph B (http://www.jguru.com/guru/viewbio.jsp?EID=737304

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]

Comments and alternative answers

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.

Re: web-app declaration


Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727), Feb 1, 2002
Hi,
Yes, Tomcat 3 wasn-t doing validity check on the document, while Tomcat 4,
fortunately, is doing it.

Re[2]: web-app declaration


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Feb 2,
2002
I'd say, "unfortunately." DTDs are silly. Why would you ever care about the
*order* of elements in an XML document? Plus, if there's a *missing* element
that's required, then the container would figure that out anyway when it tries to
read it, and just possibly know how to deal with it when it's gone. All the XML
parser can do is just die stupidly.

Re[3]: web-app declaration


Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727), Feb 2, 2002
Well, Alex... this time I do not agree...
:-)

Re[4]: web-app declaration


Author: Jitendra Mehta
(http://www.jguru.com/guru/viewbio.jsp?EID=64025), Mar 1, 2002
Folks, I need help!
Here is my web.xml,

<?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">
<web-app>

<servlet> <servlet-name>main</servlet-name> <servlet-class>


moore.mifc.system.MainServlet</servlet-class> </servlet>

<servlet> <servlet-name>fop</servlet-name> <servlet-


class>moore.mifc.system.FopServlet</servlet-class> </servlet>

<servlet-mapping> <servlet-name>fop</servlet-name> <url-


pattern>/fop</url-pattern> </servlet-mapping>

<servlet-mapping> <servlet-name>main</servlet-name> <url-


pattern>*.html</url-pattern> </servlet-mapping>

<session-config> <session-timeout>30</session-timeout> </session-


config>

</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.

Am I missing something here??


Thank you.

Re[5]: web-app declaration


Author: Alex Chaffee
(http://www.jguru.com/guru/viewbio.jsp?EID=3), Mar 1, 2002
Please post this as separate question in the servlets forum.

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.

How to close database connection explicitly when session is ended?


Location: http://www.jguru.com/faq/view.jsp?EID=744074
Created: Feb 2, 2002
Author: Luigi Viggiano (http://www.jguru.com/guru/viewbio.jsp?EID=101985)
Question originally posed by Karthikeyan B
(http://www.jguru.com/guru/viewbio.jsp?EID=203250

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:

public class MyConnectionHolder implements HttpSessionBindingListener {


//transient to avoid "passivation"
private transient Connection conn;

public Connection getConnection() {


if (null == conn) {
//connect to the DB...
...
}
return conn;
}

public void valueBound(HttpSessionBindingEvent event) {


// you may want to initialize
// the connection there...
conn = getConnection();
}

public void valueUnbound(HttpSessionBindingEvent event) {


conn.close();
conn = null;
}

}
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):
<%

MyConnectionHolder connHolder = new MyConnectionHolder();

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.

My habit is to get a Connection from a ConnectionPool only when I need it (before of


a query), and release it to the pool as soon as I've finished to use it (after the
query). I believe it's the best policy.

[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]

Comments and alternative answers

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?

How to get url of current request from HttpServletRequest? for example


"http://site/index.jsp?id=1"
Location: http://www.jguru.com/faq/view.jsp?EID=744079
Created: Feb 2, 2002
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Maxim Markaitis
(http://www.jguru.com/guru/viewbio.jsp?EID=521563

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

Unit Testing With Cactus!


Author: Michael Rimov (http://www.jguru.com/guru/viewbio.jsp?EID=295251), Feb
8, 2002
Check out the Cactus project @ jakarta.apache.org . Great stuff there!

Re: Unit Testing With Cactus!


Author: Omindra Rana (http://www.jguru.com/guru/viewbio.jsp?EID=1164665),
Jun 6, 2005
u can make main method within ur servlet class and test from command line.
Omindra

Why can't I upload image files using com.oreilly.servlet.multipart.FilePart?


Location: http://www.jguru.com/faq/view.jsp?EID=757536
Created: Feb 13, 2002
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Louise Guibal
(http://www.jguru.com/guru/viewbio.jsp?EID=741630

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.

Known servers/configurations that this is a problem with:

• iPlanet (fixed in recent versions)


• Tomcat 4.0 WarpConnector (running behind Apache)

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) ?

Comments and alternative answers

I have the same problem with Tomcat5.0 standalone


Author: imma califano (http://www.jguru.com/guru/viewbio.jsp?EID=1183532), Jul
3, 2004
Hallo travis, can you send me your version of wrap.jar? Have you wrote some jsp
code for read the request-body with the file content. Which is? Thanks

I have the same problem with Tomcat5.0 standalone


Author: imma califano (http://www.jguru.com/guru/viewbio.jsp?EID=1183532),
Jul 4, 2004
Hallo travis, can you send me your version of wrap.jar? Have you wrote some jsp
code for read the request-body with the file content. Which is? Thanks

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.

Hope this helps.

Regards,

Günther.

Comments and alternative answers

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

<user name="user1" password="password1" roles="standard,manager"/>

and access the url http://localhost:8080/manager/list .

Everything works great.

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"/>

Then access http://localhost:8080/manager/list as above. When the


authenticate dialog comes up, just hit return, and it works.
Needless to say, you don't wanna do this on a deployed Tomcat server. :-)

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.

Admin App for Tomcat.


Author: Shiva Ramabadran (http://www.jguru.com/guru/viewbio.jsp?EID=1080705),
Apr 30, 2003
I've setup the tomcat-users.xml file, but am unable to get into the admin app.
Attempting to login causes the app to generate an error message (HTTP error code
400) The manager app works fine. I'm trying this on tomcat 4.1.24. What exactly does
the admin app do anyway ? I can't even see its use mentioned in any documentation.
Thanks in advance,

Re: Admin App for Tomcat.


Author: Linda van der Pal
(http://www.jguru.com/guru/viewbio.jsp?EID=1087047), May 22, 2003
I have the exact same problem, also with Tomcat 4.1.24. Just adding an admin role
doesn't work.

Re[2]: Admin App for Tomcat.


Author: Juvenal Guzman
(http://www.jguru.com/guru/viewbio.jsp?EID=1088120), May 26, 2003
The main page of Tomcat says:
"NOTE: For security reasons, using the administration webapp is
restricted to users with role "admin". The manager webapp is restricted
to users with role "manager". Users are defined in
$CATALINA_HOME/conf/tomcat-users.xml."

so, in "$CATALINA_HOME/conf/tomcat-users.xml" you need to add follow:

<role rolename="admin"/>
<user username="system" password="password" roles="admin"/>

to get access to "administration webapp" try with "system" user and


"password" for password.

I tried this and am still being prompted for logon credentials


Author: Wilbur Haven (http://www.jguru.com/guru/viewbio.jsp?EID=1146773), Feb
17, 2004
I am using tomcat 3.2.1 that I installed from a CD that came with a book I bought 'JSP
Weekend Crash Course'. My tomcat-users file in conf (C:\jakarta-tomcat-
3.2.1\conf\tomcat-users.xml) contains the following: <tomcat-users> <user
name="tomcat" password="tomcat" roles="tomcat" /> <user name="role1"
password="tomcat" roles="role1" /> <user name="both" password="tomcat"
roles="tomcat,role1" /> <user name="user1" password="password1"
roles="standard,manager" /> </tomcat-users> When I try to use any of the user name
/password combinations I still can not get authenticated. I checked my Environment
variables nd they seem OK. Any ideas what may be wrong.

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

It looks like another bug in the weblogic servlet container part.


Can you take your web application and try it with a fully compliant servlet container
(like Tomcat) and see if you have the same problem? I'm positive it will work.
[See the forum thread (the "a question" link above) for more details. -A]

Comments and alternative answers

Weblogic Servlet Container Problems


Author: Paul Lester (http://www.jguru.com/guru/viewbio.jsp?EID=845923), Apr 19,
2002
I agree. I'm having the same types of issues with WebLogic. You have to put the jar
files in the classpath or WebLogic won't find them. If you can, do yourself a favor
and use JBoss/Catalina. My application works well there and never has any of the
issues that I have with WebLogic. I have to jump through all kinds of hoops to get it
to work in WebLogic. What a joke!

Use the manifest classpath


Author: Frank Bourgeois (http://www.jguru.com/guru/viewbio.jsp?EID=907839), Jun
8, 2002
I had the same problem with Weblogic 6.1 sp2. I fixed it by adding a MANFEST.MF
file to my WAR file, then adding a Class-Path: entry that lists all of the jar files in my
WEB-INF/lib directory.

Remove dots from the jar filename


Author: Albert Tumanov (http://www.jguru.com/guru/viewbio.jsp?EID=983356), Aug
15, 2002
I have found the solution, thanks to Mark Foley:
http://www.opencms.com/majordomo/opencms-dev/0205/msg00055.html

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."

I renamed my jars and it solved the problem.

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

public class ConnectionPool


{
private Connection _connection;

public ConnectionPool(Connection connection)


{
_connection = connection;
}

public synchronized Connection getConnection()


{
while(null == _connection)
{
try { wait(); }
catch (InterruptedException ie) {}
}
return(_connection);
}

public synchronized void returnConnection(Connection connection)


{
if(null != _connection)
throw new IllegalStateException();

_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 I send user authentication information while making


URLConnection?
Location: http://www.jguru.com/faq/view.jsp?EID=759689
Created: Feb 14, 2002
Author: Christopher Schultz (http://www.jguru.com/guru/viewbio.jsp?EID=138382)
Question originally posed by Jayaprakash A
(http://www.jguru.com/guru/viewbio.jsp?EID=284375

You'll want to use HttpURLConnection.setRequestProperty and set all the


appropriate headers to to HTTP authorization.
-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

Unfortunately... I don't think you can do that.

[Alessandro A. Garbagnati, Feb 20, 2002 adds:


Since Tom's suggestion did not work, I'm afraid you need to put something in your
servlet that will just forward the request to the jsp page when the request is a jsp
page. ]

Comments and alternative answers

Servlet URL patterns


Author: Ryan Breidenbach (http://www.jguru.com/guru/viewbio.jsp?EID=45212),
Feb 24, 2002
In a way, you can. The servlet patterns are matched from more specific to less. For
example, if you map all requests starting with "/" to one servlet, then all requests that
do not meet a more specific pattern will go to this servlet. Basically, any pattern is
more specific than this pattern. So if you map all "*.jsp" request patterns to a different
serlvet, this will have the effect you are wanting.

Re: Servlet URL patterns


Author: Per Kreipke (http://www.jguru.com/guru/viewbio.jsp?EID=843093), Apr
17, 2002
That's helpful but I have a follow up question.

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>

<!-- Serve images from /images -->


<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/images</url-pattern>
</servlet-mapping>

<!-- Execute JSPs from /private -->


<servlet-mapping>
<servlet-name>jsp</servlet-name>
<url-pattern>/private/*.jsp</url-pattern>
</servlet-mapping>
Needless to say, this doesn't work the way I expected it to. Everything is served by
the servlet.

Per

Re[2]: Servlet URL patterns


Author: j wishnie (http://www.jguru.com/guru/viewbio.jsp?EID=897786), Jul
9, 2002
I have a similar configuration with Tomcat 4.0.4/Linux and it seems to work
fine.

Here are the differences between your config and mine:

1. In the images mapping you are using the incorrect url-pattern.

You have:

<url-pattern>/images</url-pattern>

But that is mapping only the SPECIFIC path "/images" to default.

You need:

<url-pattern>/images/*</url-pattern>

Which will map EVERYTHING under /images to the default servlet.

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:

User requests "http://example.org/private/foo.jsp", tomcat matches the url-


pattern and knows to use the JSP servlet BUT the file-path it gives the servlet
appears to be "foo.jsp" NOT "/private/foo.jsp"

A quick&dirty way to solve this is to make your url-pattern:


"*.jsp"

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"

My specific config is as follows:

<!-- map the main servlet to handle all unmatched


requests -->
<servlet-mapping>
<servlet-name>Main</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

<!-- 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

Yes, you must!

See the installation requirement for Struts:


http://jakarta.apache.org/struts/userGuide/installation.html

Request parameter How to find whether a parameter exists in the request


object?
Location: http://www.jguru.com/faq/view.jsp?EID=771300
Created: Feb 25, 2002
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Unnikrishnan Nair
(http://www.jguru.com/guru/viewbio.jsp?EID=432032

boolean hasFoo = !(request.getParameter("foo") == null ||


request.getParameter("foo").equals(""));
Tom Paris adds:
boolean hasParameter = request.getParameterMap().contains(theParameter);
(which works in Servlet 2.3+)
Comments and alternative answers

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)

MultipartRequest multi = new MultipartRequest(request, basedir,


iSize);
Enumeration files = multi.getFileNames();
String strText = multi.getParameter("txtLink");
Now easily you can enumerate through the file names.
Comments and alternative answers

Jakarta Commons FileUpload Bean


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Feb 15, 2003
The Jakarta Commons FileUpload Bean provides this feature and more! It's a great
solution to the annoyingly long-standing problem of servlet file upload.

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

Some old versions of Tomcat do not include WEB-INF/lib/*.jar in WebApp classpath.


You may handle it updating to a newer version of tomcat or (as you did) unpacking
jars into WEB-INF/classes/.

[Get the latest version of Tomcat (currently 4.0.2) from http://jakarta.apache.org


-Alex]

Comments and alternative answers

Tomcat & jarfiles...


Author: May Thomas (http://www.jguru.com/guru/viewbio.jsp?EID=757571), Feb
25, 2002
Put your jarfile into $TOMCAT_HOME/common/lib. Tomcat should find them there.

Re: Tomcat & jarfiles...


Author: Ryan Breidenbach (http://www.jguru.com/guru/viewbio.jsp?EID=45212),
Feb 26, 2002
Just be careful about what JAR files you put under
$TOMCAT_HOME/common/lib. These libraries become available to all web
applications and can lead to some nasty classpath problems. Make sure you only
place JARs here that you know will be needed by all your applications, and that
all of these applications will need the same version of that JAR.

zip file will not be loaded


Author: Guizhong Chen (http://www.jguru.com/guru/viewbio.jsp?EID=772849), Feb
26, 2002
Classes in WEB-INF/lib/*.zip files will not be loaded. It is the behavior in Tomcat-
4.0.2. Unzip zip files and jar them into jar files in WEB-INF/lib.

Re: zip file will not be loaded


Author: Karri Salli (http://www.jguru.com/guru/viewbio.jsp?EID=781982), Mar
4, 2002
I got the same problem, the only JAR
file on the classpath is bootstrap.jar.

Re: zip file will not be loaded


Author: prem Gogineni (http://www.jguru.com/guru/viewbio.jsp?EID=853193),
Apr 24, 2002
I got it working by just renaming oracles *.zip to *.jar

Re[2]: zip file will not be loaded


Author: Feng Ji (http://www.jguru.com/guru/viewbio.jsp?EID=1013740), Oct
17, 2002
Hi there, Which directory you put your oracle file in? I got the similiar
problem. The oracle driver cannot be found in my JSP application. I use
tomcat-4.1 under unix. my email is fengji@ufl.edu many thanks, Feng Ji

Re[2]: zip file will not be loaded


Author: Sunil Bhadauriya
(http://www.jguru.com/guru/viewbio.jsp?EID=1242137), May 2, 2005
Exactly, I did the same, and it worked for me. I wanted use classes12.zip-the
file containing oracle driver. There was no lib folder in my web application,
deployed in Tomcat.I simply created a lib folder in my WEB-INF folder, kept
the classes12.zip in this folder, renamed classes12.zip to classes12.jar and my
application was able to connect to the intended database and was fetching data
successfully. Thanks.

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.

None of lib files in webapps/cocoon2/WEB-INF/lib are being found.

If I copy all the jar files to $CATALINA_HOME/common/lib, the application works


fine but I definately don't want a large pile of application-specific jars in the common
directory.

I've already tried explicitly adding a context for the application in


$CATALINA_HOME/conf/server.xml

any more suggestions?

Tomcat 4.0.2 & jar files problem


Author: Davide B. (http://www.jguru.com/guru/viewbio.jsp?EID=780374), Mar 4,
2002
My jar files under WEB-INF/lib are not found. Tomcat version is 4.0.2.
These lines are from the server log:

2002-03-04 11:15:11 WebappLoader[/lutest]: Deploying class repositories to work


directory D:\jakarta-tomcat\dist\work\localhost\lutest

2002-03-04 11:15:11 WebappLoader[/lutest]: Deploy JAR /WEB-INF/lib/crimson.jar


to e:\Progetti\lutest\WEB-INF\lib\crimson.jar

2002-03-04 11:15:11 ContextConfig[/lutest]: Scanning library JAR files

2002-03-04 11:15:11 ContextConfig[/lutest]: tldConfigJar(/WEB-


INF/lib/crimson.jar): java.io.IOException: Impossibile trovare il percorso specificato

(Impossibile trovare il percorso specificato -> Could not find specified path)

Where do I go wrong ?
David

Re: Tomcat 4.0.2 & jar files problem


Author: hitesh shah (http://www.jguru.com/guru/viewbio.jsp?EID=874279), May
10, 2002
I think this is a bug in tomcat 4+. see the link,

http://www.mail-archive.com/tomcat-dev@jakarta.apache.org/msg24405.html
thanks,

How to force Tomcat to use your classes


Author: Sergio Almeida (http://www.jguru.com/guru/viewbio.jsp?EID=1194460),
Aug 20, 2004
It's a drastic approach, but worked for me.

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..."

Add to your machine CLASSPATH the following code:


%CATALINA_HOME%\work\Catalina\[name of the host]\_

As I'm using the localhost (127.0.0.1), it ended up as:

%CATALINA_HOME%\work\Catalina\localhost\_

Below this directory, resides the package org.apache.jsp

That's the secret:

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 compile your adapted sources inside this directory:


%CATALINA_HOME%\work\Catalina\localhost\_\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

Just a problem: Everything is in Portuguese, as I am a Brazilian.

Good look and comment it back!

Sergio Almeida

Re: How to force Tomcat to use your classes


Author: ravi kanth (http://www.jguru.com/guru/viewbio.jsp?EID=318820), Mar
18, 2005
By default, the jar files in the lib folder are not on the build classpath. The
example build.xml provided with Tomcat installation indicates that.

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 tested this with Tomcat 5.0.

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.

Can we use the constructor, instead of init(), to initialize servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=776892
Created: Feb 28, 2002
Author: Chandra Patni (http://www.jguru.com/guru/viewbio.jsp?EID=33585)
Question originally posed by P SK
(http://www.jguru.com/guru/viewbio.jsp?EID=748577

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

Sure you can


Author: Christopher St. John (http://www.jguru.com/guru/viewbio.jsp?EID=778908),
Mar 1, 2002
Yes, of course you can use the constructor instead of init(). There's nothing to stop
you. But you shouldn't. The original reason for init() was that ancient versions of Java
couldn't dynamically invoke constructors with arguments, so there was no way to give
the constructur a ServletConfig. That no longer applies, but servlet containers still
will only call your no-arg constructor. So you won't have access to a ServletConfig or
ServletContext. Plus, all the other servlet programmers are going to expect your init
code to be in init(). Why confuse them?

Re: Sure you can


Author: Sheikh Azad (http://www.jguru.com/guru/viewbio.jsp?EID=967553), Aug
4, 2002
can use constructor only if you are intantiating your servlet class.it is not must to
call super.init(config) you can hold your config at your own without calling
super.init(config).

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?

1. javax.servlet.http.HttpServletRequest: method getSession


2. javax.servlet.http.HttpSession: method setAttribute
3. javax.servlet.ServletContext: method getRequestDispatcher

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.

1. javax.servlet.http.HttpServletRequest: method getSession(true)


2. javax.servlet.http.HttpSession: method putValue(String str, Object o);
3. javax.servlet.ServletContext: method getRequestDispatcher This method is
supported by JSPs but not by servlets in JServ. It's weird but don't ask me
why.

How do I run a servlet from command-line mode?


Location: http://www.jguru.com/faq/view.jsp?EID=777592
Created: Feb 28, 2002
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by maha devan
(http://www.jguru.com/guru/viewbio.jsp?EID=463184

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.

Why is my servlet called twice from a JavaScript button?


Location: http://www.jguru.com/faq/view.jsp?EID=777595
Created: Feb 28, 2002
Author: Bozidar Dangubic (http://www.jguru.com/guru/viewbio.jsp?EID=433955)
Question originally posed by Arvind S
(http://www.jguru.com/guru/viewbio.jsp?EID=585871

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

Submit from Javascript


Author: Igor Dikhtyaruk (http://www.jguru.com/guru/viewbio.jsp?EID=860508),
May 2, 2002
How about if I need an action attribute to specify mapping (servlet URL)? for
example:

<form name="runReport" method="post" action="myServlet"


<input type="hidden" name="pagetype" value="report">
</form>

<script language="JavaScript">
function submitRequest() {
document.runReport.submit();
}
</script>

Re: Submit from Javascript


Author: kamalanathan vijatt
(http://www.jguru.com/guru/viewbio.jsp?EID=833101), May 2, 2002

sir u have mentioned that Action attribute should not be used . Then, how i will
map my destination URLfrom the Javascript funtion.

Re[2]: Submit from Javascript


Author: DD DD (http://www.jguru.com/guru/viewbio.jsp?EID=865851), May
4, 2002
document.form.action=target just before submitting form in javascript.

Why is my servlet is called twice.


Author: Rajkumar Murugesan
(http://www.jguru.com/guru/viewbio.jsp?EID=521246), May 15, 2002
As said by Bozidar Dangubic, if in the form we have a submit button and write a
Script to submit, we land up sending two request. Again.. If we use Image as an input
type and provide an onclick action then also the request will sent twice [even though
Action attribute is not set in the form, but set in the Script]. To avoid this we can have
the Input type tag outside the form tag. By this we can ensure only the Script submit()
sends the request.

Re: Why is my servlet is called twice.


Author: Scott Yaung (http://www.jguru.com/guru/viewbio.jsp?EID=915592), Jul
1, 2002
you can try add an hidden value like beensubmit in the form, before submit the
form in javascript , you can check it.
another way to do it is not add a click even handler in your img button, just use
onsubmit() event handler, and return a true when the all the form fileds are well
filled, return a false, if any fields can not match your request.
like this
<form name="form1" action="youraction" method="post"
onsubmit="return checkb4send();" >
......
<input type="img" src="...">

function checkb4send()
{
if (...document.form1.fields are well filled...)
{return true;}
return false;
}

Facing the same problem with websphere 4.0


Author: Dhanesh Choudhary
(http://www.jguru.com/guru/viewbio.jsp?EID=1089617), May 30, 2003
I have coded my jsps in the same way as it was suggested. I donot have more than one
action parameter in my jsp. But wherever I submit a page to servlet It is called always
called twice. I sending hidden parameter to servlet, first time it works well but since it
is calling twice second time it goes with null. and servlet throw null pointer exception.
Not able to understand why it is happening. Same thing is working fine with
weblogic. . Here is the sample code I am using <SCRIPT language="JavaScript">
function getPage(choice) { document.view_search_result.eventID.value=choice;
document.view_search_result.submit(); } </script> <form
name="view_search_result" method="post"
action="<%=request.getContextPath()%>/servlet/RCAServlet">
<div align="right"> </div>
</form>

Why is my servlet called twice from a JavaScript button?


Author: Hubert Carvallo (http://www.jguru.com/guru/viewbio.jsp?EID=1250033),
Jun 23, 2005
If you have a javascript function which does document.formName.submit() and a
form that has a submit button when you click on submit the form will be submitted
twice. A simple way to avoid that it is to change the type of the submit button from
"submit" to "button" then only the javascript function will submit the form.

Is possible to subdir webapps directory?


Location: http://www.jguru.com/faq/view.jsp?EID=779619
Created: Mar 3, 2002
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
Peter Burgstaller (http://www.jguru.com/guru/viewbio.jsp?EID=763476

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.

Why request.getRemoteUser() returns NULL ?


Location: http://www.jguru.com/faq/view.jsp?EID=842151
Created: Apr 17, 2002
Author: Mikkel Bruun (http://www.jguru.com/guru/viewbio.jsp?EID=771030)
Question originally posed by Muhammad Asif
(http://www.jguru.com/guru/viewbio.jsp?EID=301509

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

Re[2]: How does one go about authenticating so that getRemoteUser()


does not return null?
Author: YAC YAC (http://www.jguru.com/guru/viewbio.jsp?EID=949856), Jul
15, 2002
hello I have a problem with TOMCAT 4.O with IIS server, the OS is
WINDOWS NT 4 I am making an upload from the client to the server. in the
server IIS where I installed TOMCAT and the OS is WINDOWS 2000, all
thing are ok and the upload works but in the server IIS where I installed
TOMCAT and the OS is WINDOWS NT 4, it doesn't work. have you any idea
about this problem or how I can to know all right that have the TOMCAT
USER or any idea about this thank you yac yacsil@hotmail.com

Re[2]: How does one go about authenticating so that getRemoteUser()


does not return null?
Author: robert luo (http://www.jguru.com/guru/viewbio.jsp?EID=953211), Jul
17, 2002
Hi Joachim Aschoff, Your message is great. What if I am using Apache with
Tomcat as webserver? I would like to get remote user's profile, such as the
machine/domainname and user role to determine if the client is accessible to
the secured page (an intranet application). Your help is greatly appreciated.
Robert

Re[3]: 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), Jul 18, 2002
Sorry Robert, I only tried it with IIS as web server. Maybe somebody else
can help.

Re[3]: How does one go about authenticating so that getRemoteUser()


does not return null?
Author: rondari shabang
(http://www.jguru.com/guru/viewbio.jsp?EID=1018536), Oct 28, 2002
You can use getRemoteUser() on tomcat hooked on to APache by doing the
following

- I use mod_webapp as the apache/tomcat connector (dont know if the


others work)
- I use apache 2 and tomcat 4.2.12
- in Apache's httpd.conf, configure mod_webapp by adding lines like this:
LoadModule webapp_module /opt/apache/modules/mod_webapp.so

<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[3]: How does one go about authenticating so that getRemoteUser()


does not return null?
Author: Alain Chiorboli
(http://www.jguru.com/guru/viewbio.jsp?EID=1155141), Mar 17, 2004
I've the same problem with Apache 1.3.28 / Tomcat 5.0.19 and mod_jk
1.2.5. After long searches on the net I finally found how to do this. Update
the connector configuration in the server.xml file: <Connector port="8009"
protocol="AJP/1.3"
protocolHandlerClassName="org.apache.jk.server.JkCoyoteHandler"
redirectPort=" 8443" tomcatAuthentication="false"> By setting the
tomcatAuthentication="false" for the AJP1.3 connector now the
getRemoteUser return the user authenticated through Apache!

Re[2]: How does one go about authenticating so that getRemoteUser()


does not return null?
Author: Arthur Simberg
(http://www.jguru.com/guru/viewbio.jsp?EID=1025501), Nov 14, 2002
I can't setup Tomcat & IIS. Method getRemoteUser() returns null. I've tried
almost everything. Please help me.

Re[2]: How does one go about authenticating so that getRemoteUser()


does not return null?
Author: aris javier (http://www.jguru.com/guru/viewbio.jsp?EID=1196565),
Aug 31, 2004
Hello! i'm using Tomcat with IIS.. i followed this steps.. i went to the
properites of virtual directory "ces", selected the security tab and press edit...
unchecked anonymous access and checked windows authentication... but still,
calling getRemoteUser returns null... =| what else did you do? please help! aris

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

Re: request.getRemoteUser() = null


Author: manish janjani
(http://www.jguru.com/guru/viewbio.jsp?EID=1158150), Mar 28, 2004
The method request.getRemoteUser() returns null when a HTML client
requests for the servlet. Can any 1 help me solve this problem? mail me at
mjanjani@yahoo.com. thnks

Re: request.getRemoteUser() = null


Author: manish janjani
(http://www.jguru.com/guru/viewbio.jsp?EID=1158150), Mar 28, 2004
The method request.getRemoteUser() returns null when a HTML client
requests for the servlet. Can any 1 help me solve this problem? mail me at
mjanjani@yahoo.com. thnks

Re[2]: How does one go about authenticating so that getRemoteUser()


does not return null for websphere and weblogic?
Author: Greg Guerin (http://www.jguru.com/guru/viewbio.jsp?EID=1177197),
Jun 8, 2004
This is not a the answer if a good security model is your objective. There is no
authentication happening at all. Your application will read the logged in user
and that's the extent of your security model. If you try to log into the website
from a machine you are logged into as someone else (i.e. your home computer,
a co-workers machine, etc..) you will pass credentials for that machine only.
Yes, basic authentication dialog will prompt, but regardless of what you type
in it, the same user information will be returned from a getRemoteUser() call.
That user being the one you're logged into windows as. That may be ok for
some people, but it's not very flexible.

Is the only correct answer to solve the real getRemoteUser()==null to create a


Realm? If so, does anyone have a simple example of a JAAS Realm for
WindowsNT Security? All the references I've found on JAAS are for
developing your own realm, but I thought there were some prebuilt
WindowsNT/Solaris/etc.. realms that you could use. Any references,
information and especially example w/ explanations are welcome. Thank you
in advance! Greg

Re[3]: How does one go about authenticating so that getRemoteUser()


does not return null for websphere and weblogic?
Author: Greg Guerin
(http://www.jguru.com/guru/viewbio.jsp?EID=1177197), Jun 8, 2004
Just to clarify: By "this is not a good answer" I meant setting
tomcatAuthentication="false" in the connector tag.
File upload and login using IIS6 and Tomcat5. There are problems related to file
upload (POST) when using JK2.04 and there is a patch for it.
Author: Terje Christensen (http://www.jguru.com/guru/viewbio.jsp?EID=1212259),
Nov 22, 2004
http://www.odindata.no/infopot/tomcat_iis_errors.htm How to get Tomcat and IIS to
work.for file uploading and login There are several pages on how to get Tomcat and
IIS working. But I have (unfortunately) found some undocumented problems. I have
used several weeks to figure out the reason and how to solve these problems and I
think that my findings are useful for others. Terje (terchris2<at>hotmail.com) My case
is Tomcat 5.024 and IIS6 running on Windows 2003 server standard edition. (Java 1.5
is used) If you need to have users logging in to your app and file upload then you can
read on. INTRO When using IIS6 and Tomcat5 you need a connector that enables IIS
to forward requests to .jsp and servlets to Tomcat. You have to my knowledge 3
connectors to choose from JK – the first connector JK2 – A newer and better, faster
version of JK jspISAPI – a commercial connector DEVELOPMENT STATUS ON
THE CONNECTORS: JK The JK connector is the oldest one and Apache Jakarta
(makers of Tomcat) and on the Tomcat connectors page they suggest to use JK2
instead of JK. JK2 The newest connector for Tomcat from Apache Jakarta project.
Latest official version is JK2.04. The connector is as of 14. November no longer
supported. jspISAPI A commercial connector developed by www.jspisapi.com. The
connector is maintained and supported. Latest news After JK2 development was shut
down it seems that functionality from JK2 will be ported to JK. But this has not
happened yet. BUGS IN THE CONNECTORS: Unfortunately there are bugs in the
connectors. The bugs are not permanent and occur when there is many users or high
load on your app. JK I did not test this connector since the Tomcat connectors page
encourages use of JK2 over JK. JK2 File upload (PUT) does not work 100% using
JK2.04 I have situations where users on fast lines (LAN) can upload, but users on
slow lines cannot upload at all. Users that have good speed can upload most of the
time. See “JK2 upload bug” for full description of the bug. This problem has been
corrected in JK2, but the patch is not officially released. Unfortunately the patch
creates another problem when displaying pages. The display problem is not
permanent and you will need some load on your sever to experience it. jspISAPI
jspisapi does not support getting user logged in by request.getRemoteUser() so you
must rewrite your app to use request.getHeader("IIS-REMOTE-USER") The
request.getHeader("IIS-REMOTE-USER") works on XP version of IIS and is
reported to work on Windows Server 2003 web edition. But sadly it does not work on
Windows Server 2003 standard edition. The jspISAPI is smart and removes the load
of serving static content from Tomcat so I tried to use jspISAPI on sites that do not
require login. But after running jspISAPI for a while I saw that jspISAPI did not serve
pages anymore. I could verify that the problem was not in Tomcat by accessing the
page on port 8080. I did not test file upload using jspISAPI because of the above
problems. The jspISAPI is a promising connector, but the bugs must be sorted out
before it can be used. HOW I SOLVED THE PROBLEMS I found that the JK2
connector was the best. The official JK2.04 has no problems displaying pages. I use
this on public sites. I use the JK2.04 patch on sites that require login. It can do file
upload. The site that requires file upload and login does not have a high load.
Therefore I don’t get the display page errors on this site. If you need file upload
(POST) on pages that has high load. Then you can continue the search for a solution.
If you find it then please inform me terchris2<at>hotmail.com HOW TO INSTALL
JK2 I found the documentation for installing and setting up the connectors hard to
understand. Now that I have spent a lot of time on this I see that what was hard to
understand was all the manual steps and the mixing of how to install JK and JK2. The
simplest way to install JK2 is to download the Shiftomat JK2 installer. It sets up the
JK2 for you. To get authentication working you must add these lines in <tomcat
dir>\conf\jk2.properties request.tomcatAuthentication=false
request.registerRequests=false REFERED LINKS Tomcat connectors page
http://jakarta.apache.org/tomcat/connectors-doc/jk2/index.html JK2 upload bug
http://issues.apache.org/bugzilla/show_bug.cgi?id=15278 JK2 upload patch
http://jakarta.apache.org/~mturk/isapi_redirector2.zip JK2 is officially unsupported
message http://jakarta.apache.org/~mturk/docs/ Shoftomat JK2 installer
http://www.shiftomat.com/opensource/ THE LINKS I GATHERED WHILE TRYING
TO SOLVE THE PROBLEM http://wiki.apache.org/jakarta-tomcat/Tomcat_2fLinks
http://jakarta.apache.org/tomcat/tomcat-4.1-doc/config/jk.html
http://www.unlimitedftp.ca/support/resources/tomcat-iis.html
http://cephas.net/blog/2004/06/25/getting_iis_5x_tomcat_5x_to_play_nice.html
http://www.jguru.com/faq/view.jsp?EID=842151
http://www.junlu.com/msg/107129.html http://www.rit.edu/~ack5504/tomcat-iis6-
howto/narantugs-sengee-guide.html http://jakarta.apache.org/tomcat/connectors-
doc/jk2/index.html http://jakarta.apache.org/~mturk/docs/
http://www.jguru.com/forums/view.jsp?EID=741701 http://servlets.com/cos/faq.html
http://www.servlets.com/jservlet2/examples/ch04/index.html#ex04_21
http://www.servlets.com/soapbox/bugs.html METADATA FOR SEARCH ENGINES
JK, JK2, Tomcat, IIS, Connector, Upload, unexpected end of part,
java.io.IOException: Stream closed, POST, Multipart,
request.getRemoteUser(),com.oreilly.servlet, ParamPart, MultipartParser

What is a "javax.servlet.ServletException: Broken pipe" exception?


Location: http://www.jguru.com/faq/view.jsp?EID=994194
Created: Sep 4, 2002
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by David Howie
(http://www.jguru.com/guru/viewbio.jsp?EID=494945

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.

Comments and alternative answers


broken pipe exception
Author: sudarshan prasad (http://www.jguru.com/guru/viewbio.jsp?EID=1041572),
Dec 29, 2002
I had this problem sometime back. My servlet used to call a stored proc.after the call
there used to be this error immediately. the problem was that there were cursors
declared in the stored proc which were not opened( because they were opened
conditionally) and the java program expected the resultset which it did not get. Open
all the declared cursors and this must solve the problem

How can an HttpSessionListener comunicate directly to an user web


browser that his session has been destroyed by server web.xml "timeout"
parameter?
Location: http://www.jguru.com/faq/view.jsp?EID=994198
Created: Sep 4, 2002
Author: Lasse Koskela (http://www.jguru.com/guru/viewbio.jsp?EID=573277)
Question originally posed by JL JLCHIP
(http://www.jguru.com/guru/viewbio.jsp?EID=305597

It can't.

The request-response nature of the HTTP protocol prevents us from sending "push"
data to the browser.

When the HttpSessionListener.sessionDestroyed() method is called by the


container, the session is already dead (the actual HttpSession object is alive,
though). If the browser sends a request just before that moment (session still alive),
the session timeout is renewed. If the browser sends a request just after that
moment (session already dead), we cannot recognize the relation between "the
session that was killed about 48 seconds ago" and the incoming request (which
doesn't have an existing session, yet).

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]

Comments and alternative answers

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;

public void doGet(HttpServletRequest request,


HttpServletResponse response) throws IOException, ServletException
{
int localVariable;
HttpSession session = request.getSession();
String sessionVariable =
session.getAttribute("SomeAttribute");
}
}

Taking the above code block as an example, the instanceVariable will be


available to any thread that makes use of the servlet. If you are just using the
variable for reading, and not for any modifications, then it should be fine. You can
also declare the variable as static if you wanna, and it would still be acceptable to
all threads that are executing the doGet method of the servlet.

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.

Hope that explains, or clarifies your doubts.

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 the Servlet Container had 2 instances of SomeServlet running, there would


be 2 different versions of the instanceVariable. One for each instance of the
SomeServlet within the context of the Servlet Engine.

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

Another possible clarification of terminology is that an "Instance Variable"


(the general Object Oriented term) is also often called a "Member Field",
in Java-specific parlance.

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() ;

public ... doGet(...) {


// ...add a timestamp to the array
long lTimestamp1 = System.currentTimeMillis() ;
al_.add(new Long(lTimestamp1)) ;

// ...do some stuff that takes a bit of time so we cant test


the concurrency situation
(blah, blah, blah)

// ...(vainly?) attempt to retrieve the timestamp we set


before
long lTimestamp2 = (Long) al_.get(al_.size()-1) ;
if(lTimestamp2 != lTimestamp1) {
System.out.println("The timestamp we set was " + lTimestamp
+ ", the one we retrieved was" + lTimestamp2) ;
}
}

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.

How to send a SMS or MMS from a servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=1019760
Created: Oct 30, 2002
Author: Lasse Koskela (http://www.jguru.com/guru/viewbio.jsp?EID=573277)
Question originally posed by Surapun Assaratt
(http://www.jguru.com/guru/viewbio.jsp?EID=975585

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.

Oops. Actually there is one that I know of: www.kannel.org

Comments and alternative answers

Java SMS API


Author: Markus Eriksson (http://www.jguru.com/guru/viewbio.jsp?EID=1029113),
Nov 22, 2002
If you want to send SMS:es from Java I would suggest that you look at some of the
Java SMS libraries that is available.

For example:
http://smsj.sourceforge.net/
http://www.sourceforge.net/projects/smsj

[Yes, I'm the developer of that library :)]

Maintaining database state across session I have a servlet, which when


called from a web page calls a PL/SQL procedure that updates certain
records in the database. After which the servlet redirects the user to
another Web page. Only if the user Submits from this page, do I need to
COMMIT the UPDATES done in the stored procedure. How can I ensure this?
Location: http://www.jguru.com/faq/view.jsp?EID=1019764
Created: Oct 30, 2002
Author: Eugene Kuleshov (http://www.jguru.com/guru/viewbio.jsp?EID=442441)
Question originally posed by Arun Iyer
(http://www.jguru.com/guru/viewbio.jsp?EID=1018788

[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.

What is a "Distributed Web Application"?


Location: http://www.jguru.com/faq/view.jsp?EID=1021034
Created: Nov 3, 2002
Author: Lasse Koskela (http://www.jguru.com/guru/viewbio.jsp?EID=573277)
Question originally posed by sabu vs PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=476248

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]

I've recently installed j2sdk1.4.1, having previously been developing in


jdk1.2.1 and my old code is not compiling as it can't find packages
javax.servlet.* and javax.servlet.http.*. How can I fix this?
Location: http://www.jguru.com/faq/view.jsp?EID=1027648
Created: Nov 19, 2002
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Rahul Rohatgi
(http://www.jguru.com/guru/viewbio.jsp?EID=852923

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.

(Tomcat is probably what you want -- it's a lot lighter.)

Then add the JAR to your classpath and you're all set.

See How do I set my CLASSPATH for servlets?

How do I map a JSP using web.xml and RequestDispatcher?


Location: http://www.jguru.com/faq/view.jsp?EID=1027649
Created: Nov 19, 2002
Author: Abhinav Srivastava (http://www.jguru.com/guru/viewbio.jsp?EID=981434)
Question originally posed by Abhinav Srivastava
(http://www.jguru.com/guru/viewbio.jsp?EID=981434
It is not mandatory for JSPs to be registered in the web.xml but it is sometimes
done; the <servlet-class> tag being replaced by the <jsp-file> tag (and others
remaining the same).

e.g <jsp-file>/index.jsp</jsp-file>

And thus you can give a JSP an alias.

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.

How do I access an Init Parameter set in web.xml from a JavaBean?


Location: http://www.jguru.com/faq/view.jsp?EID=1027650
Created: Nov 19, 2002
Author: Bozidar Dangubic (http://www.jguru.com/guru/viewbio.jsp?EID=433955)
Question originally posed by Lee KF
(http://www.jguru.com/guru/viewbio.jsp?EID=768959

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).

How can I make Apache/Tomcat notice that my servlet changed, without


having to restart it?
Location: http://www.jguru.com/faq/view.jsp?EID=1027658
Created: Nov 19, 2002
Author: Shelleen Qian (http://www.jguru.com/guru/viewbio.jsp?EID=1021730)
Question originally posed by Venkat Rangachari
(http://www.jguru.com/guru/viewbio.jsp?EID=1026229

You need to turn on Servlet Reloading on your Tomcat.

[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]

To turn on servlet reloading, edit install_dir/conf/server.xml and add a


DefaultContext subelement to the main Service element and supply true for the
reloadable attribute. The easiest way to do this is to find the following comment:

<!-- 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.

Comments and alternative answers

See also
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jan 12, 2003
Restarting Tomcat after rebuilding a servlet

Modifying server.xml for automatically reloading class files


Author: Rommel Sharma
(http://www.jguru.com/guru/viewbio.jsp?EID=1006127), Jan 14, 2003
In addition, in case you wish to specify reloading after a certain interval add the
following attributes also to the server.xml:

<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

Re: Modifying server.xml for automatically reloading class files


Author: Brian Kaplan (http://www.jguru.com/guru/viewbio.jsp?EID=1110555), Aug 24, 2003
I have tried everything and still cannot get the file to reload... the server.xml entry is:
<Context path="/assignment1" docBase="assignment1" debug="0" reloadable="true"
crossContext="true"/>
I am running Tomcat 4.1.27 & J2SDK 1.4.2 on a Win 98SE box. When I run java, I tweak the java
it the dos window message: Aug 24, 2003 12:47:53 PM org.apache.jk.server.JkMain start INFO: J
time=50/770 config=C:\tomcat-4.1.27\conf\jk2.properties WebappClassLoader: Resource '/WEB-
INF/classes/PageTwo.class' was modified; Date is now: Sun Aug 24 12:50:12 CDT 2003 Was: Sun
11:52:32 CDT 2003 javax.servlet.ServletException: Wrapper cannot find servlet class PageTwo or
depends on at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:891) a
org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:668) at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:210) at
org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPip
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480) at
org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995) at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at
org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPip
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480) at
org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995) at
org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2416) at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180) at
org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPip
at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:171) at
org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPip
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:172) at
org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPip
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480) at
org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995) at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174) at
org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPip
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480) at
org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995) at
org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:223) at
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:601) at
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Pr
at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:565) at
org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:619) at
java.lang.Thread.run(Thread.java:534) root cause java.lang.ClassNotFoundException: PageTwo at
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1444) at
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1289) at
org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:885) at
org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:668) at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:210) at
org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPip
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480) at
org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995) at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at
org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPip
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480) at
org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995) at
org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2416) at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180) at
org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPip
at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:171) at
org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPip
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:172) at
org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPip
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480) at
org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995) at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174) at
org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPip
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480) at
org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995) at
org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:223) at
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:601) at
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Pr
at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:565) at
org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:619) at
java.lang.Thread.run(Thread.java:534) I refresh the page again and now get this error: HTTP Statu
page2 is currently unavailable type Status report message Servlet page2 is currently unavailable de
requested service (Servlet page2 is currently unavailable) is not currently available. I hope someon
figure this out. Brian

java beans reloading


Author: Tushar Kapila (http://www.jguru.com/guru/viewbio.jsp?EID=1059392), Feb
22, 2003
this did not work for common java beans in install_foler//common/classes how do i
set tomcat to scan and reload these?

Re: java beans reloading


Author: Hilke Heremans (http://www.jguru.com/guru/viewbio.jsp?EID=1070504),
Mar 27, 2003
A 'trick' you can use for Java Beans (I realize it's not the cleanest thing to do, but it
does work)..

1) Delete the class file


2) Try to access the class file directly (by referring to it via your browser, might
also work if you try to run the app that depends on it, I don't remember)
3) Tomcat will realize it's gone and throw an exception
4) Copy over a newer version of the .class
5) Reload

Similar problem with Tomcat 5.5.7


Author: Gautam Singh (http://www.jguru.com/guru/viewbio.jsp?EID=1237364), Aug
26, 2005
I also want to turn on the auto reloading for tomcat 5.5.7. But could not find the
comment '<!-- 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. -->'in server.xml. Where should I place
the following line '<DefaultContext reloadable="true"/>'

In order to find the proper URL to which to submit forms, I need to


manually set the context name in every URL, using somthing like:

<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>
...

How do I redirect from a servlet in one context to a servlet in another?


Specifically I'd like to know how to share objects between contexts.
Location: http://www.jguru.com/faq/view.jsp?EID=1028275
Created: Nov 20, 2002
Author: Michael Dean (http://www.jguru.com/guru/viewbio.jsp?EID=805382)
Question originally posed by Bryan Dollery PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=963590

If you're trying to do a redirection (i.e. response.sendRedirect(String)), it


requires an absolute URI (including the context path). If you don't know the context
path, you're out of luck. :(
If you're trying to forward, you need to get a ServletContext reference pointing to
the other context, then get a RequestDispatcher from that other context. Once
again, you'll need to know the context path.

To get a reference pointing to the other context, just call getContext(String


uripath) on the ServletContext reference for your context. The uripath should be
a String specifying the context path of another web application in the container.

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)

Comments and alternative answers

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

OK, let me rephrase my first sentance:

Although the sendRedirect(String) method of the HttpServletResponse


interface accepts relative URL's, a URL that does not start with a "/" is interpreted
as relative to the current context and a URL that starts with a "/" is interpreted as
relative to the container root (this was changed in Servlets 2.3--in previous
versions the spec was ambiguous, so there is no guarantee as to which way your
servlet container implemented it--in which case you need to use an absolute URL
to achieve portability). Therefore, to redirect a request to a servlet in another
context (which was the original question), you will need either an absolute URL or
a container-relative URL (which is an absolute URL without the protocol and
domain information), and, therefore, you will need to know the context path of the
other web application. (Although you could use a request-relative URL that
"backs out" of the current context with "../" (repeated as necessary), using an
absolute- or container-relative URL would be a far more clear and concise means
of expressing the information.)

I thought the shorter version presented the information more clearly, but the longer
version is technically more correct. :)

Sending object from servlet on one machine to JSP on another machine


Author: Vishal Rodge (http://www.jguru.com/guru/viewbio.jsp?EID=1038665), Dec
17, 2002
I want to send certain information from servlet running on one server to JSP on
another server. i do not want to send that info as a FLAT FILE nor i want to send it
through URL rewriting. can anybody suggest me a solution to this vishal

Can destroy() be called from inside the service() method of my servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=1029043
Created: Nov 21, 2002 Modified: 2002-11-22 11:45:19.872
Author: Andrew Postoyanets (http://www.jguru.com/guru/viewbio.jsp?EID=343575)
Question originally posed by rajesh [missing]
(http://www.jguru.com/guru/viewbio.jsp?EID=1028350

destroy() is a servlet life-cycle method called by servlet container to kill the


instance of the servlet.

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:]

On the other hand, if the question is,

"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."

To use an image, just use a tag like:

<img src="/servlet/MySpyWareServlet" />

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.

[Another poster suggests using an IFRAME]

Comments and alternative answers

META HTTP-EQUIV="refresh" CONTENT="5;


URL=http://host:port/servlet/YourServlet"
Author: preveeth ott (http://www.jguru.com/guru/viewbio.jsp?EID=1037194), Dec
12, 2002
try using this in your html page
'<META HTTP-EQUIV="refresh" CONTENT="5;
URL=http://host:port/servlet/YourServlet"> '

after 5 seconds your servlet will be called.

Incase your html page is generated from a servlet u could as well use the below
statement

res.setHeader("Refresh", "5; URL=http://host:port/servlet/YourServlet");

Re: META HTTP-EQUIV="refresh" CONTENT="5;


URL=http://host:port/servlet/YourServlet"
Author: shashidhar kache
(http://www.jguru.com/guru/viewbio.jsp?EID=1215318), Dec 8, 2004
res.setHeader("Refresh", "5; URL=http://host:port/servlet/YourServlet"); This
does not refresh the html page through servlet. i am trying tor refresh same page
from servlet handler. Am i doing anything wrong. Shashi

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.

4: Unique within an object within a millisecond. Finally digits 25-32 represent a


random 32 bit integer generated on every method call using the cryptographically
strong java.security.SecureRandom class.

[See also the following FAQs:

• 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.

Re: Random class


Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727), Feb 28, 2003
Hi,
java.util.Random will generate random numbers, not unique numbers.

Re[2]: Random class


Author: Prashanth Nandavanam
(http://www.jguru.com/guru/viewbio.jsp?EID=818802), Apr 24, 2003
Look at the JUG class by Tatu Saloranta:
http://www.doomdark.org/doomdark/proj/jug/index.html It is based on the
IETF UUID drafts, and works wonderfully.

Re: Random class


Author: Nathan Ciliberto
(http://www.jguru.com/guru/viewbio.jsp?EID=1139136), Jan 14, 2004
You can also use some built-in java classes:
java.rmi.server.UID
or
java.rmi.dgc.VMID
I'm guessing the UID class is the one you want though.

(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.

Re: Making it Faster


Author: Scott Carlson (http://www.jguru.com/guru/viewbio.jsp?EID=1085622),
Oct 8, 2003
There are two reasons to use the random number instead of incrementing your
last. 1. The number would be predictable and, depending on what this is used for,
you could be opening up a potential security issue. This is why ProcessIDs are
randomized on some OSes (AIX for one). 2. You must synchronize on that counter
to guarantee that your number isn't reused. Your random number generator need
not be synchronized, (though its implementation may be).

There are Three possible ways


Author: Narayana Prasad (http://www.jguru.com/guru/viewbio.jsp?EID=1142103),
Jan 29, 2004
1) If ur using Oracle You can create a sequence ,by which u can generate unique
primary key or universal primary key. 2) U can generate by using random nunmbers
but u may have to check the range and check for unique id. ie random number
generate 0.0 to 1.0 u may have to make some logic which suits ur unique id 3) Set the
maximum value into an XML file and read that file at the time of loding ur
application from xml . thanks and regards prasad

UUID and Random IDs


Author: Wesley Theobalds (http://www.jguru.com/guru/viewbio.jsp?EID=1165144),
Apr 22, 2004
Hi, I've just finished implementing the Sequence Block pattern a la Marinescu using a
Session bean and an entity bean representing the sequence, and its working well.
Using a UUID makes life harder for any Data analysis further down the line, having
to enter a 32 bit number for the key for any ad hoc SQL queries you may need to
write, and I've often found it helpful to have an incremental key as it indicates when
the record was created in the absence of a timestamp.

hashcode isn't unique


Author: x x (http://www.jguru.com/guru/viewbio.jsp?EID=1174058), May 27, 2004
> System.identityHashCode(), which is guaranteed to return > distinct integers for
distinct objects within a JVM. Sorry, but it isn't true. See
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4990451 Tomas

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.

How to get international unicode characters from a a form input


field/servlet parameter into a string?
Location: http://www.jguru.com/faq/view.jsp?EID=1030399
Created: Nov 25, 2002
Author: charief gael (http://www.jguru.com/guru/viewbio.jsp?EID=1005789)
Question originally posed by Martin Kultermann
(http://www.jguru.com/guru/viewbio.jsp?EID=520941
[ I have a servlet based app that generates and processes HTML forms. I would like
to support mutiple languages/character sets that will be stored in unicode UTF-8 in
the database. I am setting the following tags, for example:

<meta content="text/html; charset=Shift_JIS" http-equiv="Content-Type">


and
<form accept-charset="Shift_JIS"...

I am also setting the locale and content type on the HttpServletResponse to "ja" and
"text/html; charset=Shift_JIS" respectively.

Unfortunately, the CharacterEncoding on the HttpServletRequest from the post is


always null even though it's set properly in the browser.

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:

If the request.getCharacterEncoding() is null, the default parsing value of the String


is ISO-8859-1.

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:

String myparam = request.getParameter("myparamname");


if (myparam != null)
myparam = new String(myparam.getBytes"8859_1"),"UTF8");
Comments and alternative answers

How to get international unicode characters from a a form input field/servlet


parameter into a string?
Author: Arthur Tang (http://www.jguru.com/guru/viewbio.jsp?EID=34155), Dec 13,
2002
myparam.getBytes("8859_1") will definitely kill double byte string if page encoding
is not 8859_x or latins.

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).

JSP and UTF8 is simple


Author: dom sir (http://www.jguru.com/guru/viewbio.jsp?EID=1135191), Dec 21,
2003
I don't know way many people suggest things like the following "myparam = new
String(myparam.getBytes"8859_1"),"UTF8");" You don't have to do that all you need
is putting the following on top of your JSPs <META HTTP-EQUIV="Content-Type"
CONTENT="text/html; charset=UTF-8"> <%@ page pageEncoding="UTF-8" %>
<%@ page language="java" contentType="text/html;charset=UTF-8" %>

Re: JSP and UTF8 is simple


Author: june Quin (http://www.jguru.com/guru/viewbio.jsp?EID=579553), Jan 29,
2004
HI, The reason is all of the settings you mentioned don't solve the problem. I tried
those and after getting a double byte character value using
request.getParameter("name") and print out the value, the value is corrupted, but if
I do what many people suggested, the value is not corrupted.

Reading non-Latin form data from forms on UTF-8 pages


Author: Malcolm McMahon (http://www.jguru.com/guru/viewbio.jsp?EID=1151003),
Mar 3, 2004

I've found for myself the approach.

parm = new String(param.getBytes("ASCII"), "UTF-8");

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.

Non-Latin form data


Author: Malcolm McMahon (http://www.jguru.com/guru/viewbio.jsp?EID=1151003),
Mar 3, 2004
Just tried it another way and it seems to work (at least for a UTF-8 form).
if(request.getCharacterEncoding() == null)
request.setCharacterEncoding("UTF-8");
address = request.getParameter("address");
This has successfully input Greek text without the need for explicit conversion and
should be more future-proof (since it doesn't depend on the servlet engine not doing
the translation automatically.)

Re: Non-Latin form data


Author: K Fl (http://www.jguru.com/guru/viewbio.jsp?EID=1256922), Aug 6,
2005
And just make sure you set the method="post" in your form declaration! GETs do
not seem to work with non-latin character sets. K

Can an Application Scope Variable be clustered?


Location: http://www.jguru.com/faq/view.jsp?EID=1031015
Created: Nov 26, 2002
Author: John P Jensen (http://www.jguru.com/guru/viewbio.jsp?EID=985825)
Question originally posed by ashok ayengar
(http://www.jguru.com/guru/viewbio.jsp?EID=137446

[ 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.

As per Servlet 2.2 spec:

4.3.1 Context Attributes in a Distributed Container


Context attributes exist locally to the VM in which they were created and placed. This
prevents the ServletContext from being used as a distributed shared memory store.
If information needs to be shared between servlets running in a distributed
environment, that information should be placed into a session, a database or set in
an Enterprise JavaBean.

Oh.. By the way...

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.

I would place the data as a static instance variable on the servlet!

Comments and alternative answers

Can an Application Scope Variable be clustered? Static vs Application scope


Author: ras ras (http://www.jguru.com/guru/viewbio.jsp?EID=1184726), Jul 8, 2004
.... 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. I would
place the data as a static instance variable on the servlet! ... Is there a reason not to
store data that "doesn't change often" in an application scope variable? How is it
different from storing it in a static variable defined in a servlet? In a "production
environment", I believe a servlet (and hence the static variable) exists until the
webapp is restarted. IMHO, the advantages of storing in a static variable is "lazy-
loading". But if the data is static and small, say "US states", and if a large number of
web pages require "US states", you could retrieve this data from the DB and store it in
application scope at webapp start-up time since: 1) the data-set is small 2) US states
don't change (added/deleted/updated) often The key to remember is "what works for
you may not work for others" :)

How to find the parent directory of a servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=1031016
Created: Nov 26, 2002
Author: Gerrit Goetsch (http://www.jguru.com/guru/viewbio.jsp?EID=992616)
Question originally posed by Shanthi Natarajan
(http://www.jguru.com/guru/viewbio.jsp?EID=141300

try this..

to get the URL

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 ....
}

or this to get the real path

String path = new


java.io.File(getServletContext().getRealPath("")).getParent();

Why does cookie.getMaxAge() always return -1 (regardless of real expiry)?


Location: http://www.jguru.com/faq/view.jsp?EID=1033944
Created: Dec 4, 2002
Author: Hitoshi Gosen (http://www.jguru.com/guru/viewbio.jsp?EID=1027729)
Question originally posed by Garrett Smith
(http://www.jguru.com/guru/viewbio.jsp?EID=733867

By default, the maxAge is set to a negative number.

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.

Comments and alternative answers

Cookie max age


Author: Petru Curticapean (http://www.jguru.com/guru/viewbio.jsp?EID=995730),
Dec 5, 2002
Depending on application server and configuration, cookies can be generated
automatically by servlet engine. In such case you can control the max age trough
configuration. For example in IBM Websphere you can set (trough Admin Console)
the max age in the Session Manager.

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?

How can I keep track of how may times my servlet is called?


Location: http://www.jguru.com/faq/view.jsp?EID=1033951
Created: Dec 4, 2002
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Robert Taylor
(http://www.jguru.com/guru/viewbio.jsp?EID=1006063

See How do I implement a hit counter in Servlets or JSP? for a definitive answer.

How can I access an NNTP newsgroup using JSP or Servlets?


Location: http://www.jguru.com/faq/view.jsp?EID=1033959
Created: Dec 4, 2002
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by wu min (http://www.jguru.com/guru/viewbio.jsp?EID=910820

Your servlet must know how to speak NNTP, or call a library that does.

There are NNTP implementation in the following packages:


• JavaMail: See the JavaMail:NNTP FAQ subtopic.

• Jakarta Commons Sandbox.

• Jakarta James mail server

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

Try using a hidden frame, similar to this:


<frameset rows="0,*" framespacing="0" frameborder="0" border="0">
    <frame name="hiddenfrm" src="blank.jsp" scrolling="no" noresize>
    <frame name="content" src="home.jsp" noresize>
</frameset>
Then all querystrings will be hidden, the address bar will display only where the
default document is located.

[However, Michael Dean warns:]

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

Could you give me small example in detail?


Author: cathy HAN (http://www.jguru.com/guru/viewbio.jsp?EID=1070144), Mar 26,
2003
I don't understand this every well, but I think this is a great idea to solve this problem,
could you give me a more detail example? thanks. Cathy

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

the original forum thread

Is there a way to detect when the session has expired, so that we can send a
redirect to a login page?

Comments and alternative answers

Regarding Session Expire


Author: Madhav Lonari (http://www.jguru.com/guru/viewbio.jsp?EID=1036985),
Dec 12, 2002
This can be achieved with the HttpSessionBindingListener interface If the session is
going to expire the ,valueUnbound(HttpSessionBindingEvent event) method of this
interface get called provided this interface is implemented to valid concrete class and
object of this class is bounded with this binding listener

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.

At least that's how I understand it.

Stephen McConnell

Comments and alternative answers

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

Comments and alternative answers

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.

Why shouldn't we make the service() method synchronized?


Location: http://www.jguru.com/faq/view.jsp?EID=1041533
Created: Dec 28, 2002
Author: Michael Dean (http://www.jguru.com/guru/viewbio.jsp?EID=805382)
Question originally posed by anil reddy
(http://www.jguru.com/guru/viewbio.jsp?EID=505941

[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).

Unbeknownst to the servlet container, the thread executing in the service(...)


method "locks the door" behind it (holds the lock for the servlet object). Not knowing
any better, the servlet container starts the other nine threads and assumes they are
happily executing the service(...) method. In reality, each of the nine other
threads finds the object (the servlet instance) locked, so they go into a "wait" state.

Meanwhile, the first thread finishes executing the service(...) method, so it


releases the lock on the servlet instance. One of the other threads--not necessarily
the second thread, so we'll say the eighth thread--awakens to find the servlet's lock
available, so it requests the lock and starts processing the service(...) method.
Meanwhile, the servlet container may be receiving other requests. It's possible that
when the eighth thread (which was the second to execute the service(...)
method) finishes, the thirty-fifth thread grabs the lock.

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.

Best of luck, and have fun with threads.

How do I keep Tomcat 4.1.x from persisting Session Objects?


Location: http://www.jguru.com/faq/view.jsp?EID=1041534
Created: Dec 28, 2002
Author: Brendan Patterson (http://www.jguru.com/guru/viewbio.jsp?EID=999118)
Question originally posed by Nathan Christiansen
(http://www.jguru.com/guru/viewbio.jsp?EID=1039297

[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.

This is a bit of a hack, but it's encapsulated and could work.

Set up a filter to run incoming requests past a JSP that with page directive
&lt;%@ page session="false" %&gt;.

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!

There is an HttpSessionBindingListener for changes to the session. Is there


anything similar for changes of ServletContext?
Location: http://www.jguru.com/faq/view.jsp?EID=1041535
Created: Dec 28, 2002
Author: G M (http://www.jguru.com/guru/viewbio.jsp?EID=802175) Question
originally posed by guru prasanth PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=847725

Yes, as of Servlet Spec 2.3. See javax.servlet.ServletContextListener,


javax.servlet.ServletContextAttributeListener.

How can I access a configuration and/or log.properties file (stored under


WEB-INF) in a web application?
Location: http://www.jguru.com/faq/view.jsp?EID=1041791
Created: Dec 30, 2002
Author: Charles Cuozzo (http://www.jguru.com/guru/viewbio.jsp?EID=3774)
Question originally posed by Charles Cuozzo PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=3774

I place the log.properties and the appconfig.xml file in the WEB-INF/classes


directory. (appconfig.xml is the other configuration file I spoke of.)

I get the locations as a URL object using the following code:

String logFile = getInitParameter("logger"); // or just logFile =


"log.properties"
URL logurl = this.getClass().getResource("/" + logFile);
if(logurl != null)
{
PropertyConfigurator.configure(logurl);
}
else
{
System.out.println("log.properties not found!!");
}

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.

When using a dispatcher and calling .forward(), will doGet() or doPost() be


called in the target servlet?
Location: http://www.jguru.com/faq/view.jsp?EID=1041792
Created: Dec 30, 2002
Author: Eelco Cramer (http://www.jguru.com/guru/viewbio.jsp?EID=200853)
Question originally posed by Simon Kelly
(http://www.jguru.com/guru/viewbio.jsp?EID=1036030

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

When using a dispatcher and calling .forward(), will doGet() or doPost() be


called in the target servlet?
Author: Kotra Mallikanand (http://www.jguru.com/guru/viewbio.jsp?EID=1176065),
Jun 3, 2004
could you please elaborate on this point a little further.

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.

How to do a simple session timeout?


Location: http://www.jguru.com/faq/view.jsp?EID=1044373
Created: Jan 8, 2003
Author: Christopher Schultz (http://www.jguru.com/guru/viewbio.jsp?EID=138382)
Question originally posed by Patrick Wardhana
(http://www.jguru.com/guru/viewbio.jsp?EID=1042019

In WEB-INF/web.xml, use the following incantation:


&lt;webapp&gt;
.
.
&lt;session-config&gt;
&lt;session-timeout&gt;30&lt;/session-timeout&gt; &lt;!-- 30
minutes --&gt;
&lt;/session-config&gt;
.
.
&lt;/webapp&gt;

It's one of the last sub-elements of &lt;webapp&gt;. 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?

• How do I set session timeouts of greater than 30 minutes?

Comments and alternative answers

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 ")

How to deploy and run a simple servlet on websphere?


Location: http://www.jguru.com/faq/view.jsp?EID=1044409
Created: Jan 8, 2003
Author: Subbareddy Kalakota
(http://www.jguru.com/guru/viewbio.jsp?EID=1017528) Question originally posed
by new user (http://www.jguru.com/guru/viewbio.jsp?EID=999934

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.

Comments and alternative answers

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

How can I set parameters in a JSP, something equivalent to setAttribute on


a request object? That is, I need to do setParameter in order to read it as
getParameter in the servlet.
Location: http://www.jguru.com/faq/view.jsp?EID=1044746
Created: Jan 9, 2003
Author: Michael Dean (http://www.jguru.com/guru/viewbio.jsp?EID=805382)
Question originally posed by Rita Vepa
(http://www.jguru.com/guru/viewbio.jsp?EID=1016597

[One solution is: I am assuming you're referring to "intercepting" a request, then


checking/modifying the values. If so, have a look at one of the newer features of
the Servlet API, Filters. ]

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.

Case 2: An HTTP request is submitted to a JSP that is forwarding (or including) a


request to a (third-party) servlet. You would like to "add" parameters to the request
when received by the JSP. Do so with the <jsp:param ... > tag.

<jsp:forward page="/servlet/some.ThirdPartyServlet" >


<jsp:param name="param_name" value="somevalue" />
</jsp:forward>

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:

<input type="hidden" name="param_name" value="somevalue" />

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).

Comments and alternative answers

How can I set parameters in JSP?


Author: Scott Andrews (http://www.jguru.com/guru/viewbio.jsp?EID=1188219), Jul
23, 2004

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?

Re: How can I set parameters in JSP?


Author: Rishi Venkatarama
(http://www.jguru.com/guru/viewbio.jsp?EID=1193458), Aug 16, 2004
When the form is being submitted, you can use javascript to add parameters
"dynamically" as the form is beign submitted.
function addMenuContextParam (form,paramValue) {
if (document.getElementById) {
var input = document.createElement('INPUT');
if (document.all) { // what follows should work
// with NN6 but doesn't in M14
input.type = 'HIDDEN';
input.name = 'SOME_NAME';
input.value = paramValue;
}
else if (document.getElementById) { // so here is the
// NN6 workaround
input.setAttribute('type', 'HIDDEN');
input.setAttribute('name', 'SOME_NAME');
input.setAttribute('value', paramValue);
}
form.appendChild(input);
}
}
hope this helps. Rishi

I too need to a logical response.setParameter


Author: Greg Marsh (http://www.jguru.com/guru/viewbio.jsp?EID=1255498), Jul 28,
2005
I currently have a login page that uses a form to pass a username and password. The
receipent of the post is a hardware box that I cannot change. I can add the parameters
on the URL and it works just fine. But then the username and password are shown in
the address line of the browser. I would like ot simulate what a form does but from
code rather than from form. It is enough that it does not show in the address line -- I
don't need better security. It seems like there must be some way to write parameters
into the stream going back to the browser, but I haven't found it!

How could I use NTLM Authentication to authenticate via Windows NT


Authentication for a servlet based intranet-application ?
Location: http://www.jguru.com/faq/view.jsp?EID=1045412
Created: Jan 11, 2003
Author: Chad Skeeters (http://www.jguru.com/guru/viewbio.jsp?EID=976796)
Question originally posed by Manfred Regele PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=230192

[There was a great discussion of this at


http://www.jguru.com/faq/viewquestion.jsp?EID=393110 The code below seems to
be the final solution, but I recommend reading the thread to make sure, especially
since there was much discussion about making it not take 40 seconds to return.

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.

Brett Knights also recommends:

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]

String auth = request.getHeader("Authorization");


if (auth == null)
{
response.setStatus(response.SC_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", "NTLM");
response.flushBuffer();
return;
}
if (auth.startsWith("NTLM "))
{
byte[] msg = new
sun.misc.BASE64Decoder().decodeBuffer(auth.substring(5));
int off = 0, length, offset;
if (msg[8] == 1)
{
byte z = 0;
byte[] msg1 = {(byte)'N', (byte)'T', (byte)'L',
(byte)'M', (byte)'S', (byte)'S', (byte)'P',
z,(byte)2, z, z, z, z, z, z, z,(byte)40, z, z, z,
(byte)1, (byte)130, z, z,z, (byte)2, (byte)2,
(byte)2, z, z, z, z, z, z, z, z, z, z, z, z};
response.setHeader("WWW-Authenticate", "NTLM " +
new sun.misc.BASE64Encoder().encodeBuffer(msg1));
response.sendError(response.SC_UNAUTHORIZED);
return;
}
else if (msg[8] == 3)
{
off = 30;

length = msg[off+17]*256 + msg[off+16];


offset = msg[off+19]*256 + msg[off+18];
String remoteHost = new String(msg, offset, length);

length = msg[off+1]*256 + msg[off];


offset = msg[off+3]*256 + msg[off+2];
String domain = new String(msg, offset, length);

length = msg[off+9]*256 + msg[off+8];


offset = msg[off+11]*256 + msg[off+10];
String username = new String(msg, offset, length);

out.println("Username:"+username+"<BR>");
out.println("RemoteHost:"+remoteHost+"<BR>");
out.println("Domain:"+domain+"<BR>");
}
}
Comments and alternative answers

NT Authentication using servlets


Author: P N (http://www.jguru.com/guru/viewbio.jsp?EID=1054248), Feb 6, 2003
This code is fine except that when I tried, it does not pop up the username/password
(authentication) box in the browser, although it does manage to get the required data,
decode it and prints the username, remote host and domain. Any idea why it is
behaving in this manner?

Re: NT Authentication using servlets


Author: Jon Peccarelli (http://www.jguru.com/guru/viewbio.jsp?EID=1057547),
Feb 17, 2003
Because it is using NTLM authenication. It is a "silent" authentication with your
current NT credentials. If this fails, you will get a login box (i.e. you are in a
different domain then the servers you are trying to access and there is not a trust
setup). You only get the login box all of the time using clear text authentication.

Re[2]: NT Authentication using servlets


Author: Maggie Chau
(http://www.jguru.com/guru/viewbio.jsp?EID=1064841), Mar 10, 2003
I tried this coding, however I keep getting the Login box. I'm in the same
domain where I try to logon. Can you pls help me out. Thanks. Maggie

Re: NT Authentication using servlets


Author: Abhay Kumar (http://www.jguru.com/guru/viewbio.jsp?EID=1145500),
Feb 11, 2004
Hello, I am using the same code as given in this thread. I am having a problem, I
am not able to use the POST method for sending data from a JSP to an servlet.
Please help Regards Abhay

Re[2]: NT Authentication using servlets


Author: Dave Jarvis (http://www.jguru.com/guru/viewbio.jsp?EID=1154253),
Mar 15, 2004
Hi i have exactly the same problem "I am not able to use the POST method for
sending data from a JSP " when using NTLM Authentication. What was the
solution please ? Thanks Dave

Re[2]: NT Authentication using servlets


Author: Anup Vijayaraghavan
(http://www.jguru.com/guru/viewbio.jsp?EID=1177514), Jun 9, 2004
Did you get a solution for not being able to use POST in forms with
mod_ntlm. We are having the same problem with our intranet. Thanks in
advance ... Anup

Re: NT Authentication using servlets


Author: Akash Kava (http://www.jguru.com/guru/viewbio.jsp?EID=1135160), Feb
25, 2004
Hi,

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

Experience with trying to use NTLM


Author: Frederik Heick (http://www.jguru.com/guru/viewbio.jsp?EID=886161), Mar
27, 2003
I have made some serious attempts to implements NTLM, using to code mentioned.

It wont work with Windows 95, no matter what I did. But in my firm we still have
some WS that uses it, hmmmm.

Secondly, it has to be in every doPost method, not great.

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

Re: Experience with trying to use NTLM


Author: Robert McKenzie
(http://www.jguru.com/guru/viewbio.jsp?EID=1079571), Apr 27, 2003

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.

response.setHeader("WWW-Authenticate", "NTLM " +


new sun.misc.BASE64Encoder().encodeBuffer(msg1).trim());

Re: Experience with trying to use NTLM


Author: Babu Kopparam (http://www.jguru.com/guru/viewbio.jsp?EID=1196844),
Sep 2, 2004
Hi! Frederik,

I am trying to achieve the same using asp page hosted on IIS.

I am using the following code :

<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>

This is not giving me any user id hint logged in.

Any help is highly appreciated.


-Babu.

Re: Experience with trying to use NTLM


Author: joan cao (http://www.jguru.com/guru/viewbio.jsp?EID=1257118), Aug 8,
2005
How did you make it work, can you tell me, I'd like to do the same way as you do.

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:

Negotiate Unicode (0x00000001)


Always Sign (0x00008000)
Negotiate NTLM (0x00000200)

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

Re: Can NTLM communicate with active directories using a servlet?


Author: Edward Castellarin
(http://www.jguru.com/guru/viewbio.jsp?EID=1149996), Feb 28, 2004
Can the NTLM communicate with the windows LDAP
(active directories) from a Servlet or JSP program?

Re[2]: Can NTLM communicate with active directories using a servlet?


Author: Brian Compton
(http://www.jguru.com/guru/viewbio.jsp?EID=111701), Mar 2, 2004

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();

String DOMAIN_NAME = "domain";


String DOMAIN_CONTROLER = "domaincontroller";

Hashtable env = new Hashtable();

env.put(Context.SECURITY_AUTHENTICATION,"simple");

// TODO: change to a user on your domain!


String activeDirUser = DOMAIN_NAME + "\\user";
String activeDirPassword = "cleartextpassword!";

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

String url = new String("ldap://"+host+":"+port);


env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL,url);

System.out.println("Connecting to " +url);

DirContext ctx;
ctx = new InitialDirContext(env);

SearchControls ctls = new SearchControls();


ctls.setCountLimit(1);
ctls.setReturningObjFlag(false);
ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String userLogon =
userName.substring(DOMAIN_NAME.length() +1);
System.out.println(userLogon);
String filter = "(&(objectCategory=User)(cn="+
userLogon +"))";
NamingEnumeration n= ctx.search("DC="+ DOMAIN_NAME
+",DC=COM", filter, ctls);

System.out.println(" Attributes .... ");


while (n.hasMoreElements()) {
System.out.println(n.next());
}

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.

Please help What is this error ?? where my i wrong


Author: Rajesh Francis
(http://www.jguru.com/guru/viewbio.jsp?EID=1157367), Mar 25, 2004
Please help >> What is this error ?? where my i wrong. I just want to
retireve the User Name from the Active Directory using JNDI and Tomcat
3.3

Problem getting attribute: javax.naming.InvalidNameException:


cn=Woods, Anthony (HQ), ou=Silverdale, ou=sews-e: [LDAP: error code
34 - 0000208F: NameErr: DSID-031001B6, problem 2006 (BAD_NAME),
data 8350, best match of: 'cn=Woods, Anthony (HQ), ou=Silverdale,
ou=sews-e,dc=sews-e,dc=com' ]; remaining name 'cn=Woods, Anthony ,
ou=Silverdale, ou=sews-e'

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

Entering worng user id.


Author: Selvapandian Gurunathan
(http://www.jguru.com/guru/viewbio.jsp?EID=1025470), Aug 31, 2003
If the user enters wrong user id in the pop up i am getting the wrong user id. HOw to
avoid showing the pop-up?

Re: Entering worng user id.


Author: Jaya Selvan (http://www.jguru.com/guru/viewbio.jsp?EID=1199885), Sep
18, 2004
Hi i'm facing the same problem.Can u suggest me if u have come across any valid
solutions. Thanks in advance.

Problem using the above code on Web sphere running SSL


Author: Altaf Malik (http://www.jguru.com/guru/viewbio.jsp?EID=1113901), Sep 8,
2003
The above mentioned code is not running on Websphere running SSL. When it tries to
send type2 message to client, the browser says, invalid response from the server. can
anyone suggest any better solution or changes in this code???? I really need it
immediately. Altaf Malik
How to save the authenticated user info to a java Bean
Author: joan cao (http://www.jguru.com/guru/viewbio.jsp?EID=1257118), Aug 8,
2005
I used the code to get userID and password, but I need to save the ID and password in
a session bean which can be shared among pages.

Do you know how to do that with the code.

Any help is greatly appreciated.

Thanks

Joan

NTLM Hash password


Author: Sherjeel Ghouse (http://www.jguru.com/guru/viewbio.jsp?EID=1260744),
Sep 2, 2005
Is there a way to get NTLM hash password with this code. Otherwise, how would i
authenticate a user against a domain like Active Directory using JNDI/LDAP.
« previous beginning next »

How do I use HttpServletRequest.getHeaderNames() to get the names of the


headers of the HTTP request?
Location: http://www.jguru.com/faq/view.jsp?EID=1045427
Created: Jan 11, 2003
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
Chris Marks (http://www.jguru.com/guru/viewbio.jsp?EID=1007132

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.

for (Enumeration enum=request.getHeaderNames();


enum.hasMoreElements();) {
String headerName = (String)enum.nextElement();
System.out.println("Name = " + headerName);
}

Remember, that HttpServletRequest is an interface, so you don't have to worry about


the implementation, otherwise if you decide to switch to another Servlet Container,
then you will not be able to do that...
That's why they are called interfaces.

What is the role of the controller in MVC architecture?


Location: http://www.jguru.com/faq/view.jsp?EID=1045434
Created: Jan 11, 2003
Author: Lasse Koskela (http://www.jguru.com/guru/viewbio.jsp?EID=573277)
Question originally posed by sabu vs PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=476248

The role of controller is to dictate what to do behind the scenes and what to display
in the view next.

1. Controller receives a request


2. Controller decides the requested activities based on request parameters
3. Controller delegates tasks to be performed based on the request parameters
4. Controller delegates the next view to be shown

There must be a lot better explanations for the controller's responsibilities, but at
least I tried...

As it comes to choosing between a JSP and a servlet for the controller


implementation, servlet is the obvious choice as JSPs are designed for simplifying
generating dynamic responses primarily (mixing HTML and logic).

[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
]

How should I configure JBuilder7 to work on servlets?


Location: http://www.jguru.com/faq/view.jsp?EID=1045506
Created: Jan 12, 2003
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
Krystof Malak (http://www.jguru.com/guru/viewbio.jsp?EID=1001958

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.

How can I read parameters from a multipart/form-data upload form?


Location: http://www.jguru.com/faq/view.jsp?EID=1045507
Created: Jan 12, 2003
Author: Sean Sullivan (http://www.jguru.com/guru/viewbio.jsp?EID=203382)
Question originally posed by Sean Sullivan
(http://www.jguru.com/guru/viewbio.jsp?EID=203382

[That is, given the form:


<FORM ACTION="/servlet/FooServlet"
ENCTYPE="multipart/form-data"
METHOD=POST>

What is your name? <INPUT TYPE=TEXT NAME='submitter'><br>

What file are you sending? &lt;INPUT TYPE=FILE NAME=secretDocument><br>

<input type="submit" value=Submit><br>


</FORM>
I cannot read the submitter using request.getParameter("submitter") (it returns
null). ]
Situation:

javax.servlet.HttpServletRequest.getParameter(String) returns null when


the ContentType is multipart/form-data

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 Struts. Struts 1.1 handles this automatically.


Comments and alternative answers

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

Example for multi part request


Author: srinivas kandagatla (http://www.jguru.com/guru/viewbio.jsp?EID=1150943),
Mar 2, 2004
/* * DemoParserUploadServlet.java * * Example servlet to handle file uploads using
MultipartParser for * decoding the incoming multipart/form-data stream */ import
javax.servlet.*; import javax.servlet.http.*; import java.io.*; import
com.oreilly.servlet.multipart.*; public class DemoParserUploadServlet extends
HttpServlet { private File dir; public void init(ServletConfig config) throws
ServletException { super.init(config); // Read the uploadDir from the servlet
parameters String dirName; //= config.getInitParameter("uploadDir");
dirName="C:\\Program Files\\Apache Group\\Tomcat 4.1\\webapps\\examples\\WEB-
INF\\classes\\cal"; //if (dirName == null) { // throw new ServletException("Please
supply uploadDir parameter"); //} dir = new File(dirName); if (! dir.isDirectory())
{ throw new ServletException("Supplied uploadDir " + dirName + " is invalid"); } }
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { PrintWriter out = response.getWriter();
response.setContentType("text/plain"); out.println("Demo Parser Upload Servlet");
if(false) { 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); } }

Re: Example for multi part request


Author: srinivas kandagatla
(http://www.jguru.com/guru/viewbio.jsp?EID=1150943), Mar 2, 2004
<HTML> <HEAD> <META NAME="GENERATOR" Content="Microsoft
Visual Studio 6.0"> <TITLE></TITLE> </HEAD>
/*
* DemoParserUploadServlet.java
*
* Example servlet to handle file uploads using MultipartParser
for
* decoding the incoming multipart/form-data stream
*/

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

import com.oreilly.servlet.multipart.*;

public class DemoParserUploadServlet extends HttpServlet {


private File dir;

public void init(ServletConfig config) throws ServletException {


super.init(config);
// Read the uploadDir from the servlet parameters
String dirName; //= config.getInitParameter("uploadDir");
dirName="C:\\Program Files\\Apache Group\\Tomcat
4.1\\webapps\\examples\\WEB-INF\\classes\\cal";
//if (dirName == null) {
// throw new ServletException("Please supply uploadDir
parameter");
//}
dir = new File(dirName);
if (! dir.isDirectory()) {
throw new ServletException("Supplied uploadDir " + dirName +
" is invalid");
}
}

public void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
response.setContentType("text/plain");
out.println("Demo Parser Upload Servlet");
if(false)
{

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>

How can I read parameters from a multipart/form-data upload form using


"http://jakarta.apache.org/commons/fileupload/" library?
Author: Dharmanand Singh (http://www.jguru.com/guru/viewbio.jsp?EID=1207306),
Oct 26, 2004
> Solution B:
> 1. download
> http://jakarta.apache.org/commons/sandbox/fileupload/
> 2. invoke readHeaders() in
> org.apache.commons.fileupload.MultipartStream

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).

1. Download one of the versions of UploadFile from


http://jakarta.apache.org/commons/fileupload/
2. Invoke parseRequest(request) on org.apache.commons.fileupload.FileUploadBase
which returns list of org.apache.commons.fileupload.FileItem objects.
3. Invoke isFormField() on each of the FileItem objects. This determines whether the
file item is a form paramater or stream of uploaded file.
4. Invoke getFieldName() to get parameter name and getString() to get parameter
value on FileItem if it's a form parameter. Invoke write(java.io.File) on FileItem to
save the uploaded file stream to a file if the FileItem is not a form parameter.

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.

[See also Files:Downloading subtopic]

[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]

Comments and alternative answers

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")

it would be stored as an array

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).

How do you create a browser cookie that persists to a different domain?


Location: http://www.jguru.com/faq/view.jsp?EID=1063895
Created: Mar 6, 2003
Author: Jeff Hubbach (http://www.jguru.com/guru/viewbio.jsp?EID=504430)
Question originally posed by Eric Cho
(http://www.jguru.com/guru/viewbio.jsp?EID=1051283

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

Cookie aCookie1 = new Cookie("_user", USER1);


aCookie1.setDomain("12.23.34.45"); //to server2
aCookie1.setPath("/cgi-bin/");
response.addCookie(aCookie1);

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

How do you create a browser cookie that persists to a different domain?


Author: tech tech (http://www.jguru.com/guru/viewbio.jsp?EID=809635), Mar 6,
2003
Totally right.
And also think in terms of security.
Say one user is surfing bank site ( say bank.com) and the bank site puts a cookie with
some user info in it. Now the same user is surfing on say foo.com and now if the
foo.com application had an access to the bank.com cookie, then foo.com will be rich
in no time :-). They can access all secure / non secure, confidential info of all the
cookies of that user.
So u see, it is absoultely NOT ACCEPTABLE for one domain to share cookies of
other one.

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.

I will be grateful if I get the sample code for the same.


thanks.
mani.

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.

How can we find out the number of ServletContext currently active in a


servlet container?
Location: http://www.jguru.com/faq/view.jsp?EID=1063899
Created: Mar 6, 2003
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
Ashutosh Satyam (http://www.jguru.com/guru/viewbio.jsp?EID=1063699

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.

Comments and alternative answers

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).

If this question is not directly Servlet/JAVA related, maybe the answer is


Javascript???

-----
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.

Hope that helps.


About the Javascript...there *is* a trick I have used to check the file size of a file,
but it requires the user to load it locally. You basically create a new Image object
with that file name the same way you do with image pre-loaders and check the size
property of the Image object. I have used it to get file sizes of images and audio
files, but it should work with other types as well.

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 do think, though, that providing a server-side check is preferable.

Comments and alternative answers

I think we can do before we upload a file


Author: rajesh khanna (http://www.jguru.com/guru/viewbio.jsp?EID=1172410), Mar
31, 2005
we have <form name="f" enctype="multipart/form-data"> which is used to upload.
we can get the size of file by using request.getContentLength() you can get a good
example from sun.com. we can also do using java script we can use the File class for
mozilla and an active Control for IE.(but I think the server side validation is better).
thank u.

How can we add file upload utility in a program


Author: Jyotsna Sharma (http://www.jguru.com/guru/viewbio.jsp?EID=1249491),
Jun 21, 2005
Hi, I am making some application in which i want add file upload for the users.Plz
tell me the way to do it through ftp protocol or other.

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...

[See http://www.jguru.com/forums/view.jsp?EID=1072839 for the source code and


more discussion. -Alex]

[Todo: add "Filters" category; add this to it]

I want to exclude a certain file, "*/SlideMenu.js", from a filter. Can I do it?


Location: http://www.jguru.com/faq/view.jsp?EID=1074633
Created: Apr 8, 2003
Author: Eelco Cramer (http://www.jguru.com/guru/viewbio.jsp?EID=200853)
Question originally posed by Garrett Smith
(http://www.jguru.com/guru/viewbio.jsp?EID=745187

<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.

What is the proper way to do it?


------------
There is no way to exclude files from an url-pattern. You could change your
mapping strategy or change the extension of the file you want to exclude (not so
nice). You could configure your filter to not process certain files.

Good luck.

What's difference between Servlet/JSP session and EJB session?


Location: http://www.jguru.com/faq/view.jsp?EID=1082544
Created: May 7, 2003
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
guru prasanth PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=847725

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.

Comments and alternative answers

which will be of high performance,maintaining the session in http/jsp or EJB.


Author: munish kumar (http://www.jguru.com/guru/viewbio.jsp?EID=1101096), Jul
14, 2003
if we simply have to place the objects required in session , then which will be
faster.As we have to implement the scrolling in the pages.I think that accessing the
object from http/jsp session will be faster then the EJB session. Am i right pls let me
know. Thanks. Munish

Re: which will be of high performance,maintaining the session in http/jsp or


EJB.
Author: Nanda Kumar (http://www.jguru.com/guru/viewbio.jsp?EID=1116828),
Sep 22, 2003
Hi, I have one question regarding this... If Httpsession Object is Expired, what
will happen Stateless or Stateful session bean ??? Any idea. Thanks in advance,
Nanda

Re[2]: If Httpsession Object is Expired, what will happen Stateless or


Stateful session bean
Author: Sergey Pomytkin
(http://www.jguru.com/guru/viewbio.jsp?EID=1045816), Oct 29, 2003
With Stateless - nothing, once it done with your method invocation it's don't
care about you. About satefull it’s up to particular app sever
implementation/configuration .. Chances are if you hold reference to it in
httpsession and it’s get expired (= user will never be able to release this EJB)
server eventually will recycle this instance

Re[2]: which will be of high performance,maintaining the session in


http/jsp or EJB.
Author: Ram V.L.T (http://www.jguru.com/guru/viewbio.jsp?EID=449849),
Jun 28, 2004
If Httpsession is expired irrespective of the type of the bean all the references
stored in the Httpsession will be lost.

Re: which will be of high performance,maintaining the session in http/jsp or


EJB.
Author: Murthy VVVS (http://www.jguru.com/guru/viewbio.jsp?EID=1243697),
May 11, 2005
It is more of design issue rather than performance. The concept/scope of both
HTTPSession and EJB Session Bean are different from each other.

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.

In JBoss you will have to look at standardjboss.xml and

http://www.jboss.org/j2ee/dtd/jboss_3_0.dtd

and for others, you will have to look at that containers


documentation to see how to set that.
hope that helps

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.

2. EJB Container : Stateful Session Bean.


The Stateful Session Bean LOGICALLY is a "client thread
with State".This thread can be Activated/Passivated as
per the situation.But during this
activation/passivation essentially the state is saved
plus anything else instructed by the bean developer in
respective methods.
In other words the state mangement control is available to
Bean developer also.This is what missing in servlet.In other words for Stateful
Session Bean instance variable are
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.

Performance wise it is a FEELING that SFB are slower then


simple http sessions.Hence needs to be used with care.

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...

Tomcat 4.x and /servlet/ mapping.


Location: http://www.jguru.com/faq/view.jsp?EID=1105228
Created: Jul 31, 2003
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727)

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:

<!-- The mapping for the invoker servlet -->


<!--
<servlet-mapping>
<servlet-name>invoker</servlet-name>
<url-pattern>/servlet/*</url-pattern>
</servlet-mapping>
-->
A developer can simply map all the servlet inside the web application descriptor of
its own web application (that is highly suggested), or simply uncomment that
mapping (that is highly discouraged).
It is important to notice that the /servlet/ isn't part of Servlet 2.3 specifications so
there are no guarantee that the container will support that. So, if the developer
decides to uncomment that mapping, the application will loose portabiliy.
Comments and alternative answers

Tomcat 4.x and /servlet/ mapping. In


http://[domain]:[port]/[context]/servlet/[servlet full qualified name].What is
context in this url?
Author: Nataraj CV (http://www.jguru.com/guru/viewbio.jsp?EID=1221732), Jan 19,
2005

Please clarify ASAP, Thanks in advance.

Cross Site Scripting (XSS) with Jakarta Tomcat.


Location: http://www.jguru.com/faq/view.jsp?EID=1105229
Created: Jul 31, 2003
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
Michael Murphy (http://www.jguru.com/guru/viewbio.jsp?EID=1090804

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.

Das könnte Ihnen auch gefallen