Java Servlet MVC, Show Database Query Result to JSP Table - java

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>

Related

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

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

Displaying the result set values from servlet to jsp

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);

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);
}

Changing view (from MVC) using jsps

Im attempting to write a web application using MVC. I have the bean, the jsp, and servlets.
What I want to accomplish: the user will be able to create a (shopping)list in a table. The table will have a thead that shows the day it was created. Then it will create rows with 3 columns(1-id,2-name of product, 3- a 'bought' link). When the user clicks on the 'bought' link, it will remove the link from the 3 column and will turn the name of the product green.
There will be another link somewhere outside the table that will let the user create a new list. If there is an existing list, then the products that have not been 'bought' yet, would automatically go to the new list. Once the user clicks the "create new list" link, it will only display the new list(with unpurchased products if any).
I am currently having issues with:the date will not display only until the bought link is clicked but when clicked it will not turn the text green or remove the "bought" link.
here is my code, any help would be greatly appreciated. Thank you.
Item.java
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Item {
//property names
String name;
Integer id;
boolean available = true;
Format formatter = new SimpleDateFormat("MM/dd/yyyy");
String today = formatter.format(new Date());
public Item(Integer id, String name, boolean available){
this.id = id;
this.name = name;
this.available = available;
}
public String getToday() {
return today;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isAvailable() {
return available;
}
public void setAvailable(boolean available) {
this.available = available;
}
}
DisplayList.jsp
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%# 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" %>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!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>Grocery List</title>
</head>
<body>
<h1>Grocery List</h1>
<table border='1'>
<tr><th colspan='3'>${entry.today}</th></tr>
<c:forEach items="${entries}" var="entry">
<tr>
<td>${entry.id}</td>
<c:choose>
<c:when test="${entry.available != false }">
<td>${entry.name}</td>
<td>Bought</td>
</c:when>
<c:when test="${entry.available != true }">
<td style="color:green;" >${entry.name}</td>
<td></td>
</c:when>
</c:choose>
</tr>
</c:forEach>
<tr>
<form action="Groceries" method="post">
<td colspan='2'><input type="text" name="product" /></td>
<td><input type="submit" name="add" value="Add" /></td>
<p><input type="button" name="new" value="New List" /></p>
</form>
</tr>
</table>
</body>
</html>
Groceries.java
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletConfig;
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("/Groceries")
public class Groceries extends HttpServlet {
private static final long serialVersionUID = 1L;
int y = 3;
public Groceries() {
super();
}
public void init(ServletConfig config) throws ServletException {
super.init( config );
List<Item> entries = new ArrayList<Item>();
entries.add( new Item(1, "Milk", true) );
entries.add( new Item(2, "Soda", true) );
getServletContext().setAttribute( "entries", entries );
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/DisplayList.jsp").forward(request, response);
}
#SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("product");
Item entry = new Item(y, name, true);
y++;
List<Item> entries = (List<Item>) getServletContext().getAttribute("entries");
entries.add( entry );
response.sendRedirect("Groceries");
}
}
Bought.java
import java.io.IOException;
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;
#WebServlet("/Bought")
public class Bought extends HttpServlet {
private static final long serialVersionUID = 1L;
public Bought() {
super();
}
/**
* Given an id, retrieve the List entry.
*/
#SuppressWarnings("unchecked")
private Item getEntry( Integer id )
{
List<Item> entries = (List<Item>) getServletContext().getAttribute("entries" );
for( Item entry : entries )
if( entry.getId().equals( id ) )
return entry;
return null;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// get the entry to be edited
Integer id = Integer.valueOf( request.getParameter( "id" ) );
Item entry = getEntry( id );
// pass the entry to jsp using request scope
request.setAttribute( "entry", entry );
request.getRequestDispatcher( "/WEB-INF/DisplayList.jsp" ).forward(request, response );
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// get the entry to be edited
Integer id = Integer.valueOf( request.getParameter( "id" ) );
Item entry = getEntry( id );
// change the entry based on user input
entry.setAvailable(true);
// send the user back to the guest book page
request.getRequestDispatcher( "/WEB-INF/DisplayList.jsp" ).forward(request, response );
}
}
The following link should replace to map a servlet in JSP.
Bought
In the doGet method you need to set availability condition
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// get the entry to be edited
Integer id = Integer.valueOf( request.getParameter( "id" ) );
Item entry = getEntry( id );
entry.setAvailable(false);
// pass the entry to jsp using request scope
request.setAttribute( "entry", entry );
request.getRequestDispatcher( "/WEB-INF/DisplayList.jsp" ).forward(request, response );
}

Java MVC JSP get Connection and Values from JavaBean

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.

Categories