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 .
Related
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>
I need help in checking the data into the database before insertion.
Issue:
I have used the general method to insert the values into database.But I need to include this condition into my servlet code i.e if a data is already present in the database,then that data should not be inserted into the database and the remaining data should be inserted into the database.While doing this no alert should be raised to the user.
This is my code.
products.jsp
<%#page import="java.util.List"%>
<%#page import="web.Products"%>
<%#page import="java.util.ArrayList"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<form method="post" action="Save_Products">
<b>
Brand Name:<font color="green">
<% String brand_name=(String)session.getAttribute("brand_name");
out.print(brand_name);%>
<c:set var="brand_name" value="brand_name" scope="session" />
</font></b>
<table>
<tr>
<th> Products</th>
<th> Description </th>
</tr>
<tr>
<td> <b><%
List<Products> pdts = (List<Products>) request.getAttribute("list");
if(pdts!=null){
for(Products prod: pdts){
out.println("<input type=\"checkbox\" name=\"prod\" value=\"" + prod.getProductname() + "\">" + prod.getProductname()+"<br>");
} %> </b></td>
<td><%for(Products prod: pdts){
out.println("<input type=\"text\" name=\"desc\" style=\"width:50px; height:22px\"/><br/>");
}
}
%> </td>
</tr>
<br/>
<br/>
<tr><td align="center"> <input type="submit" value="Save" name="save"/> </td></tr>
</table>
</form>
</body>
</html>
Servlet code
import java.io.IOException;
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.sql.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpSession;
public class Save_Products extends HttpServlet {
static final String dbURL = "jdbc:mysql://localhost:3306/pdt";
static final String dbUser = "root";
static final String dbPass = "root";
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ResultSet rs=null;
Connection connection = null;
try{
HttpSession session = request.getSession();
String brand_name =(String) session.getAttribute("brand_name");
String [] prod_list = request.getParameterValues("prod");
String [] desc_list = request.getParameterValues("desc");
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection (dbURL,dbUser,dbPass);
String sql="insert into pdt_list(brand_name,product_name,desc)values(?,?,?)";
PreparedStatement prep = connection.prepareStatement(sql);
int num_values = Math.min(prod_list.size(), desc_list.size());
int count_updated = 0;
for(int i = 0; i < num_values; i++){
prep.setString(1, brand_name);
prep.setString(2, prod_list[i]);
prep.setString(3,desc_list[i]);
count_updated += prep.executeUpdate();
}
if(count_updated>0)
{
out.print("Products Saved Successfully...");
RequestDispatcher rd=request.getRequestDispatcher("Save_Success.jsp");
rd.forward(request,response);
}
else{
RequestDispatcher rd=request.getRequestDispatcher("Save_Failure.jsp");
rd.forward(request,response);
}
prep.close();
}
catch(Exception E){
//Any Exceptions will be caught here
System.out.println("The error is"+E.getMessage());
}
finally {
try {
connection.close();
}
catch (Exception ex) {
System.out.println("The error is"+ex.getMessage());
}
}
}
}
I need help in forwarding the result set values from servlet to jsp without using JSTL implementation
Work flow :
The user enters a value in text box and clicks search button
On clicking search the servlet is called.
The servlet focuses on the database implementation and forward the result set values to the same jsp page from where the request comes.
Issue:
My result set size is 3, but the value which is in the top of my table alone is getting printed in my jsp page. The remaining 2 values are missing.I want all the values to be printed in my jsp page.
This is my code:
Productlist.jsp
<%#page import="java.util.List"%>
<%#page import="web.Products"%>
<%#page import="java.util.ArrayList"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Products</title>
</head>
<body>
<form method="post" align="center" action="ProductList">
Company Name:<input type="text" size="20" id="company" name="company" />
<input type="submit" value="search"/>
<%
List<Products> pdts = (List<Products>) request.getAttribute("list");
if(pdts!=null){
for(Products prod: pdts){
out.println("<br/>" + prod.getProductname());
}
}
%>
</form>
</body>
</html>
Products.java
public class Products {
private String productname;
public String getProductname() {
return productname;
}
public void setProductname(String productname) {
this.productname=productname ;
}
}
ProductList.java(servlet-code)
import java.io.IOException;
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.sql.*;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpSession;
public class ProductList extends HttpServlet {
static final String dbURL = "jdbc:mysql://localhost:3306/pdt";
static final String dbUser = "root";
static final String dbPass = "root";
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ResultSet rs = null;
Connection connection = null;
List<Products> pdt = new ArrayList<Products>();
try{
String company =request.getParameter("company");
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection (dbURL,dbUser,dbPass);
String sql="select product_pck from comp_pdt_list where company_name='"+company+"'";
PreparedStatement prep = connection.prepareStatement(sql);
rs=prep.executeQuery();
while(rs.next()) {
Products prod=new Products();
prod.setProductname(rs.getString("product_pck"));
pdt.add(prod);
request.setAttribute("list",pdt);
RequestDispatcher rd=request.getRequestDispatcher("Productlist.jsp");
rd.forward(request,response);
return;
}
prep.close();
} catch(Exception E) {
//Any Exceptions will be caught here
System.out.println("The error is"+E.getMessage());
} finally {
try {
connection.close();
} catch (Exception ex) {
System.out.println("The error is" + ex.getMessage());
}
}
}
}
You set the attribute to request in your while loop. So the "list" contains only one product. (method returns on first iteration)
Add products to the list in while loop and set your list (request attribute) only after while loop.
Following should fix it:
while(rs.next()){
Products prod=new Products();
prod.setProductname(rs.getString("product_pck"));
pdt.add(prod);
}
request.setAttribute("list",pdt);
RequestDispatcher rd=request.getRequestDispatcher("Productlist.jsp");
rd.forward(request,response);
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);
}
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>