Problem in printing the data from database when i print inside servlet

hi to all!
the objective of the code below is getting the data from database table and has to send that data to the web browser using out.println .note: out - PrintWriter object
In a getQuestion method, i am getting the data from database table and store it in String q and when i print the q within this method it is getting printed, but i got the null value when i printed the String q inside service method doPost. why..? its puzzling me.
package servlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class test extends HttpServlet {
     Connection con;
     ResultSet rs;
     Statement s;
     StringBuffer q;
     StringBuffer o1;
     StringBuffer o2;
     StringBuffer o3;
     public void getQuestion() throws Exception
          if(rs.next())
               q=new StringBuffer(rs.getString("question"));
               o1=new StringBuffer(rs.getString("option1"));
               o2=new StringBuffer(rs.getString("option2"));
               o3=new StringBuffer(rs.getString("option3"));
               System.out.println(q);
               System.out.println(o1);
               System.out.println(o2);
               System.out.println(o3);
     public void connect(){
          try
          Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
          con=DriverManager.getConnection("jdbc:odbc:ds","sa","server");
          s=con.createStatement();
          rs=s.executeQuery("select * from qa order by newid()");
          getQuestion();
          catch(Exception e)
               System.out.println("erroe");
     public void doPost(HttpServletRequest request,HttpServletResponse response)
     throws IOException,ServletException
          response.setContentType("text/html");
          new test().connect();
          PrintWriter out=response.getWriter();
          request.setAttribute("question", q);
          request.setAttribute("option1", o1);
          request.setAttribute("option2", o2);
          request.setAttribute("option3", o3);
          //RequestDispatcher rd=getServletContext().getRequestDispatcher("/show.jsp");
          //rd.forward(request, response);
          out.println("<html>");
out.println("<head>");
     out.println("<title>" + "shock!!!" + "</title>");
out.println("</head>");
out.println("<body>");
out.println("<h2>"+"Read twice before u answer"+"<h2>");
out.println("<p></p>");
//why the value of q is not getting printed, instead i get null
out.println("<h2>"+ q +"<h2>");
out.println("how is it");
out.println("</body>");
out.println("</html>");
Edited by: Mahesh_yeswecan on Nov 29, 2008 10:42 AM

As u said , i have done a silly mistake earlier. though i have corrected the code still i am getting the same null value
package servlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class test extends HttpServlet  {
     Connection con;
     ResultSet rs;
     Statement s;
     StringBuffer q;
     StringBuffer o1;
     StringBuffer o2;
     StringBuffer o3;
     public void getQuestion() throws Exception
          if(rs.next())
               q=new StringBuffer(rs.getString("question"));
               o1=new StringBuffer(rs.getString("option1"));
               o2=new StringBuffer(rs.getString("option2"));
               o3=new StringBuffer(rs.getString("option3"));
               System.out.println(q);
               System.out.println(o1);
               System.out.println(o2);
               System.out.println(o3);
     public void connect(){
          try
          Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
          con=DriverManager.getConnection("jdbc:odbc:ds","sa","server");
          s=con.createStatement();
          rs=s.executeQuery("select * from qa order by newid()");
          getQuestion();
          catch(Exception e)
               System.out.println("erroe");
     public void doPost(HttpServletRequest request,HttpServletResponse response)
     throws IOException,ServletException
          response.setContentType("text/html");
          connect();
          PrintWriter out=response.getWriter();
          request.setAttribute("question", q);
          request.setAttribute("option1", o1);
          request.setAttribute("option2", o2);
          request.setAttribute("option3", o3);
          //RequestDispatcher rd=getServletContext().getRequestDispatcher("/show.jsp");
          //rd.forward(request, response);
          out.println("<html>");
        out.println("<head>");
         out.println("<title>" + "shock!!!" + "</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h2>"+"Read twice before u answer"+"<h2>");
        out.println("<p></p>");
        //why the value of q is not getting printed, instead i get null
        out.println("<h2>"+ q +"<h2>");
        out.println("how is it");
        out.println("</body>");
        out.println("</html>");
}

Similar Messages

  • Problem with displaying the data from Database on swf file.

    Hi ,
      I am new to flash.Thanks in Advance Please help me....
    Actually my requirement is my application consists a button(submit_Btn) when we click on the button(submit_Btn), each time it must to database(through servlet) and brings the data from database and places it on the flash swf file.Here my problem is for the first time when we click on the button it goes to database and place the data(which was returned from database) on the swf file.Next  when we click on the button for the second time(or anytime) it is not going  and bringing the new data from database(if some data is modified in database or not),Infact it is showing the old data(the data that was collected from previous ClickListener) only on the swf file and it is also not showing any complile time or run time error.
    my Code looks like this:
    submit_Btn.addEventListener(MouseEvent.CLICK,onCheck2);
    function onCheck2(evnt:MouseEvent):void {
    var xmlLoader:URLLoader = new URLLoader();
        var xmlurl:String = "http://localhost:8888/xmlServlet";
        var xmlrequest:URLRequest = new URLRequest(xmlurl);
    xmlLoader.dataFormat = URLLoaderDataFormat.TEXT;
    xmlLoader.addEventListener(Event.COMPLETE, xmlcompleteHandler);
    xmlLoader.load(xmlrequest);
    function xmlcompleteHandler(event:Event):void {
        var loader:URLLoader = URLLoader(event.target);
        var succData:String=loader.data;
            var xmlData:XML = new XML();
            var xmlList:XMLList;
            xmlData = XML(loader.data);
            xmlList = xmlData.children();
            for (var i=0; i<xmlList.length(); i++) {
                for (var n=0; n<xmlData.UserHumanap[i].HumanapDot.length(); n++) {
                        var x_coordinate:Number = xmlData.UserHumanap[i].HumanapDot[n].@x;
                        var y_coordinate:Number = xmlData.UserHumanap[i].HumanapDot[n].@y;
                        var point2:Point = new Point(x_coordinate,y_coordinate);
                        var circle:Sprite = new Sprite();
                        circle.graphics.beginFill(0x00ff00);
                        circle.graphics.drawCircle(point2.x,point2.y,3);   //Placing the data as dots on the swf file
    Thanks in Advance.......Please Help me..........
    its Urgent..........
    Thanks,
    Swarthi

    Checkout following line in your code
    var xmlurl:String = "http://localhost:8888/xmlServlet";
    now change it to
    var xmlurl:String = "http://localhost:8888/xmlServlet?random="+String(MAth.random());
    I think you will get the point now

  • Facing a Problem while downloading the data from ALV Grid to Excel Sheet

    Hi Friends,
    Iam facing a problem while downloading the data from ALV Grid to excel sheet. This is working fine in Development server , when comes to Quality and Production servers I have this trouble.
       I have nearly 11 fields in ALV Grid and out of which one is PO number of length 10 , all the ten numbers are visible in the excel sheet if we download it from development server but when we download it from Quality or Production it is showing only 9 numbers.
    Can any one help me out in this case.

    hi...
    if this problems happens dont display the same internal as u finally got.
    just create new internal table without calling any standard data elements and domains... but the new internal table s similar like ur final internal table and move all the values to new int table.
    for eg.
    ur final internal int table for disp,
         data : begin of itab occur 0,
                        matnr like mara-matnr,
                   end of itab.
    create new like this,
               data : begin of itab occur 0,
                        matnr(12) type N,
                   end of itab.

  • Pull the data from database.

    Hi EveryBody,
                     I have a requirement in universe if the end user will select the date from (1/8/14 to 10/8/14) then pull the data from the database. but when the end user select the data more than 10 days(e.g 1/8/14 to 15/8/14 etc...) then no need to pull the data from database.
    how will write the filter in the universe?
    how will achieve this? please help me.
    Thank you.

    Hi  ,
    I am assuming you are giving prompt for start date and end date  respectively start_date and end_date.
    please see the below work around. (below is pseudo code)
    1. create one dummy objects as
    case when @prompt(end_date) - @prompt(start_date) <= 10 then = 1 end
    Remember text used in dummy object should be same as you use it for you date prompts
    2. pull this objects in where clause along with your date prompts as
    dummy_object = 1 
    It will work as below :=
    your report will be prompted for start_date and end_date .
    Same values will be passed to dummy objects.
    When dummy object will be executed , it will check for  end_date-start_date <=10 or not.
    If it is less then 10 then query will executed else it will come out as where  clause is not satisfied.
    Hope this answers your question :-).
    Regards
    Jeevan 

  • Problem while exporting the data from a report to an excel file.

    Hi SAP guru's,
    I have a problem while exporting the data from a report to an excel file.
    The problem is that after exporting, the excel file seems to have some irrelevant characters....I am checking this using SOST transaction..
    Required text (Russian):
    Операции по счету                                    
    № документа     Тип документа     № учетной записи     Дата документа     Валюта     Сумма, вкл. НДС     Срок оплаты     Описание документа
    Current Text :
       ? 5 @ 0 F 8 8  ? >  A G 5 B C                                   
    !   4 > : C       "" 8 ?  4 > : C      !   C G 5 B = > 9  7 0 ? 8 A 8        0 B 0  4 > : C         0 ; N B 0      ! C <       ! @ > :  > ? ; 0 B K        ? 8 A 0 = 8 5  4 > : C
    Can you help me making configuration settings if any?
    Regards,
    Avinash Raju

    Hi Avinash
    To download  such characteres you need to adjust code page to be used during export. You can review SAP note 73606 to identify which code page is required for this language
    Best regards

  • [webdynpro] How to get the data from database and store in Excel sheet

    Hi All-
    I am developing an application in Webdynpro and I need to provide a URL ( link ) which if clicked , need to collect the data from Database ( SQL Server ) and puts in an Excel Sheet corresponding fields and opens the sheet.....
    Please look into this issue and help me out......
    Regards,
    Cris

    Hi Cris,
    Add-on to wat santosh has pointed to:
    Exporting table data to MS-Excel Sheet(enhanced Web Dynpro Binary Cache)
    (Or) If you have implemented your logic to get Database records below Blog should guide you in opening an excel with ur records.
    Exporting table data to MS-Excel Sheet(enhanced Web Dynpro Binary Cache)
    Regards,
    N.

  • How to display the data from database(MS access) to a textbox

    anyone know ?

    how to display the data from database(MS access) to a
    textboxThe reply hasn't changed over these years. Read the tuutorial on how to fetch the data. You can display it anywhere you feel like. :)
    http://java.sun.com/docs/books/tutorial/jdbc/

  • I am using window.print() to print the data of my webpage, it prints only first page and left the remaining while it works fine with IE and Google Chrome, ie print all the pages.

    My Page has data more than one page, it has verticle scroll bar to view all data .
    I used window.print() to print the data of webpage, but it prints only first page and left the remaining information.
    This works fine with Internet Explorer 6+ and Google Chrome.

    Does the entire webpage appear in Print Preview? <br />
    File > Print Preview

  • Problem in populating jtable data from database

    hi,
    i am using JTable to retrieve data from database and show it in table. JTable
    is working fine with static data. but while retrieving from databse its giving a NullPointerException at getColumnClass() method. Below is complete source code. plzz help.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.sql.*;
    import javax.swing.table.*;
    /*jdbc connection class*/
    class connect
    Connection con;
    Statement stat;
    public connect()throws Exception
    Class.forName("org.postgresql.Driver");
    con=DriverManager.getConnection("jdbc:postgresql://localhost/dl","dl","dl");
    stat=con.createStatement();
    public ResultSet rsf(String rsstr)throws Exception
    ResultSet rs=stat.executeQuery(rsstr);
    return rs;
    public void upf(String upstr)throws Exception
    stat.executeUpdate(upstr);
    class MyTableModel extends AbstractTableModel
    private String[] columnNames = {"name","id","dep","cat","rem","chkout"};
    Object[][] data;
    public MyTableModel()
    try{
    connect conn=new connect();
    ResultSet rs3=conn.rsf("select * from usertab");
    ResultSetMetaData rsmd=rs3.getMetaData();
    int col=rsmd.getColumnCount();
    int cou=0;while(rs3.next()){cou++;}
    data=new Object[cou][col];
    System.out.println(cou+" "+col);
    ResultSet rs2=conn.rsf("select * from usertab");
    int i=0;int j=0;
    for(i=0;i<cou;i++)
    rs2.next();
    for(j=0;j<col;j++)
    data[i][j]=rs2.getString(getColumnName(j));
    System.out.println(data[0][2]);
    }catch(Exception e){System.out.println("DFD "+e);}
            public int getColumnCount() {
                return columnNames.length;
            public int getRowCount() {
                return data.length;
            public String getColumnName(int col) {
                return columnNames[col];
            public Object getValueAt(int row, int col) {
                return data[row][col];
           public Class getColumnClass(int c) {
              return getValueAt(0, c).getClass();
            public boolean isCellEditable(int row, int col) {
                if (col < 2) {
                    return false;
                } else {
                    return true;
            public void setValueAt(Object value, int row, int col) {
                data[row][col] = value;
                fireTableCellUpdated(row, col);
    class MyFrame extends JFrame
    public MyFrame()
         setSize(600,500);
         JPanel p1=new JPanel();
         p1.setBackground(new Color(198,232,189));
         JTable table = new JTable(new MyTableModel());
         table.setPreferredScrollableViewportSize(new Dimension(500,200));
         table.setBackground(new Color(198,232,189));
         JScrollPane scrollPane = new JScrollPane(table);
         scrollPane.setBackground(new Color(198,232,189));
         p1.add(scrollPane);
         getContentPane().add(p1);
    /*Main Class*/
    class test2
         public static void main(String args[])
         MyFrame fr =new MyFrame();
         fr.setVisible(true);
    }thanx

    hi nickelb,
    i had returned Object.class in the getColumnClass() method. But then i
    got NullPointerException at getRowCount() method. i could understand that the
    main problem is in data[][] object. In all the methods its returning null values as it is so declared outside the construtor. But if i declare the object inside the constructor, then the methods could not recognize the object. it seems i cant do the either ways. hope u understood the problem.
    thanx

  • How can print the data from notepad into the web application.

    Hi,
    I am Buntty, I want to read the data from the notepad and print into text area of web application, I have written the code to invoke the file and store data in temporary buffer, then I want to Print that data, but while printing the data 1st line replaces when the 2nd line prints, java code is below.
    BufferedReader bin=new BufferedReader(new FileReader("mydata.txt"));
    while((credit_number=bin.readLine())!=null)
         selenium.type("inputString", credit_number);
    Please help me to print all the lines in the text area of web application.
    Any method to print the all the data in the notepad at a time into the text area on web application.
    Thanks
    Buntty
    Edited by: Buntty on Nov 15, 2008 4:24 PM
    Edited by: Buntty on Nov 15, 2008 4:37 PM

    Try this:
    BufferedReader bin=new BufferedReader(new FileReader("mydata.txt"));
    String tempString = "";
    while((credit_number=bin.readLine())!=null)
    tempString = tempString + credit_number;
    selenium.type("inputString", tempString); Hope this helps.
    All the best

  • Problem in getting the data from a cache in hibernate

    I am storing data inside a cache. When i am geeting the data from a cache its showing null.
    How can i retrieve the data from a cache.
    I am using EHCache

    Hi ,
    You have done one mistake while setting the input parameters for BAPI..Do the following steps for setting input to BAPI
    Bapi_Goodsmvt_Getitems_Input input = new Bapi_Goodsmvt_Getitems_Input();
    wdContext.nodeBapi_Goodsmvt_Getitems_Input().bind(input);
    Bapi2017_Gm_Material_Ra input1 = new Bapi2017_Gm_Material_Ra();
    wdContext.nodeBapi2017_Gm_Material_Ra().bind(input1);
    Bapi2017_Gm_Move_Type_Ra input2 = new Bapi2017_Gm_Move_Type_Ra();
    wdContext.nodeBapi2017_Gm_Move_Type_Ra().bind(input2);
    Bapi2017_Gm_Plant_Ra input3 = new Bapi2017_Gm_Plant_Ra();
    wdContext.nodeBapi2017_Gm_Plant_Ra().bind(input3);
    Bapi2017_Gm_Spec_Stock_Ra input4 = new Bapi2017_Gm_Spec_Stock_Ra();
    wdContext.nodeBapi2017_Gm_Spec_Stock_Ra().bind(input4);
    input1.setSign("I");
    input1.setOption("EQ");
    input1.setLow("1857");
    input2.setSign("I");
    input2.setOption("EQ");
    input2.setLow("M110");
    input3.setSign("I");
    input3.setOption("EQ");
    input3.setLow("309");
    input4.setSign("I");
    input4.setOption("EQ");
    input4.setLow("W");
    wdThis.wdGetWdsdgoodsmvmtcustController().execute_BAPI_GOODSMOVEMENT_GETITEMS();
    Finally inavidate your output node like
    wdContext.node<output node name>.invalidate();
    also put your code inside try catch to display any exception if any
    Regards,
    Amit Bagati

  • Problem in Selecting the data from EKPO and KONV tables

    Hi Experts,
    Presently I am working on Report with Comparision-Sheet Between the vendor's Quotations. I have to display the Discount, Freight, Packing and Forwarding, Vat in Item level data based on the conditions made in PO.
    As per my Knowledge, Condition Types are stored in KONV Table. But there is no relation between KONV and EKPO tables.  So, I am unable to print the data for Discount, Freight, Packing and Forwarding, Vat... How can I get the values from EKPO and KONV tables?
    Thanks in Advance.
    Thanks n Regards,
    Muralikrishna.

    Don't recall if this is correct, but you may need the condition number from the header (EKKO) combined with EKPO-EBELP or other field as you key to access KONV (KNUMH and KPOSN).  My site doesn't run PP, so can't verify if the data is actually stored that, so just a possibility.

  • Problem in showing binary data from database

    Hi,
    I store some image files in my Oracle database and I want to show them in JSP pages. I constructed a jsp page which returns the image, foto.jsp looks like this:
    <jsp:useBean id="photo" class="BizDel.Foto" scope="session" />
    <%
    int iNumPhoto;
    Connection conn=null;
    try{
    DriverManager.registerDriver(new OracleDriver());
    conn=DriverManager.getConnection("jdbc:oracle:thin:@server:1521:orcl", "username", "password");
    conn.setAutoCommit (false);
    byte[] imgData=Foto.getPhoto(conn);
    response.setContentType("image/gif");
    ServletOutputStream o=response.getOutputStream();
    o.write(imgData);
    o.flush();
    o.close();
    catch(Exception e)
    e.printStackTrace();
    throw e;
    finally
    conn.close();
    %>
    Foto.getPhoto() returns the image file as a binary array.
    In the jsp page that I want to display the image, I wrote
    <img src=foto.jsp/>
    I see that the image processed, but nothing is displayed in the page. When I wrote the foto.jsp directly in the address bar, the image is retrieved properly and the page tries to process it as a file(tries to find a plugin for displaying the image file, that I dont want to.).
    Can anyone help?

    Andi,
    Thanks for your suggestion.
    I tried your way. Here is the servlet code:
    public void doGet(HttpServletRequest request,
    HttpServletResponse response) throws ServletException, IOException {
    int iNumPhoto;
    Connection conn=null;
    if(request.getParameter("imgID")!=null){
    iNumPhoto=Integer.parseInt(request.getParameter("imgID"));
    try{
    DriverManager.registerDriver(new OracleDriver());
    conn=DriverManager.getConnection("jdbc:oracle:thin:@server:1521:orcl", "username", "password");
    conn.setAutoCommit (false);
              //retrieves the photo from database, works well...
    byte[] imgData=Foto.getPhoto(conn);
    response.setContentType("image/gif");
    OutputStream o=response.getOutputStream();
    o.write(imgData);
    o.flush();
    o.close();
    catch(Exception e)
    e.printStackTrace();
    throw e;
    finally
    try{conn.close();}catch(Exception e){}
    Again, there is no exception but the page does not show the image. When I directly write the servlet in the address bar, this time nothing happens, I cannot see the image.
    Any suggestions...?

  • Selecting the data from database and sending to users  using javamail

    how to select the records from database table in oracle and send automatically to users using javamail. I am able to send the txt msg. but dont know how to send the selected table data to users automatically.
    can anyone suggest how to write the steps with database connection to send msgs containing data to different users
    Thank You

    using JDBC..you want to
    1. create the connect
    2. open the connection
    3. query the table for the data
    4. loop through the resultset to retrieve rows of data
    5. do something with the data
    6. email the result
    once you have the data, it is up to you to determine the format to send to the user using JavaMail. It is easiest to send plain text
    here's a site that give code example (for all steps above relating to JDBC):
    http://javaalmanac.com/egs/java.sql/pkg.html

  • Extract the data from database and send to XI in form of file

    hi,
        I am working on a scenario in which i am to extract thew data from an ODBC database. and send it to Integration Engine using a file adapter. In this case which adapter i should use? If i go for file adapter then how i will extract the data and if i go for JDBCadapter then i can't send the data in the form of file which is my basic requirement.
    Can someone help me out.

    Hi,
    You can Use JDBC Adapter to pull the data from Dbase very well.
    Check this For Refference Use
    PERIODIC SCHEDULING OF DATA BETWEEN ORACLE DB & R/3 SYSTEM
    Regards
    Seshagiri

Maybe you are looking for

  • How can I have two fields with the same name if it makes sense?

    Hello, folks :) I have a pretty hard time figuring out how I can have two text fields with the same binding name. The whole problem is that when I need two fields with the same binding name they are still differnent coz they have the same name but di

  • Not possible to get rid of Welcome Screen

    In 309 we wish to get rid of the Welcome Screen and go straight to the login screen. In 307 we did this by making the Welcome Screen not accessible to public users. If we try doing that in 309 the Sign On Screen comes up fine, but once the user has l

  • Re-painting in JApplet

    I'm trying to build a very simple picture browser from JApplet. There is just a picture, next, previous, last and first buttons. I have got the picture viewer working to a point. The program loads the default image to start. However if I click the fi

  • Can I set up more than one player to itunes?

    just purchased a portable player, can I hook/set up more than one player to my computer?

  • HND not even installed and still ruining my day

    I installed the EasyLink router configuration software with my new WRT160N router.  I chose not to install the Home Network Defender. In the EasyLink software, there is a page to configure HND.  If I go to that page, it prompts me to install the 30 d