?
Solved

Auto-submit a form on a jsp page

Posted on 2005-03-14
12
Medium Priority
?
3,844 Views
Last Modified: 2008-01-16
Hi all,

I have a jsp form. The requirement is that it gets all the details from a servlet and displays on the jsp form page. This has to be done for more than 100 users and it should be automatic. ALso all the information displayed in the text boxes should be submitted automatically to a servlet without any user intervension. How can this be done.
Actually I have got a jsp form to get the details for 10 users (for example) and I use meta-tag refresh and display the details.
The next part is I have the script
<script language="JavaScript" type="text/javascript">
//document.frmServeBetter.action = /test/ctrl?do=SUBMIT";// This should go to a servlet
    document.frmServeBetter.submit();
    </script>
at the bottom of the page, ie after the </form> tag.


But how can I integrate this?

But even when I dont have the meta tag refresh, all the 10 users are displayed and the loop wont stop. Please can you go thru my jsp code and let me know where I am wrong.
Thanks for the help.



JSP FILE
---------

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD><TITLE>Information</TITLE>
<META http-equiv=Content-Type content="text/html; charset=iso-8859-1">
<LINK href="/test/images/survey_StyleSheet.css" type=text/css rel=stylesheet>
<META content="Microsoft FrontPage 5.0" name=GENERATOR>
<!-- <meta http-equiv="refresh" content="5"> -->

<%@page import="java.lang.*"%>
<%@page import="java.util.*" %>

<%  String strCaller = new String(request.getRemoteHost());%>
<script>
function fnSubmit()
{
    alert("Inside fnSubmit: ");
   
     document.frmServeBetter.action = "/test/ctrl?do=SUBMIT";
      
      document.frmServeBetter.submit();
   
}

</script>

</HEAD>

<BODY>
<form name="frmServeBetter" method="post" >

<%

 HashMap objHashMap = new HashMap();
 ArrayList objArrayList = new ArrayList();
 
 //objHashMap = (HashMap)request.getAttribute("DETAILS");
 
 objArrayList = (ArrayList)request.getAttribute("DETAILS");
 
%>

<%!
static int size = 10;
 static int counter = 0;
 static int counter1 = 0;
%>

<INPUT TYPE=hidden Name="Caller" value=strCaller>


<TABLE class=content borderColor=#FEE25B cellSpacing=0 cellPadding=0 width=700
border=1>
  <TBODY>
 
 
  <TR>
 
      <TD vAlign=top align=middle height=353>
        <table width="650" border="0" cellspacing="0" cellpadding="5">
       
           
          <tr>
            <td height="351" align="center" valign="top" bgcolor="#FFFced">
              <TABLE cellSpacing=0 cellPadding=3 width=700 border=0>
                <TBODY>
                  <TR>
                    <TD colspan="2" class=content><img src="/test/images/space.gif" width="5" height="8"></TD>
                  </TR>
                 
                  <TR class=content>
                    <TD height=14 colspan="2"><img src="/test/images/space.gif" width="5" height="8"></TD>
                  </TR>
                 
                 <%
                   while(counter < size)
                   {
                     objHashMap = (HashMap)objArrayList.get(counter);
                 %>
                  <TR>
                    <TD class=content height=25><font color="#FF0000">FirstName :</TD>
                   
                 
                    <TD> <INPUT class=field value = "<%=objHashMap.get("FIRSTNAME")%>" name="FirstName" size="20" ></TD>
                 
                    <TR>
                  <TD class=content height=25><font color="#FF0000">LastName :</TD>
                  <TD> <INPUT class=field value = "<%=objHashMap.get("LASTNAME")%>" name="LastName" size="20"></TD>
                  </TR>


                  <TR>
                  <TD colspan="2"><img src="/test/images/space.gif" width="5" height="8"></TD>
                  </TR>
                  <TR>
                  <TD class=content><font color="#FF0000">EMail Address :</TD>
                  <TD> <INPUT class=field value = "<%=objHashMap.get("EMAIL")%>" name="EMailAddress" size="20"></TD>
                     </TR>
                 
                  <%
                   
                    counter ++;
                   %>
                   
                    <%
                    break;
                    }//whileloop
                    %>
                  </TR>
                 
                 
                  <TR>
                 
                 <TD class=content height=24><INPUT class="btn" type="Reset"   value=Cancel name="B1"></TD>
                  </TR>
                  <TR>
                    <TD class=content colSpan=2 height=24>&nbsp;</TD>
                  </TR>
                </TBODY>
              </TABLE>
            </td>
          </tr>
        </table></TD></TR></TBODY></TABLE>
