How to download data from database into JSP table? - java

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.

Related

MySql date one day split

I'm trying to do a very simple java web app which allows to informations of a person: fristname, surname, date of birth and store them in a MySql db.
The issue is that when I try to insert a date(e.g.07/03/2019), on db the date is one day before(06/03/2019).
How is it possible to fix that?
Below the code:
The bean
package bean;
import java.io.Serializable;
import java.sql.Date;
public class Persona implements Serializable {
private int idPersona;
private String nome;
private String cognome;
private Date dataNascita;
public Persona() {
super();
}
public Persona(String nome, String cognome, Date dataNascita) {
super();
this.nome = nome;
this.cognome = cognome;
this.dataNascita = dataNascita;
}
public Persona(int idPersona, String nome, String cognome, Date dataNascita)
{
super();
this.idPersona = idPersona;
this.nome = nome;
this.cognome = cognome;
this.dataNascita = dataNascita;
}
public int getIdPersona() {
return idPersona;
}
public void setIdPersona(int idPersona) {
this.idPersona = idPersona;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCognome() {
return cognome;
}
public void setCognome(String cognome) {
this.cognome = cognome;
}
public Date getDataNascita() {
return dataNascita;
}
public void setDataNascita(Date dataNascita) {
this.dataNascita = dataNascita;
}
}
The servlet
package servlet;
import java.io.IOException;
import java.sql.Date;
import java.sql.SQLException;
import java.text.ParseException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import bean.Persona;
import dao.ProvaDao;
import utility.ManipolazioneDate;
#WebServlet("/Inserimento")
public class Inserimento extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public Inserimento() {
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
String nome = request.getParameter("nome");
String cognome = request.getParameter("cognome");
String dataNascita = request.getParameter("dataNascita");
Date dataN = null;
try {
dataN = (Date) ManipolazioneDate.convertiData(dataNascita);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Persona p = new Persona(nome, cognome, dataN);
System.out.println(p.getNome());
System.out.println(p.getCognome());
System.out.println(p.getDataNascita());
try{
ProvaDao.registraPersona(p);
}catch(SQLException e){
e.printStackTrace();
}
}
}
A class with a static method to parse a String date format into a java.sql.Date format
package utility;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ManipolazioneDate {
public static Date convertiData(String data) throws ParseException{
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date parser = format.parse(data);
java.sql.Date dataSql = new java.sql.Date(parser.getTime());
return dataSql;
}
}
Dao
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import bean.Persona;
import utility.Connessione;
public class ProvaDao {
public static void registraPersona(Persona persona) throws SQLException{
Connection conn = Connessione.getConnection();
PreparedStatement ps = null;
String ins = "insert into prova2.persona(nome, cognome, dataNascita)
values(?,?,?)";
try{
ps = conn.prepareStatement(ins);
ps.setString(1, persona.getNome());
ps.setString(2, persona.getCognome());
ps.setDate(3, persona.getDataNascita());
ps.executeUpdate();
System.out.println("Persona inserita");
}catch(SQLException e){
System.out.println(e.getMessage());
System.out.println("Errore nell'inserimento");
}finally{
if(ps != null){
ps.close();
}
if(conn != null){
conn.close();
}
}
}
}
JSP with form
<%# 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>
<div align="center">
<form action="/Prova/Inserimento" method="get">
<p>Nome</p>
<input type="text" value="" name="nome">
<br>
<p>Cognome</p>
<input type="text" value"" name="cognome">
<br>
<p>Data di nascita</p>
<input type="text" value="" name="dataNascita">
<br>
<input type="submit" value="Invia">
</form>
</div>
</body>
</html>
Thank you.
Maybe code is not wrong. (Because code does not manipulate datetime.)
At java code, do SELECT CURRENT_TIMESTAMP; get and check the timestamp. If the timestamp is wrong, it is due to MySQL server.

java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long Spring with sql and java

so i made simple site where i can add products to list (text area) using Spring framework 4.0.1, i can see page content but in text area on the bottom there is this exception preventing me from getting products on list.
Model class
package model;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
*
* #author mkSS
*/
public class Products {
public int product_id;
public String productname;
public String productstock;
public String productdescription;
public int getProduct_id() {
return product_id;
}
public void setProduct_id(int product_id) {
this.product_id = product_id;
}
public String getProductname() {
return productname;
}
public void setProductname(String productname) {
this.productname = productname;
}
public String getProductstock() {
return productstock;
}
public void setProductstock(String productstock) {
this.productstock = productstock;
}
public String getProductdescription() {
return productdescription;
}
public void setProductdescription(String productdescription) {
this.productdescription = productdescription;
}
public static String productList() throws ClassNotFoundException, SQLException {
StringBuilder product_list = new StringBuilder();
Class.forName("com.mysql.jdbc.Driver");
try (java.sql.Connection conn= DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "miksa988");){
Statement st= conn.createStatement();
st.executeQuery("select productname, productstock,productdescription from products");
ResultSet rs= st.getResultSet();
while (rs.next()){
product_list.append(rs.getString("productname"));
product_list.append(rs.getString(", "));
product_list.append(rs.getString("productstock"));
product_list.append(rs.getString(", "));
product_list.append(rs.getString("productdescription"));
product_list.append(rs.getString("\n"));
}
} catch(SQLException ex){
product_list.append(ex.getMessage());
}
return product_list.toString();
}
public void addProduct() throws ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
try (java.sql.Connection conn= DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "miksa988");){
if (productname !=null && !(productname.isEmpty()) && productstock !=null && !(productstock.isEmpty()) && productdescription !=null && !(productdescription.isEmpty())){
Statement st = conn.createStatement();
st.execute("insert into products (productname,productstock, productdescription) values ('"+ productname + "','"+productstock+"','"+productdescription+"')");
}
}catch(SQLException ex){
System.out.println("Error while trying to connect with databse"+ex);
}
}
}
And now this is my controller class
package controller;
import java.sql.SQLException;
import model.Products;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class ProductController {
#RequestMapping(value = "/product", method= RequestMethod.GET)
public String createForm(ModelMap model) throws ClassNotFoundException, SQLException{
model.addAttribute("product", new Products());
model.addAttribute("products", Products.productList() );
return "product";
}
#RequestMapping(value = "/product", method= RequestMethod.POST)
public String addProduct(#ModelAttribute("product") Products product , ModelMap model) throws ClassNotFoundException ,SQLException {
product.addProduct();
createForm(model);
return "product";
}
}
and this is my JSP page
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>E-commerce</title>
</head>
<body>
<h1>Our Products</h1>
<form:form action="product.htm" method="post" commandName="product">
<form:label path="productname">Enter product name:</form:label></br>
<form:input id="pname" type="text" path="productname" placeholder="product name"></form:input><br>
<form:label path="productstock">Enter amount of items in stock:</form:label></br>
<form:input id="pstock" type="text" path="productstock" placeholder="product stock"></form:input><br>
<form:label path="productdescription">Enter product description:</form:label></br>
<form:input id="pdescription" type="text" path="productdescription" placeholder="product description"></form:input><br>
<input type="submit" value="Dodaj proizvod"/>
</form:form>
<label for="product_list" id="products_list_label">List of products: </label> </br>
<textarea id="products_list" rows="20" cols="100" readonly>${products}</textarea>
</body>
</html>
this is my SQL Query
`product_id` INT NOT NULL AUTO_INCREMENT,
`productname` VARCHAR(45) NOT NULL,
`productstock` INT NOT NULL,
`productdescription` VARCHAR(45) NOT NULL,
PRIMARY KEY (`product_id`));
Error occurred when i load page, i can see content (those labels and text area) but in text-area i can see this java lang class cast exception is there, so when i try to get products on list i can't. What could it be?

