Cannot show ArrayList from Servlet to JSP - java

I am using servlet and jsp to show Access database.
MainDatabase.java
public class MainDatabase
{
private int proId;
private String proName;
private String proQuantity;
private String proPrice;
public MainDatabase()
{
this.proId = 0;
this.proName = "";
this.proQuantity = "";
this.proPrice = "";
}
public int getProId() {
return proId;
}
public void setProId(int proId) {
this.proId = proId;
}
public String getProName() {
return proName;
}
public void setProName(String proName) {
this.proName = proName;
}
public String getProQuantity() {
return proQuantity;
}
public void setProQuantity(String proQuantity) {
this.proQuantity = proQuantity;
}
public String getProPrice() {
return proPrice;
}
public void setProPrice(String proPrice) {
this.proPrice = proPrice;
}
}
MainDatabaseUtil.java
import org.hsqldb.Database;
import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.ArrayList;
import java.util.List;
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
public class MainDatabaseUtil
{
public static List<MainDatabase> getMainDB() throws Exception
{
List<MainDatabase> mainDatabases = null;
JSONArray payload = null;
try
{
Connection conn = DriverManager.getConnection("jdbc:ucanaccess://D:\\study_materials\\Java\\Resources\\Database\\smsDemo.accdb");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * from Database");
stmt.close();
conn.close();
mainDatabases = new ArrayList<>();
//payload = new JSONArray();
if(rs != null)
{
while(rs.next())
{
MainDatabase proDB = new MainDatabase();
proDB.setProId(rs.getInt("ID"));
proDB.setProName(rs.getString("ProName"));
proDB.setProQuantity(rs.getString("Quantity"));
proDB.setProPrice(rs.getString("Price"));
mainDatabases.add(proDB);
}
}
return mainDatabases;
//return payload;
}
catch(Exception el)
{
return mainDatabases;
}
}
}
MainDatabaseServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.RequestDispatcher;
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 org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import javax.servlet.*;
#WebServlet("/MainDatabaseServlet")
public class MainDatabaseServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
public MainDatabaseServlet()
{
super();
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
try
{
List<MainDatabase> mainDatabases = MainDatabaseUtil.getMainDB();
request.setAttribute("main_list", mainDatabases);
RequestDispatcher dispatcher = request.getRequestDispatcher("/MainDatabaseView.jsp");
dispatcher.forward(request, response);
}
catch (Exception el)
{
el.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doGet(request, response);
}
}
MainDatabaseView.jsp
<%--
Created by IntelliJ IDEA.
User: Xenon
Date: 11/15/2018
Time: 9:15 PM
To change this template use File | Settings | File Templates.
--%>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page import ="java.util.ArrayList"%>
<%# page import ="java.util.List"%>
<html>
<head>
<title>Main Database</title>
</head>
<body>
<h2>Student Table Demo</h2><br>
<hr>
<br>
<table border="1">
<tr>
<th>ID</th>
<th>NAME</th>
<th>QUANTITY</th>
<th>PRICE</th>
</tr>
<c:forEach var="tempData" items="${main_list}">
<tr>
<td>${tempData.proId}</td>
<td>${tempData.proName}</td>
<td>${tempData.proQuantity}</td>
<td>${tempData.proPrice}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
I am using IntelliJ Idea. It's showing that in MainDatabaseView.jsp, it cannot resolve variable main_list.
Current Output: Its showing table column name but no data in it.
Expected output should be showing database value in table view when the program is run.
Please help. Thank you.

Call stmt.close(); and conn.close(); after retrieving the values from the ResultSet
https://docs.oracle.com/javase/tutorial/jdbc/basics/processingsqlstatements.html
When you are finished using a Statement, call the method Statement.close to immediately release the resources it is using. When you call this method, its ResultSet objects are closed.
If you close the statement before retrieving the result set, the result set will no longer have any reference to the data.

Related

How do I output results of an SQL query using java servlet

