JDBC query theme in a JSP page

Hi, everyone
I tried to write JDBC query theme in a JSP page at MapViewer, but it did not work.
The following is the codes.
1.JDBC theme in a map request in XML
<theme name="jdbc_theme_contour">
<jdbc_query
datasource="spatial10g"
jdbc_srid="8703"
spatial_column="geom"
render_style="C.RED">
Select geom from contour where time='01-JUL-07'
</jdbc_query>
</theme>
2. JDBC theme in a JSP request.
"<theme name=\"jdbc_theme_contour\" >\n" +
" <jdbc_query \n" +
" jdbc_srid=\"" + srid + "\"\n" +
" datasource=\"" + dataSource + "\"\n" +
" spatial_column=\" geom \"\n" +
" render_style=\"C.RED\" >\n" +
" SELECT geom from contour where time='01-JUL-07' \n" +
" </jdbc_query> \n" +
" </theme> \n" +
I do not know whether the second form is right or not. I did not display the JDBC query in MapViewer. Does anyone know the second form is right? or Maybe give me a right form in a JSP request. (contour is a table , geom is the column of geometry attribute in contour)
Gengsheng

Hi
Here is the map request in JSP
// Construct a map request
mapRequest = "xml_request=" +
"<?xml version=\"1.0\" standalone=\"yes\" ?>\n" +
"<map_request \n" +
// " title=\"" + title + "\"\n" +
" datasource=\"" + dataSource + "\"\n" +
" basemap=\"" + basemap + "\"\n" +
" width=\"" + width + "\"\n" +
" height=\"" + height + "\"\n" +
" bgcolor=\"#FFFFFF\" >\n" +
" format=\"PNG_URL\" >\n" +
" <center size=\"" + size + "\">\n" +
" <geoFeature>\n" +
" <geometricProperty typeName=\"center\">\n" +
" <Point>\n" +
" <coordinates>\n" +
" " + cx + ", " + cy + "\n" +
" </coordinates>\n" +
" </Point>\n" +
" </geometricProperty>\n" +
" </geoFeature>\n" +
" </center>\n" +
"<themes> \n" +
(flood.equals("true")?
("<theme name=\"jdbc_theme_contour\" >\n" +
" <jdbc_query \n" +
" jdbc_srid=\"" + srid + "\"\n" +
" datasource=\"" + dataSource + "\"\n" +
" spatial_column=\"GEOM\"\n" +
" render_style=\"C.RED\" >\n" +
" SELECT * from contour where time='01-JUL-07' \n" +
" </jdbc_query> \n" +
     " </theme> \n") : "") +
     (waterdepth.equals("true")?
     (" <theme name=\"FLOOD.LINKS\" >\n" +
     " </theme> \n") : "") +
     " <theme name=\"net_theme\" user_clickable=\"false\"> \n" +
" <jdbc_network_query \n" +
" network_name=\"" + networkName + "\"\n" +
" network_level=\"1\" \n" +
" jdbc_srid=\"" + srid + "\"\n" +
" datasource=\"" + dataSource + "\"\n" +
(showlinks.equals("true")?
(" link_style=\"L.CRM_SROADS\"\n") : "") +
(showlinks.equals("true") && showdir.equals("true")?
(" direction_style=\"M.IMAGE105_BW\"\n" +
" direction_position=\"0.75\"\n" +
" direction_markersize=\"" + dirsize + "\"\n") : "") +
(showlinks.equals("true") && showlklabels.equals("true")?
(" link_labelstyle=\"" + lklbstyle + "\"\n" +
" link_labelcolumn=\"link_id\"\n") : "") +
(shownodes.equals("true") ?
(" node_style=\"M.CITY HALL 4\"\n" +
" node_markersize=\"" + nodesize + "\"\n") : "") +
(shownodes.equals("true") && showndlabels.equals("true")?
(" node_labelstyle=\"" + ndlbstyle + "\"\n" +
" node_labelcolumn=\"" + ndlbcolumn + "\"\n") : "") +
(showpath.equals("true") ?
(" path_ids=\"" + pathid + "\"\n" +
" path_styles=\"L.PH\"\n") : "") +
" asis=\"false\"></jdbc_network_query> \n" +
" </theme> \n" +
(runanalysis.equals("true") &&
(algorithm.equals("DIJKSTRA") || algorithm.equals("ASEARCH")) ?
(" <theme name=\"spath_theme\" user_clickable=\"false\"> \n" +
" <jdbc_network_query \n" +
" network_name=\"" + networkName + "\"\n" +
" network_level=\"1\" \n" +
" jdbc_srid=\"" + srid + "\"\n" +
" datasource=\"" + dataSource + "\"\n" +
" analysis_algorithm=\"" + algorithm + "\"\n" +
" shortestpath_style=\"L.DPH\"\n" +
" shortestpath_startnode=\"" + startnode + "\"\n" +
" shortestpath_endnode=\"" + endnode + "\"\n" +
" shortestpath_startstyle=\"M.STAR\"\n" +
" shortestpath_endstyle=\"M.CIRCLE\"\n" +
" asis=\"false\"></jdbc_network_query> \n" +
" </theme> \n") : "") +
"</themes>\n" +
"</map_request>\n";
in this request, other themes and JDBC network query theme work except the JDBC query theme. I guess the style or format in the following are not right.
" spatial_column=\" geom \"\n" +
" SELECT geom from contour where time='01-JUL-07' \n" +
Anyway, I hope you can give me instructions.
Gengsheng

