[Webinar] Streamline your web hosting managementRegister Today


Servlets -- repeated browser requests possible?

Posted on 1999-11-16
Medium Priority
Last Modified: 2013-11-24
Is it possible to have a browser (Navagator, IE, etc.), without any use of applets, carry on a "dialog" with a servlet, or will a new instance of the servlet always be created every time a browser sends a request?

The situation I'm envisioning is an order-entry type situation.  The user first enters personal identification and product information into an html form.  When the user clicks "submit," a servlet checks the form information to be sure the form was accurately filled out, and (assuming it is), generates a new page asking the user to confirm the information entered.  I would like the same servlet to continue processing the information if the user confirms, but whenever I try to have the confirmation submitted to the same servlet, I get an error.

Currently, I have the confirmation page submitted to a second servlet, which then processes the confirmed information.  To do this, however, I am using hidden fields in the confirmation page (containing information generated by the first servlet).  Some of the information I am hiding should not be accessible to the user, but it is accessible if the user just views the page source.

I want to avoid the use of applets, for a number of reasons.  Is  there any other way I can have multiple "submits" to the same servlet directly from a browser?

I hope I'm being clear in stating my problem.

Any help/advice would be appreciated.

Question by:skylar1

Expert Comment

ID: 2211229
See http://www.experts-exchange.com/bin/Q.10226569 for reference

and if it solves ur problem i will propose.

In short,
Use a sendPostMessage() from Jason Hunter's at www.servlets.com and close streams.

pasting text from there to here in order to save u 30 pts.

Previously Asked Java Programming Question
From: NickH  Title: "More on Servlet/Page Lifetime..."  
Points: 30 Points  Date: Friday, October 29 1999 - 07:05AM PDT  
I logged into my bank onlinethe other day, and when I logged off, I notied that any attempt to use the browser back button was successfully blocked by whatever system they were using...ASP, I think.  I'm aware of the Session object and how it works in servlets, namely putting objects, grabbing objects, and invalidating, but I don't know for certain how to catch an attempt to move back in the browser history.

I once read the following line of code in a book on servlets:

   res.setHeader("Expires", "Tues, 01 Jan 1980 00:00:00 GMT");
where res is the HttpServletResponse object.  Does this in fact do anything?  I think it's supposed to force reloading of a page when you come to it through the history buttons, but I can't find a good list of what properties the header possesses.

I'll stop talking now.  Any help would be appreciated.
Question History  
 From: ravindra76
 Date: Friday, October 29 1999 - 07:29AM PDT  
Hi Nickh,

We are using a solution to remove back button processing

What we are doing, we will genrate a key for a page.
 if you press back button, the key of page we will get.
since it's value is old key value, we will ignore it.  

 From: mbormann
 Date: Saturday, October 30 1999 - 05:36AM PDT  
What i feel is that once you force the browser to load the page everytime from the servlet by having these in servlet code

// the servlet-generated pages should not be stored on cache
pw.println("<META http-equiv=\"pragma\" content=\"no-cache\">");
pw.println("<META http-equiv=\"expires\" content=\"10-JAN-1980\">");