I'm trying to implement a search feature to my web application that allows a user to search a database of products. I've attempted to do this using the following:
The .jsp file for the web page which starts by listing all products (productSearch.jsp):
<%#page import="java.sql.Connection"%>
<%#page import="databaseManagement.DBConnection"%>
<%#page import="java.sql.ResultSet" %>
<%#page import="java.sql.SQLException"%>
<%#page import="java.sql.Connection"%>
<%#page import="java.sql.PreparedStatement"%>
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Search Our Products</title>
</head>
<body>
<form method="post">
Search:<input type="text" name="Search">
<input type="submit" value="Go">
<table border="2">
<tr>
<td>ID</td>
<td>NAME</td>
<td>DESCRIPTION</td>
<td>PRICE</td>
</tr>
<%
try
{
DBConnection db = new DBConnection();
Connection con = db.getConnection();
PreparedStatement ps = con.prepareStatement("select * from products");
ResultSet rs = ps.executeQuery();
while(rs.next())
{
%>
<tr>
<td><%=rs.getInt("ID") %></td>
<td><%=rs.getString("NAME") %></td>
<td><%=rs.getString("DESCRIPTION") %></td>
<td><%=rs.getString("PRICE") %></td>
</tr>
<%
}
%>
</table>
<%
rs.close();
con.close();
}
catch(Exception e)
{
e.printStackTrace();
}
%>
</form>
</body>
</html>
The class to take the user's input and run the query (ProductSearch.java):
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import databaseManagement.DBConnection;
#WebServlet("/ProductSearch")
public class ProductSearch extends HttpServlet {
private static final long serialVersionUID = 1L;
public ProductSearch() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
String searchTerm = request.getParameter("Search");
try {
DBConnection db = new DBConnection();
Connection con = db.getConnection();
PreparedStatement ps = con.prepareStatement("select * from products where name like %?%");
ps.setString(1, searchTerm);
ResultSet rs = ps.executeQuery();
return;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And lastly a class to handle the connection to the database (DBConnection):
package databaseManagement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnection {
public Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
// TODO: finish
//CHANGE USERNAME AND PASSWORD WHEN IMPLIMENTING ON VM
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/applicationdata", "root", "safepassword");
return con;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
}
The issue I'm now having is that I'm not sure how to take the results I got from the ProductSearch class and display them back in the productSearch.jsp page.
I'm quite new to this, so I apologise if I've made any glaring mistakes. Any help is greatly appreciated :)
Firstly , create a class where all values which you want return back is declared and also getter/setter of that variable .
i.e Suppose variable user.
import java.util.*;
public class Abc{
private String user;
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public Abc(String user) {
this.user = user;
}
}
Next , In your ProductSearch.java file put this code :
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
String searchTerm = request.getParameter("Search");
ArrayList<Abc> ab= new ArrayList();
try
{
String sql1 ="select * from products where name like %?%";
PreparedStatement ps = conn.prepareStatement(sql1);
ps.setString(1,searchTerm);
resultSet = ps.executeQuery();
while(resultSet.next())
{
Abc b=new Abc();
b.setUser(resultSet.getString("user"));
ab.add(b);
}
request.setAttribute("r1", ab);
request.getRequestDispatcher("productSearch.jsp").forward(request, response);
}
catch(Exception s2)
{
s2.printStackTrace();
}
}
}
Lastly print result back in your productSearch.jsp page using jstl
<!-- this is use because we use jstl tag-->
<%#taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<table align="center" border="1">
<tr bgcolor="#d9ac26">
<td><b>search</b></td>
</tr>
<!--Here we are printing result-->
<c:forEach var="book" items="${r1}">
<tr bgcolor="">
<td>${book.user}</td>
</tr>
</c:forEach>
</table>
Hope this helps you. Make necessary changes as per your requirement . This is not complete code .

Java Servlet MVC, Show Database Query Result to JSP Table

