Link to home
Start Free TrialLog in
Avatar of aman0711
aman0711

asked on

confused over a silly problem

Hi Experts,

          I am real confused with this problem. I have all the code yet I dont know how to
              get this fixed.

              so the scanrio is:

              In the snapshot you can see a form. The "Transaction" dropdown has two values:
              "Add Note", "Update Note".

              If user picks "Add Note", a simple insert statement is invoked and this part is working fine.

              When the user picks "Update Note", the page refreshes and the notes already present in the
              database are display (Shown in the snapshot).

               So in my Servlet, I had this piece of code:

            if (transType.equalsIgnoreCase("Add Note")) //TRANSACTION TYPE IS "Add Note"
                {
                        nt.addNotes(noteInfo); //invoke addNotes method in notes class
                  }
                  else {
                        list =  nt.updateNote(); // invoke updateNote method and return the table
                        getServletContext().setAttribute("notesTable", list);
                  }
            

          Now the place where I am confused is:

              Once this table is displayed after picking "Update Note" dropdown, User can click on anyone
              of the check boxes and update that particular note.

              I have posted my Notes.java class, where I have a condition inside addNote() for insert and update
              query (I know the update query wont make any sense in this method).

              updateNote() is right below it which returns the already present notes in database.

              How do I solve this problem?
package com.si.dao;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.Vector;
 
import com.si.admin.Note;
import com.si.admin.NoteTable;
import com.si.dao.DbConn;
 
 
public class Notes {
	
//	prod
	String url = "jdbc:oracle:thin:@xyz12.abcd.com:1522:td08";
	String user = "user1";
	String password = "pass1";
	String driver = "oracle.jdbc.driver.OracleDriver";
 
 
	 Connection conn= null;
     PreparedStatement pstmt = null;
     Statement stmt = null;
 	 ResultSet rs = null;
	
     DbConn db = null;
        