and then doing a session.invalidate(); on user's logout
(have a forced logout() in applet's destroy() )

is sufficient I think

BTW i have read here and there abt Netscape being bad so try to use the Plug in's VM.

 From: mbormann
 Date: Saturday, October 30 1999 - 07:15AM PDT  
You cab also manually invalidate the stale sessions.
See a nice example at

 From: NickH
 Date: Saturday, October 30 1999 - 03:54PM PDT  
Godo answers so far, and I did find out about setting the no-cache heading.  mbormann, to continue on your point ...

YOu mention having a forced logout in the applet destroy method...that is actually precisely what I am trying to do.  My situation is a little unusual...the applet is actually loaded as an HttpResponse from an authentication servlet, so the browser url still looks like the servlet, even though the applet is loaded.  When I try to send a post message to this authentication servlet, along the lines of your "logout" idea in the applet destroy method, I get the following stack dump :
 java.io.FileNotFoundException: brahms:80//servlet/ChatDispatch

and some other garbage.  Basically, it seems like the applet can't see the servlet that it is inside (i.e. ChatDispatch)!  Has anybody else run into this problem?  I can post to another servlet in that path just fine, but not the one I'm in.

 From: ravindra76
 Date: Saturday, October 30 1999 - 10:23PM PDT  
Hi NickH,

I faced the same problem prevoiusly when i don't know much about  java and webserver.

According to my view,

  your webserver is running on port 80.

 and your servlet is running on some another port which is not 80.

Suppose, it is 8080, then adjust your URL to


It will solve your problem.


 From: ravindra76
 Date: Saturday, October 30 1999 - 10:31PM PDT  

Hi NichK,

Sorry. I mistakenly submitted the answer.

 Instead of of submitting as comment, i submitted as answer.

It is just a comment and it is not a answer.

You may reject it for better commnets.

Thank you


 From: mbormann
 Date: Sunday, October 31 1999 - 07:45PM PST  
read Jason Hunter's Servlet Programing tutorial and u will get it as I think it has almost the same fact covered there.Sorry but i am rushed for time.

 From: mbormann
 Date: Sunday, October 31 1999 - 07:46PM PST  
see www.servlets.com and clicl on Chat chapter.

 From: NickH
 Date: Monday, November 01 1999 - 10:45AM PST  
ravindra:  That's an intriguing possibility.  I have to check this later on today, but I will respond tomorrow.  BTW, does it make sense that I could move to another servlet, but not post to the one that I'm currently running inside, based on your port explanation?

 From: ravindra76
 Date: Monday, November 01 1999 - 10:05PM PST  

Hi NickH.

You can send to same servlet also with some parameter .
Add a new paramer assume it is Type.

When you first login,  type=login
When you logout,     type=logout.

If you are using get, you can append to URL after ?type=Login

If type=Login, Your servlet executes one method and it type=logout, it  executes another method


 From: ravindra76
 Date: Monday, November 01 1999 - 10:10PM PST  
Hi Nickh,

 What is your environment?

 For servlets what are you running as server?

servletrunner or javawebserver or  IIS or .............. on what port?

If it is not servletrunner and it is a webserver, are you using same port for handling htmlpage requests and servlets?


 From: NickH
 Date: Tuesday, November 02 1999 - 04:44AM PST  
I am running IIS at home, PWS at work, both with JRun 2.3.3 as the servlet engine.  The servlet does not seem to be the problem, however, as otherwise, it seems just fine.  The problem is with the applet that is called from one of the servlets methods...basically, after login, ChatDispatch is called again to print the applet page.  Once the applet is loaded, however, I have not been able to post to ChatDispatch  again.  I can post to another servlet without difficulty from the applet, using sendPostMessage().  i think it has something to do with the fact that the servlet is active running an applet, and doesn't support a second request, or something along that line.  My other thought was to use appletContext.showDocument, but then I'd have to use get parameters, and I was hoping to only use Post.  Any ideas?  

 From: mbormann
 Date: Tuesday, November 02 1999 - 05:17AM PST  
>>>>Once the applet is loaded, however, I have not been able to post to ChatDispatch  again.

Whta is the exact problem?

>>>>> i think it has something to do with the fact that the servlet is active running an applet,and doesn't support a second request, or something along that line

Absolutely not.

what type of code are u using to communicate to Servlet? post it or tell us.

 From: ravindra76
 Date: Tuesday, November 02 1999 - 06:16AM PST  

 Hi NickH,

   It's beteer to post the code of applet and servlet as suggested by mbormann. It will give a clear picture about the problem

 From: NickH
 Date: Tuesday, November 02 1999 - 08:39AM PST  
I'm only rejecting this answer to get some more comments on the code I'm going to post...

 From: NickH
 Date: Tuesday, November 02 1999 - 08:52AM PST  
Okay, here is the relevant servlet (ChatDispatch) method that spawns the chat client (an applet):
  private void printAppletPage(HttpServletRequest req,
                               HttpServletResponse res, String method)
                    throws IOException {
    PrintWriter out = res.getWriter();
    log("printing applet page...");
    res.setHeader("Expires", "Tues, 01 Jan 1980 00:00:00 GMT");
    out.println("<HEAD><TITLE>An Simple Chat</TITLE></HEAD>");
    out.println("<H1>A Simple Chat</H1>");

    String user = req.getRemoteUser();
    if (user == null) {
      user = getParameter(req,"user");

    String applet = null;

    if ("http".equals(method)) {
      applet = "HttpChatApplet";

    else {
      // No method given, or an invalid method given.
      // Explain to the user what we expect.
      out.println("Sorry, this servlet requires a <TT>method</TT> " +
                  "parameter with one of these values: " +
                  "http, socket, rmi");
    String me = req.getServletPath();

    // Print the HTML code to generate the applet.
    // Choose the applet code based on the method parameter.
    // Provide a user parameter if we know the remote user.
    out.println("<BR><Table border = 2>");
    out.println("<TR><TD Align = Center>Chatting via " + method + "</TD></TR><TR></TR>");
    out.println("<TR><TD><APPLET CODE=" + applet + " CODEBASE=/ WIDTH=500 HEIGHT=170>");
    if (user != null) {
      String TCPNum = req.getRemoteAddr();
      out.println("<PARAM NAME=IP VALUE=\"" + TCPNum + "\">");
      out.println("<PARAM NAME=user VALUE=\"" + user + "\">");

Now when the user clicks on the applet's logout button, the following code should run:

        else if (event.target == LogoutButton) {
  ThreadContinue = false;
  ExplicitLogout = true;
  URL url = new URL(getCodeBase() + "servlet/ChatDispatch");
          URL url2 = new URL(getCodeBase() + "servlet/ChatServlet");
          HttpMessage msg = new HttpMessage(url2);
       Properties props = new Properties();
        props.put("action", "Logout");

  msg = new HttpMessage(url);
  props = new Properties();

As you can see, first I attempt to log out of the chat server, and that works.  When I try to execute the next sendPostMessage to ChatDispatch, however, Nothing happens, and  iget the error in the applet logs that I pasted in a few messages ago, along the lines of "address not found."  I tried changing to the specific port number of the servlet engine (8081) in the destination url.  I no longer got the error, but the page still didn't change.

Here is the code that is supposed to execute when the logout action is posted to the ChatDispatch servlet :

     else if ((action != null) && (action.equals("Logout"))) {
printWelcomePage(req, res);

With straight html forms, I know you can keep reposting to the same servlet and get different pages depending on the parameters you send.  It just seems that the applet is unable to execute a post command that moves the browser t oa new page.  

 From: ravindra76
 Date: Tuesday, November 02 1999 - 10:24PM PST  

Hi Nickh,

 8001 is your servlet port?

 From: mbormann
 Date: Tuesday, November 02 1999 - 10:56PM PST  
at first u do a >>>>session.invalidate();
and then u try to connect to servlet???.
That's ur problem

 From: NickH
 Date: Wednesday, November 03 1999 - 06:31AM PST  
   the servlet port is 8081

   Wha I left out was some log messages  I was using to debug...I put logging messages before invalidating the session, and it's never even getting to that call.

I've come up with a couple of work arounds, but the one stumbling block is this...even when I can move to a new page, the back button still allows me to view the new page...I'm using IE4 on NT Workstation running PWS.  I always include these two lines at the top of any html I retunr from a servlet:

    res.setHeader("Expires", "Tues, 01 Jan 1980 00:00:00 GMT");

It was my understanding that this code was supposed to prevent the page from being accessed by the back button.  When I work at home, using IIS on NT Server and IE4, those same lines of code cause the browser to return a data not found type page, but If a refresh, it still seems to be able to report the data.  What am I missing?

 From: ravindra76
 Date: Wednesday, November 03 1999 - 10:10PM PST  

Hi NickH,


URL url = new URL(getCodeBase() + "servlet/ChatDispatch");
                              URL url2 = new URL(getCodeBase() + "servlet/ChatServlet");

If you replace the code with

URL url = new URL(getCodeBase() + ":8081/servlet/ChatDispatch");
                              URL url2 = new URL(getCodeBase() + ":8081/servlet/ChatServlet");

Then what will happned?.

Your applets will execute on default port( I think it is 80 if you won't modify )

But servlets are running on 8081.

You have to mention that port to know to applet

Try with this.


 From: mbormann
 Date: Thursday, November 04 1999 - 09:58AM PST  
>>>>> Those same lines of code cause the browser to return a data not found type page, but If a refresh, it still seems to be able to report the data.

 Does this mean that by using those lines of code you can't see the the data page, but by using Refresh you can ???

 These lines actually tell the browser not to keep the page returned in cache, but to reload it from the server every time it is shown (via the back button or whatever) or when the specified date/time expires.

 BTW in the printAppletPage() method you are not closing the streams at all. Try using

 at the end of every method.

Accepted Answer
 From: mbormann
 Date: Thursday, November 04 1999 - 10:11PM PST  
Oops i forgot to add but if I recall correctly if u dont close the streams then as the connection is still alive in cases where the server supports Keep alive connections then the Applet can't post to that servlet since the connection is still there.

I am not entirely sure abt this but .....

 From: NickH
 Date: Wednesday, November 10 1999 - 11:24AM PST  
I think you ultimately hit the nail on the head.  I found that by using the appletcontext.showDocument method, I could actually do a GET as I wanted...maybe not the most elegant, but it served the purpose.  Also, as far as expiration, I foudn that the following 4 lines seem to do the trick as far as wiping pages from memory and cache...

res.setHeader("pragma", "no-cache");
res.setHeader( "Cache-Control","no-cache" );
res.setHeader( "Cache-Control","no-store" );
res.setDateHeader( "Expires", 0 );

I fixed my streams problem as well.  thanks for your effort.

 From: mbormann
 Date: Thursday, November 11 1999 - 12:01AM PST  
res.setHeader("pragma", "no-cache");
res.setHeader( "Cache-Control","no-cache" );
res.setHeader( "Cache-Control","no-store" );

pragma was intoduced in HTTP 1.0 for no cache option only.

Cache Control is for the same thing.But the next one is the one going to be considered i.e no -store.


Author Comment

ID: 2212211
I don't think this is really addressing my issue.  Perhaps I wasn't clear -- I'll try again.

Once a servlet checks an order-entry form for completeness, that servlet knows the relevant values needed for database manipulation.  Once it sends a confirmation page to the browser/client, is it possible for the user, by clicking a "submit" button on the html confirmation page, to tell the same servlet to go ahead and do the database processing, using the values it already knows from checking the initial form?  Again, I'm not using applets at all, and don't want to use them.  Is the servlet's destroy() method called after it generates the confirmation page, or is there some other reason that the user can not send the confirmation to the same servlet by clicking a "submit" button in an html form? (I tried to do this, but got a server error message.)



Expert Comment

ID: 2212880

Try to use JavaScript.
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.


Expert Comment

ID: 2213377
it seems that u r trying to use a server side include or JSP,right?

see if u can use something like this?in ur present Servlet ,have it like a servlet chain.

out.println("<FORM ACTION="+response.encodeUrl("/servlet/YourMainServlet")+" METHOD=POST>");

out.println("<p><BR><Font color=#800000>User ID :</font>&nbsp;&nbsp;<INPUT NAME=NameID SIZE=15>");

out.println("<p><BR><Font color=#800000>Password:<INPUT name=Passwd TYPE = PASSWORD SIZE=15>");

out.println("<p><INPUT TYPE=SUBMIT VALUE=Submit>");

in ur present servlet u would just call a servlet called as LoginServlet which would then call another one with method as post/get depends if u called it with get/post.

Accepted Solution

blairdye earned 300 total points
ID: 2213812
From what i understand from your problem,
1)you want to open a session specific to the person that logs in.
2)you want the same servlet to deal with several requests from several different pages what ever they may be.

Having done the same thing myself, i find the simplest method to address problem 2 is to send various parameters to the servlet depending on what you want the servlet to do. For example, in the first html/jsp the servlet call looks like this:


And in your second html/jsp your servlet call looks like this


(These are doGet requests, doPost is just as easy).
This means that you just need to act depending on what your toDo parameter is:
String action = (String)getParameter("toDo");



The problem 1 is a matter of opening a session for the user and recording session specific information in it.
(from memory)

HttpSession mySession = new HttpSession()
mySession.putValue("MySessionBean", MySessionBean)

and then later, to get this session information out

HttpSession mySession = new HttpSession()

Is that what you are asking?

Author Comment

ID: 2215065
I think that's what I want to do, yes.  I've never used beans, and don't know much about them (I'm only a novice), but it looks like your solution will probably work for my problem.  I see I have some more learning to do.


Author Comment

ID: 2215808
What package is HttpSession in?  I can't seem to find it in my documentation.



Author Comment

ID: 2215943
Nevermind -- my documentation is out-of-date.  I found it elsewhere.  Thanks anyway,


Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
A solution for Fortify Path Manipulation.
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Suggested Courses
Course of the Month7 days, 22 hours left to enroll

607 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question