Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Answers Viewqa Struts access data from mysql through struts

Have Programming Question? Ask it here!
 
 
 


pradeep Kundu
access data from mysql through struts
0 Answer(s)      2 years and 3 months ago
Posted in : Struts


I am Pradeep Kundu. I am making a program in struts in which i want to access data from MySQL through struts. I am using Strut 1.3.8 , Netbean 6.7.1 and MySQL 5.5. In this program ,I want to insert, delete & search data. In insert statement , i take a number variabe with long Data Type. I found this error

java.lang.integer cannot be cast into java.lang.long

In delete page , My program is deliting data successfully but not giving any response.

In search page , when i click submit button , other page open but blanks.

These are my action classes code

InserDataAction.java

package com.myapp.struts;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.DynaActionForm;

public class InsertDataAction extends org.apache.struts.action.Action {

    /* forward name="" path="" */
    private static final String SUCCESS = "success";
    private static final String FAILURE = "failure";

    Connection con = null;

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        ActionErrors errors = new ActionErrors();

        DynaActionForm actionForm = (DynaActionForm) form;


        int userId = (Integer) actionForm.get("userId");
        String firstName = (String) actionForm.get("firstName");
        String lastName = (String) actionForm.get("lastName");
        int age = (Integer) actionForm.get("age");
        long number = (Long) actionForm.get("number");
        long size = Long.toString(number).length();

        boolean flag1 = false;
        boolean flag2 = false;

        if (userId == 0 ) {
            errors.add("userId", new ActionMessage("error.userId.required"));
        }
        if (firstName == null || firstName.length() < 1) {
            errors.add("firstName", new ActionMessage("error.firstName.required"));
        }
        if (lastName == null || lastName.length() < 1) {
            errors.add("lastName", new ActionMessage("error.lastName.required"));
        }
        if (age == 0 || age < 16) {
            errors.add("age", new ActionMessage("error.age.required"));
        }
        if (number==0 || size < 10) {
            errors.add("number", new ActionMessage("error.number.required"));
        }

        saveErrors(request, errors);

        if (errors.isEmpty()) {
            flag1 = true;
        } else {
            flag1 = false;
        }


       try {

            Class.forName("com.mysql.jdbc.Driver").newInstance();
            con = DriverManager.getConnection("jdbc:mysql:///employee", "root", "1234");

            if (!con.isClosed()) {

                PreparedStatement ps = (PreparedStatement) con.prepareStatement("INSERT INTO emp(`userId`,`firstName`,`lastName`,age,`number`)"
                        + " VALUES (?,?,?,?,?) ");

                ps.setInt(1, userId);
                ps.setString(2, firstName);
                ps.setString(3, lastName);
                ps.setInt(4, age);
                ps.setLong(5, number);


                ps.execute();

            } else {
                errors.add("SQL", new ActionMessage("error.SQLConnectivity"));
            }
       }
       catch (Exception ex) {
            errors.add("SQLException", new ActionMessage("error.SQLException"));
            throw new SQLException(ex.fillInStackTrace());
        } finally {

            try {
                if (con != null) {
                    con.close();
                }
            } catch (SQLException e) {
                throw new SQLException(e.getSQLState() + e.fillInStackTrace());
            }
        }    


        saveErrors(request, errors);
        if (errors.isEmpty()) {
            flag2 = true;
        } else {
            flag2 = false;
        }

        if (flag1 == true && flag2 == true) {
            return mapping.findForward(SUCCESS);
        } else {
            return mapping.findForward(FAILURE);
        }

    }
}

DeleteDataForm.java

package com.myapp.struts;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

/**
 * @author pradeep.kundu
 */
public class DeleteDataForm extends org.apache.struts.action.ActionForm {

    Connection con = null;
    int n;

    int userId;

    public int getuserId() {
        return userId;
    }

    public void setuserId(int userId) {
        this.userId = userId;
    }

    public DeleteDataForm() {
    super();
     }

    @Override
    public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
        ActionErrors errors = new ActionErrors();
        if (getuserId()==0 || getuserId() < 1) {
            errors.add("userId", new ActionMessage("error.userId.required"));
        }
           try {
            String str = "DELETE from emp where userId =?";
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            con = DriverManager.getConnection("jdbc:mysql:///employee", "root", "1234");

            if (!con.isClosed()) {

                PreparedStatement ps = (PreparedStatement) con.prepareStatement(str);

                ps.setInt(1, userId);

                n = ps.executeUpdate();
                if(n!=0){
                  System.out.println("Record is deleted");
                } else {
                    System.out.println("Record is not deleted");
                }
            }
            else {
                errors.add("SQL", new ActionMessage("error.SQLConnectivity"));
            }

        } catch (Exception ex) {
            errors.add("SQLException", new ActionMessage("error.SQLException"));

        } finally {

            try {
                if (con != null) {
                    con.close();
                }
            } catch (SQLException e) {

            }
        }

