By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
458,088 Members | 1,270 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 458,088 IT Pros & Developers. It's quick & easy.

JSP - Onchange Event - Logic problems refreshing selection

100+
P: 108
Greetings,

I'm slowly building up code to do the following:-
  • Display TWO selection option boxes (cascading).
  • If the FIRST selection option box changes then reload the jsp using onchange event (not changing the option box value on relaod i.e. not re-running the SQL query).
  • ONLY on initial entry should the form FIRST selection option box should be populated using JDBC SQL.
  • The SECOND selection option box can then be populated from the value of the FIRST selection option box.
  • Then when the selection is made from the SECOND selection option box display the correspong record details

My code was attempting to check the value of the option box and if it was null i.e. the first time the user had entered the screen then populate the Option value ELSE just forward its current Value which could be picked up by the SECOND selection box.

However I dont know how to check the Option value as I get the following error message:-

An error occurred at line: 12 in the jsp file: /examples/wk465682UserMenu.jsp
Generated servlet error:
The method getparameter(String) is undefined for the type HttpServletRequest

An error occurred at line: 12 in the jsp file: /examples/wk465682UserMenu.jsp
Generated servlet error:
OptionCategoryValue cannot be resolved

Expand|Select|Wrap|Line Numbers
  1. <!-- the % tag below is what is called a scriptlet tag - allows java to be embedded in the jsp -->
  2. <%@ page import="java.util.*" %>
  3. <%@ page language="java" %>
  4. <%@ page import="java.sql.*" %>
  5. <HTML>
  6. <H1>FAQ</H1>
  7. <% String  OptionCategory = null;%>
  8. <H3>Please choose a category</H3>
  9.  
  10. <FORM ACTION="wk465682UserMenu.jsp" METHOD="POST">
  11. <SELECT NAME="category" onChange="location.href='wk465682UserMenu.jsp?option='+this.value;">
  12.         <% 
  13.  
  14.             Connection conn = null, conn1 = null, conn2 = null;
  15.  
  16.             if (request.getparameter("OptionCategoryValue") == null)     
  17.             {                            
  18.                 try 
  19.                     {
  20.                         Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
  21.                         conn1 = DriverManager.getConnection("jdbc:odbc:FAQ"); 
  22.                     }
  23.                         catch (Exception e1)  {System.out.print(e1);}
  24.                     {
  25.                         try
  26.                             {  
  27.                                 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
  28.                                 conn2 = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver*.mdb)};DBQ=C:/ProgramFiles/Apache Software Foundation/Tomcat 6.0/webapps/2008-sem2/wk465682/FAQ.mdb");        
  29.                             }
  30.                                 catch (Exception e2) {System.out.print(e2);}
  31.                     }
  32.  
  33.         if(conn1 == null) conn = conn2;
  34.         else conn = conn1;
  35.  
  36.         PreparedStatement mystatement = conn.prepareStatement("SELECT category from category");
  37.         ResultSet result = mystatement.executeQuery();
  38.  
  39.         while(result.next()) { 
  40.                                 OptionCategoryValue=result.getString(1); %>
  41.                                 <OPTION VALUE=OptionCategoryValue><%out.println(OptionCategory);%></OPTION>
  42.                             <%}
  43.         } %>
  44.  
  45.     </SELECT>
  46. </FORM>
  47. </HTML>
Mar 15 '08 #1
Share this Question
Share on Google+
7 Replies


100+
P: 108
Expand|Select|Wrap|Line Numbers
  1.  if (request.getparameter("OptionCategoryValue") == null) 
should be getParameter

Now I get error message :-

An error occurred at line: 12 in the jsp file: /examples/wk465682UserMenu.jsp
Generated servlet error:
OptionCategoryValue cannot be resolved
Can any assist or offer advice, is it clear what I want to achieve overall?
Mar 16 '08 #2

Expert 100+
P: 785
Expand|Select|Wrap|Line Numbers
  1.  if (request.getparameter("OptionCategoryValue") == null) 
should be getParameter

Now I get error message :-



Can any assist or offer advice, is it clear what I want to achieve overall?
Yessir!

The error you get is because you used a new variable "OptionCategoryValue" and did not define it. You should change it to "String optionCategoryValue".
Please notice that I changed your variable name, starting with capital letter "O" to lowercase letter "o", see the java coding standards. Else you get yourself confused if you name it like java classes are named, but it's not a java class.