<p>&nbsp;</p>

</form>
<script language="JavaScript" type="text/javascript">
//document.frmServeBetter.action = "/test/jsp/test1.jsp";
    document.frmServeBetter.submit();
    </script>


</BODY>
</HTML>

---------------------------------------------------------------

Thanks once again. If you didnt understand any part, please let me know.
0
Comment
Question by:Vjy
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 5
12 Comments
 
LVL 27

Expert Comment

by:BigRat
ID: 13534736
This bit of code in the HTML :-

<script language="JavaScript" type="text/javascript">
//document.frmServeBetter.action = "/test/jsp/test1.jsp";
    document.frmServeBetter.submit();
</script>

gets parsed when the page loads. When the "OnLoad" page event occurs this code gets executed and the code simply causes a submit to occur and to the address given in the "ACTION" atrribute of the form (or what you set dynamically).

Now my first question is what is the URL of this HTML (=JSP) page?
My second question is what is the URL to which the data in this page is going to be posted? If these two are the same a loop will occur.

0
 

Author Comment

by:Vjy
ID: 13541752
Dude,
Thanks for your reply, but I will not be able to work on what you told for now as I am told to do this in a different way, but sure I will do this at my house whenever time permits.

Now what my people said to me is that, they want to retrieve all the details from our databse and submit it to another website and submit that data to the other site.

I will explain my work, so no one thinks I am submitting personal information or giving out details.

We are a travel agent software developer, we ourselves are a agent. So whatever data the user submits to us, we need that data to be submitted to our parent company or the agency. Like if its airtickets, we collect all details and submit the details to Delta, Continental, AA or other airline site. Likewise in cruises also. Hope you get what I am saying.

So now I am retreiving all the data, our customers had entered in our form from the database. But how can I get all the data to be submitted to other site. The exact details ahould be given.
Suppose if I get the first name, the exact data in the first name column should be submitted in the first name column of the other site. Am I making any sense.
Can this be done. I have no idea how to start. Any help would be appreciated.
Thanks

p.s Should I post this in a new topic or can I continue in this, moderators can help me in this. Thanks
0
 
LVL 27

Expert Comment

by:BigRat
ID: 13543321
The usual way of doin g this is with server side code which connects to the third party's machine and POSTs data to a URL. The major problem with that however, is if the third party does not respond you have no way of really repeating the action, since it was started on storing into your database.

The correct way is to use a server system which queues such messages up and guarentees delivering them by retrying. Systems like Microsofts BizTalk provide such functionality.

Your way of extracting the data into an auto-submit HTML form is OK provided that when you have submitted the third party returns a reasonable URL. If not it can get into a loop.

Under those circumstances it might be better to collect the data in a form and use Javascript to "submit" the form to both sites. This works by creating an XML object, adding the forms parameters as POST (or GET) data and then calling the XML.Load() method. Ideally the third party should return XML data, so you should look into whether the sites, to whom you submit data, actually have some sort of XML interface - at least as far as returning whether the data was successfully registered or not.
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

Author Comment

by:Vjy
ID: 13555435
Thanks for the reply dude. But I have to assume that the other side return a valid response.

The Code I used is

----------------------------------------------
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.*;

public class FormDemo
{


    static final String LOGON_SITE = "localhost";



    static final int    LOGON_PORT = 8080;

    public FormDemo() {
        super();
    }

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