        return errors;
    }
}

DeleteDataAction.java

package com.myapp.struts;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 * @author pradeep.kundu
 */
public class DeleteDataAction extends org.apache.struts.action.Action {


    private static final String SUCCESS = "success";

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

          return null;
    }
}

SearchDataForm.java

package com.myapp.struts;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;


public class SearchDataForm extends org.apache.struts.action.ActionForm {

      Connection con = null;
       ResultSet rs;

     int userId;

       public int getuserId() {
        return userId;
    }


    public void setuserId(int userId) {
        this.userId = userId;
    }
    public SearchDataForm() {
        super();

    }

   @Override
    public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
        ActionErrors errors = new ActionErrors();
         if (getuserId()==0 || getuserId() < 1) {
            errors.add("userId", new ActionMessage("error.userId.required"));
        }  
              try {
             String str = "SELECT * from emp where userId = ? " ;
             Class.forName("com.mysql.jdbc.Driver");
             con = DriverManager.getConnection("jdbc:mysql:///employee", "root", "1234");

             PreparedStatement  ps =  con.prepareStatement(str);

                ps.setInt(1, userId);
                rs = ps.executeQuery(str);

               System.out.println("<html><head><title>search</title></head><body>");
               System.out.println("<table><tr>");
               System.out.println("<td><b>User Id</b></td>");
               System.out.println("<td><b>First Name</b></td>");
               System.out.println("<td><b>Last Name</b></td>");
               System.out.println("<td><b>Age</b></td>");
               System.out.println("<td><b>Number</b></td>");
               System.out.println("</tr>");  

               while(rs.next())
                 {

                     Integer Id = rs.getInt("userId");
                     String firstname = rs.getString("firstName");
                     String lastname = rs.getString("lastName");
                     Integer age = rs.getInt("age");
                     Integer number = rs.getInt("number"); 

                      System.out.println("<tr>");
                      System.out.println("<td>"+Id+"</td>");
                      System.out.println("<td>"+firstname+"</td>");
                      System.out.println("<td>"+lastname+"</td>");
                      System.out.println("<td>"+age+"</td>");
                      System.out.println("<td>"+number+"</td>");
                      System.out.println("</tr>");   

                 }
                     System.out.println("</table>");
                     System.out.println("</body></html>");
                     con.close();
                     ps.close();
            }
              catch(SQLException sx)
         {
               System.out.println(sx);
          }
               catch(ClassNotFoundException cx)
          {
               System.out.println(cx);

          }

        return errors;
    }
}

SearchDataAction.java

package com.myapp.struts;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 * @author pradeep.kundu
 */
public class SearchDataAction extends org.apache.struts.action.Action {

    private static final String SUCCESS = "success";


    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

       return null ;
    }
}

if you know about these problem , please give me suggesstion

thanks.


Advertisement
View Answers