Please help me about MVC java servlet. I found problem when show database query result on multiple rows and multiple columns (load all data, let say I get 10 rows after query), I want load all list student in JSP table.
How to setAttribute in the servlet and getAttribute in the JSP?
I'm set query result into a array list, this my code:
Bean Class
package com.mvc.bean;
public class StudentBean {
private String name;
private String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
DAO Class
package com.mvc.dao;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import com.mvc.bean.StudentBean;
import com.mvc.util.DBConnection;
public class StudentDao {
public ArrayList<StudentBean> getStudent() {
ArrayList<StudentBean> list_student = new ArrayList<StudentBean>();
Connection con = null;
Statement statement = null;
ResultSet resultSet = null;
try {
con = DBConnection.createConnection();
statement = con.createStatement();
resultSet = statement.executeQuery("SELECT * FROM tbl_student");
while(resultSet.next()){
StudentBean studentBean = new StudentBean();
studentBean.setId(resultSet.getString("id"));
studentBean.setName(resultSet.getString("name"));
list_student.add(studentBean);
}
} catch (Exception e) {
e.printStackTrace();
}
return list_student;
}
}
Servlet Class
package com.mvc.controller;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mvc.bean.StudentBean;
import com.mvc.dao.StudentDao;
public class StudentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public StudentServlet() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
StudentDao studentDao = new StudentDao();
ArrayList<StudentBean> studentList = studentDao.getStudent();
//I have get value studentBean as array list
//Here, how to request.setAttribute ? i want passing to jsp table
request.getRequestDispatcher("/Student.jsp").forward(request, response);
}
}
JSP
<!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>Student</title>
</head>
<body>
<table>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
<tr>
//Here i want get array value from servlet, how to ?
<td><%=request.getAttribute("?") %></td>
<td<%=request.getAttribute("?") %>></td>
</tr>
</table>
</body>
</html>
Or otherwise ?
From java code you can use : request.setAttribute("mylist", studentBean);
in you JSP you need to use request.getAttribute("mylist")
you will get your list.
For table you need to make loop for extracting information from your list.
Solved, in the Servlet Class added request.setAttribute.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
StudentDao studentDao = new StudentDao();
ArrayList<StudentBean> studentList = studentDao.getStudent();
//added here
request.setAttribute("studentList", studentList);
request.getRequestDispatcher("/Student.jsp").forward(request, response);
}
And get the studentList in the JSP.
Add #taglib prefix="c" in the top line:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
In the table use forEach to extract <tr> tag.
.getID() and .getName() refer to Bean Class method:
<table>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
<c:forEach var="studentBean" items="${studentList}">
<tr>
<td>${studentBean.getID()}</td>
<td>${studentBean.getName()}</td>
</tr>
</c:forEach>
</table>

Insert time and date in MySQL database using jsp,bean class and servlet

