Solved

Trying to insert checkbox array into single DB cell.

Posted on 2006-11-12
19
229 Views
Last Modified: 2010-03-31
I have a servlet that retrieves all checked boxes of a certain name into an array (currently i have two set up below).  I want to convert that array into a String using comma delimitation and have it inserted into my DB.  I seem to be having a problem converting this string- the problem is my lack of know how.

I will post the important parts of my servlet so everyone can see how it looks.  This servlet might have some garbage code in there- i've been messing with this for hours trying to get it to work.

Thank you in advance to anyone who can get this working properly.  It's been a massive headache.


[code]
package savedata;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.*;

public class MandatoryServlet extends HttpServlet {
   public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Reading All Request Parameters";
    Enumeration paramNames = request.getParameterNames();
            while(paramNames.hasMoreElements()) {
              String paramName = (String)paramNames.nextElement();
              //out.println("<TR><TD>" + paramName + "\n<TD>");
              for(int count = 0; count<20; count++){
                    String[] exterior = request.getParameterValues("frmExterior"+count);

                                    if(exterior == null) {
                                    } else {
                                          for(int i=0; i<exterior.length; i++) {
                                                if(exterior.length != 0) {
                                                out.print("frm"+count +exterior[i] +",");
                                                getServletContext().setAttribute("foo", exterior);
                                                out.print(getServletContext().getAttribute("foo").setArray());
                                                }
                                          }
                                      }
                        
                    String[] fincancing = request.getParameterValues("frmFinancing"+count);
                                    if(fincancing == null) {
                                    } else {
                                          for(int i=0; i<fincancing.length; i++) {
                                                if(fincancing.length != 0) {
                                                out.print("frm"+count +fincancing[i] +",");
                                                }
                                          }
                                      }
                        }
                        break;
            
      
    }
      out.println("<a href=uadmin/b/requestdatafromservlettest.jsp>asdasd</a>");
  }

  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
    doGet(request, response);
  }
 
 
  public void insert() {
    Connection con = null;
      PreparedStatement prep = null;
      String sql = null;
      ResultSet result;
      

    try {
      Class.forName("org.gjt.mm.mysql.Driver").newInstance();
      con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jobprop?user=xxx&password=");

      if(!con.isClosed())
        System.out.println("Successfully connected to " +
          "MySQL server using TCP/IP...");
             
                          try
            {
            sql = "INSERT INTO form_main(username)VALUES(?)";            
            prep = con.prepareStatement(sql);
prep.setString(1, getServletContext().getAttribute("foo").setArray());
            prep.executeUpdate();
           }
           catch(Exception m)
           {
            System.out.print(m.getMessage());
           }

    } catch(Exception e) {
      System.err.println("Exception: " + e.getMessage());
    } finally {
      try {
        if(con != null)
          con.close();
      } catch(SQLException e) {}
    }
  }

 
}
[/code]
0
Comment
Question by:domoaarongato
  • 11
  • 8
19 Comments
 
LVL 16

Expert Comment

by:suprapto45
Comment Utility
I think that you can use String to accomplish that.

