I was trying to get the values (List productList = data.getProductList();) in ShowProductCatalog.jsp from the JavaBean ProductDataBean.java. I'm getting the error nullpointerexception. Please help! Your help will be much appreciated.
*edited: I realised the connection I'm getting in ProductDataBean.java in getProductList() is null. Now the question is, how can I make the changes to insert the value? If I put the whole connection in getProductList(), there is error message. "No Suitable Driver found."
**ShowProductCatalog.jsp**
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import = "java.util.*" import="cart.*,java.net.*,java.text.*"%>
<jsp:useBean id="data" scope="session" class="cart.ProductDataBean" />
<!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">
</head>
<body>
<%
List productList = data.getProductList();
Iterator prodListIterator = productList.iterator();
%>
**ProductDataBean.java**
package cart;
import java.io.*;
import java.sql.*;
import java.util.*;
public class ProductDataBean implements Serializable{
private static Connection connection;
private PreparedStatement addRecord, getRecords;
public ProductDataBean(){
try{
// Step1: Load JDBC Driver
Class.forName("com.mysql.jdbc.Driver");
// Step 2: Define Connection URL
String connURL ="jdbc:mysql://localhost/onlineshop?user=root&password=teck1577130713";
// Step 3: Establish connection to URL
connection = DriverManager.getConnection(connURL);
}catch(Exception e){e.printStackTrace();}
}
public static Connection getConnection(){
return connection;
}
public ArrayList getProductList() throws SQLException{
ArrayList productList = new ArrayList();
Statement statement = connection.createStatement();
ResultSet results = statement.executeQuery("SELECT * FROM products");
while (results.next()){
DVD movie = new DVD();
movie.setMovie(results.getString("movieName"));
movie.setRating(results.getString("movieRate"));
movie.setYear(results.getString("movieYear"));
movie.setPrice(results.getDouble("moviePrice"));
productList.add(movie);
}
return productList;
}
}
Check your build path mySql driver is added. and please add exception to the question what you getting, then easily can answer.
mysql-connector-java-5.1.24-bin.jar
you can get it from here
have a look this SO How to avoid java code in jsp
I suggest you to use Servlets instead of writing java code in jsp.
If you write code in servlets then easily you can test/debug your code.
To answer: how can I make the changes to insert the value?
Create a PreparedStatement obj with sql insert query and call [executeUpdate()][3] to perform INSERT, UPDATE or DELETE operations.
Add this piece of code in your ProductDataBean class to add a new record to table.
public static void addRecord(DVD dvd) throws SQLException{
PreparedStatement pStatement =
getConnection().prepareStatement("insert into products(movieName, movieRate, movieYear, moviePrice) values(?,?,?,?)");
pStatement.setString(1, dvd.getMovie());
pStatement.setString(2, dvd.getRating());
pStatement.setString(3, dvd.getYear());
pStatement.setDouble(4, dvd.getPrice());
pStatement.executeUpdate();
}
Make your DVD class a POJO like
package cart;
public class DVD {
private String movie;
private String rating;
private String year;
private Double price;
public DVD(){}
public DVD(String movie, String rating, String year, Double price) {
this.movie = movie;
this.rating = rating;
this.year = year;
this.price = price;
}
public String getMovie() {
return movie;
}
public void setMovie(String movie) {
this.movie = movie;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
#Override
public String toString() {
return "DVD [movie=" + movie + ", rating=" + rating + ", year=" + year
+ ", price=" + price + "]";
}
}
And in your jsp page call servlet url pattern to perform GET and POST, and to render all products in jsp user standard tag lib jstl1.2.jar you get it from here
So replace your jsp file with:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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">
</head>
<body>
<c:url value="/Product" var="pdctServletUrl"/>
Product Page
<form method="post" action="${pdctServletUrl}">
<h4>Enter New Movie details:</h4>
<label>Name</label>
<input type="text" name="movie"/>
<label>Rating</label>
<input type="text" name="rating"/>
<label>Year</label>
<input type="text" name="year"/>
<label>Price</label>
<input type="text" name="price"/>
<input type="submit" value="save movie"/>
</form>
<br/>
To get a list of products click
Get Products
<c:if test="${not empty products}">
<h4>Available Products.</h4>
<table>
<tr>
<th>Movie Name</th>
<th>Rating</th>
<th>Year</th>
<th>Price</th>
</tr>
<c:forEach items="${products}" var="pd">
<tr>
<td>${pd.movie}</td>
<td>${pd.rating}</td>
<td>${pd.year}</td>
<td>${pd.price}</td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
A servlet to handle GET and POST request's and transfering data to client etc.
Product.java
package cart;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Product
*/
#WebServlet("/Product")
public class Product extends HttpServlet {
private static final long serialVersionUID = 1L;
private ProductDataBean pDataBean = new ProductDataBean();
public Product() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Product> products;
try {
products = pDataBean.getProductList(); // Obtain all products.
request.setAttribute("products", products); // Store products in request scope.
request.getRequestDispatcher("/test.jsp").forward(request, response); // Forward to JSP page to display them in a HTML table.
} catch (SQLException e) {
e.printStackTrace();
}
}
/* (non-Javadoc)
* #see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String movie = req.getParameter("movie");
String rating = req.getParameter("rating");
String year = req.getParameter("year");
Double price = Double.valueOf(req.getParameter("price"));
if(movie!=null && rating!=null && year!=null && price!=null)
try {
ProductDataBean.addRecord(new DVD(movie, rating, year, price));
} catch (SQLException e) {
e.printStackTrace();
}
doGet(req, resp);
}
}
I think this may help you to understand.
Your JSP page is working properly and there is no mistake. Check your database and confirm that you have rows inside the products table. Null pointer exception occurs because the method getProductList() is not returning an ArrayList.
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 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);
}
A user clicks on edit on the index.jsp page and it sends them to a editCustomer.jsp page. The problem is when I click update it doesnt update the customer information on the index page.
How can I do this using the code I have?
INDEX.JSP
<%#page import="edu.witc.Assignment02.controller.CustomerServlet"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.util.ArrayList" %>
<!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>Home</title>
</head>
<body>
<ul>
<% String customerString ="";
ArrayList<edu.witc.Assignment02.model.Customer> customers = (java.util.ArrayList)request.getAttribute("customers");
for (edu.witc.Assignment02.model.Customer customer : customers) {
customerString += "<li>" + customer.getName() +
"(" + customer.getCity() + ") (" +
"<a href='editCustomer?id=" + customer.getId() +
"'>edit</a>)</li>";
}%>
<%=customerString %>
</ul>
<body>
</html>
EDITCUSTOMER.JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#page import="edu.witc.Assignment02.controller.CustomerServlet"%>
<!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>Edit Customer</title>
</head>
<body>
<h2>Edit Customer</h2>
<% int customerId =
Integer.parseInt(request.getParameter("id"));%>
<form method='post' action='customer'>
<input type='hidden' name ='id' value='<%=customerId%>'/>
<table>
<tr><td>Name:</td><td>"
<input name='name' />
</td></tr>
<tr><td>City:</td><td>
<input name='city' />
</td></tr>
<tr>
<td colspan='2' style='text-align:right'>
<input type='submit' value='Update'/></td>
</tr>
<tr><td colspan='2'>
<a href='customer'>Customer List</a>
</td></tr>
</table>
</form></body>
</html>
SERVLET
package edu.witc.Assignment02.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
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 edu.witc.Assignment02.*;
import edu.witc.Assignment02.model.Customer;
/*
* Not thread-safe. For illustration purpose only
*/
#WebServlet(name = "CustomerServlet", urlPatterns = {
"/customer", "/editCustomer", "/updateCustomer"})
public class CustomerServlet extends HttpServlet {
private static final long serialVersionUID = -20L;
private List<edu.witc.Assignment02.model.Customer> customers = new ArrayList<Customer>();
#Override
public void init() throws ServletException {
Customer customer1 = new Customer();
customer1.setId(1);
customer1.setName("Donald D.");
customer1.setCity("Miami");
customers.add(customer1);
Customer customer2 = new Customer();
customer2.setId(2);
customer2.setName("Mickey M.");
customer2.setCity("Orlando");
customers.add(customer2);
}
private void sendCustomerList(HttpServletResponse response, HttpServletRequest request)//redirect to index
throws IOException, ServletException {
String url = "/index.jsp";
request.setAttribute("customers", customers);
request.getRequestDispatcher(url).forward(request,response);
}
private Customer getCustomer(int customerId) {
for (Customer customer : customers) {
if (customer.getId() == customerId) {
return customer;
}
}
return null;
}
private void sendEditCustomerForm(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
String url = "/editCustomer.jsp";
request.setAttribute("customers", customers);
request.getRequestDispatcher(url).forward(request,response);
}
#Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String uri = request.getRequestURI();
if (uri.endsWith("/customer")) {
sendCustomerList(response, request);
} else if (uri.endsWith("/editCustomer")) {
sendEditCustomerForm(request, response);
}
}
#Override
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException, ServletException {
// update customer
int customerId = 0;
try {
customerId =
Integer.parseInt(request.getParameter("id"));
} catch (NumberFormatException e) {
}
Customer customer = getCustomer(customerId);
if (customer != null) {
customer.setName(request.getParameter("name"));
customer.setCity(request.getParameter("city"));
}
sendCustomerList(response, request);
}
}
CUSTOMER.JAVA
package edu.witc.Assignment02.model;
public class Customer {
private int id;
private String name;
private String city;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
I'm not sure what you expect to happen. You are submitting this form
<form method='get' action='customer'>
<table>
<tr>
<td>Name:</td>
<td>
"
<input name='name' />
</td>
</tr>
<tr>
<td>City:</td>
<td>
<input name='city' />
</td>
</tr>
<tr>
<td colspan='2' style='text-align:right'>
<input type='submit' value='Update' />
</td>
</tr>
<tr>
<td colspan='2'>
<a href='customer'>Customer List</a>
</td>
</tr>
</table>
</form>
And handling it with
if (uri.endsWith("/customer")) {
sendCustomerList(response, request);
and
private void sendCustomerList(HttpServletResponse response, HttpServletRequest request)//redirect to index
throws IOException, ServletException {
String url = "/index.jsp";
request.setAttribute("customers", customers);
request.getRequestDispatcher(url).forward(request,response);
}
Nothing in the code above modifies anything in the customers List. Objects don't get changed on their own. You have to make the modifications yourself.
Maybe you meant to submit the form with a POST request. In that case, you would need an <input> field for the id.
Think about the request-response cycle.
Your Servlet container receives an HTTP request, it dispatches your Servlet to handle it. Your servlet performs some logic and forwards to a JSP. The JSP renders some HTML which is written to the body of the HTTP response. The response is sent to the client. In this case, your client is a browser which reads the HTML text and renders it graphically. You can then interact with it, fill in input fields and click buttons. When you do this, the browser takes the values you've entered and produces an HTTP request which it sends to your server. And so on, and so on...
I am till a learner in Java, please help me out. Here is my sample code, when I execute this program. It should retrieve info from the data base and store the values in the Java class and there by send the value to JSP but when i look at JSP it shows value "null"
Here are the 5 files related to my problem, any answers or solutions are happily accepted.
-------------------------this my basic input form---------------------------
<!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=utf-8" />
<title>WELCOME TO DISCOUNTLOVERS.IN</title>
<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<link href="stylesheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="wrapper">
<div><%#include file="header.jsp" %></div>
<div><table width="920" border="0" cellpadding="0" cellspacing="0" id="main-content" >
<form method ="post" action ="Registrationform" >
<tbody>
<tr>
<td width="382" valign="top" class="formtext">
<div>First Name</div>
<div>Last name</div>
<div>E-mail</div>
<div>Password</div>
<div>Confirm Password</div>
<div>phone no</div>
<div>Address</div>
<div>City</div>
<div>State</div>
<div>country</div>
<div>post code</div>
</td>
<td width="52" class="formtext-gap">
<div>:</div>
<div>:</div>
<div>:</div>
<div>:</div>
<div>:</div>
<div>:</div>
<div>:</div>
<div>:</div>
<div>:</div>
<div>:</div>
<div>:</div>
</td>
<td width="486" valign="top">
<div><input type="text" name="username_first"/></div>
<div><input type="text" name="username_last"/></div>
<div><input type="text" name="username_email"/></div>
<div><input type="text" name="username_pw"/></div>
<div><input type="text" name="username_cpw"/></div>
<div><input type="text" name="username_tele"/></div>
<div><input type="text" name="username_add"/></div>
<div><input type="text" name="username_city"/></div>
<div><input type="text" name="username_state"/></div>
<div><input type="text" name="username_country"/></div>
<div><input type="text" name="username_postcode"/></div>
</td>
</tr>
<tr><td colspan="3" align="center"><input type="checkbox"/> Terms and conditions of Discountlovers.in accpeted</td></tr>
<tr><td colspan="3" align="center"><div><input type="submit" value="Submit" class=""/></div></td></tr>
</tbody></form></table></div>
<div><%#include file="footer.jsp" %></div>
</div>
</body>
</html>
------------------------ this is data insertion servlet------------------------
package registration_Servlets;
import registration_Servlets.intialization_form;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Registrationform
*/
#WebServlet("/Registrationform")
public class Registrationform extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Registrationform() {
super();
// TODO Auto-generated constructor stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
intialization_form obj = new intialization_form();
String name;
String lastname;
String username_email;
String username_pw ;
String username_cpw;
String id ;
String username_add;
String username_city ;
String username_state;
String username_country;
String username_postcode;
try {
name = request.getParameter("username_first");
lastname = request.getParameter("username_last");
username_email = request.getParameter("username_email");
username_pw = request.getParameter("username_pw");
username_cpw = request.getParameter("username_cpw");
id = request.getParameter("username_tele");
username_add = request.getParameter("username_add");
username_city = request.getParameter("username_city");
username_state = request.getParameter("username_state");
username_country = request.getParameter("username_country");
username_postcode = request.getParameter("username_postcode");
DataBase db = new DataBase();
PreparedStatement pst = db.getConnection().prepareStatement("insert into registrationinfo values(?,?,?,?,?,?,?,?,?,?,?)");
pst.setString(1, name );
pst.setString(2, lastname);
pst.setString(3, username_email);
pst.setString(4, username_pw);
pst.setString(5, username_cpw);
pst.setString(6, id);
pst.setString(7, username_add);
pst.setString(8, username_city);
pst.setString(9, username_state);
pst.setString(10, username_country);
pst.setString(11, username_postcode);
int i = pst.executeUpdate();
if(i==1){
//request.setAttribute("name",name);
/*String site = new String("Retrivin_user_reg_form");
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site); */
response.sendRedirect("Retrivin_user_reg_form");
}
pw.println("done");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
--------------------------------this is my data retrieve servlet-----------------
package registration_Servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Retrivin_user_reg_form
*/
#WebServlet("/Retrivin_user_reg_form")
public class Retrivin_user_reg_form extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Retrivin_user_reg_form() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
try {
DataBase db = new DataBase();
PreparedStatement pst = db.getConnection().prepareStatement("Select * from registrationinfo");
intialization_form obj = new intialization_form();
ResultSet i = pst.executeQuery();
while(i.next()){
// pw.println("EmpName" + " " + "EmpSalary" + "<br>");
obj.name= i.getString(1);
obj.lastname=i.getString(2);
obj.username_email=i.getString(3);
obj.username_pw=i.getString(4);
obj.username_cpw=i.getString(5);
obj.id=i.getString(6);
obj.username_add=i.getString(7);
obj.username_city=i.getString(8);
obj.username_state=i.getString(9);
obj.username_country=i.getString(10);
obj.username_postcode=i.getString(11);
String site = new String("registrationcompleted.jsp");
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
/*request.getRequestDispatcher("registrationcompleted.jsp").forward(request, response);*/
}
}
catch (Exception e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
}
}
-----------this is my Java class where i want to store my retrieved data--------------
package registration_Servlets;
public class intialization_form
{
String name;
String lastname;
String username_email;
String username_pw;
String username_cpw;
String id;
String username_add;
String username_city;
String username_state;
String username_country;
String username_postcode;
public void setname( String value )
{
name = value;
}
public String getname() { return name; }
public void setlastname( String value )
{
lastname = value;
}
public String getlastname() { return lastname; }
public void setusername_email( String value )
{
username_email = value;
}
public String getusername_email() { return username_email; }
public void setusername_pw(String value){
username_pw= value;
}
public String getusername_pw() { return username_pw; }
public void setusername_cpw(String value){
username_cpw=value;
}
public String getusername_cpw(){
return username_cpw;
}
public void setid(String value){
id= value;
}
public String getid(){
return id;
}
public void setusername_add(String value){
username_add= value;
}
public String getusername_add(){
return username_add;
}
public void setusername_city(String value){
username_city= value;
}
public String getusername_city(){
return username_city;
}
public void setusername_state(String value){
username_state= value;
}
public String getusername_state(){
return username_state;
}
public void setusername_country(String value){
username_country = value;
}
public String getusername_country(){
return username_country;
}
public void setusername_postcode(String value){
username_postcode= value;
}
public String getusername_postcode(){
return username_postcode;
}
}
-------------------------this is my out put JSP where I get null value-------------
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import = "registration_Servlets.intialization_form" %>
<!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=utf-8" />
<title>WELCOME TO DISCOUNTLOVERS.IN</title>
<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<link href="stylesheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="wrapper">
<div><%#include file="header.jsp" %></div>
<div><table width="920" border="0" cellpadding="0" cellspacing="0" id="main-content">
<tbody>
<tr>
<td>
<% intialization_form user = new intialization_form(); %>
first Name: <%= user.getname() %>
last name: <%= user.getlastname() %><BR>
Email: <%= user.getusername_email() %><BR>
</td>
</tr>
</tbody></table></div>
<div><%#include file="footer.jsp" %></div>
</div>
</body>
</html>
I can see you have used
request.getRequestDispatcher("registrationcompleted.jsp").forward(request, response);
before doing this add line given below before forward() method
request.setAttribute("your-key", yourObjectReference);
This method of request object will set your form object as an attribute which you want to access in your output jsp, which you can retrieve using request.getAttribute("key") method.
put below code in your output jsp.
<% intialization_form user = (intialization_form)request.getAttribute("your-key"); %>
since request.getAttribute() method returns Object you will have to cast it in intialization_form
And don't forget to remove below lines from your code before doing this
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
It is because the values in you form class are NULL. You never assign any values to them.
You just create an empty form object and the "print" some of its values.
<% intialization_form user = new intialization_form(); %>
first Name: <%= user.getname() %>
last name: <%= user.getlastname() %><BR>
Email: <%= user.getusername_email() %><BR>
#See https://stackoverflow.com/tags/servlets/info for some info how to start jsp and servlet programming.