I want to insert the date and time in the database table. I got error in the insertdao.java as incompatible types timestamp cannot be convert to time.
I have a dttable in my MySQL database with columnname & data type Logindate DATE,Logintime TIMESTAMP,LogoutTime TIMESTAMP.
In index.jsp we have to insert the value in Logindate,Logintime,LogoutTime
<%#page language="java" contentType="text/html charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Timesheet Page</title>
</head>
<body>
<header>
<h2>WEEKLY TIME SHEET MANAGEMENT V 1.0</h2>
</header>
<form action="insertservlet" method="post">
<fieldset style="width: 90%">
<legend>Timesheet</legend>
<table>
<thead>
<tr>
<th>Date</th>
<th>Time In</th>
<th>Time Out</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="date" name="logindate" required="required" /></td>
<td><input type="time" name="logintime" required="required" /></td>
<td><input type="time" name="logouttime" required="required" /></td>
</tr>
</tbody>
</table>
</fieldset>
<input type="submit" value="Submit">
</form>
Logout
</body>
</html>
Bean.java:
package com.eis.bean;
import java.sql.Date;
import java.sql.Timestamp;
public class Bean {
public Bean() {}
private java.sql.Date logindate;
private java.sql.Timestamp logintime;
private java.sql.Timestamp logouttime;
public Date getLogindate() {
return logindate;
}
public void setLogindate(Date logindate) {
this.logindate = logindate;
}
public Timestamp getLogintime() {
return logintime;
}
public void setLogintime(Timestamp logintime) {
this.logintime = logintime;
}
public Timestamp getLogouttime() {
return logouttime;
}
public void setLogouttime(Timestamp logouttime) {
this.logouttime = logouttime;
}
#
Override
public String toString() {
return "Bean [logindate=" + logindate + ", logintime=" + logintime + ", logouttime=" + logouttime + "]";
}
}
insertdao.java:
package com.eis.bean;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Date;
import java.sql.Timestamp;
public class insertdao {
public static int addBean(Bean user, String sql) throws SQLException {
int i = 0;
Connection conn = ConnectionProvider.getConn();
try {
PreparedStatement preparedStatement = conn.prepareStatement(sql);
// Parameters start with 1
preparedStatement.setDate(1, new Date(user.getLogindate().getTime()));
preparedStatement.setTimestamp(2, new Timestamp(user.getLogintime().getTime()));
preparedStatement.setTimestamp(3, new Timestamp(user.getLogouttime().getTime()));
i = preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return i;
}
}
insertservlet.java:
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.eis.bean.Bean;
import com.eis.bean.insertdao;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
public class insertservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private insertdao dao;
public insertservlet() {
super();
dao = new insertdao();
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Bean user = new Bean();
try {
Date logindate = new SimpleDateFormat("yyyy/MM/dd").parse(request.getParameter("logindate"));
user.setLogindate((java.sql.Date) logindate);
} catch (ParseException e) {
e.printStackTrace();
}
try {
Date logintime = new SimpleDateFormat("HH:mm").parse(request.getParameter("logintime"));
user.setLogintime((java.sql.Timestamp) logintime);
} catch (ParseException ex) {
Logger.getLogger(insertservlet.class.getName()).log(Level.SEVERE, null, ex);
}
try {
Date logouttime = new SimpleDateFormat("HH:mm").parse(request.getParameter("logouttime"));
user.setLogouttime((java.sql.Timestamp) logouttime);
} catch (ParseException ex) {
Logger.getLogger(insertservlet.class.getName()).log(Level.SEVERE, null, ex);
}
insertdao dao = new insertdao();
String sql = "INSERT INTO dttable (LoginDate, LoginTime, LogoutTime) VALUES (?, ?, ?)";
try {
int i = insertdao.addBean(user, sql);
if (i != 0) {
out.print("<p style=\"color:Green\">Record saved successfully!!</p>");
RequestDispatcher rd = request.getRequestDispatcher("Sucsess.jsp");
rd.forward(request, response);
} else {
out.print("<p style=\"color:red\">**Record cannot be saved!**</p>");
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.include(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
#
Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}#
Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}#
Override
public String getServletInfo() {
return "Short description";
}
}
Please go through my code and help if my code is not right.
Try setTimestamp(int parameterIndex, java.sql.Timestamp x)
preparedStatement.setTimestamp(2, new Timestamp(user.getLogintime().getTimes()));
preparedStatement.setTimestamp(3, new Timestamp(user.getLogouttime().getTime()));

insert data into database through MVC model using setter getter class

I want to insert data into database in an organised way, i have a jsp page that takes the input id name salary from user and send to database table employee. table has three columns eid, ename ,esalary.
In my coding part i have three packages: com.mvc.javaclassbeans,com.mvc.javaclasses,com.mvc.servlets.
myservlet class in com.mvc.servlets package takes the parameter (eid,ename,esalary)from jsp page and process to set the parameters creating an object of employee class and insert the eid ename esalary values using new insertclass().insertfunction(obj);
My code is not showing any error but not inserting values. I am not getting the problem as i have parted my codes into different packages to make it work as mvc.
my com.mvc.javaclasses pakage consists of
dbconnector
insertclass
com.mvc.javaclassbeans consists of
employeeclass
com.mvc.servlets consists of
myservlet class
Below is my code:
insert.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="myservlet" method="post">
ID:<input type="text" name="eid">
NAME:<input type="text" name="ename">
SALARY:<input type="text" name="esalary">
<button type="submit" name="submit" value="submit" >Sign in</button>
</form>
</body>
</html>
mysevlet
package com.mvc.servlets;
import com.mvc.javaclassbeans.employee;
import com.mvc.javaclasses.dbconnector;
import com.mvc.javaclasses.insertclass;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(name = "myservlet", urlPatterns = {"/myservlet"})
public class myservlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
employee obj = new employee();
obj.setId(request.getParameter("eid"));
obj.setName(request.getParameter("ename"));
obj.setSalary(request.getParameter("esalary"));
try {
new insertclass().insertfunction(obj);
} catch (ClassNotFoundException ex) {
Logger.getLogger(myservlet.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(myservlet.class.getName()).log(Level.SEVERE, null, ex);
}
out.print("sucess");
}
catch (Exception ex) {
Logger.getLogger(myservlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Please help me to find the problem that i am missing.
This code just worked for me. For the sake of testing my configuration is:
Main code (Just put this code in Test class):
package sarah;
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 java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
class dbconnector {
//String user = "system";
//String pass = "system";
//String driver = "oracle.jdbc.OracleDriver";
//String dbURL = "jdbc:oracle:thin:#localhost:1521:XE";
ResultSet rs;
Connection connection = null;
Statement stmt = null;
public Connection Open() {
System.out.println("-------- MySQL JDBC Connection Testing ------------");
try {
Class.forName("org.postgresql.Driver");
connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/test", "postgres", "root");
System.out.println("Succeed!");
// return connection;
} catch (Exception e) {
System.out.println("you have stucked with error!!!!!!");
}
System.out.println("MySQL JDBC Driver Registered!");
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
return connection;
}
public void db_Close(Connection con) throws SQLException {
con.close();
return;
}
}
class employee {
String eid;
String ename;
String esalary;
// public employee(String eid, String ename, String esalary) {
// this.eid = eid;
// this.ename = ename;
// this.esalary = esalary;
//}
public String getId() {
return eid;
}
public void setId(String eid) {
this.eid = eid;
}
public String getName() {
return ename;
}
public void setName(String ename) {
this.ename = ename;
}
public String getSalary() {
return esalary;
}
public void setSalary(String esalary) {
this.esalary = esalary;
}
}
class insertclass {
// Connection connection = null;
PreparedStatement ps;
public String query;
public boolean insertfunction(employee ob) throws ClassNotFoundException, SQLException {
try {
dbconnector dbc = new dbconnector();
Connection connection = dbc.Open();
query = "insert into employee (eid,ename,esalary) values(?,?,?)";
java.sql.PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, ob.getId());
ps.setString(2, ob.getName());
ps.setString(3, ob.getSalary());
ps.executeUpdate();
return true;
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
}
}
#WebServlet(name = "Test", urlPatterns = {"/Test"})
public class Test extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
employee obj = new employee();
obj.setId(request.getParameter("eid"));
obj.setName(request.getParameter("ename"));
obj.setSalary(request.getParameter("esalary"));
try {
new insertclass().insertfunction(obj);
} catch (ClassNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
out.print("sucess");
} catch (Exception ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Table definition:
CREATE TABLE employee
(
eid text,
ename text,
esalary text
)
WITH (
OIDS=FALSE
);
ALTER TABLE employee
OWNER TO postgres;
And test.jsp file:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="Test" method="post">
ID:<input type="text" name="eid">
NAME:<input type="text" name="ename">
SALARY:<input type="text" name="esalary">
<button type="submit" name="submit" value="submit" >Sign in</button>
</form>
</body>
</html>

Retrieving a table from database: javax.el.PropertyNotFoundException

I want to retrieve a entire table from database and display it into my jsp page, but I am getting an error
my StaffBean. java is
package com.staff.bean;
import java.util.Date;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class StaffBean {
private String date;
private int workload;
private int hourId;
private int daysId;
private int staffId;
private String StaffName;
private String ActiveORInactive;
private String Stafftype;
private String subcode;
private boolean valid = false;
public String getdate() {
// DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
// Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); // your template here
java.util.Date dateStr = null;
try {
dateStr = formatter.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
java.sql.Date dateDB = new java.sql.Date(dateStr.getTime());
return formatter.format(dateDB);
}
public void setdate(String date){
this.date=date;
}
public int gethourId() {
return hourId;
}
public void sethourId(int hourId) {
this.hourId = hourId;
}
public int getdaysId() {
return daysId;
}
public void setdaysId(int daysId) {
this.daysId = daysId;
}
public int getworkload() {
return hourId;
}
public void setworkload(int workload) {
this.workload = workload;
}
public int getstaffId() {
return staffId;
}
public void setstaffId(int staffId) {
this.staffId = staffId;
}
public String getStaffName() {
return StaffName;
}
public void setStaffName(String StaffName) {
this.StaffName = StaffName;
}
public String ActiveORInactive() {
return ActiveORInactive;
}
public void setActiveORInactive(String ActiveORInactive) {
this.ActiveORInactive = ActiveORInactive;
}
public String getStafftype() {
return Stafftype;
}
public void setStafftype(String Stafftype) {
this.Stafftype = Stafftype;
}
public String getsubcode() {
return Stafftype;
}
public void setsubcode(String subcode) {
this.subcode = subcode;
}
public boolean isValid() {
return valid;
}
public void setValid(boolean valid) {
this.valid = valid;
}
}
and my GetAllDetailDAO.java is
package com.staff.DAO;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import com.staff.bean.StaffBean;
import com.staff.DB.ConnectionProvider;
public class GetAllDetailDAO {
Connection con;
Statement stmt;
private int noOfRecords;
public List<StaffBean> viewAllStaff(int offSet, int noOfRecords){
List<StaffBean> list = new ArrayList<StaffBean>();
StaffBean _staffBean;
try {
con = ConnectionProvider.getConnection();
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select SQL_CALC_FOUND_ROWS * from tblstaffdetails limit "+offSet+","+noOfRecords);
//+offSet+","+noOfRecords);
//SQL_CALC_FOUND_ROWS
while(rs.next()){
_staffBean = new StaffBean();
_staffBean.setStaffName(rs.getString("StaffName"));
_staffBean.setstaffId(rs.getInt("staffId"));
_staffBean.setActiveORInactive(rs.getString("ActiveORInactive"));
_staffBean.setStafftype(rs.getString("Stafftype"));
list.add(_staffBean);
}
rs.close();
rs = stmt.executeQuery("SELECT FOUND_ROWS()");
if(rs.next())
this.noOfRecords = rs.getInt(1);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
public int getNoOfRecords() {
return noOfRecords;
}
}
connection provider
package com.staff.DB;
import java.sql.*;
public class ConnectionProvider {
static Connection con;
static String url;
public static Connection getConnection() throws SQLException{
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/StaffAllocation","root", "success");
}catch(ClassNotFoundException cnf){
cnf.printStackTrace();
}
return con;
}
}
and my GetAllDetailServlet.java is
package com.staff.servlet;
import java.io.IOException;
import java.util.List;
import java.sql.*;
import javax.servlet.RequestDispatcher;
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 com.staff.bean.StaffBean;
import com.staff.DAO.GetAllDetailDAO;
import com.staff.DB.*;
#WebServlet("/GetAllDetailServlet")
public class GetAllDetailServlet extends HttpServlet{
/**
* Servlet implementation class GetAllDetailsServlet
*/
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public GetAllDetailServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
int page = 1;
int recordsPerPage = 4;
if(request.getParameter("page") != null)
page = Integer.parseInt(request.getParameter("page"));
GetAllDetailDAO allDetailDAO = new GetAllDetailDAO();
List<StaffBean> list = allDetailDAO.viewAllStaff((page-1)*recordsPerPage, recordsPerPage);
int noOfRecords = allDetailDAO.getNoOfRecords();
int noOfPages = (int) Math.ceil(noOfRecords * 1.0 / recordsPerPage);
request.setAttribute("staffList", list);
request.setAttribute("noOfPages", noOfPages);
request.setAttribute("currentPage", page);
RequestDispatcher view = request.getRequestDispatcher("jsp/displayAllDetail.jsp");
view.forward(request, response);
}
}
and my DisplayAllDetail.jsp is
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title> :: All Details</title>
</head>
<body>
<fieldset>
<table border="1" cellpadding="4" cellspacing="4" align="center">
<tr>
<th>staffId</th>
<th>StaffName</th>
<th>ActiveORInactive</th>
<th>Stafftype</th>
<c:forEach var="_staffBean" items="${staffList}">
<tr>
<td>${_staffBean.staffId}</td>
<td>${_staffBean.StaffName}</td>
<td>${_staffBean.ActiveORInactive}</td>
<td>${_staffBean.Stafftype}</td>
</tr>
</c:forEach>
</tr>
</table>
<c:if test="${currentPage != 1}">
<td>Prev</td>
</c:if>
<table border="1" cellpadding="5" cellspacing="5" align="center">
<tr>
<c:forEach begin="1" end="${noOfPages }" var="i">
<c:choose>
<c:when test="${currentPage eq i }">
<td>${i}</td>
</c:when>
<c:otherwise>
<td>${i}</td>
</c:otherwise>
</c:choose>
</c:forEach>
</tr>
</table>
<c:if test="${currentPage lt noOfPages }">
<td>Next</td>
</c:if>
</fieldset>
</body>
</html>
my error is
HTTP Status 500 - An exception occurred processing JSP page /jsp/displayAllDetail.jsp at line 22
type Exception report
message An exception occurred processing JSP page /jsp/displayAllDetail.jsp at line 22
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: An exception occurred processing JSP page /jsp/displayAllDetail.jsp at line 22
19: <c:forEach var="_staffBean" items="${staffList}">
20: <tr>
21: <td>${_staffBean.staffId}</td>
22: <td>${_staffBean.StaffName}</td>
23: <td>${_staffBean.ActiveORInactive}</td>
24: <td>${_staffBean.Stafftype}</td>
25: </tr>
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:470)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
com.staff.servlet.GetAllDetailServlet.doGet(GetAllDetailServlet.java:56)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
root cause
javax.el.PropertyNotFoundException: Property 'StaffName' not found on type com.staff.bean.StaffBean
javax.el.BeanELResolver$BeanProperties.get(BeanELResolver.java:237)
javax.el.BeanELResolver$BeanProperties.access$400(BeanELResolver.java:214)
javax.el.BeanELResolver.property(BeanELResolver.java:325)
javax.el.BeanELResolver.getValue(BeanELResolver.java:85)
org.apache.jasper.el.JasperELResolver.getValue(JasperELResolver.java:104)
org.apache.el.parser.AstValue.getValue(AstValue.java:183)
org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:185)
org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:1026)
org.apache.jsp.jsp.displayAllDetail_jsp._jspx_meth_c_005fforEach_005f0(displayAllDetail_jsp.java:157)
org.apache.jsp.jsp.displayAllDetail_jsp._jspService(displayAllDetail_jsp.java:99)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
com.staff.servlet.GetAllDetailServlet.doGet(GetAllDetailServlet.java:56)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.42 logs.
Try to declare
private String staffName;
private String activeORInactive;
private String stafftype;
And not with capital letters.
I suggest you to follow the Java Code convertions
Further to Blanca Hdez's correct answer, change the JSP so the case of staffName is correct:
<td>${_staffBean.StaffName}</td>
should be:
<td>${_staffBean.staffName}</td>
Note the lowercase 's' for 'staffName' - very important!

Categories