Second, what you code trying to achieve is: only reading the values from the database table and put it out as JSP. It doesn't do anything described in your list on top. So how comes? I mean you probably would not have listed these points which have nothing to do with the source code you listed if you don't need some help in that, too? Ok, here it goes:

First, load the data for your first option box only and keep the second option box empty. Then in an OnChange-event on the first option box, make an AJAX-request to load the data for the second option box and display it. Look for "prototype.js" in the internet, it will help you much for the AJAX functions.

By the way, if the data for all the options inside the boxes is very small (let's say less than 20000 characters), I would not "dynamically reload" it. You can just put all the data in one two-dimensional string array, and dynamically rebuild your second option box from there with clientside javascript.
Mar 16 '08 #3

100+
P: 108
Thanks for the reply I've fixed the code errors.

The code offers very little functionality at the moment as Im trying to build it up piece by piece so I can understand whats going on.

I was advised that the OnChange event would pass in the users selection and not re-populate the Option box.

I didnt see how this would work as I thought the Onchange would simply run all of the JSP again, Is this the case ??

Unfortunately I have been advised against using AJAX, without going into too much detail Im a university student and the module lecturer doesnt want any AJAX code (I dont think they will be able to understand it!!)


Expand|Select|Wrap|Line Numbers
  1. <!-- the % tag below is what is called a scriptlet tag - allows java to be embedded in the jsp -->
  2. <%@ page import="java.util.*" %>
  3. <%@ page language="java" %>
  4. <%@ page import="java.sql.*" %>
  5. <HTML>
  6. <H1>FAQ</H1>
  7. <% String  OptionCategory = null;%>
  8. <H3>Please choose a category</H3>
  9.  
  10. <FORM ACTION="wk465682UserMenu.jsp" METHOD="POST">
  11. <SELECT NAME="category" onChange="location.href='wk465682UserMenu.jsp?option='+this.value;">
  12.         <% 
  13.  
  14.             Connection conn = null, conn1 = null, conn2 = null;
  15.  
  16.             if (request.getParameter("OptionCategoryValue") == null)     
  17.             {                            
  18.                 try 
  19.                     {
  20.                         Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
  21.                         conn1 = DriverManager.getConnection("jdbc:odbc:FAQ"); 
  22.                     }
  23.                         catch (Exception e1)  {System.out.print(e1);}
  24.                     {
  25.                         try
  26.                             {  
  27.                                 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
  28.                                 conn2 = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver*.mdb)};DBQ=C:/ProgramFiles/Apache Software Foundation/Tomcat 6.0/webapps/2008-sem2/wk465682/FAQ.mdb");        
  29.                             }
  30.                                 catch (Exception e2) {System.out.print(e2);}
  31.                     }
  32.  
  33.         if(conn1 == null) conn = conn2;
  34.         else conn = conn1;
  35.  
  36.         PreparedStatement mystatement = conn.prepareStatement("SELECT category from category");
  37.         ResultSet result = mystatement.executeQuery();
  38.  
  39.         while(result.next()) { 
  40.                                 String OptionCategoryValue=result.getString(1); %>
  41.                                 <OPTION VALUE="OptionCategoryValue"><%out.println(OptionCategoryValue);%></OPTION>
  42.                             <%}
  43.         } %>
  44.  
  45.     </SELECT>
  46. </FORM>
  47. </HTML>
Mar 16 '08 #4

Expert 100+
P: 785
The code offers very little functionality at the moment as Im trying to build it up piece by piece so I can understand whats going on.
It will help you if you try to break down your code into small pieces instead of
doing it all in a big chunk.
For example in your code above, you should separate database logic from HTML logic.
That means you should have one method that returns all the values of your SQL-query in a string-array (or Vector of strings). This method should have a parameter that defines for which option box it should load the data.
Then you should have a second method where you pass the string-array, and it will return the HTML-code for the option box.
Then you should write a main method which calls these 2 other methods repeatedly. Like here:

Expand|Select|Wrap|Line Numbers
  1. String categoryArray[] = getOptionBoxData(categoryName);
  2. String categoryHtml = getHtmlCode(categoryArray);
  3. String subcategoryArray[] = getOptionBoxData(subcategoryName);
  4. String subcategoryHtml = getHtmlCode(subcategoryArray);
  5. out.print("please select category:");
  6. out.print(categoryHtml);
  7. out.print("<BR>\nplease select subcategory:");
  8. out.print(subcategoryHtml);
I hope you get the idea. If you start with this setup, you will be successful and ease your work.

