Retrieving a table from database: javax.el.PropertyNotFoundException - java

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!

Related

Cannot show ArrayList from Servlet to JSP

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.

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>

javax.el.PropertyNotFoundException: Property 'id' not found on type model.Grocery [duplicate]

This question already has answers here:
javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean
(6 answers)
Closed 6 years ago.
I am making a page where you are able to update,edit,delete,insert data in a database. The insert page works well, and the data is inserted successfully, but when i click the "Add" button i am not redirected to the AllGrocery page but i am given this error by Eclipse.Can't figure out where the problem is.Can anyone help me out? Database : GroceryStore, Table : grocerys(id,name,price)
DataAccess.java
package dao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
import com.sun.istack.internal.logging.Logger;
import db.DBUtils;
import model.Grocery;
public class DataAccess {
public void addNew(Grocery g) throws ClassNotFoundException, SQLException{
try {
PreparedStatement ps = DBUtils.getPreparedStatement("insert into grocerys values(?,?,?)");
ps.setInt(1, g.getID());
ps.setString(2, g.getName());
ps.setDouble(3, g.getPrice());
ps.executeUpdate();
} catch(ClassNotFoundException | SQLException ex){
}
}
public static List<Grocery> getAll(){
List<Grocery> gs = new LinkedList<>();
try {
ResultSet rs = DBUtils.getPreparedStatement("select * from grocerys").executeQuery();
while (rs.next()){
Grocery g = new Grocery();
g.setID(rs.getInt(1));
g.setName(rs.getString(2));
g.setPrice(rs.getDouble(3));
gs.add(g);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return gs;
}
}
DBUtils.java
package db;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Connection;
import java.sql.SQLException;
public class DBUtils {
public static PreparedStatement getPreparedStatement(String sql) throws ClassNotFoundException, SQLException{
PreparedStatement ps = null;
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/GroceryStore";
String user = "root";
String pass = "adil";
Connection conn = DriverManager.getConnection(url,user,pass);
ps = conn.prepareStatement(sql);
return ps;
}
public static void main(String[] args)throws ClassNotFoundException, SQLException {
getPreparedStatement("select * from grocerys");
}
}
Grocery.java
package model;
public class Grocery {
private int id;
private String name;
private Double price;
public void setID(int id_){
id = id_;
}
public void setName(String name_){
name = name_;
}
public void setPrice(Double price_){
price = price_;
}
public int getID(){
return id;
}
public String getName(){
return name;
}
public Double getPrice(){
return price;
}
}
AllGrocery.java
package servlet;
import java.io.IOException;
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 dao.DataAccess;
/**
* Servlet implementation class AllGrocery
*/
#WebServlet("/AllGrocery")
public class AllGrocery extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public AllGrocery() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("AllGrocery", DataAccess.getAll());
RequestDispatcher rd = request.getRequestDispatcher("AllGrocery.jsp");
rd.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
public Double getPrice(){
return price;
}
}
AddNew.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Add Grocery</title>
</head>
<body>
<h1>Add New Grocery</h1>
<form action = "ManagerAddNew.jsp" method = "post">
<table>
<tr>
<th>ID</th>
<td><input type = "number" name = "id" style = "width : 200px;"/></td>
</tr>
<tr>
<th>NAME</th>
<td><input type = "text" name = "name" style = "width : 200px;"/></td>
</tr>
<tr>
<th>PRICE</th>
<td><input type = "number" name = "price" style = "width : 200px;"/></td>
</tr>
<tr>
<th></th>
<td><input type = "submit" name = "submit" value = "ADD"/></td>
</tr>
</table>
</form>
</body>
</html>
AllGrocery.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<!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>Grocerys Available</title>
</head>
<body>
<div syle = "width : 1200px; margin-left:auto;margin-right:auto;">
<table cellpadding = "10">
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
</tr>
<c:forEach items = "${AllGrocery}" var = "p">
<tr>
<td>${p.id}</td>
<td>${p.name}</td>
<td>${p.price}</td>
<td>
Edit
Delete
</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
ManagerAddNew.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import = "model.Grocery" %>
<%# page import = "dao.DataAccess" %>
<!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>
<%
String name = request.getParameter("name");
int id = Integer.parseInt(request.getParameter("id"));
Double price = Double.parseDouble(request.getParameter("price"));
Grocery g = new Grocery();
g.setID(id);
g.setName(name);
g.setPrice(price);
DataAccess da = new DataAccess();
da.addNew(g);
response.sendRedirect("/SimpleServletProject/AllGrocery");
%>
</body>
</html>
Error :
org.apache.jasper.JasperException: An exception occurred processing JSP page /AllGrocery.jsp at line 29
26: <c:forEach items = "${AllGrocery}" var = "p">
27:
28: <tr>
29: <td>${p.id}</td>
30: <td>${p.name}</td>
31: <td>${p.price}</td>
32: <td>
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:575)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:477)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
servlet.AllGrocery.doGet(AllGrocery.java:38)
javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
javax.el.PropertyNotFoundException: Property 'id' not found on type model.Grocery
javax.el.BeanELResolver$BeanProperties.get(BeanELResolver.java:290)
javax.el.BeanELResolver$BeanProperties.access$300(BeanELResolver.java:243)
javax.el.BeanELResolver.property(BeanELResolver.java:377)
javax.el.BeanELResolver.getValue(BeanELResolver.java:97)
org.apache.jasper.el.JasperELResolver.getValue(JasperELResolver.java:104)
org.apache.el.parser.AstValue.getValue(AstValue.java:184)
org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:950)
org.apache.jsp.AllGrocery_jsp._jspx_meth_c_005fout_005f0(AllGrocery_jsp.java:215)
org.apache.jsp.AllGrocery_jsp._jspx_meth_c_005fforEach_005f0(AllGrocery_jsp.java:163)
org.apache.jsp.AllGrocery_jsp._jspService(AllGrocery_jsp.java:113)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:439)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
servlet.AllGrocery.doGet(AllGrocery.java:38)
javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
If you see the exception it is unable to find the property id in the Grocery object. Your getter method name for the id should be changed to getId() and it is not getID(). It should be getId() since when you camelCase you just change the first character of the variable to capital not the entire variable.
Your java Bean Grocery is not as per Bean standards. JavaBeans Conventions
If you are using some IDE, you can always right click and Generate Getters and Setters. Most of the IDEs do provide the facility to generate.
Then few extra suggestions for the code.
<c:forEach items = "${AllGrocery}" var = "p">
should be changed to
<c:forEach items = "${requestScope.AllGrocery}" var = "p">
and
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("AllGrocery", DataAccess.getAll());
RequestDispatcher rd = getServletContext().getRequestDispatcher("/AllGrocery.jsp");
rd.forward(request, response);
}

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>

Categories