       public String addNotes(Note noteInfo) {
    	 
    	   System.out.println("Inside Add Note method");
    	   
    	 String fromDate = noteInfo.getFromDate();
    	 String toDate = noteInfo.getToDate();
    	 String placement = noteInfo.getPlacement();
    	 String note = noteInfo.getNotes();
    	 String transaction = noteInfo.getTransType();
    	 String attuid = noteInfo.getAttUid();
    	     
    	 
    	 if (transaction.equalsIgnoreCase("Add Note"))
    	 {
    	 
      	 String qry = "INSERT INTO SIWEB_NOTES(PLACEMENT, FROM_DATE, TO_DATE, NOTE, CREATED_BY) VALUES (?,?,?,?,?)";
      	 
    	     try {
    	    	 
    		  db = new DbConn();
    		  Class.forName(driver);
    		  conn = DriverManager.getConnection(url, user, password);
    		  pstmt = conn.prepareStatement(qry); 
    		  
    		  
    		  
    		  SimpleDateFormat df=new SimpleDateFormat("MM/dd/yyyy", Locale.US);
    		  
    		   java.util.Date sqlFromDate=null;
    		   java.util.Date sqlToDate=null;
			try {
				 sqlFromDate = df.parse(fromDate);
				  sqlToDate = df.parse(toDate);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    		  
    		   
    		   pstmt.setString(1, placement);
    		   pstmt.setDate(2, new java.sql.Date(sqlFromDate.getTime()));
    		   pstmt.setDate(3, new java.sql.Date (sqlToDate.getTime()));
    		   pstmt.setString(4, note);
    		   pstmt.setString(5, attuid);
    		   
    		   pstmt.executeUpdate();
    		      		    
    		  
    	 }  catch (SQLException sqle) {
 			sqle.printStackTrace();
    	 } catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				conn.close();
				pstmt.close();
				} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
    	  } // if ends here 
    	 
    	 
    	 else {
    		 
    		  System.out.println("Inside update block");
    		  
    		  String qry = "UPDATE SIWEB_NOTES SET PLACEMENT = ?, FROM_DATE = ?, TO_DATE = ?, NOTE = ?, UPDATED_BY = ?";
    		 
    		   try {
      	    	 
    	    		  db = new DbConn();
    	    		  Class.forName(driver);
    	    		  conn = DriverManager.getConnection(url, user, password);
    	    		  pstmt = conn.prepareStatement(qry); 
    	    		  
    	    		  
    	    		  
    	    		  SimpleDateFormat df=new SimpleDateFormat("MM/dd/yyyy", Locale.US);
    	    		  
    	    		   java.util.Date sqlFromDate=null;
    	    		   java.util.Date sqlToDate=null;
    				try {
    					 sqlFromDate = df.parse(fromDate);
    					  sqlToDate = df.parse(toDate);
    				} catch (ParseException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    	    		  
    	    		   
    	    		   pstmt.setString(1, placement);
    	    		   pstmt.setDate(2, new java.sql.Date(sqlFromDate.getTime()));
    	    		   pstmt.setDate(3, new java.sql.Date (sqlToDate.getTime()));
    	    		   pstmt.setString(4, note);
    	    		   pstmt.setString(5, attuid);
    	    		   
    	    		   pstmt.executeUpdate();
    	    		      		    
    	    		  
    	    	 }  catch (SQLException sqle) {
    	 			sqle.printStackTrace();
    	    	 } catch (ClassNotFoundException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			} finally {
    				try {
    					conn.close();
    					pstmt.close();
    					} catch (Exception e) {
    					e.printStackTrace();
    				}
    			}
    	    		 
    	 }
 
 	   	 
    	return fromDate;
     
       }
       
       
       public Vector<NoteTable> updateNote() {
    	      	   
    	    System.out.println("Inside Update Note method");
    	   
    	    NoteTable noTab;
    	 	     	
            Vector<NoteTable> nTabVec = new Vector<NoteTable>();
       	    String qry = "SELECT CREATED_BY, UPDATED_BY, PLACEMENT, TO_CHAR(FROM_DATE, 'MM/DD/YYYY'), TO_CHAR(TO_DATE, 'MM/DD/YYYY'), NOTE FROM SIWEB_NOTES";
    	      
    	     try {
    	    	db = new DbConn();
       		    Class.forName(driver);
       		    conn = DriverManager.getConnection(url, user, password); 
    	        	    	 
				pstmt = conn.prepareStatement(qry);
				
				rs = pstmt.executeQuery(qry);
				
				while (rs.next()) {
					
					noTab = new NoteTable();
					
					noTab.setCreatedBy(rs.getString(1));
					noTab.setUpdatedBy(rs.getString(2));
					noTab.setPlacement(rs.getString(3));
					noTab.setFrom(rs.getString(4));
					noTab.setTo(rs.getString(5));
					noTab.setNote(rs.getString(6));
					
					nTabVec.add(noTab);	
																						
					}
						
			  } catch (SQLException e) {
				// TODO Auto-generated catch block
			    	e.printStackTrace();
		      	} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				           try {
				        	   pstmt.close();
				        	   rs.close();
				        	   conn.close();
				           } catch (Exception e) {
				        	   e.printStackTrace();
				           }
				
		      	}
		   	
		      	return nTabVec;
			
       }
       
    	   	
 }

Open in new window

snap1.PNG
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Not quite sure what your question is: you have a binary choice - you either add or update. What's the problem?

Avatar of aman0711
aman0711

ASKER

hi Charles,

               The problem is:

               First time user picks "update Note", page refreshes and gives the table below the form.
              Now user will pick one of the notes from checkbox, and hit submit again so that the changes get updated. But when user clicks submit, the same updateNote() will be invoked because of the conditional code in the servlet (shown in the question).

             So on the high level,

          - First time Update note (Page refreshes and gives the table)
         - users picks a note and hits submit (but data doesnt get updated), so I want this update to happen.
 
            Hope I explained it fine this time?
                 