Similar Messages

  • Paged query results in a JSP page

    Hi All,
    I have a requirement to display only a small number of records (say 50) in a JSP page at a time from a database query that returns more than 10,000 records. For accessing all the other records I have to provide links from the same page. I should be able to go to the first, last, next & previous sets of records at any time. Database is Oracle and the table I am using to query doesn't have a serial number column. Any easy way? Thanks Raj

    Hi Raj,
    There are two ways to handle it.
    One is to fetch the entire set of record from the Database and store the details in a Container which has session level context. But if the fetched size is higher then Session cannot hold that much amount of data.
    Alternatively you can go about fetching fixed chunks of data from the
    Database(preferably of size 50 to 100). This can be achieved using SQL queries. I have done this and seems to work pefectly in situations where large data available in Database has to be displayed pagewise to the users. (U will find the query in AskTom site of Oracle Corporation).
    Please revert back if any further help is needed in this regard.
    Ilamparithi

  • How do i display every 10 Records in my JSP page??

    Hi..
    I have developed one web-page which shows ALL employee records fetched from a employee table and display them in my JSP page.
    It has contain more than 1000's of records. I need to display first 10 Records in my page. There should be some 4 links below the records display which get me to see next 10 records or previous 10 records or first 10 records or Last 10 records.
    IS it possible in JSP??
    This is my sample code for your ref:
    <jsp:useBean id="empOperation" class="com.venki.gen.EmployeeOperation" />
    <html>
    <head>
         <title>Stardeveloper : DataAccess JSP Tag</title>
         <style>
         p, td { font-family:Tahoma,Sans-Serif; font-size:8pt;
              padding-left:15; }
         </style>
    </head>
    <body>
    <p align="center"><u>DataAccess JSP Tag</u></p>
    <%
         EmployeeList empList[] = null;
         empList = empOperation.getEmployees(empName);
    %>
    <table align="center" border="0" width="90%" cellspacing="2" cellpadding="2">
    <tr bgcolor="#CCDDEE">
         <td>EMPNO</td>
         <td>EMP Name</td>
         <td>DESIGNATION</td>
    </tr>
    <%if(empList!=null)
         for(int i=0; i<empList.length; i++)
          EmployeeList emp = empList;%>
         <tr bgcolor="#F7F7F7">
         <td><%= emp.getEmpNo() %></td>
         <td><%= emp.getEmpName() %></td>
         <td><%= emp.getEmpDesignation()%></td>
         </tr>
         <% }%>
    </table>
    </body>
    </html>
    It would be extremely useful,if i know the technique how to display every 10 Records thru JSP.
    Waiting for You people valuable reply and code!
    Regards
    venki

    I do it by pages. i.e. http://example.com/page.jsp?page=1 would show records 1-10, ?page=2 would show records 11-20
    let's pretend each record is identified by one field in the database, `id`
    then the SQL query you'd use to grab the records could be..
    SELECT * FROM `your_table` WHERE `id` >= (page*10) and <= (page*10+10)or this might even work:
    SELECT * FROM `your_table` ORDER BY `id` ASC LIMIT (page*10),10(all examples untested as I'm at work :P)

  • Convert jsp page into xml  or dom for search

    Hello everyone,
    I have to build an application that searches for message beans in all jsp page. I did it the traditional way, using scanner and string methods. Its working but its not perfect. So i want to convert all my jsp page into xml format and then process them. My jsp pages are quite complicated. I used some jars that convert them into jspx . But its not working. Please help
    Thanks in advance

    Well its like this.I need to develop a program that reads all the message bean keys.. We have lots of struts webapps. All messages in the jsp pages have been externalised and internationalised. Now i have to build a program that given a webapp path prints out all the message bean keys used in the webapp. I have developed the program using the Plexus Directory scanner to filter all the jsp pages and java util Scanner to read line by line and used String functions to search for keys.
    Now thats not the best soultion. The best way, imo, is to cinvert the jsp into xml pages and then we can parse the xml pages easily. The' problem is to find a way to convert the jsp pages(jstl +javascript) into xml.
    Can you help me out?
    Thanks

  • How to use a jdbc query result to redirect to a variable html page

    uh, my problem is that i'm making a servlet which should redirect to a variable html page based on jdbc query (I'm really sorry if this is not the correct forum to post it, but since it's jdbc i thought it was).
    Anyway, the problem is that when a string say, "mystring" is equal to the value in a column, say "column1" of the database then page should redirect to "mystring.html".
    Is this possible, if so then how?
    and if not then is there any other way to solve my problem?
    please, help!!
    thanks in advance.

    uh, since i've already asked man, please gimme an answer if you know, it'll be appreciated.
    OK, HERE'RE THE DETAILS:(as you requested them)
    i have an html page where there's a textfield say "t1", the value of that text field is sent to the servlet which compares the value of the field with the value in Database, say "db1" in column say "column1".
    if there's a value in the column matching the value inputted in the textfield, then i need the servlet to redirect to an html page of the same name as inputted in the textfield. Hope that helps you understand.....
    thanks in advance.......

  • JDBC-ODBC connectivity from JSP page

    hi
    i am trying to connect a jsp page with database using jdbc-odbc driver. i have created a dsn with the name 'test' that connects to a database 'test' in SQL server. the following lines has been added to the web.xml file placed in the \WEB-INF folder
    <context-param>
    <param-name>
    javax.servlet.jsp.jstl.sql.dataSource
    </param-name>
    <param-value>
    jdbc:odbc:text, sun.jdbc.odbc.JdbcOdbcDriver
    </context-param>
    i have also placed the rt.jar file in the \WEB-INF\lib folder. but, when i run the jsp page and ty to make any database interaction, an expection occurs
    java.lang.ClassNotFoundException : sun.jdbc.odbc.JdbcOdbcDriver
    please help

    I think you need to download the JDBC/ODBC driver jar file into your project. For example, if you need a JDBC driver for the Oracle database, you search google for 'oracle jdbc driver'. Its driver is something like classes14.jar. I suggest you create and test your database connection pool in a servlet so you will have an easier time debugging any issues in getting it to work.
    Also, as the previous post points out, JSP is for displaying data and submitting user input back to the servlet. Put all your business logic in the servlet, put any data you get from the database in request scope by the servlet, dispatch to the JSP page so it can be displayed. This is a crude example. For a better design read up on MVC (Model View Controller) design.

  • How to find the backend  SQL query of the JSP page in OIC

    Does anybody how the best way to find the backend SQL QUERY of OIV JSP page?

    How To Generate Trace Files in in HTML/JSP (using Profile Option)
    •     • Note: This requires proper responsibility to set SQL Initialization statement using Profile option.      
         Step 1.     Login to the desired Form application.     
         Step 2.     Select +Profile >> System ('Find System Profile Values' screen will pop up)     
         Step 3.     Check 'User' and Type in the Username (in which the account for that user will be trace)     
         Step 4.     Type 'Initialization%' in the Profile box and Hit 'Find' (Click here for preview.)     
         Step 5.     In the User box, type the following statement and Hit 'Save' (Click here for preview)
         BEGIN FND_CTL.FND_SESS_CTL('','','TRUE','TRUE','','ALTER SESSION SET TRACEFILE_IDENTIFIER = TESTING MAX_DUMP_FILE_SIZE = 5000000 EVENTS ='||''''||' 10046 TRACE NAME CONTEXT FOREVER, LEVEL 12'||'''');END;     
         Note:     specify any name you like to identify your trace, in this case, testing is the end name on the trace. You can also specify the amount of data allowable to be in the trace, in this case, 5000000 is the amount set. Make sure you hit 'Save' afterwards.[Quotes in the statement are all 'Single' quotes.]
              specifying TRACEFILE_IDENTIFIER value is mandatory when setting up the trace using the above profile option value
         Step 6.     Login to HTML / JSP page with username/password and start your flow. (Everything you do once login to HTML / JSP will get trace.)     
         Step 7.     Logout of HTML / JSP application once you completed with your flow.      
         Step 8.     Go back to the Profile option in the Form application and delete the Initialization SQL statement, and Hit 'Save'.     
         Step 9.     Log in to the database server or login server and retrieve your trace file.
         Identify and retrieve the trace file using the tracefile_identifier specified in Step 5.
         In this case the tracefile_identifier is “TESTING”. (Click here for Trace file locations) *     
         Note:     If you need to regenerate your trace or tracing a new flow, then repeat Step 1 to Step 8. To avoid self-confusion, choose a different name for your trace identifier everytime you set to trace.     
         Step 10.     See TKPROF section on how to format trace file into readable text.
         Trace Options Definition
         No Trace          Tracing is not activated
         Activities will not get traced.
         Regular Trace
         (Level 1)          Contains SQL, execution statistics, and execution plan.
         Provides execution path, row counts as well as produces smallest flat file.
         Trace with Binds
         (Level 4)          Regular Trace plus value supplied to SQL statement via local variables.
         Trace with Waits
         (Level 8)          Regular Trace plus database operation timings that the SQL waited to have done in order to complete, i.e. disk access.
         Trace with Binds and Waits
         (Level 12)          Regular trace with both waits and binds information.
         Contains the most complete information and will produce the largest trace file.
    ****Send me an email to [email protected],I will share the document with you.

  • What is the best way to output query result in jsp page?

    I have several pages with 2-3 queries on each one.
    My jsp pages call a class that I've created, the class will create a connection with the db, execute the query and returns the ResultSet to the jsp page. Then I iterate the RS on the jsp page.
    Is there a better way of sending the data back to the jsp? I was thinking of .xml.

    Send it back as a java.util.List, or some other Collection. Then iterate through the collection. My preference is to make a Bean of the date that represents a Row on the ResultSet and put those in the List. Then when we get to the JSP, iterate the List to get the beans, and call get methods to get the values...
      /* In a method that traverses ResultSet and fills a List of  beans... */
      List data = new ArrayList();
      while(results.next())
        MyBean mb = new MyBean();
        mb.setProperty1(rs.getString(1)); //But give properties good names
        mb.setProperty2(rs.getString(2)); //Not 'Property1 and Property2
        data.add(mb);
      return data;If you are using JSTL you can do something like this:
      <c:set var="myBeans" value="${theDbObject.results}"/> //Assuming the above method was called 'getResults()'
      <table>
      <c:forEach var="mb" items="${myBeans}">
        <tr><td>${mb.property1}</td><td>${mb.property2}</td>...</tr>
      </c:forEach>
      </table>

  • Can we place jsp pages on JAVA_TOP and access them from controllers

    can we place jsp pages on JAVA_TOP and access them from controllers from the same path?
    Soujanya

    Hi All,
    Can any one please resond to this thread for atleas discussion.We have folder on HTML top with all jsps.We want to move the folder from HTML top to some other TOP.We are planning to move them to JAVA_TOP.
    But we could not refer or call the file from JAVA_TOP.
    Any solution.
    Thanks
    Soujanya

  • How to query from view with parameter, only  when the JSP-page loading

    I use JSF/ADF BC, create two viewes:view1 and view2, in the JSP page the user press a button to query from the view1, but I hope the view2 can be queried only when the page loading, it have no relation with user-operator, and pass the column value of view2 into some variables, the view2 return one record.

    Hi -
    You may want to have a look at this other thread:
    Re: Execute ViewObject with Parameters at JSF Page Load?  JSF/ADF/BC 10.1.3
    John

  • Complex Query JSP page

    I have a JSP page where I want to display the results from a query with a parameter supplied by a form.
    The problem is, my query does not have a where clause but instead is a hierarchical query e.g.
    http://www.dbazine.com/mishra3.shtml
    SELECT LEVEL, EMP_NAME , EMP_ID, MGR_ID
    FROM EMPLOYEE
    START WITH MGR_ID IS :1
    CONNECT BY PRIOR EMP_ID = MGR_ID;
    Where :1 is where I want to put in a parameter.
    Can I do this using an ADF ViewObject and JSP page?
    I am open to design suggestions here.
    I have tried two naive ways of doing this which did not work.
    1. Just try to set the parameters before opening the page using a DataActionMethod that opens the page on success
    ViewObject vo = findViewObject("TrayTrackFwdHistory1");
    vo.setWhereClauseParam(0, my_parameter);
    vo.executeQuery();
    In this case, somehow the page errors out before the set method is invoked with a ":1 is not set as an input or output parameter"
    2. Simply drop and recreate the view object with the query parameter value inside it. e.g.
    ViewObject vo = findViewObject("TrayTrackRevHistory1");
    vo.remove();
    vo = createViewObjectFromQueryStmt("TrayTrackRevHistory1", sqlStr);
    vo.executeQuery();
    In this case I get the error
    Operation getCurrentRowSlot cannot be performed because the working set object is not bound. So somehow I have to reset the iterator binding for the JSP page I generated versus the above view?
    Any help much appreciated.

    So, I figured out the solution for this.
    The answer here was to set the parameter value in the prepareModel event before the page is loaded. It turns out that setWhereClauseParam seems to set a parameter even if it is not part of a where clause so e.g.
    protected void prepareModel(DataActionContext ctx) throws Exception {
    String manager= ctx.getHttpServletRequest().getParameter("manager");
    DCDataControl dc = ctx.getBindingContext().findDataControl("AppModuleDataControl");
    AppModule am = (AppModule)dc.getDataProvider();
    ViewObject vo = am.findViewObject("EmployeeManagers");
    vo.setWhereClauseParam(0, manager);
    vo.executeQuery();
    super.prepareModel(ctx);
    }

  • Can't visit jsp pages in 64 bit mode without first visiting them in 32 bit

    we have an application that we deployed into a standalone oc4j running on solaris 10 x86 sun workstation.
    Oc4j is run in 64 bit mode. After Oc4j is started, any jsp page we try to visit, the page fails to be shown and the
    below error is shown in the log:
    INFO: Unable to dispatch JSP Page : Exception:oracle.jsp.provider.JspCompileException: Errors compiling:/opt/oc4j/j2ee/home/application-deployment_
    s/App/App/persistence/_pages//_info_jspx.java
    Oct 17, 2009 1:46:41 PM oracle.jsp.logger.JspMessages infoCannotDispatchJspPage_
    INFO: Unable to dispatch JSP Page : Exception:oracle.jsp.provider.JspCompileException: Errors compiling:/opt/oc4j/j2ee/home/application-deployment_
    s/App/App/persistence/_pages//_info_jspx.java
    As a workaround to this issue, we had to visit every page in the application while oc4j is running in 32 bit mode and then restart OC4j in 64 bit
    mode. After this, we are able to successfully visit every jsp page. This is very painful as everytime we redeploy the application, we have to
    revisit all pages in 32 bit mode before we can revisit them in 64 bit mode.
    How can we avoid this painfull excercise of having to visit all pages in 32 bit mode in order to successfully visit them in 64 bit mode ?
    we are using:
    JDeveloper 10.1.3.2.9.4066 with JDK 1.5.0_06.

    Could be corrupted preferences.
    In the Finder, choose Go > Go to Folder from the menu.
    Type ~/Library/Preferences in the "Go to the folder" field.
    Press the Go button.
    Remove the  com.apple.logic.pro.plist  file from the Preferences folder. Note that if you have programmed any custom key commands, this will reset them to the defaults. You may wish to export your custom key command as a preset before performing this step. See the Logic Pro User Manual for details on how to do this. If you are having trouble with a control surface in Logic Pro.
    Be sure and use the ~ character in the path name.

  • Database query ResultSet from servlet to JSP page

              Hi there,
              I have an Access 2000 database. I am running Apache and Tomcat on Windows Me.
              I would like to know if it is possible for me to use a Servlet to search the
              database (I know this bit is possible!), but then I would like the servlet to
              forward to a jsp page which will then display the ResultSet that the servlet has
              retrieved, i.e. when forwarding from a servlet to a jsp, is it possible for the
              jsp page to have access to the servlet's data? I know that it gets access to
              the response and request objects, but what about a ResultSet?
              Sorry it this sounds a little silly - i am a bit of a newbie.
              Thanks in advance for your help,
              SJ
              

    HttpServletRequest.setAttribute let's you share data for a particular
              request. When you call forward you can store the resultset in the request.
              Make sure your JSP does close the result set though, because what you are
              trying to do doesn't sound good :)
              If you want to share data across the session, take a look at the HttpSession
              object.
              read through the servlet specification, it is fairly easy to read and will
              give you all the info you need
              Filip
              ~
              Namaste - I bow to the divine in you
              ~
              Filip Hanik
              Software Architect
              [email protected]
              www.filip.net
              "SJ" <[email protected]> wrote in message
              news:[email protected]...
              >
              > Hi there,
              >
              > I have an Access 2000 database. I am running Apache and Tomcat on Windows
              Me.
              > I would like to know if it is possible for me to use a Servlet to search
              the
              > database (I know this bit is possible!), but then I would like the servlet
              to
              > forward to a jsp page which will then display the ResultSet that the
              servlet has
              > retrieved, i.e. when forwarding from a servlet to a jsp, is it possible
              for the
              > jsp page to have access to the servlet's data? I know that it gets access
              to
              > the response and request objects, but what about a ResultSet?
              >
              > Sorry it this sounds a little silly - i am a bit of a newbie.
              >
              > Thanks in advance for your help,
              >
              > SJ
              

  • Problem in loading jsp page

    Hi ,
    I'm facing a problem in displaying a JSP page . I'm displaying records from the database on the page . I want to display only 20 records at a time . I have given the navigation facility for previous,first ,last ,next etc.
    I'm getting all the records at once and displaying them at once . But , I show only 20 records at a time ,hiding the remaining records .
    This works fine for less no . of records but for more records ,say 2000-3000 records , it gets quite slow as expected .
    I don't want to fire the query again .
    Is there any other way possible using this technique .
    It's very urgent . So kindly help .
    Thanks.

    Just get a scrollable ResultSet with the row amount for 1 page, e.g.
          * Returns a result set for the given query, that is read only and scrollable
         * (cursor can move forward and backward). The default fetch size is used and
         * can be changed anytime by calling resultSet.setFetchSize(newFetchSize).
         * <p>
         * Note: be sure that the used JDBC driver supports scrollable result sets via
         * <code>DatabaseMetaData.supportsResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE)</code>
          * @param select SQL select query.
         * @param fetchSize Number of rows to prefetch.
          * @return Scrollable, read-only result set.
        private ResultSet getScrollableResultSet(String select, int fetchSize) {
            ResultSet result = null;
            if (select != null) {
                try {
    //TYPE_SCROLL_SENSITIVE can throw SQLException "Unsupported syntax for refreshRow()" with the
    //current ORACLE driver (8.1.7.0.0).
    //                Statement stmt = createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
                    Statement stmt = createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
                    int maxRows = stmt.getMaxRows();
                    if (fetchSize < 0 || fetchSize > maxRows) {
                        fetchSize = 0; //ignore fetch size
                    stmt.setFetchSize(fetchSize);
                    long t = System.currentTimeMillis();
                    result = stmt.executeQuery(select);
                    logger.debug(select + (" ("+(System.currentTimeMillis() - t)+")"));
                    if (result == null) {
                        stmt.close();
                } catch (SQLException sqle) {
                    logger.error("Error getting scrollable ResultSet for '"+select+"'.", sqle);
                    throw new BavException(sqle);
            return result;
        }//getScrollableResultSet()and fetch the next/previous page records via the resultSets next()/previous() methods. But beware that the SQL statement doesn't use an ORDER BY or GROUP BY that needs to fetch all rows anyway.

  • Using an Array in a JSP page

    I am currently storing values from a database into an array
    im my servlet. I have a JSP page and I'm trying to set
    the datafields on this page to the values held in the array.
    I need to send the array from the servlet to the JSP page
    and then figure out how I retrieve it at the other end.
    Can anyone help????????

    Here's the code I'm using for my Sevlet:
    package SASSSpkg;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.*;
    import java.sql.*;
    import javax.swing.*;
    public class UserLogin extends HttpServlet{
         private Connection connection;
    private ResultSet resultSet;
         private Statement statement;
         public String getusername, getpassword, getdatabase;
         private String customerId;     
         private String title;
         private String firstName;
         private String secondName;
         private String surname;
         private String residentialAddress;
         private String dateOfBirth;
         private String correspondenceName;
         private String maritalStatus;
         private String gender;
         private String securityId;
         private String postCode;
         private String dateOfFirstContact;
         private String homeTel;
         private String businessTel;
         private String currentAddressEntryDate;
         private String nationalInsuranceNumber;
         private String dateLastUpdated;
         public ArrayList values = new ArrayList();
         public void init(ServletConfig config) throws ServletException
              super.init(config);
         public UserLogin()
         public void ConnectToDatabase() throws Exception
    String url = "jdbc:odbc:SASSS";
    String username = getusername;
    String password = getpassword;
    // Load the driver to allow connection to the database
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    connection = DriverManager.getConnection( url, username,
    password);
    catch (ClassNotFoundException cnfex)
    throw new Exception("cannot connect to database");
    catch (SQLException sqlex)
    throw new Exception("cannot connect to database");
    public void getResultSetData()
    try
    String query = "SELECT DISTINCT CUSTOMER_ID, TITLE, FORENAME1, FORENAME2, SURNAME, DATE_OF_BIRTH, CUSTOMER_SALUTATN, MARITAL_STATUS, GENDER, SECURITY_NAME, FIRST_CONTACT_DATE,POSTCODE, TELEX, DATE_AT_ADDRESS, NATIONAL_INS_NUM, ADDRESS.LAST_UPDATED, ADDRESS.TELEPHONE FROM CUSTOMER, ADDRESS, CUSTOMER_ADDRESS WHERE CUSTOMER.CUSTOMER_CODE = CUSTOMER_ADDRESS.CUSTOMER_CODE AND CUSTOMER_ADDRESS.ADDRESS_ID = ADDRESS.ADDRESS_ID";
    statement = connection.createStatement
    (ResultSet.TYPE_SCROLL_INSENSITIVE,
    ResultSet.CONCUR_UPDATABLE);                
    resultSet = statement.executeQuery(query);
    resultSet.first();
         for (int i = 0; i <= 16; i ++)
              values.add(resultSet.getString(i + 1));
              statement.close();          
    catch(SQLException sqlex)
    sqlex.printStackTrace();
         public void doPost(HttpServletRequest req, HttpServletResponse
    res)
              throws ServletException, IOException
         try{
                   boolean dbConnection;
                   // Get username and password from fields on web
    page
                   getusername = req.getParameter("UserName");
                   getpassword = req.getParameter("Password");
                   getdatabase = req.getParameter("Database");
                   PrintWriter output = res.getWriter();
                   res.setContentType("text/html");
                   if(getusername.equals("") || getpassword.equals
                   res.sendRedirect
    ("http://localhost:9080/SASSS/ErrorPage.jsp");
                   return;
                   else
                        ConnectToDatabase();
                        getResultSetData();
                        res.sendRedirect
    ("http://localhost:9080/SASSS/EmployeeDetails.jsp");
              catch(Exception ex) {
                   res.sendRedirect
    ("http://localhost:9080/SASSS/ErrorPage.jsp");          
         public void doGet(HttpServletRequest req, HttpServletResponse
    resp)
              throws ServletException, IOException
              req.setAttribute("myArrayList", values);
         public String getCustomerId()
              return customerId;
         public void setCustomerId(String Id)
              customerId = Id;
         public String getTitle()
              return title;
         public void setTitle(String theTitle)
              title = theTitle;;
         public String getFirstName()
              return firstName;
         public void setFirstName(String theFirstName)
              firstName = theFirstName;
         public String getSecondName()
              return secondName;
         public void setSecondName(String theSecondName)
              secondName = theSecondName;
         public String getSurname()
              return surname;
         public void setSurname(String theSurname)
              surname = theSurname;
         public String getResidentialAddress()
              return residentialAddress;
         public void setResidentialAddress(String theResidentialAddress)
              residentialAddress = theResidentialAddress;
         public String getDob()
              return dateOfBirth;
         public void setDob(String theDOB)
              dateOfBirth = theDOB;
         public String getCorrespondenceName()
              return correspondenceName;
         public void setCorrespondenceName(String theCorrespondenceName)
              correspondenceName = theCorrespondenceName;
         public String getMaritalStatus()
              return maritalStatus;
         public void setMaritalStatus(String theMaritalStatus)
              maritalStatus = theMaritalStatus;
         public String getGender()
              return gender;
         public void setGender(String theGender)
              gender = theGender;
         public String getSecurityId()
              return securityId;
         public void setSecurityId(String theSecurityId)
              securityId = theSecurityId;
         public String getPostCode()
              return postCode;
         public void setPostCode(String thePostCode)
              postCode = thePostCode;
         public String getDateOfFirstContact()
              return dateOfFirstContact;
         public void setDateOfFirstContact(String theDateOfFirstContact)
              dateOfFirstContact = theDateOfFirstContact;
         public String getHomeTel()
              return homeTel;
         public void setHomeTel(String theHomeTel)
              homeTel = theHomeTel;
         public String getBusinessTel()
              return businessTel;
         public void setBusinessTel(String theBusinessTel)
              businessTel = theBusinessTel;
         public String getCurrentAddressEntryDate()
              return currentAddressEntryDate;
         public void setCurrentAddressEntryDate(String
    theCurrentAddressEntryDate)
              currentAddressEntryDate = theCurrentAddressEntryDate;
         public String getNationalInsuranceNumber()
              return nationalInsuranceNumber;
         public void setNationalInsuranceNumber(String
    theNationalInsuranceNumber)
              nationalInsuranceNumber = theNationalInsuranceNumber;
         public String getDateLastUpdated()
              return dateLastUpdated;
         public void setDateLastUpdated(String theDateLastUpdated)
              dateLastUpdated = theDateLastUpdated;
    Here's the code I'm using for my JSP:
    <HEAD><SCRIPT type="text/javascript">
    <!--
    var _sstmrID = null;
    var _sstmrON = false;
    var _sspos   = 80;
    function _ScrollStatus(msg, delay)
    if (_sstmrON)
    window.clearTimeout(_sstmrID);
    _sstmrON = false;
    var statmsg = "";
    if (_sspos >= 0)
    for (s = 0; s < _sspos; s++)
    statmsg += " ";
    statmsg += msg;
    else
    statmsg = msg.substring(-_sspos, msg.length);
    window.status = statmsg;
    sspos = (-sspos > msg.length) ? 80 : _sspos - 1;
    fname = "_ScrollStatus('" + msg + "', " + delay + ")";
    _sstmrID = window.setTimeout(fname, delay);
    _sstmrON = true;
    //-->
    </SCRIPT><SCRIPT type="text/javascript">
    <!--
    function _ShowObj(lId)
    var ob;ob=new Array;
    var appVer=parseInt(navigator.appVersion);
    var isNC=false,isN6=false,isIE=false;
    if (document.all && appVer >= 4) isIE=true; else
    if (document.getElementById && appVer > 4) isN6=true; else
    if (document.layers && appVer >= 4) isNC=true;
    if (isNC)
    w_str = "document." + lId;ob[lId] = eval(w_str);
    if (!ob[lId]) ob[lId] = _FindHiddenObj(document, lId);
    if (ob[lId]) ob[lId].visibility = "show";
    if (isN6)
    ob[lId] = document.getElementById(lId);
    ob[lId].style.visibility = "visible";
    if (isIE)
    w_str = "document.all.item(\"" + lId + "\").style";ob[lId] = eval(w_str);
    ob[lId].visibility = "visible";
    function _FindHiddenObj(doc, lId)
    for (var i=0; i < doc.layers.length; i++)
    var w_str = "doc.layers.document." + lId;
    var obj;obj=new Array;
    obj[lId] = eval(w_str);
    if (!obj[lId]) obj[lId] = _FindHiddenObj(doc.layers[i], lId);
    if (obj[lId]) return obj[lId];
    return null;
    //-->
    </SCRIPT></HEAD>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
    <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
    <html:html>
    <HEAD>
    <%@ page
    language="java"
    contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"
    errorPage="ErrorPage.jsp"
    %>
    <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <META name="GENERATOR" content="IBM WebSphere Studio">
    <META http-equiv="Content-Style-Type" content="text/css">
    <LINK href="style.css" rel="stylesheet" type="text/css">
    <h2>
    <%@page import="SASSSpkg.UserLogin"%>
    <%@page import="java.util.*"%>
    <%@page import="javax.servlet.*"%>
    <%@page import="javax.servlet.http.*"%>
    <% UserLogin ul = new UserLogin(); %>
    <TITLE>SASSS Employee Details</TITLE>
    </HEAD>
    <BODY bgcolor="#c0c0c0"><FORM action="servlet/SASSSpkg.UserLogin" method="get">
    <%
    if (request.getAttribute("myArrayList") != null) {
    ArrayList Alist = (ArrayList)request.getAttribute("myArrayList");
    ul.setCustomerId(Alist.get(0).toString());
    else {
    response.sendRedirect("http://localhost:9080/SASSS/ErrorPage.jsp");
    %>
    <TABLE border="0" width="792" height="359">
         <TBODY>
              <TR>
                   <TD colspan="6" valign="middle" align="center" height="58"><B>Customer
                   Id</B> <INPUT type="text" name="customerId" size="20" maxlength="10"
                        disabled value='<%= ul.getCustomerId() %>'></TD>
              </TR>
              <TR>
                   <TD align="center" height="57" width="160"><SPAN
                        style="font-weight: bold"><B>Title</B><BR>
                   <SELECT name="title" size="1">
                             <OPTION><%= ul.getTitle()%></OPTION>
                             <OPTION>Mr</OPTION>
                             <OPTION>Mrs</OPTION>
                             <OPTION>Miss</OPTION>          
                   </SELECT></SPAN></TD>
                   <TD align="left" height="57" width="171"><SPAN
                        style="font-weight: bold"><B><STRONG>First Name</STRONG></B><BR>
                   <SCRIPT type="text/javascript">
    <!--
    _ScrollStatus("How cool is this", 2);
    //-->
    </SCRIPT><INPUT type="text" name="firstName" size="20" maxlength="25" value = '<%= ul.getFirstName() %>' ></SPAN></TD>
                   <TD align="left" height="57" colspan="2"><SPAN
                        style="font-weight: bold"><B>Second Name</B><BR>
                   <INPUT type="text" name="secondName" size="20" maxlength="25" value='<%= ul.getSecondName() %>'></SPAN></TD>
                   <TD align="left" height="57" colspan="2"><SPAN
                        style="font-weight: bold">Surname<BR>
                   <INPUT type="text" name="surname" size="20" maxlength="25" value='<%= ul.getSurname() %>'> </SPAN></TD>
              </TR>
              <TR>
                   <TD colspan="2" align="center" rowspan="3"><B>Residential Address</B><BR>
                   <TEXTAREA rows="7" cols="31" name="residentialAddress" ><%= ul.getResidentialAddress() %></TEXTAREA></TD>
                   <TD align="left" height="66" colspan="2"><B>Date of Birth</B><BR>
                   <INPUT type="text" name="dateOfBirth" size="20" maxlength="10" value='<%= ul.getDob() %>'></TD>
                   <TD align="left" colspan="2"><B>Correspondence Name<BR>
                   <INPUT type="text" name="correspondenceName" size="20" maxlength="25" value='<%= ul.getCorrespondenceName() %>'>
                   </B></TD>
              </TR>
              <TR>
                   <TD align="left" height="42" colspan="2"><B>Marital Status </B> <SELECT
                        name="maritalStatus" style="">
                        <OPTION selected><%= ul.getMaritalStatus()%></OPTION>
                        <OPTION>Divorced</OPTION>
                        <OPTION>Married</OPTION>
                        <OPTION>Seperated</OPTION>
                        <OPTION>Single</OPTION>
                        <OPTION>Widowed</OPTION>
                   </SELECT></TD>
                   <TD align="left" colspan="2"><B>Gender</B> <SELECT name="gender">
                        <OPTION><%= ul.getGender()%></OPTION>
                        <OPTION>Female</OPTION>
                        <OPTION>Male</OPTION>
                   </SELECT></TD>
              </TR>
              <TR>
                   <TD colspan="4" height="56"><B>Security
                   Id     </B><INPUT type="text" name="securityId"
                        size="20" maxlength="20" value='<%= ul.getSecurityId() %>'></TD>
              </TR>
              <TR>
                   <TD height="55" align="left" colspan="2" nowrap><B>
                      Post Code   </B> <INPUT type="text"
                        size="15" maxlength="8" value='<%= ul.getPostCode() %>' name="postCode"></TD>
                   <TD height="55" align="left" colspan="2"><B>Date of First Contact</B><BR>
                   <INPUT type="text" name="dateOfFirstContact" size="10" maxlength="10" value='<%= ul.getDateOfFirstContact() %>'>
                   </TD>
                   <TD height="55" rowspan="5" align="center" colspan="2"><SELECT
                        size="9" name="aditionalDetailForms">
                        <OPTION value="">Products Held</OPTION>
                        <OPTION>Employment</OPTION>
                        <OPTION>Dependants</OPTION>
                        <OPTION>Residential Details</OPTION>
                        <OPTION>Assets/Liabilities</OPTION>
                        <OPTION>Income/Commitments</OPTION>
                        <OPTION>Banks/Building Societies</OPTION>
                        <OPTION>Credit Cards</OPTION>
                        <OPTION>Leads and Follow ups</OPTION>
                        <OPTION value=""></OPTION>
                   </SELECT></TD>
              </TR>
              <TR>
                   <TD height="41" align="left" colspan="2" nowrap><B>   Home
                   Tel                         </B>
                   <INPUT type="text" name="homeTel" size="18" maxlength="14" value='<%= ul.getHomeTel() %>'></TD>
                   <TD height="41" align="left" colspan="2"><INPUT type="button"
                        name="lastAddress" value="Last Address"></TD>
              </TR>
              <TR>
                   <TD height="49" align="left" colspan="2" nowrap><B>   Business
                   Tel                  </B>
                   <INPUT type="text" name="businessTel" size="18" maxlength="14" value='<%= ul.getBusinessTel() %>'></TD>
                   <TD height="49" align="left" valign="bottom" colspan="2"><B>N.I.
                   Number</B></TD>
              </TR>
              <TR>
                   <TD height="42" colspan="2" nowrap><B>   Current
                   Address Entry Date  </B> <INPUT
                        type="text" name="currentAddressEntryDate" size="10" maxlength="10" value='<%= ul.getCurrentAddressEntryDate() %>'></TD>
                   <TD height="42" colspan="2"><INPUT type="text"
                        name="nationalInsuranceNumber" size="20" maxlength="9" value='<%= ul.getNationalInsuranceNumber() %>'></TD>
              </TR>
              <TR>
                   <TD height="44" colspan="2" nowrap><B>   Date Last
                   Updated                   </B>
                   <INPUT type="text" name="dateLastUpdated" size="10" maxlength="15" value='<%= ul.getDateLastUpdated() %>'></TD>
                   <TD height="44" align="left" colspan="2"><INPUT type="button"
                        name="directMailExclusions" value="Mail Exclu">    <INPUT
                        type="button" name="telephoneExclusions" value="Tel Exclu"></TD>
              </TR>
              <TR>
                   <TD height="44" align="left" colspan="6" nowrap>        <INPUT
                        type="submit" name="ok" value=" OK ">            <INPUT
                        type="button" name="forward" value=" >> ">            <INPUT
                        type="button" name="exit" value=" Exit ">            <INPUT
                        type="button" name="delete" value=" Delete ">            <INPUT
                        type="reset" name="refresh" value=" Refresh ">            <INPUT
                        type="button" name="help" value=" Help "></TD></TR>
    </TABLE></FORM>
    </BODY>
    </html:html>
    The problem is, I'm trying to store String values into an array,
    or a result set and then store them in the data fields on my jsp page.
    When I use my set method such as setCustomerId(values.get(0));
    it sets the variable customerId to the value I want but when I try to
    call the get method in the JSP page to assign it to the data field it
    will not retrieve it.
    Can anyone solve this, I've been at it for days now????

Maybe you are looking for