        HttpClient client = new HttpClient();
        client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT, "http");

        GetMethod authget = new GetMethod("/test/jsp/test.jsp");

        client.executeMethod(authget);
        System.out.println("Login form get: " + authget.getStatusLine().toString());
        // release any connection resources used by the method
        authget.releaseConnection();


        PostMethod authpost = new PostMethod("/test/jsp/test.jsp");
        // Prepare login parameters
        NameValuePair action   = new NameValuePair("FirstName", "Vijay");
        NameValuePair url      = new NameValuePair("LastName", "Chinna");
        //NameValuePair action1   = new NameValuePair("Vijay", "FirstName");

        //NameValuePair userid   = new NameValuePair("UserId", "userid");
        //NameValuePair password = new NameValuePair("Password", "password");
        authpost.setRequestBody(
          new NameValuePair[] {action, url});

        client.executeMethod(authpost);
        System.out.println("Login form post: " + authpost.getStatusLine().toString());
        // release any connection resources used by the method
        authpost.releaseConnection();

        // Usually a successful form-based login results in a redicrect to
        // another url
        int statuscode = authpost.getStatusCode();
        System.out.println("statuscode: " + statuscode);

        if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) ||
            (statuscode == HttpStatus.SC_MOVED_PERMANENTLY) ||
            (statuscode == HttpStatus.SC_SEE_OTHER) ||
            (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT) ||
            (statuscode == 200)) {
            Header header = authpost.getResponseHeader("location");
            System.out.println("Header : " + header);

            String newuri = "http://localhost:8080/test/jsp/test1.jsp?FirstName=Vijay&LastName=Chinna";

            System.out.println("Redirect target: " + newuri);
                                  GetMethod redirect = new GetMethod(newuri);

                                  client.executeMethod(redirect);
                                  System.out.println("Redirect: " + redirect.getStatusLine().toString());
                                  // release any connection resources used by the method
                redirect.releaseConnection();

            /*if (header != null) {
                //String newuri = header.getValue();
                 System.out.println("Redirect target(newuri): " + newuri);

                if ((newuri == null) || (newuri.equals(""))) {
                    newuri = "/";
                }
                System.out.println("Redirect target: " + newuri);
                GetMethod redirect = new GetMethod(newuri);

                client.executeMethod(redirect);
                System.out.println("Redirect: " + redirect.getStatusLine().toString());
                // release any connection resources used by the method
                redirect.releaseConnection();
            } else {
                System.out.println("Invalid redirect");
                System.exit(1);
            }
            */
        }
    }
}
----------------------------------------------------------------

The jsps are

test.jsp
========
<html>
<head>

<script>
function fnSubmit()
{
    alert("Inside fnSubmit: ");
 
        //document.frm.action = "/test/ctrl?do=SUBMIT";
       
        document.frm.action = "/test/jsp/test1.jsp";
      //document.frm.submit();
   
}

</script>

</head>
<body onload="document.frm.submit()" > 
<!--<body> -->
<!-- <form name="frm" method="post"  onload="document.frm.submit()">-->

<!--<form name="frm" method="post"  onload="fnSubmit()" action="JavaScript:fnSubmit()" >-->

<form name="frm" method="post" action="http://localhost:8080/test/jsp/test1.jsp" >

<%

System.out.println("I am Inside test.jsp");
   String strFName = request.getParameter("FirstName");
   String strLName = request.getParameter("LastName");
   
   System.out.println("strFName Inside test.jsp: "+strFName);
   System.out.println("strLName Inside test.jsp: "+strLName);

%>

First Name
<INPUT class=field name="FirstName" value = <%=strFName%> size="20">

Last Name
<INPUT class=field name="LastName" value = <%=strLName%> size="20">

<INPUT class="btn" type="button"  value=Submit name="B1" onClick="fnSubmit();">

</form>
</body>


</html>

----------------------------


test1.jsp
=========
<html>
<head>

<script>
function fnSubmit()
{
    //alert("Inside fnSubmit: ");
 
        document.frm.action = "/test/ctrl?do=SUBMIT";
      document.frm.submit();
   
}

</script>

</head>
<body>
<form name="frm" method="post" >
<%
   System.out.println("I am Inside test1.jsp");
   String strFName = request.getParameter("FirstName");
   String strLName = request.getParameter("LastName");
   
   System.out.println("strFName Inside test1.jsp: "+strFName);
   System.out.println("strLName Inside test1.jsp: "+strLName);
%>
Thanks
</form>
</body>


</html>

-----------------------------------------------------

This works ok. But I need to give
String newuri = "http://localhost:8080/test/jsp/test1.jsp?FirstName=Vijay&LastName=Chinna";