Only invoke update if exactly one of the note checkboxes is checked and the note text is present
No, you still didnt get my problem.

My problem is,

         First time "Update Note" is picked. onChange event is called, form gets submitted which invoked the updateNote() method and returns the table.

          It's fine till now.

     Now, when we are the this point, users picks one note to update, The form gets auto filled with all the values and now user hits the submit button again in order to Update the Table.

        BUT, because the dropdown value is still "Update Note", it will again invoke the updateNote() method. Where as what I want is: this time, it should invoke the block which contains the "UPDATE SQL"
You can set the selected item in the dropdown to anything you want in the response
Sounds like you don't explicitly specify the current selection in the html. If you don't do that then the first item will be selected by default.

Either set the selection explicitly
or a simple fix would be to add a blank option at the top of the drop down. that would force the user to explicitly specify what they want to do
@ Charles,

                  Didnt exactly get you.

@ Mick,

              Adding a blank option wont work.


Here's the confusion, "Update Note" is suppose to do two tasks, when user picks it for the first time, the control fetches a table and displays below the form.
Now user will pick any one of the note, Fills the form, and then submits it. (Note: Dropdown value is still Update Note).

So basically Update Note has to do two different things, First time, get the data back, and second time, run the Update SQL.

Now Update Note field is common is both the case (which is the deriving factor here), how do I make it run the Update SQL the second time
>>Here's the confusion, "Update Note" is suppose to do two tasks, when user picks it for the first time, the control fetches a table and displays below the form.

And at that time, no checkbox is checked, is it?
Hi Charles,

             You are right, after first step no check box is selected.

             I have attached the 3 steps in snapshot.

Step-1.PNG
Step-2.PNG
Step-3.PNG
That's absolutely clear thanks. It absolutely clearly illustrates the point i'm making: there's no problem in distinguishing the two different invocation. In only one of them is there a checkbox checked
Yes thats true.

So what would be the work around?
I mentioned that at http:# 25677552

Make sure you clear the checkbox after an update
if (transType.equalsIgnoreCase("Add Note")) //TRANSACTION TYPE IS "Add Note"
                {
                        nt.addNotes(noteInfo); //invoke addNotes method in notes class
                  }
                  else {
                        list =  nt.updateNote(); // invoke updateNote method and return the table
                        getServletContext().setAttribute("notesTable", list);
                  }

   Charles, addNotes() has the UPDATE SQL block. I am still confused, though I did get your solution.
   
   Will something like below would work?

   



 if (transType.equalsIgnoreCase("Add Note")) //TRANSACTION TYPE IS "Add Note"
                {
                        nt.addNotes(noteInfo); //invoke addNotes method in notes class
                  }
                  else if (transType.equalsIgnoreCase("Update Note") && CheckBox value == null) {
                            nt.addNotes(noteInfo);
                  } else {
				      list =  nt.updateNote(); // invoke updateNote method and return the table
                        getServletContext().setAttribute("notesTable", list);
 
				  }

Open in new window

That's the right kind of pseudo-code, yes
Thanks Charles... please keep an eye on this post. I will try and post the result.
Hi Charles,

                      so I made this change:

                    updateFlag = request.getParameter("grp");  // gets me checkbox status either null or on

                 Now page loads perfectly fine, but as soon as I pick "Update Note" from dropdown, it throws Error 500 in the page.

This is the stack trace:

[10/28/09 14:05:44:191 CDT] 00000021 ServletWrappe E   SRVE0068E: Uncaught exception thrown in one of the service methods of the servlet: NoteControl. Exception thrown : java.lang.NullPointerException
    at com.si.controller.NoteControl.doPost(NoteControl.java:170)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:763)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:966)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:907)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:145)
    at com.si.security.LoginFilter.doFilter(LoginFilter.java:143)
    at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:190)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:130)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain._doFilter(WebAppFilterChain.java:87)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:701)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:646)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:475)
    at com.ibm.ws.wswebcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:463)
    at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3129)
    at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:238)
    at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:811)
    at com.ibm.ws.wswebcontainer.WebContainer.handleRequest(WebContainer.java:1433)
    at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:93)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:465)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewInformation(HttpInboundLink.java:394)
    at com.ibm.ws.http.channel.inbound.impl.HttpICLReadCallback.complete(HttpICLReadCallback.java:102)
    at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:152)
    at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:213)
    at com.ibm.io.async.AbstractAsyncFuture.fireCompletionActions(AbstractAsyncFuture.java:195)
    at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:136)
    at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:194)
    at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:741)
    at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:863)
    at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1510)


	fDate = request.getParameter("from");
		tDate = request.getParameter("to");
		note = request.getParameter("notes");
		transType = request.getParameter("transType");
		placement = request.getParameter("place");
		updateFlag = request.getParameter("grp");
 
		
		System.out.println("Check box flag: " + updateFlag);
		
		Note noteInfo = new Note();
 
		noteInfo.setFromDate(fDate);
		noteInfo.setToDate(tDate);
		noteInfo.setNote(note);
		noteInfo.setTransType(transType);
		noteInfo.setPlacement(placement);
		noteInfo.setAttUid(attuid);
				
		Notes nt = new Notes();
        
		System.out.println("Transaction type is : " + transType);
		List<NoteTable> list=null;
		
		
		getServletContext().setAttribute("transaction", transType);
		
		if (transType.equalsIgnoreCase("Add Note"))
		{
		nt.addNotes(noteInfo);
		}
		else if (transType.equalsIgnoreCase("Update Note") && updateFlag.equalsIgnoreCase("on")) {
			
			nt.addNotes(noteInfo);
		} else {
			list =  nt.updateNote();
		     getServletContext().setAttribute("notesTable", list);
		}
		
		
		response.setContentType("text/html");
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/jsp/notes.jsp");
	    dispatcher.forward(request, response);	
			

Open in new window

So I Put tons of print statements, and I noticed no matter what the Value for:

updateFlag = request.getParameter("grp");  

null or on, it always runs the second block of if else statements. Below is the console output.



Authentication successful
[10/28/09 15:56:22:851 CDT] 00000020 SystemOut     O >>>LoginFilter>>>>UID = at7138
[10/28/09 15:56:22:851 CDT] 00000020 SystemOut     O qry:SELECT ACCESS_TYPE FROM WEB_USERS WHERE lower(ID) = lower('at7138')
[10/28/09 15:56:23:835 CDT] 00000020 SystemOut     O Check box flag: null
[10/28/09 15:56:23:835 CDT] 00000020 SystemOut     O Transaction type is : Update Note
[10/28/09 15:56:23:835 CDT] 00000020 SystemOut     O inside block 2
[10/28/09 15:56:23:835 CDT] 00000020 SystemOut     O Inside Update Note method
[10/28/09 15:56:24:238 CDT] 00000020 ExportViewFac I org.displaytag.export.ExportViewFactory <init> Initializing ExportViewFactory with type={csv,excel,xml,pdf}
[10/28/09 15:56:24:270 CDT] 00000020 TableProperti I org.displaytag.properties.TableProperties getLocaleResolverInstance No LocaleResolver configured.
[10/28/09 15:57:08:071 CDT] 00000020 SystemOut     O Authentication successful
[10/28/09 15:57:08:071 CDT] 00000020 SystemOut     O >>>LoginFilter>>>>UID = at7138
[10/28/09 15:57:08:071 CDT] 00000020 SystemOut     O qry:SELECT ACCESS_TYPE FROM WEB_USERS WHERE lower(ID) = lower('at7138')
[10/28/09 15:57:08:539 CDT] 00000020 SystemOut     O Check box flag: on
[10/28/09 15:57:08:539 CDT] 00000020 SystemOut     O Transaction type is : Update Note
[10/28/09 15:57:08:539 CDT] 00000020 SystemOut     O inside block 2
[10/28/09 15:57:08:539 CDT] 00000020 SystemOut     O Inside Update Note method



	fDate = request.getParameter("from");
		tDate = request.getParameter("to");
		note = request.getParameter("notes");
		transType = request.getParameter("transType");
		placement = request.getParameter("place");
		updateFlag = request.getParameter("grp");
 
		
		System.out.println("Check box flag: " + updateFlag);
		
		Note noteInfo = new Note();
 
		noteInfo.setFromDate(fDate);
		noteInfo.setToDate(tDate);
		noteInfo.setNote(note);
		noteInfo.setTransType(transType);
		noteInfo.setPlacement(placement);
		noteInfo.setAttUid(attuid);
				
		Notes nt = new Notes();
        
		System.out.println("Transaction type is : " + transType);
		List<NoteTable> list=null;
				
		if (transType.equalsIgnoreCase("Add Note"))
		{
			System.out.println("inside block 1");
     		nt.addNotes(noteInfo);
		}
		else if (transType.equalsIgnoreCase("Update Note")) 
		{
			System.out.println("inside block 2");
	    	list =  nt.updateNote();
		    getServletContext().setAttribute("notesTable", list);
		} else if (transType.equalsIgnoreCase("Update Note") && updateFlag != null) {
			System.out.println("inside block 3");
		    nt.addNotes(noteInfo);
		}