MySQL classNotFoundException & no suitable Driver found for jdbc

I'm new to study JSP.
I have added this jar file mysql-connector-java-5.1.38-bin.jar
mysql-connector
The IML file:
<CLASSES>
<root url="jar://$USER_HOME$/Downloads/mysql-connector-java-5.1.38/mysql-connector-java-5.1.38/mysql-connector-java-5.1.38-bin.jar!/" />
</CLASSES>
I made a class of a table like this:
package test;
public class Student {
private int id;
private String name;
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 Student(int id,String name){
super();
this.name = name;
this.id = id;
}
}
and a operating class:
package test;
import java.sql.*;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class StudentOperation {
public List readStudent(){
List<Student> list = new ArrayList<>();
com.mysql.jdbc.Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try{
Class.forName("com.mysql.jdbc.Driver");
}catch (ClassNotFoundException e){
e.printStackTrace();
}
try{
connection = (com.mysql.jdbc.Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root",null);
String sql = "SELECT * FROM student WHERE student_id>=?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,1);
resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
String studentName = resultSet.getString("student_name");
int studentId = resultSet.getInt("student_id");
Student student = new Student(studentId,studentName);
list.add(student);
}
}catch (SQLException e){
e.printStackTrace();
}finally {
try{
if(resultSet!=null){
resultSet.close();
}
if(preparedStatement!=null){
preparedStatement.close();
}
if(connection!=null){
connection.close();
}
}catch (SQLException e){
e.printStackTrace();
}
}
return list;
}
public static void main(String[] args){
StudentOperation studentOperation = new StudentOperation();
List<Student> list = studentOperation.readStudent();
System.out.println(list.size());
for(Student student : list){
System.out.println(student.getName()+"\t");
System.out.println(student.getId());
}
}
}
run the main method, it output the result like this:
3
student3
201592385
student2
201592386
student1
201592387
It's the right result. But when I add to the jsp file:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# page import="test.Student" %>
<%# page import="test.StudentOperation" %>
<%# page import="java.util.List" %>
<html>
<head>
<title>Homework</title>
</head>
<body>
<h1 align="center">Student Database</h1>
<table border="1">
<tr>
<td>Student Name</td>
<td>Student ID</td>
</tr>
<%
try {
StudentOperation studentOperation = new StudentOperation();
List<Student> list = studentOperation.readStudent();
for(Student student : list){ %>
<tr>
<td><%= student.getName() %></td>
<td><%= student.getId() %></td>
</tr>
<% }
}catch (Exception e){e.printStackTrace();}
%>
</table>
</body>
</html>
It is like this:
the result
And throw the exception:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/student
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
What's wrong?
put the jar of driver in the server lib folder
i.e. at ($CATALINA_HOME/lib) Then check. Hope it helps

How to fetch data from dynamically generated JSP page in Struts 2?

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

delete from jsp view. can't get the table id while deleting it’s row

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

Categories