I'm not sure what's going wrong here. I've written similar projects that worked just fine but for whatever reason, the data is not being written to the database.
The functionality I'm trying to achieve at the moment is to grab the information from the sign up form and store it in my phpmyadmin db.
This code is identical (word for word) to another person doing this project and theirs is working fine. Leads me to believe the issue is with the JDBC driver or the the database in some way.
Here is the form page code
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>Phone Auction Site</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Login</h1>
<form action="login.jsp">
Username:<br>
<input type="text" name="username"><br>
Password:<br>
<input type="password" name="password"><br>
<input type="submit" value="Log In">
</form>
<h1>Sign Up</h1>
<form action="signup.jsp">
Username:<br>
<input type="text" name="username"><br>
Password:<br>
<input type="password" name="password"><br>
First Name:<br>
<input type="text" name="firstName"><br>
Last Name:<br>
<input type="text" name="lastName"><br>
Address:<br>
<input type="text" name="address"><br>
Phone Number:<br>
<input type="text" name="phoneNum"><br>
Email:<br>
<input type="text" name="email"><br>
<input type="submit" value="Sign Up">
</form>
</body>
</html>
Here is the signup.jsp page that gets the attributes, creates the instance and calls the saveToDatabase method
<%#page import="phoneauctionronan.Customer"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Sign Up</title>
</head>
<body>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String address = request.getParameter("address");
String phoneNum = request.getParameter("phoneNum");
String email = request.getParameter("email");
Customer c = new Customer(username, password, firstName, lastName, address, phoneNum, email);
c.saveToDatabase();
%>
</body>
</html>
Here is the Customer class
package phoneauctionronan;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Customer
{
private int id;
private String username;
private String password;
private String firstName;
private String lastName;
private String address;
private String phoneNum;
private String email;
public Customer()
{
}
public Customer(String username, String password, String firstName, String lastName, String address, String phoneNum, String email)
{
this.username = username;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.phoneNum = phoneNum;
this.email = email;
}
public boolean saveToDatabase()
{
boolean saved = false;
Connection c = DBHelperClass.getConnection();
if (c != null)
{
try
{
Statement s = c.createStatement();
String template = "INSERT INTO customer (username, password, firstName, lastName, address, phoneNumber, emailAddress) VALUES (?, ?, ?, ?, ?, ?, ?)";
PreparedStatement inserter = c.prepareStatement(template);
inserter.setString(1, this.username);
inserter.setString(2, this.password);
inserter.setString(3, this.firstName);
inserter.setString(4, this.lastName);
inserter.setString(5, this.address);
inserter.setString(6, this.phoneNum);
inserter.setString(7, this.email);
inserter.executeUpdate();
saved = true;
}
catch (SQLException ex)
{
Logger.getLogger(Customer.class.getName()).log(Level.SEVERE, null, ex);
}
}
return saved;
}
public Customer validateCustomer(String username, String password)
{
boolean found = false;
Connection c = DBHelperClass.getConnection();
if(c!=null)
{
try
{
Statement s = c.createStatement();
String template = "SELECT * from customers where username = ? and password = ?";
PreparedStatement inserter = c.prepareStatement(template);
inserter.setString(1, username);
inserter.setString(2, password);
ResultSet resultSet = inserter.executeQuery();
while(resultSet.next())
{
this.id = resultSet.getInt("userID");
this.username = resultSet.getString("userName");
this.password = resultSet.getString("password");
this.firstName = resultSet.getString("firstName");
this.lastName = resultSet.getString("lastName");
this.address = resultSet.getString("address");
this.phoneNum = resultSet.getString("phoneNum");
this.email = resultSet.getString("email");
found = true;
}
}
catch (SQLException ex)
{
Logger.getLogger(Customer.class.getName()).log(Level.SEVERE, null, ex);
}
}
return this;
}
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public String getAddress()
{
return address;
}
public void setAddress(String address)
{
this.address = address;
}
public String getPhoneNum()
{
return phoneNum;
}
public void setPhoneNum(String phoneNum)
{
this.phoneNum = phoneNum;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
}
Finally here is the DBConnection class
package phoneauctionronan;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DBHelperClass
{
public static Connection getConnection()
{
String host = "localhost";
String dbName = "phones";
int port = 3306;
String mySqlUrl = "jdbc:mysql://" + host + ":" + port
+ "/" + dbName;
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e)
{
System.out.println("ClassNotFound !!!!" + e);
}
Properties userInfo = new Properties();
userInfo.put("user", "root");
userInfo.put("password", "password");
try
{
Connection connection = DriverManager.getConnection(mySqlUrl, userInfo);
return connection;
}
catch (SQLException ex)
{
Logger.getLogger(DBHelperClass.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
}
Here is a pic of my customer table structure
Here a pic of the name of the db and table just in case
Completely lost as to what might be causing this!
Related
As the title says, I'm having difficulty in my Java + Spring/Hibernate project where when I go to update and Employee or Customers information, it removes their role from the employee_roles/customer_roles table in the database.
I had this same issue with the username being removed however, I was able to work around this by creating a hidden input form for the username in the html page.
The files for running this project can be found below, if you find that you can't get it to work properly on Mac, that may be because you will need to change the jdbc.url to just: jdbc:mysql://localhost:3306/spring_pie_deal
https://drive.google.com/file/d/1YAdaGCQXH-tjDy8EfnV0WagcV33I8ADM/view?usp=sharing
Employee:
#Entity
#Table(name = "employee")
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "username")
private String userName;
#Column(name = "password")
private String password;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "email")
private String email;
#Column(name = "phone_number")
private String phoneNumber;
#Column(name = "address")
private String address;
#Column(name = "zipcode")
private String zipcode;
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(name = "employee_roles",
joinColumns = #JoinColumn(name = "employee_id"),
inverseJoinColumns = #JoinColumn(name = "role_id"))
private Collection<Role> roles;
public Employee() {
}
public Employee(String userName, String password, String firstName, String lastName, String email, String phoneNumber, String address, String zipcode) {
this.userName = userName;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.phoneNumber = phoneNumber;
this.address = address;
this.zipcode = zipcode;
}
public Employee(String userName, String password, String firstName, String lastName, String email, String phoneNumber, String address, String zipcode, Collection<Role> roles) {
this.userName = userName;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.phoneNumber = phoneNumber;
this.address = address;
this.zipcode = zipcode;
this.roles = roles;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public Collection<Role> getRoles() {
return roles;
}
public void setRoles(Collection<Role> roles) {
this.roles = roles;
}
#Override
public String toString() {
return "Employee{" +
"id=" + id +
", userName='" + userName + '\'' +
", password='" + password + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", phoneNumber='" + phoneNumber + '\'' +
", address='" + address + '\'' +
", zipcode='" + zipcode + '\'' +
", roles=" + roles +
'}';
}
}
Role:
#Entity
#Table(name = "role")
public class Role {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "name")
private String name;
public Role() {
}
public Role(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "Role{" + "id=" + id + ", name='" + name + '\'' + '}';
}
}
EmployeeDAOImpl:
#Repository
public class EmployeeDaoImpl implements EmployeeDAO{
#Autowired
private SessionFactory sessionFactory;
// define getEmployee method
#Override
public Employee getEmployee(Long theId) {
// get current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
// get Employee by the id
Employee theEmployee = currentSession.get(Employee.class, theId);
// return the employee
return theEmployee;
}
// define saveEmployee method
#Override
public void saveEmployee(Employee theEmployee) {
// get current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
// save Employee by the id
currentSession.saveOrUpdate(theEmployee);
}
// define deleteEmployee method
#Override
public void deleteEmployee(Long theId) {
// get current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
// delete Employee by id
currentSession.delete(theId);
}
#Override
public List<Employee> getEmployees() {
// get current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
// create query
Query<Employee> theQuery =
currentSession.createQuery("from Employee order by lastName", Employee.class);
// apply result list to variable list
List<Employee> theEmployees = theQuery.getResultList();
// return the result list variable
return theEmployees;
}
#Override
public Employee findByUserName(String userName) {
// get current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
// now create query... where username(from database) matches uName(direct relationship with userName1)
Query<Employee> theQuery = currentSession.createQuery("from Employee where username=:uName", Employee.class);
theQuery.setParameter("uName", userName);
Employee theEmployee = null;
try {
theEmployee = theQuery.getSingleResult();
}
catch (Exception e) {
theEmployee =null;
}
return theEmployee;
}
#Override
public void save(Employee employee) {
// get current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
// create or save user
currentSession.saveOrUpdate(employee);
}
}
Employee-form.jsp:
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
<!DOCTYPE html>
<html>
<head>
<title>Update Employee</title>
<link type="text/css"
rel="stylesheet"
href="${pageContext.request.contextPath}/resources/css/style.css">
<link type="text/css"
rel="stylesheet"
href="${pageContext.request.contextPath}/resources/css/add-customer-style.css">
</head>
<body>
<div id="wrapper">
<div id="header">
<h2>ERM - Employee Relationship Manager</h2>
</div>
</div>
<div id="container">
<h3>Update Employee</h3>
<form:form action="saveEmployee"
modelAttribute="employee">
<!-- need to associate this data with a employee id -->
<form:hidden path="id" />
<table>
<tbody>
<tr>
<td><form:input type="hidden" path="userName" /></td>
</tr>
<tr>
<td><form:input type="hidden" path="password" /></td>
</tr>
<tr>
<td><label>First name:</label></td>
<td><form:input path="firstName" /></td>
</tr>
<tr>
<td><label>Last name:</label></td>
<td><form:input path="lastName" /></td>
</tr>
<tr>
<td><label>Email:</label></td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td><label>Phone Number:</label></td>
<td><form:input path="phoneNumber" /></td>
</tr>
<tr>
<td><label>Address:</label></td>
<td><form:input path="address" /></td>
</tr>
<tr>
<td><label>Zip Code:</label></td>
<td><form:input path="zipcode" /></td>
</tr>
<tr>
<td><label></label></td>
<td><input type="submit" value="Save" class="save" /></td>
</tr>
</tbody>
</table>
</form:form>
<div style="clear; both;"></div>
<!-- Add a logout button -->
<form:form action="${pageContext.request.contextPath}/logout"
method="POST">
<input type="submit" value="Logout" />
</form:form>
<p>
Back to List
</p>
</div>
</body>
</html>
I have searched around but can't find any help.
I'm trying to create a user but 2 fields keeps being null (firstname and department).
The Gui (html):
<div style="width: 900px; margin-left: auto; margin-right: auto">
<form action="EmployeesAddManager.jsp" method="post">
Firstname:<br>
<input type="text" name="firstname" style="width: 200px"><br>
Lastname:<br>
<input type="text" name="lastname" style="width: 200px"><br>
Gender:
<select name="gender">
<option value="Male">Male</option>
<option value="Female">Female</option>
</select><br>
Email:<br>
<input type="text" name="email" style="width: 200px"><br>
Role:
<select name="role">
<option value="Department Leader">Department Leader</option>
<option value="Assistant">Assistant</option>
</select><br>
Department:
<select name="department">
<option value="Tetriz">Tetriz</option>
<option value="Cube">Cube</option>
</select><br>
Image:<br>
<input type="text" name="image" style="width: 200px"><br>
Username:<br>
<input type="text" name="username" style="width: 200px"><br>
Password:<br>
<input type="text" name="password" style="width: 200px"><br>
<input type="submit" value="Create Employee">
</form>
</div>
Already in the 'EmployeesAddManager.jsp' I try to print out the inputs, but firstname and department will be null (all the others works):
<%#page import="model.EmployeeModel"%>
<%#page import="model.Employees"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
//We get the fulfilled parameters
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
String gender = request.getParameter("gender");
String email = request.getParameter("email");
String role = request.getParameter("role");
String department = request.getParameter("department");
String image = request.getParameter("image");
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("Firstname from EmployeesAddManager.jsp: "+firstname);
System.out.println("Lastname from EmployeesAddManager.jsp: "+lastname);
System.out.println("Department from EmployeesAddManager.jsp: "+department);
//We instantiate an employee and set the parameters
Employees emp = new Employees(0, firstname, lastname, gender, email, role, department, image, username, password);
//We call for the method for creating a new employee, and send the new instantiated employee
EmployeeModel empModel = new EmployeeModel();
empModel.newEmployee(emp);
/*This method is used to redirect client request to some other location
for further processing ,the new location is available on different server
or different context.our web container handle this and transfer the request
using browser ,and this request is visible in browser as a new request.
Some time this is also called as client side redirect.
*/
response.sendRedirect("/Employees_servlet");
%>
</body>
</html>
And here the Model thats connect to the database:
public void newEmployee(Employees emp) throws SQLException{
try {
PreparedStatement ps = DbModel2.getPreparedStatement("INSERT INTO employee_table (Id_employee, Firstname, Lastname, Gender, Email, RoleId_Fk, DepartmentId_Fk, Image) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
ps.setInt(1, emp.getId());
ps.setString(2, emp.getFirstname());
ps.setString(3, emp.getLastname());
ps.setString(4, emp.getGender());
ps.setString(5, emp.getEmail());
ps.setString(6, emp.getRole());
ps.setString(7, emp.getDepartment());
ps.setString(8, emp.getImage());
System.out.println("Id: "+emp.getId());
System.out.println("Firstname: "+emp.getFirstname());
System.out.println("Lastname: "+ emp.getLastname());
System.out.println("Gender: "+emp.getGender());
System.out.println("Email: "+emp.getEmail());
System.out.println("Role: "+emp.getRole());
System.out.println("Department: "+emp.getDepartment());
System.out.println("Image: "+emp.getImage());
ps.executeUpdate();
System.out.println("EXECUTED");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The Employees.java:
public class Employees {
private int id;
private String firstname;
private String lastname;
private String gender;
private String email;
private String role;
private String department;
private String image;
private String username;
private String password;
public Employees(int id, String firstname, String lastname, String gender, String email, String role, String department, String image, String username, String password) {
this.id = id;
this.firstname = firstname;
this.lastname = lastname;
this.gender = gender;
this.email = email;
this.role = role;
this.department = department;
this.image = image;
this.username = username;
this.password = password;
System.out.println("this.firstname: "+firstname);
System.out.println("this.department: "+department);
System.out.println("getFirstname: "+getFirstname());
System.out.println("getDepartment: "+getDepartment());
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Because in getters you have done it like
return department change that to this.department and same goes for firstname
Edit:
It worked in your case, as I just wanted to enforce the values using this but I need to understand why it didn't work before.
I did not try this code and this may sound bit childish but did you try changing the name? Have you checked for white spaces?
I am generating below page using Struts2. It is generating properly.
My question is how fetch the value from generated page when I click on delete button so I can further process for delete data from database and regenerate page with remaining data?
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h3>All Records:</h3>
<table>
<s:form action="upload">
<s:iterator value="list">
<tr>
<td ><s:property value="id"/></td>
<td ><s:property value="name"/></td>
<td><s:property value="password"/></td>
<td><s:property value="email"/></td>
<td><s:property value="gender"/></td>
<td><s:checkbox name="checked" label="isChecked" theme="simple" /></td>
</tr>
</s:iterator>
<s:submit value="delete" name="delete" />
</s:form>
</table>
</body>
</html>
RegisterAction.java
package com.javatpoint;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class RegisterAction {
private String name,password,email,gender,country;
int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
ArrayList<User> list=new ArrayList<User>();
public ArrayList<User> getList() {
return list;
}
public void setList(ArrayList<User> list) {
this.list = list;
}
public String execute(){
int i=RegisterDao.save(this);
if(i>0){
Connection con=RegisterDao.con;
try {
PreparedStatement ps=con.prepareStatement("select * from STRUTSUSER");
ResultSet rs=ps.executeQuery();
// rs = ps.getGeneratedKeys();
while(rs.next()){
User user=new User();
user.setId(rs.getInt(1));
user.setName(rs.getString(1));
user.setPassword(rs.getString(2));
user.setEmail(rs.getString(3));
user.setGender(rs.getString(4));
list.add(user);
// System.out.println("yo");
}
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "success";
}
return "error";
}
you can try something as below:
public class RegisterAction {
....
public String execute(){
...
}
public List<User> getAllUsers() {
List<User> users = new ArrayList<User>();
Connection con=RegisterDao.con;
try
{
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery("select * from STRUTSUSER");
while (rs.next())
{
User user = new User();
user.setID(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("pass"));
user.setEmailID(rs.getString("emailid"));
users.add(user);
}
}
catch (SQLException e)
{
e.printStackTrace();
}
return users;
}
public String delete() {
HttpServletRequest request ServletActionContext.getRequest();
int userId = request.getParameter("id");
deleteUser(userId);
return SUCCESS;
}
private void deleteUser(int userId)
{
Connection con=RegisterDao.con;
try
{
PreparedStatement ps = conn.prepareStatement("delete from STRUTSUSER where id=?");
// Parameters start with 1
ps.setInt(1, userId);
ps.executeUpdate();
} catch (SQLException e)
{
e.printStackTrace();
}
}
}
JSP page : view.jsp
<s:iterator value="list">
...
</s:iterator>
<s:hidden name="id" value="%{#list.id}" />
<s:submit value="delete" name ="delete" action="deleteUserAction"/>
In Struts.xml
<action name="deleteUserAction" class="example.RegisterAction" method="delete">
<result name="success">view.jsp</result>
</action>
After deleting user, you can call getAllUsers() from action
Hope this Helps
My task: I have to delete operation over the table “testtable” each row from jsp view.
My problem: not able to get the table id while deleting it’s row.
Application technology used: jsp as view , servlet as controller, setter and getter method as model and jdbc code for database operation.
Backend mysql:=I have two table one “userinfo” for aurtherntication and another table “testtable”.
For the two table connection I have used hidden field input in jsp as instead of using foreign key relation.
In the console print we can see after clicking the delete button
com.mysql.jdbc.JDBC4PreparedStatement#1f4bcaf: delete from testtable where id=0 and email='myswagt#yahoo.com'
at home servlet
userid is 0
please help me according to jsp,servlet,model,jdbc post below:
//expense model
package com.intermediateDemo.home.dto;
public class ItemBean {
private int id;
private String email;
private String itemName;
private Double itemPrice;
private String transactionTime;
private int userid;
public ItemBean() {
}
public ItemBean(int id, String email, String itemName, Double itemPrice, String transactionTime) {
this.id = id;
this.itemName = itemName;
this.itemPrice = itemPrice;
this.transactionTime = transactionTime;
this.email = email;
}
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("\n----------------------------------------------------------------------------------------------\n");
stringBuilder.append("Id: " + id);
//stringBuilder.append("\tName: " + firstName + ' ' + middleName + ' ' + lastName);
stringBuilder.append("\titemname: " + itemName);
stringBuilder.append("\titemprice: " + itemPrice);
stringBuilder.append("\ttime: " + transactionTime);
stringBuilder.append("\n----------------------------------------------------------------------------------------------\n");
return stringBuilder.toString();
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public Double getItemPrice() {
return itemPrice;
}
public void setItemPrice(Double itemPrice) {
this.itemPrice = itemPrice;
}
public String getTransactionTime() {
return transactionTime;
}
public void setTransactionTime(String transactionTime) {
this.transactionTime = transactionTime;
}
}
//user model
package com.intermediateDemo.login.dto;
public class LoginBean {
private int userid;
private String email;
private String password;
public boolean valid;
private String lastName;
private String firstName;
public LoginBean() {
}
public LoginBean(String email, String lastname, String firstname) {
this.email = email;
this.firstName = firstname;
this.lastName = lastname;
}
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isValid() {
return valid;
}
public void setValid(boolean valid) {
this.valid = valid;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public String getFirstName() {
return firstName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
//delete servlet
package com.intermediateDemo.home.controller;
import com.intermediateDemo.home.dao.ItemDao;
import com.intermediateDemo.home.dao.ItemDaoFactory;
import com.intermediateDemo.home.dto.ItemBean;
import com.intermediateDemo.login.dto.LoginBean;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class DeleteExpense extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws NumberFormatException, ServletException, IOException {
ItemBean item = new ItemBean() ;
try {
ItemDao dao = ItemDaoFactory.getItemDao();
HttpSession session = request.getSession(false);
LoginBean user = (LoginBean) session.getAttribute("user");
item.setId(Integer.parseInt(request.getParameter("id")));
item.setEmail(user.getEmail());
dao.deleteItem(item, user);
} catch (Exception e) {
e.printStackTrace();
}
finally {
response.sendRedirect("homeservlet");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher view;
view = request.getRequestDispatcher("/home/home.jsp");
view.forward(request,response);
}
}
//jdbc code
public void deleteItem(ItemBean item, LoginBean user) throws Exception {
try {
JdbcConnection connection = new JdbcConnection();
String query = "delete from testtable where id=? and email=?";
Connection con = connection.getConnection();
PreparedStatement pstm = con.prepareStatement(query);
pstm.setInt(1, item.getId());
pstm.setString(2, user.getEmail());
System.out.println(pstm);
pstm.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
//jsp view
<%--
Created by IntelliJ IDEA.
User: Dell
Date: 3/13/14
Time: 8:12 PM
To change this template use File | Settings | File Templates.
--%>
<%# page import="com.intermediateDemo.home.dto.ItemBean" %>
<%# page import="java.util.List" %>
<%# page import="com.intermediateDemo.login.dto.LoginBean" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>home</title>
<link rel="stylesheet" type="text/css" href="style_css/mystylesheet.css">
<link rel=”stylesheet” href=”resource/css/bootstrap.css” type=”text/css”/>
</head>
<body>
<jsp:include page="../includes/header.jsp"/>
<div id="content" style="margin-left: 330px;margin-bottom: 10px">
Welcome <%=session.getAttribute("email")%>
your id is <%=session.getAttribute("userid")%>
your firstname is <%=session.getAttribute("firstname")%>
<h2>Your Financial Management</h2>
<form action="homeservlet" method="post">
<!--start display-->
<legend>
<h2>Expense list</h2>
</legend>
<div>
<table class="table table-bordered table-striped" style="padding- left:200px;border:2px;border-bottom-color: limegreen">
<thead>
<tr style="background: limegreen">
<th >Expense title</th>
<th>Expense amount</th>
<th>Expense Date</th>
</tr>
</thead>
<tbody>
<c:forEach var="item" items="${requestScope.itemList}" >
<tr style="background:#808080;color:#ffffff">
<td><c:out value="${item.getItemName()}"> </c:out></td>
<td><c:out value="${item.getItemPrice()}"> </c:out></td>
<td><c:out value="${item.getTransactionTime()}"> </c:out></td>
<td>
<form method="post" action="/deleteexpense">
<input type="hidden" name="id" value="${item.id}">
<input class="btn btn-mini btn-danger " type="submit" value="Delete"/>
<a class="btn btn-mini " href="edit?id=${item.id}">Edit</a>
</form>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</form>
</div>
<jsp:include page="../includes/footer.jsp"/>
</body>
</html>
//DAO where I retrieve the data of ItemBean
public List<ItemBean> getItemFromdb(LoginBean user) throws SQLException {
List<ItemBean> itemList = new ArrayList<ItemBean>();
JdbcConnection connecton = new JdbcConnection();
//String query = "select * from testtable where userid = ?";
String query = "select * from testtable where email = ?";
ResultSet rs;
try {
Connection con = connecton.getConnection();
PreparedStatement pstm = con.prepareStatement(query);
// pstm.setInt(1, user.getUserid());
pstm.setString(1,user.getEmail());
rs = pstm.executeQuery();
while (rs.next()) {
ItemBean item = new ItemBean();
item.setItemName(rs.getString("itemname"));
item.setItemPrice(rs.getDouble("itemprice"));
item.setTransactionTime(rs.getString("transactiontime"));
// item.setUserid(rs.getInt("userid"));
item.setEmail(rs.getString("email"));
itemList.add(item);
}
System.out.println("at jdbc code");
for (ItemBean item1 : itemList) {
System.out.println(item1.getItemName());
System.out.println(item1.getItemPrice());
System.out.println(item1.getTransactionTime());
}
} catch (SQLException e) {
e.printStackTrace();
}
return itemList;
}
//jdbc code for item insert,retrieve and delete like operation in one page is
package com.intermediateDemo.home.dao.mysql;
import com.intermediateDemo.common.JdbcConnection;
import com.intermediateDemo.home.dto.ItemBean;
import com.intermediateDemo.login.dto.LoginBean;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class JdbcItemMysql {
public void itemtodb(ItemBean item, LoginBean user) throws Exception {
JdbcConnection connection = new JdbcConnection();
//String query = "insert into testtable (itemname,itemprice,transactiontime,userid) values (?,?,?,?)";
String query = "insert into testtable (itemname,itemprice,transactiontime,email) values (?,?,?,?)";
try {
Connection con = connection.getConnection();
PreparedStatement pstm = con.prepareStatement(query);
pstm.setString(1, item.getItemName());
pstm.setDouble(2, Double.parseDouble(String.valueOf(item.getItemPrice())));
pstm.setString(3, item.getTransactionTime());
pstm.setString(4, user.getEmail());
// pstm.setInt(4,user.getId());
pstm.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
public List<ItemBean> getItemFromdb(LoginBean user) throws SQLException {
List<ItemBean> itemList = new ArrayList<ItemBean>();
JdbcConnection connecton = new JdbcConnection();
//String query = "select * from testtable where userid = ?";
String query = "select * from testtable where email = ?";
ResultSet rs;
try {
Connection con = connecton.getConnection();
PreparedStatement pstm = con.prepareStatement(query);
// pstm.setInt(1, user.getUserid());
pstm.setString(1,user.getEmail());
rs = pstm.executeQuery();
while (rs.next()) {
ItemBean item = new ItemBean();
item.setItemName(rs.getString("itemname"));
item.setItemPrice(rs.getDouble("itemprice"));
item.setTransactionTime(rs.getString("transactiontime"));
// item.setUserid(rs.getInt("userid"));
item.setEmail(rs.getString("email"));
itemList.add(item);
}
System.out.println("at jdbc code");
for (ItemBean item1 : itemList) {
System.out.println(item1.getItemName());
System.out.println(item1.getItemPrice());
System.out.println(item1.getTransactionTime());
}
} catch (SQLException e) {
e.printStackTrace();
}
return itemList;
}
public void deleteItem(ItemBean item, LoginBean user) throws Exception {
try {
JdbcConnection connection = new JdbcConnection();
String query = "delete from testtable where id=? and email=?";
Connection con = connection.getConnection();
PreparedStatement pstm = con.prepareStatement(query);
pstm.setInt(1, item.getId());
pstm.setString(2, user.getEmail());
System.out.println(pstm);
pstm.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
You are not passing the record id to the jsp page from your method. Your getItemFromdb() should be some thing like this
public List<ItemBean> getItemFromdb(LoginBean user) throws SQLException {
// whatever you are doing comes here
while (rs.next()) {
ItemBean item = new ItemBean();
item.setId(rs.getInt("id"); // you need to have this, here id is the the primary key of the table
item.setItemName(rs.getString("itemname"));
item.setItemPrice(rs.getDouble("itemprice"));
item.setTransactionTime(rs.getString("transactiontime"));
// item.setUserid(rs.getInt("userid"));
item.setEmail(rs.getString("email"));
itemList.add(item);
}
// rest of the code
}
so that in the jsp page you can use this id to identify the record do whatever operation you want to do
To be shortly: here is simple web app. On the main page there is a button, after clickig on it it has to be another page with table that contains data from database.
Im using servlets/jsp MySQL
Here is code
Main page
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<title>University</title>
</head>
<body>
<h2 style="text-align: center">Welcome to university!</h2>
<p style="text-align: center"><img src="Images/university.jpg"></p>
<form>
<p style="text-align: center">
<button formmethod="GET" formaction="SelectStudents.do">See all students</button>
</p>
</form>
</body>
</html>
Page with table
<%# page import="java.util.List" %>
<%# page import="model.StudentDAO" %>
<%# page import="model.Student" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Students</title>
</head>
<body>
<table border="1" >
<caption>Students</caption>
<tr>
<th>ID</th>
<th>Name</th>
<th>Surname</th>
<th>Age</th>
<th>Country</th>
<th>City</th>
<th>Street</th>
<th>House</th>
<th>Flat</th>
<th>Group</th>
</tr>
<%
List<Student> students = new StudentDAO().selectAll();
for (Student s : students) {
%>
<tr>
<td><%=s.getId()%>></td>
<td><%=s.getName()%>></td>
<td><%=s.getSurname()%>></td>
<td><%=s.getAge()%>></td>
<td><%=s.getAddress().getCountry()%>></td>
<td><%=s.getAddress().getCity()%>></td>
<td><%=s.getAddress().getStreet()%>></td>
<td><%=s.getAddress().getHouseNumber()%>></td>
<td><%=s.getAddress().getFlatNumber()%>></td>
<td><%=s.getGroup().getName()%>></td>
</tr>
<%
}
%>
</table>
</body>
</html>
Class Student
public class Student {
private int id;
private String name;
private String surname;
private int age;
private Address address;
private Group group;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String name) {
this.surname = surname;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setAddress(Address address) {
this.address = address;
}
public Address getAddress() {
return address;
}
public void setGroup(Group group) {
this.group = group;
}
public Group getGroup() {
return group;
}
}
JDBCConnecto
package model;
import java.sql.*;
public class ConnectionManager {
private static final String JDBC_LOADER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost:3306/";
private static final String LOGIN = "root";
private static final String PASSWORD = "15021990";
private Connection connection;
public ConnectionManager() throws ClassNotFoundException, SQLException{
Class.forName(JDBC_LOADER);
connection = DriverManager.getConnection(URL, LOGIN, PASSWORD);
}
public Connection getConnection() throws SQLException{
return connection;
}
}
DAO
package model;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class StudentDAO {
private static final String SELECT_ALL =
"SELECT student.id, student.name, student.surname, student.age, \n" +
"\t address.country, address.city, address.street, address.house, address.flat, \n" +
"\t class.name\n" +
"\t FROM University.student join University.address \n" +
"\t on university.student.address = university.address.id join university.class\n" +
"\t on university.student.class = university.class.id";
public List<Student> selectAll() {
List<Student> result = new ArrayList<Student>();
Connection c = null;
try {
c = new ConnectionManager().getConnection();
Statement s = c.createStatement();
ResultSet students = s.executeQuery(SELECT_ALL);
while (students.next()) {
int id = students.getInt(1);
String name = students.getString(2);
String surname = students.getString(3);
int age = students.getInt(4);
String country = students.getString(5);
String city = students.getString(6);
String street = students.getString(7);
int house = students.getInt(8);
int flat = students.getInt(9);
String groupName = students.getString(10);
Address address = new Address();
address.setCountry(country);
address.setCity(city);
address.setStreet(street);
address.setHouseNumber(house);
address.setFlatNumber(flat);
Group group = new Group();
group.setName(groupName);
Student student = new Student();
student.setId(id);
student.setName(name);
student.setSurname(surname);
student.setAge(age);
student.setAddress(address);
student.setGroup(group);
result.add(student);
}
} catch (SQLException e) {
System.out.print(e.getErrorCode());
} catch (ClassNotFoundException e) {
} finally {
try {
if (c != null)
c.close();
} catch (SQLException e) {
System.out.print(e.getErrorCode());
}
}
return result;
}
}
Servlet
package controller;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class StudentsSelect extends HttpServlet {
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) {
RequestDispatcher view = request.getRequestDispatcher("table.jsp");
try {
view.forward(request, response);
} catch (ServletException e) {
} catch (IOException e) {
}
}
}
The problem is that after pressing the button there is no information about students in table in table.jsp.
You obviously forgot to add your MySQL connector (select platform independent and click download zip package, if your didn't download it). Add MySQL connector jar file to lib directory in your project. That should solve your problem.