Open in new window

What is line 170?
Here is line 170.

170.PNG
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Didnt get you :(

You mean like this?



			
		if (transType.equalsIgnoreCase("Add Note"))
		{
			System.out.println("inside block 1");
     		nt.addNotes(noteInfo);
     	} 
		else if (transType.equalsIgnoreCase("Update Note") && updateFlag != null)
		{
			System.out.println("inside block 3");
		    nt.addNotes(noteInfo);
		}
		
	      	else if (transType.equalsIgnoreCase("Update Note")) 
		{
			System.out.println("inside block 2");
	    	list =  nt.updateNote();
		    getServletContext().setAttribute("notesTable", list);
		} 

Open in new window

Yes
Thanks Charles, Now it is at least getting into the right block.

but this made me more confused, what was wrong with my earlier if else condition?
With the other way around, it will of course enter the block whether or not the flag is set
O ok :-)
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi Mick,

             for now this issue got fixed :-)

             But Now a new problem. If you see the snapshot and code for update SQL, I dont have a Where clause on it, so its updating everything.
             I am confused, what could go as WHERE clause in this case?
>              for now this issue got fixed :-)

you'd be amazed at how much simpler the code would be if you did it properly, and no need for a update flag or any conditional logic.
Would have been quicker to fix as well :)

>   I am confused, what could go as WHERE clause in this case?

you'll get lots of problems like this with the approach you are using
you'll need a where id=x
Mick what would be the simpler approach? :)
implementing each option in a separate servlet
>>am confused, what could go as WHERE clause in this case?

You need to discriminate between the checked rows of the form with an id
>> You need to discriminate between the checked rows of the form with an id

so with displayTag, id_rowNum as id for the checkbox field?

@ Mick,

         Even with different Servlets approach, "Update Note" would still be operational on two different activities. How would I determine that?

        Also, the action for the form right now specifies one servlet. isnt it a one to one mapping? like one form one servlet
if it has 2 different activities then sounds like it should have two separate servlets
though looking at your code one update is actually an Add
Yes, one is Add and one is Update.

   One last question Mick, how do I put an ID field with every row in display tag?

and I also need the same ID field in Database too right?
>>so with displayTag, id_rowNum as id for the checkbox field?

Yes. You should take the id from the db and identify it with the checkbox
Thanks Charles. :)
Thanks folks