I was advised that the OnChange event would pass in the users selection and not re-populate the Option box.
If you are not allowed to use Ajax or frames, you must always transmit the whole webpage which contains the 2 boxes, so you must always transmit the data for both boxes. If your teacher says, not to read the first option box data again from the database, then you must cache it. For example you can store the data for the first option box inside a static variable of your class.

I didnt see how this would work as I thought the Onchange would simply run all of the JSP again, Is this the case ??
Yes. You just submit the category and subcategory as variables of your URL request (either in a form or as URL-parameters), and then your JSP would bring back the HTML-code of a completely new page.

Unfortunately I have been advised against using AJAX, without going into too much detail Im a university student and the module lecturer doesnt want any AJAX code (I dont think they will be able to understand it!!)
I don't think so, I guess he thinks it's too difficult to understand for a beginner,that's why he doesn't want you to use it. Maybe you can try with frames then if he allows that: Put the second option box, (the subcategory box) in an <IFRAME> and then refresh this frame via javascript.
Footnote:
The method your teacher suggests and the "frame"-method are very old. They were used widely when clientside javascript and Ajax were not available in browsers. In the industry, nobody is developing this way anymore. I mean, for learning purposes, you should do what your teacher says. But if you have a job later on as a programmer, you should always use Ajax (if it's a large amount of data. Or if it's a small amount of data, maybe less than 20KB, load all the data inside an array only once, and dynamically recreate the second option box). The advantage of this is much less load for the server and a much faster navigation for the user.
So if you have some more time to spend after doing your task, you should try Ajax of your own, it's really worth it!
Mar 17 '08 #5

Expert 100+
P: 785
Please notice that I changed your variable name, starting with capital letter "O" to lowercase letter "o", see the java coding standards. Else you get yourself confused if you name it like java classes are named, but it's not a java class.
You did not take my advice. The name in your new code listing is not changed. Why?
I have 28 years experience of programming, and I tell you it's worth doing it, even if it looks unimportant! In general, code is reviewed by other programmers that come after you very often. Very often means roughly 10 to 100 times. If you don't stick to coding standards, you are wasting their time. So get used to it. Let me give you an example to understand the principle:
Let's say you have a cat and you call it "Dog" or "Doggy". If you now go on the street and call "Doggy come here!", everybody would expect a small dog to show up!
So just use the right naming conventions for classes and instance of classes, and your teacher and every programmer who reads your code to help you would be pleased!
Mar 17 '08 #6

100+
P: 108
You did not take my advice. The name in your new code listing is not changed. Why?
I have 28 years experience of programming, and I tell you it's worth doing it, even if it looks unimportant! In general, code is reviewed by other programmers that come after you very often. Very often means roughly 10 to 100 times. If you don't stick to coding standards, you are wasting their time. So get used to it. Let me give you an example to understand the principle:
Let's say you have a cat and you call it "Dog" or "Doggy". If you now go on the street and call "Doggy come here!", everybody would expect a small dog to show up!
So just use the right naming conventions for classes and instance of classes, and your teacher and every programmer who reads your code to help you would be pleased!
Ok Ok I now have all my jsp working.

I will now take the time to add appropriate comments, naming and formatting conventions.

Deadlines for uni meant I had to cut corners, but now I have time to sit down and properly review my code.

Your advice hasn.t fallen on deaf ears.

Thanks
Rob
Mar 17 '08 #7

Expert 100+
P: 785
Ok Ok I now have all my jsp working.

I will now take the time to add appropriate comments, naming and formatting conventions.

Deadlines for uni meant I had to cut corners, but now I have time to sit down and properly review my code.

Your advice hasn.t fallen on deaf ears.

Thanks
Rob
I am happy to hear that everything runs fine.
Sorry, I got a little excited about naming conventions. To my excuse I can only say that I experienced a lot of cases where wrong naming caused a lot of trouble. Just recently for example a new programmer used a variable name in his JSP page that exactly matched an existing class name. Then we needed to replace this class everywhere with a new improved class. But we have hundreds of files at work, so we used an automatic "replace every occurrence of the old class name with the new name, in all files". So also his variable got replaced. Unfortunately, the source code of a JSP page is only compiled when it is used, so we did not detect the error at once. But instead we got feedback of hundreds of angry users whose webpages were crashing and we had a *nice* debugging session during the night on the weekend until we found the error.
Mar 22 '08 #8

Post your reply

Sign in to post your reply or Sign up for a free account.