Related Tutorials/Questions & Answers:
access data from mysql through struts
access data from mysql through struts  I am Pradeep Kundu. I am making a program in struts in which i want to access data from MySQL through struts. I am using Strut 1.3.8 , Netbean 6.7.1 and MySQL 5.5. In this program ,I want
Access data from mysql through struts-hibernate integration
Access data from mysql through struts-hibernate integration  Hi friends, I am making a program in which I want to access data from mysql through struts-hibernate integration. My search command is working properly but my
Advertisements
Migrating from mysql to MS Access
Migrating from mysql to MS Access  Hi I am hoping for some help I need to write a conversion program (SQL statements) to import existing data in a MYSQL database to a MS Access database. any suggestions would be appreciated
How to access (MySQL)database from J2ME?
How to access (MySQL)database from J2ME?  I am new to J2ME. I am using NetBeans. Can anyone help me? How to access (MySQL)database from J2ME? ( I search a lot I found that there is need to access database through servlet
update data to mysql database through JTextField
update data to mysql database through JTextField  I am getting an error, when i am updating a data to mysql database through JTextField. Send me...(); JOptionPane.showMessageDialog(null,"Data successfully Updated to the database
Need to access data from another application
Need to access data from another application  Hi Tech masters, I want to develop a reporting application.for that I need to access data from a third party application. I want to access data from a software called service
retreiving data from microsoft access database
retreiving data from microsoft access database  How can i retrieve data from microsoft access when i have select the vaules in combo box and text box. When i select these values... i want to retrieve the corresponding columns
Retrieve The Data From MySql Datbase
Retrieve The Data From MySql Datbase   How to Retrieve The Data From MYSQL database TO Use Select the Emp_id Option.And Also Search Option
jfreechart display from access database data.
jfreechart display from access database data.  I have made a database... to retrieve the data from the access database using prepared statement and then display... is to be done in a servlet.. Note that it is a access made database. How can I
store data from a variable in mysql?
store data from a variable in mysql?  sir last time asked you tell me how to retrieve data from a database mysql and store it in an int variable... of the calculation from an int variable into mysql in a new table of database. how
Data retrieve from mysql database
Data retrieve from mysql database  Hi sir, please give some example of jsp code for retrieving mysql database values in multiple dropdown list... from the dropdown, related data will get displayed on the textboxes. Here we have
retrieve data from mysql database
retrieve data from mysql database  hi am not familiar in php.....even... selected value on combobox which is to be retrieve the relevant data from mysql...;/html> retcombosearch.php form is <?php mysql_connect ("localhost
Purge Data from Mysql tables
Purge Data from Mysql tables  Hi, i have to write a mysql procedure to purge data from tables. but written procedure clear entire tables data. Please give me the solution for purging data. CREATE DEFINER=`root`@`localhost
access image from ajax store in mysql using jsp
access image from ajax store in mysql using jsp  access image from ajax store in mysql using jsp (code to access image captured by camera and store in mysql
display data from a table in Access Database in a HTML page
display data from a table in Access Database in a HTML page  how to display data from a table in Access Database in a HTML page in a Java Program
php import data from excel to mysql
php import data from excel to mysql  php import data from excel to mysql
design chart takes data from database and through jsp page
design chart takes data from database and through jsp page  how can I design chart takes data from database and through in jsp page
To retrive data from database - Struts
To retrive data from database  How to get values ,when i select a select box in jsp and has to get values in textbox automatically from database? eg... come to jsp page automatically from database
Retrieve image from mysql database through jsp
Retrieve image from mysql database through jsp... to retrieve image from mysql database through jsp code. First create a database... need mysql connector jar file in the Tomcat-6.0.16/webapps/user/WEB-INF/lib
Fetch the data from mysql and display it on php form
Fetch the data from mysql and display it on php form  when i press on login button, after succesful login the related data of that person should be display in other textbox
retrive the data from access database to drop down list box in jsp
retrive the data from access database to drop down list box in jsp  hai, im new to jsp now im using the jsp along with access database.in table i load all the data's i need to retrive the data from database to dropdown list box
Access all the fields from table through JSP
Access all the fields from table through JSP... data from the specified table. Before running this java code you need.... This is first jsp page that has a link 'show data from table', which displays all
MYSQL retrieve record from Data table
MYSQL retrieve record from Data table  Hi. I have a field in database named stages. its datatype is varchar(60). It contains values chennai,trichy,kanchipuram for a single record. I have to retrieve these data from the field
Exporting data from mysql into csv using jsp
Exporting data from mysql into csv using jsp  Hi friends.... I want to export the data from mysql to csv file using... i am having 30 columns in my database.. Eg- text1,text2,text3,....,upto text30... i want to export this data
retrieve data from mysql database and store it in a variable ?
retrieve data from mysql database and store it in a variable ?  sir , I am working on a project , in which I have to apply operation on input data which is stored in mysql. so to apply some arithmetic operation on it we have
How to get data from Excel sheet - Struts
How to get data from Excel sheet  Hi, I have an excel sheet with some data(including characters and numbers). Now i want read the data from excel sheet and display in console first then later insert this data into database
Select Employee and display data from access database in a jtable
Select Employee and display data from access database in a jtable  I... a employee's name from a comboBox and the jtable will be filled with all... name of the customer is stored in a access database. Below is how it should
Exporting data from mysql to csv file
Exporting data from mysql to csv file  Hi friends.... I want to export the data from mysql to csv file... i am having 30 columns in my database.. Eg... example that retrieves the data from the database and save it into csv file
extract data from excel sheet to mysql
extract data from excel sheet to mysql  sir, i want to extract data from excel sheet and save the data in mysql5.0 database in the form of table
Proplem with select data - Struts
Proplem with select data  Hi , Please can u give me a example for display all data from the database (Access or MySql) using Struts
how to retreive data dynamically from mysql to drop down list
how to retreive data dynamically from mysql to drop down list   sir, i created a table in mysql and i inserted some values into the table through fron end using jsp , after storing the data successfully .i want to retrieve
retrive data from database using jsp in struts?
retrive data from database using jsp in struts?   *search.jsp* <%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%> <... searchProduct(SearchDTO sdto) { String query="select * from product
accessing ms access through jsp
accessing ms access through jsp  i have 3 tables in my database employee,project,task if i put employee id the search field .i should get details from other table what all queries should i use in servlet file and i am using
Retriving data from MYSQL without line break using java
Retriving data from MYSQL without line break using java  get data without line breaking from mysql table (i.e data stored as mediumtext )using java
sending data to google chart api from mysql database using java
sending data to google chart api from mysql database using java  how to send data from mysql database to google chart api using java
create dropdown cell in csv or excell from mysql data in php
create dropdown cell in csv or excell from mysql data in php  Hello sir i want to create drodown cell in csv from mysql data is this is possible or not? if this is posible please share answer or reference link Thanks
How to access session values through Ajax?
How to access session values through Ajax?  Suppose in a servlet a variable userName is kept in session. How can I access this variable from JSP through AJAX? Is it possible
mysql- microsoft access
mysql- microsoft access  hello, In all your tutorials, you have used Mysql. If instead of mysql i use microsoft access so how will it differ and wat will be the connection steps
how to read data from excel file through browse and insert into oracle database using jsp or oracle???
how to read data from excel file through browse and insert into oracle database... a browse button which can upload a excelfile and after uploading the data should..., Please go through the following links may this will be helpful for you. However
how to store JTree data hierarchically in mysql database from netbeans
how to store JTree data hierarchically in mysql database from netbeans  how to store JTree data hierarchically in mysql database from netbeans. I am new to this topics so I need a program and tables you are using in database
Insert data in mysql database through jsp using Prepared Statement ---- Please Resolve it
Insert data in mysql database through jsp using Prepared Statement ---- Please..."); String connectionURL ="jdbc:mysql://localhost:3306/studentdb"; Connection...;" WIDTH="30%" border="1"> <tr><th>Data is inserted
Insert data in mysql database through jsp using Prepared Statement ---- Please Resolve it
Insert data in mysql database through jsp using Prepared Statement ---- Please..."); String connectionURL ="jdbc:mysql://localhost:3306/studentdb"; Connection...: #E3E4FA;" WIDTH="30%" border="1"> <tr><th>Data is inserted
retrieve related data from database using jsp and mysql
retrieve related data from database using jsp and mysql  Hi sir, please give some example of jsp code for retrieving mysql database values in multiple dropdown list. if we change a value in a dropdown its related value must
how to retrive the particular data from database in php with mysql?
how to retrive the particular data from database in php with mysql?  ..._db("samp", $con); $Name=$_POST['unames']; $data=mysql_query("SELECT * FROM tbl_sample where Name='$Name'"); /*$info=mysql_fetch_array($data);*/ while
Data needs to be gathered in XML file from the database (MySql) using JSP
Data needs to be gathered in XML file from the database (MySql) using JSP ... data regarding particular id from the database table. Data needs to be gathered in XML file from the database (MySql) using appropriate JSP/Java Bean functions
dynamic retrivel of data from mysql database in table format at jsp
dynamic retrivel of data from mysql database in table format at jsp  ... the data from database and display it as table format in jsp... For example, i have...... At jsp, if i choose A1 from the dropdown list then the corresponding details
Data Access Object
Data Access Object  Hi sir/madam please give me some tutorial/example about Data Access Object   Hi Please Find the example of Java Data Access Object http://www.roseindia.net/tutorial/java/jdbc
sending data to google chart api from mysql database using java
sending data to google chart api from mysql database using java  Добовляйтесь в группу "МАЙНКРАФТА" Будьте участниками Группы Помогаите нам и себе Наша группа https://vk.com/club60851464 Есть свой сервер! Хорошая атмосфера
Migrating sql database to Access through coding
Migrating sql database to Access through coding  How can i migrate SQL database(table) to My access through coding
Exception handling through Struts - Struts
Exception handling through Struts  I am using eclipse 3.2 and developing project in struts. I want to do error handling through struts. I have used tag to my web.xml file but still I am getting errors on the screen
Advertisements
 

 

 

DMCA.com