Developing Java web services using Jersey(JAX-RS), MySQL and Eclipse - java

I have problem of inserting data in my database Table from HTML page. When ever I run the application and send the data, all my fields in the Table will be NULL.
This is my database connection class
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DbConnection {
public static Connection getConnection() throws Exception
{
try
{
String connectionURL = "jdbc:mysql://localhost:3306/dvd_collection";
Connection connection = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "031081");
return connection;
}
catch (SQLException e)
{
throw e;
}
catch (Exception e)
{
throw e;
}
}
public static void close(Connection connection)
{
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
This is my userVo class
package pojo;
public class UserVo {
private String username;
private String password;
private String email;
private String gender;
private String occupation;
private String marital;
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 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 getOccupation() {
return occupation;
}
public void setOccupation(String occupation) {
this.occupation = occupation;
}
public String getMarital() {
return marital;
}
public void setMarital(String marital) {
this.marital = marital;
}
}
This is my Service class
package webService;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import pojo.UserVo;
#Path("/WebService")
public class SignUpService {
#POST
#Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
#Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public UserVo create(UserVo user)throws Exception {
System.out.println("creating user");
return dao.create(user);
}
This is my JS file
// The root URL for the RESTful services
var rootURL = "http://localhost:8080/Test/REST/WebService";
$('#btnSubmit').click(function() {
if ($('#UserName').val() == '')
alert('User Name can not be empty');
else
addWine();
return false;
});
function addWine() {
console.log('addWine');
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootURL,
dataType: "json",
data: formToJSON(),
success: function(data, textStatus, jqXHR){
alert('Record created successfully: Login to your account');
},
error: function(jqXHR, textStatus, errorThrown){
alert('The User name already exist: ' + textStatus);
}
});
}
// Helper function to serialize all the form fields into a JSON string
function formToJSON() {
return JSON.stringify({
"username": $('#UserName').val(),
"password": $('#Password').val(),
"email": $('#Email').val(),
"gender": $('#Gender').val(),
"occupation": $('#Occupation').val(),
"marital": $('#MaritalStatus').val()
});
}
This is my SignUpHandler Class
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import dao.DbConnection;
import pojo.UserVo;
public class SignUpHandler {
public UserVo create(UserVo user) throws Exception {
Connection c = null;
PreparedStatement ps = null;
try {
c = DbConnection.getConnection();
ps = c.prepareStatement("INSERT INTO signin (user_name, password, e_mail, gender, occupation, marital_status) VALUES (?, ?, ?, ?, ?, ?)",
new String[] { "ID" });
ps.setString(1, user.getUserName());
ps.setString(2, user.getPassword());
ps.setString(3, user.getEmail());
ps.setString(4, user.getGender());
ps.setString(5, user.getOccupation());
ps.setString(6, user.getMarital());
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
rs.next();
// Update the id in the returned object. This is important as this value must be returned to the client.
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
DbConnection.close(c);
}
return user;
}
}
This is my HTML Form
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Test</title>
</head>
<body>
<form class="form-signup">
<h2 class="form-signin-heading">Please Register</h2>
<input name="UserName" type="text" placeholder="Username">
<input name="Password" type="password" placeholder="Password">
<input name="Email" type="text" placeholder="Email">
<input name="Gender" type="text" placeholder="Gender">
<input name="Occupation" type="text" placeholder="Occupation">
<input name="MaritalStatus" type="text" placeholder="Marital Status">
<button type="submit" id="btnSubmit">Submit</button>
</form>
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="js/jquery-1.8.2.js"></script>
<script src="js/main.js"></script>
</body>
</html>

You use $('#UserName').val() to get the value of the user name text input, but this text input doesn't have the id UserName. It has the name UserName. So you actually want
$('input[name="UserName"]').val()
or, more simply
<input name="UserName" id="UserName" type="text" placeholder="Username"/>
(same for all the other fields, of course)
Side note: what's the point of catching an exception only to rethrow it? This adds unnecessary lines to your code, and make it more difficult to identify the source of an exception.

Related

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?

Issue connecting to Database - JSP / Netbeans

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!

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

How to download data from database into JSP table?

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.

Categories