to make it work. If not its not working proper, ie, even though the test.jsp should goto test1.jsp automatically, it doesnt go. But when I just goto test.jsp directly, it takes me to test1.jsp.

What am I missing?


Also, now these are my jsps, so I can change it in anyway I want to get the parameter values. But how will i do that in other sites?

I know the method and action of the other site, but if I pass the values as I did now, will it work? But how will I make it to submit.
Thanks for the help

0
 
LVL 27

Expert Comment

by:BigRat
ID: 13557114
public class FormDemo is a program (because it contains a static method called main).

This program constructs an HTTP request and fetches the HTML code for /test/jsp/test.jsp on localhost.

The returned HTML code has two input boxes containing text from the request (they were sent as parameters) and a Javascript function. The javascript will NOT be executed.

The program, having checked a 200 reqponse code, constructs a redirect with GET (not POST) :-

        GetMethod redirect = new GetMethod(newuri);
        client.executeMethod(redirect);

so the data will not be posted. In any event the data returned from the first HTTP call (the POST) is discarded.

If I were a little clearer on what you are trying to achieve, rather than how, I might be better able to help you.

As I understand it you want to get data from one server, collect it all together, and send it to another server. Am I right?
 
0
 

Author Comment

by:Vjy
ID: 13557623
Yes,
I want to get data such as First Name, Last Name, reservation No. and so on from my database, then submit it in a 3rd party i.e my Agencies Site. This has to be done automatically. Also, if there are any errors, i.e the enterred details are wrong, then it should throw an exception. When we submit the data, the 3rd party site will check the validitiy of my data and will accept or throw an exception.

How can go about this? There is also no chance of making changes in the 3rd party site.

Thanks for the help
0
 
LVL 27

Expert Comment

by:BigRat
ID: 13564874
>>When we submit the data, the 3rd party site will check the validitiy of my data and will accept or throw an exception.

No, when you submit the data by HTTP the 3rd party site will check the data and will return some indication of failure - this could be the original form.

 For example, if http://somehost/dir/enterform.html has three fields on it and one of them is in error, the site *could* send the same form back with that field blank, or it could send a modified form back with a text area in, say, red asking you to fill in the form again.

Therefore it is necessary to know what is returned when a URL is submitted both when the data is OK and when the data is wrong. At least in the error case you can then "throw an exception".

This is why I asked whether the third party supports an XML interface. If so they usually send XML data containing the error message or OK. It is then very easy to tell whether the submission was successful.

So, to whom are you submitting the data and what do you get back?
0
 

Author Comment

by:Vjy
ID: 13590450
Dude,
Sorry for the late reply, was help up. I need to submit the form to https://secure.royalcaribbean.com/beforeyouboard/boardingDocuments.do;jsessionid=0000uiFXHpL3JYMiotE_m0DJnAH:v2mocajr?cS=NAVBAR.
I need to pull up the data from my database and submit the data in that fields.

How should I go about it now.
Thanks for ur time dude.
0
 

Author Comment

by:Vjy
ID: 13651105
Any suggestions, still I am working with this.

Thanks
0
 
LVL 27

Accepted Solution

by:
BigRat earned 400 total points
ID: 13660596
It seems that when you go to this site you need to get a new session ID. The form presented seems to take the following :-

action = https://secure.royalcaribbean.com/beforeyouboard/processBookingLookup.do;jsessionid=0000Gq2VUyHwr7YHWq4cp4VpUVr:v2mocajr

fields :-

offlineBooking=Y
lastName = ????
bookingId=????
departureDay= one of the day options
departureMonth= one of the month options
departureYear= one of the year options
shipCode= one of the options in the select

Now when this data is submitted the server will respond with something and you'll need to know exactly what comes back so as to be certain that the information has been accepted properly.

As far as sending this information using the MS XML HTTP object is probably the best way to go, since it handles https.  You might also be able to do this with Visual Basic. In any event you construct a POST string by concatenating the parameters together :-

    poststr = 'offlineBooking=Y&lastName=' + escape(RS.lastname) +
                   '&bookingId=' + escape(RS.bookingId) + etc.....

and then post it with the HTTP object.

This is of course NOT the correct way of doing this. The secure site ought to have a programmable interface.  
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

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

In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
Suggested Courses

777 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