Are these the codes that you are talking about?

                 String[] fincancing = request.getParameterValues("frmFinancing"+count);
                              if(fincancing == null) {
                              } else {
                                   for(int i=0; i<fincancing.length; i++) {
                                        if(fincancing.length != 0) {
                                        out.print("frm"+count +fincancing[i] +",");
                                        }
                                   }

If so, can you tell me what the problem with the current codes?

David
                   
0
 

Author Comment

by:domoaarongato
Comment Utility
yes. that is the code im talking about.  I will also need to pass exteriors to the same row- but i figure that i can do that after i learn how to do this.

[code]
I cannot javac the above class because it throws the below error.
MandatoryServlet.java:31: cannot find symbol
symbol  : method setArray()
location: class java.lang.Object
                                        out.print(getServletContext().getAttribu
te("foo").setArray());
                                                                   ^
freeholdMandatoryServlet.java:79: cannot find symbol
symbol  : method setArray()
location: class java.lang.Object
prep.setString(1, getServletContext().getAttribute("foo").setArray());
                                   ^

[/code]


I don't even know if set/getAttribute is the correct way of going about this.
0
 
LVL 16

Expert Comment

by:suprapto45
Comment Utility
I am quite confused with your codes as well.

Why do you need to use getServletContext().getAttribute("foo").setArray()?

First, you have parsed all the information in your doGet method. If it works correctly, you can just pass the parameters to the insert() method. For example,

                 String fincancingResult = "";
                 String[] fincancing = request.getParameterValues("frmFinancing"+count);
                              if(fincancing == null) {
                              } else {
                                   for(int i=0; i<fincancing.length; i++) {
                                        if(fincancing.length != 0) {
                                        //out.print("frm"+count +fincancing[i] +",");
                                        fincancingResult  = "frm"+count +fincancing[i] +",";
                                        }
                                   }

                             insert (fincancingResult);

Then in your insert method,

public void insert(String fincancingResult) {

}

Now, the result is available to your insert method.

David
0
 

Author Comment

by:domoaarongato
Comment Utility
I was told that to pass a value to another method i may need to set and attribute.  i've since learned this is incorrect.

Can i pass more than one parameter to the insert() method?

I will try your code out very shortly.   I hope it works:)
0
 
LVL 16

Expert Comment

by:suprapto45
Comment Utility
Yes, why not?

For example,

String a = "David";
String b = "domoaarongato ";

insert (a, b);

then in your insert method,

public void insert(String a, String b) {
  // now you can access String a and String b.
}
0
 
LVL 16

Expert Comment

by:suprapto45
Comment Utility
>>"I was told that to pass a value to another method i may need to set and attribute."
You may need this if you want to send the values FROM your Servlet to your JSP or vice versa. However, your problem is on the Servlet itself so they all are in one *scope* so you should not sue set / get attribute
0
 

Author Comment

by:domoaarongato
Comment Utility
I seem to be getting an error when i javac
MandatoryServlet.java:81: cannot find symbol
symbol  : variable fincaningResult
location: class savedata.MandatoryServlet
prep.setString(1, fincaningResult);
                  ^


Thanks for the assistance so far. I appreciate it.
0
 
LVL 16

Expert Comment

by:suprapto45
Comment Utility
Is that fincaningResult or fincancingResult?

Is that typo?
0
 
LVL 16

Expert Comment

by:suprapto45
Comment Utility
Will be back later on....
0
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 

Author Comment

by:domoaarongato
Comment Utility
ahhm, typo...

one last thing. i trigger this insert via jsp. i normally use

<jsp:useBean id="save" class="savedata.MandatoryServlet" scope="session"/>
<% save.insert();%>

but this wont work anymore.

ive also tried <% save.insert(fincancingResult);%> and <% save.insert(String fincancingResult);%> with no luck.
0
 
LVL 16

Accepted Solution

by:
suprapto45 earned 500 total points
Comment Utility
Hi domoaarongato,

Now, your logic to parse this is on your doGet method and the doGet method will subsequently call the insert method. You do not need to call it directly from your JSP using the <jsp:useBean>. What you need to do now is to submit the form that goes to MandatoryServlet.

<form action="/MandatoryServlet" method="GET">
    <%-- All the HTML components here --%>

    <input type="submit" value="Submit">
</form>
0
 

Author Comment

by:domoaarongato
Comment Utility
Hmm. nothing is entering into the DB.

here's what i have
          sql = "INSERT INTO form_main(username)VALUES(?)";          
          prep = con.prepareStatement(sql);
          prep.setString(1, fincancingResult);
          prep.executeUpdate();


If i put something static into the setString the static value inserts..
0
 
LVL 16

Expert Comment

by:suprapto45
Comment Utility
Then,

Do a little debugging....

          sql = "INSERT INTO form_main(username)VALUES(?)";          
          prep = con.prepareStatement(sql);
 
          System.out.println("fincancingResult = " + fincancingResult);
          prep.setString(1, fincancingResult);
          prep.executeUpdate();

and see what does it print in the console?
0
 

Author Comment

by:domoaarongato
Comment Utility
actually, wait. a static value isnt inserting anymore.. hmm..
0
 
LVL 16

Expert Comment

by:suprapto45
Comment Utility
>>"actually, wait. a static value isnt inserting anymore.. hmm.."
It may be because the insert method is not executed at all. Okay, for ease, can you post your current Servlet and JSP so that I can inspect?
0
 

Author Comment

by:domoaarongato
Comment Utility
ok, i found the screw up. my mistake.  IT works!  but something is happening that i didnt account for.  It's inserting each value into the db one row at a time, so if i have three checkbox results, it puts them in three rows.

i'm giving you the 500 points for fixing my problem!  let me know if you don't get them.  ive never doen this before.

P.S let me know if you have a solution for the seperate rows prolblem.
0
 
LVL 16

Expert Comment

by:suprapto45
Comment Utility
>>"ok, i found the screw up. my mistake.  IT works!"
:)

>>"It's inserting each value into the db one row at a time, so if i have three checkbox results, it puts them in three rows."
Then, I'll be asking you.

What is the purpose of "for(int count = 0; count<20; count++){"?
0
 

Author Comment

by:domoaarongato
Comment Utility
That is to set how many times it can loop. i set it to 20 incase there are ever 20 options selected.  Ideally that should be dynamic- but i didnt know how to do it so i made it a static 20. if i need to make it mroe later i can change the 20 to something higher.
0
 
LVL 16

Expert Comment

by:suprapto45
Comment Utility
I think that the solution to your problem would be bringing out the insert method from this for loop.

I can't help much now as I have something to do. You may be interested to open up another question so other experts can help you or I can pop in later on

David
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
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 …

744 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

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now