Changing view (from MVC) using jsps - java

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

Related

Java Servlet MVC, Show Database Query Result to JSP Table

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

ArrayList is empty after session sets the attribute

I have debugged this and I can see that the ArrayList is being filled up with the proper entries, but the EL is not picking up the list to display in the web page. The exact code for the session.setAttribute for the worked previously but now it doesn't. The attributes for the values from the previous page are set but the forEach table isn't. In the debug, or if you press F12, it shows that the attributen 'propertyListings' has x amount of objects in the array, but they are blank, showing as [ , , , , , , ]. Not sure what I messed up on. Thanks in advance.
I am using NetBeans 8.2 and the server is Tomcat.
THE SERVLET: Searching.java
package ServletTasks;
import Business.Inventory;
import Business.Property;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
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 javax.servlet.http.HttpSession;
/**
*
* #author ti488678
*/
#WebServlet(name = "Searching", urlPatterns = {"/Searching"})
public class Searching extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
double searchLow = Double.parseDouble(request.getParameter("searchLow"));
double searchHigh = Double.parseDouble(request.getParameter("searchHigh"));
String url = "/index.jsp";
String action = request.getParameter("action");
HttpSession session = request.getSession();
if (action == null) {
action = "search"; // default action
}
// perform action and set URL to appropriate page
if (action.equals("search")) {
url = "/searched.jsp";
Inventory inventory = new Inventory();
inventory.setAllProperties();
session.setAttribute("lowSearch", searchLow);
session.setAttribute("highSearch", searchHigh);
ArrayList<Property> propertyList = inventory.search(searchLow, searchHigh);
session.setAttribute("propertyListings", propertyList);
getServletContext()
.getRequestDispatcher(url)
.forward(request, response);
}
}
#Override
public String getServletInfo() {
return "Short description";
}
}
WEB PAGE: index.jsp
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>Foreal Estate</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css" />
</head>
<header>
<h2>FoReal Estate</h2>
</header>
<main id="wrapper">
<h4>Search: Enter low and high values to search for a property</h4>
<form action="Searching" method="post">
<input type="hidden" name="action" value="search">
<label for="searchLow">Low Value</label>
<input type="text" name="searchLow" value="">
<br><br>
<label for="searchHigh">High Value</label>
<input type="text" name="searchHigh" value="">
<br><br>
<input type="submit" value="Submit Search">
</form>
<br><br><br><br>
</main>
</html>
WEB PAGE: searched.jsp
<%--
Document : searched
Created on : Feb 8, 2017, 3:45:56 PM
Author : MyPC
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="styles.css" />
<title>Searching Properties</title>
</head>
<header>
<h2>Search Criteria: $${lowSearch} to $${highSearch}</h2>
</header>
<main id="wrapper">
<h2>Listings:</h2>
<table>
<c:forEach var="property" items="${propertyListings}">
<tr>
<td><c:out value="${property.address}"/></td>
<td><c:out value="${property.price}"/></td>
</tr>
</c:forEach>
</table>
</main>
THE XML: web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
JAVA CLASS: Inventory.java
package Business;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.Month;
import java.util.*;
public class Inventory implements Serializable{
ArrayList<Property> propertyList = new ArrayList<Property>();
public Inventory() {
}
public void setAllProperties() {
Property p = new Property();
p.setAddress("87 Ford Rd");
p.setPrice(2200000.00);
p.setSquareFeet(2000);
p.setTaxes(7000.00);
p.setYearBuilt(LocalDate.of(1865, Month.APRIL, 15));
p.setListingDate(LocalDate.now().minusYears(2));
addProperty(p);
Property p2 = new Property();
p2.setAddress("36 Grassy Knoll");
p2.setPrice(120000.00);
p2.setSquareFeet(2000);
p2.setTaxes(2200.00);
p2.setYearBuilt(LocalDate.of(1963, Month.NOVEMBER, 22));
p2.setListingDate(LocalDate.now().minusWeeks(2));
addProperty(p2);
Property p3 = new Property();
p3.setAddress("223 Oak St");
p3.setPrice(190000.00);
p3.setSquareFeet(4000);
p3.setTaxes(2600.00);
p3.setYearBuilt(LocalDate.of(1901, Month.SEPTEMBER, 14));
p3.setListingDate(LocalDate.now().minusMonths(2));
addProperty(p3);
Property p4 = new Property();
p4.setAddress("13 Foster Lane");
p4.setPrice(110000.00);
p4.setSquareFeet(2500);
p4.setTaxes(1800.00);
p4.setYearBuilt(LocalDate.of(1981, Month.MARCH, 30));
p4.setListingDate(LocalDate.now().minusDays(2));
addProperty(p4);
Property p5 = new Property();
p5.setAddress("15 Foster Lane");
p5.setPrice(115000.00);
p5.setSquareFeet(2500);
p5.setTaxes(1800.00);
p5.setYearBuilt(LocalDate.of(1981, Month.JUNE, 22));
p5.setListingDate(LocalDate.now().minusDays(2));
addProperty(p5);
Property p6 = new Property();
p6.setAddress("782 Butler Ave");
p6.setPrice(105000.00);
p6.setSquareFeet(1800);
p6.setTaxes(1900.00);
p6.setYearBuilt(LocalDate.of(1999, Month.FEBRUARY, 01));
p6.setListingDate(LocalDate.now().minusDays(2));
addProperty(p6);
Property p7 = new Property();
p7.setAddress("70 Martel Road");
p7.setPrice(285000.00);
p7.setSquareFeet(3500);
p7.setTaxes(2800.00);
p7.setYearBuilt(LocalDate.of(2012, Month.MARCH, 15));
p7.setListingDate(LocalDate.now().minusDays(2));
addProperty(p7);
Property p8 = new Property();
p8.setAddress("40th Sister Brook");
p8.setPrice(450000.00);
p8.setSquareFeet(4400);
p8.setTaxes(3720.00);
p8.setYearBuilt(LocalDate.of(2015, Month.JULY, 01));
p8.setListingDate(LocalDate.now().minusDays(2));
addProperty(p8);
Property p9 = new Property();
p9.setAddress("405 Nebraska Street");
p9.setPrice(108980.00);
p9.setSquareFeet(1500);
p9.setTaxes(1350.00);
p9.setYearBuilt(LocalDate.of(1950, Month.JANUARY, 03));
p9.setListingDate(LocalDate.now().minusDays(2));
addProperty(p9);
Property p10 = new Property();
p10.setAddress("1455 Roca Road");
p10.setPrice(423055.00);
p10.setSquareFeet(3750);
p10.setTaxes(3860.00);
p10.setYearBuilt(LocalDate.of(1995, Month.NOVEMBER, 28));
p10.setListingDate(LocalDate.now().minusDays(2));
addProperty(p10);
}
public ArrayList<Property> getProperties() {
setAllProperties();
return propertyList;
}
public void addProperty(Property property) {
propertyList.add(property);
}
public Property getProperty(int index) {
if (index >= 0) {
return (Property) propertyList.get(index);
} else {
return null;
}
}
public int numberOfProperties() {
return propertyList.size();
}
public ArrayList<Property> search(double lowPrice, double highPrice) {
ArrayList<Property> matchingList = new ArrayList<>();
for(Property p : propertyList) {
if(p.getPrice() >= lowPrice && p.getPrice() <= highPrice) {
matchingList.add(p);
}
}
return matchingList;
}
}
JAVA CLASS: Property.java
package Business;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.Month;
public class Property implements Serializable{
private String address;
private int squareFeet;
private double price;
private LocalDate yearBuilt;
private LocalDate listingDate;
private double taxes;
public Property() {
address = "000 default st";
squareFeet = 128;
price = 2048;
yearBuilt = LocalDate.of(1970, Month.JANUARY, 1);
listingDate = yearBuilt.plusYears(5);
taxes = 16;
}
public Property(String address, int squareFeet,
double price, LocalDate yearBuilt, LocalDate listingDate, double taxes) {
this.address = address;
this.squareFeet = squareFeet;
this.price = price;
this.yearBuilt = yearBuilt;
this.listingDate = listingDate;
this.taxes = taxes;
}
public void setAddress(String address) {
this.address = address;
}
public void setSquareFeet(int squareFeet) {
this.squareFeet = squareFeet;
}
public void setPrice(double price) {
this.price = price;
}
public void setYearBuilt(LocalDate yearBuilt) {
this.yearBuilt = yearBuilt;
}
public void setTaxes(double taxes) {
this.taxes = taxes;
}
public String getAddress() {
return (this.address);
}
public int getSquareFeet() {
return (this.squareFeet);
}
public double getPrice() {
return (this.price);
}
public LocalDate getYearBuilt() {
return (this.yearBuilt);
}
public LocalDate getListingDate() {
return (this.listingDate);
}
public double getTaxes() {
return (this.taxes);
}
public void setListingDate(LocalDate listingDate) {
this.listingDate = listingDate;
}
//Optional complete this method to build a String that contains all of the house's information for easy display
//it would be better to use the EL output each property's properties
public String toString() {
String ifYouBuildIt = "";
return ifYouBuildIt;
}
}

Making link go to servlet to redirect to another page

SO first off let me begin by saying that my servlet loads the option lists in a form i have just fine. The problem is when i start from the index.jsp like i want, the lists dont load. So basically, i want to click a link on the index.jsp to take me to the servlet to then redirect me to the correct page based on the link clicked. Maybe I have been looking at this too long and just need fresh eyes but I cant get why it wont work.
I have included my Index.jsp and servlet
Index.jsp
<%# 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>Insert title here</title>
</head>
<body>
<form method="get" action="customerServlet">
Add Customer
<br/>
Add Pet
</form>
</body>
</html>
Servlet
package edu.witc.Assignment03.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//import javax.servlet.annotation.WebServlet;
//import javax.servlet.http.HttpServlet;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import edu.witc.Assignment03.model.Customer;
import edu.witc.Assignment03.model.Phone;
import edu.witc.Assignment03.model.States;
#WebServlet(description = "servlet to get act as controller between form and models", urlPatterns = { "/customerServlet","/addCustomer","/addPet" })
public class CustomerServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public CustomerServlet() {
super();
}
private void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession session = request.getSession();
Phone phone = new Phone();
States state = new States();
Collection<Phone> phones = phone.getPhoneCollection();
Collection<States> states = state.getStateCollection();
session.setAttribute("phones", phones);
session.setAttribute("states", states);
request.getRequestDispatcher("/customerManagement.jsp").forward(request, response);
//}
}
private List<edu.witc.Assignment03.model.Customer> customers = new ArrayList<Customer>();
private void addCustomer(HttpServletResponse response, HttpServletRequest request)//redirect to index
throws IOException, ServletException {
String url = "/customerManagement.jsp";
processRequest(request, response);
request.getRequestDispatcher(url).forward(request,response);
}
private void addPet(HttpServletResponse response, HttpServletRequest request)//redirect to index
throws IOException, ServletException {
String url = "/pets.jsp";
request.getRequestDispatcher(url).forward(request,response);
}
private Customer getCustomer(int customerId) {
for (Customer customer : customers) {
if (customer.getCustomerId() == customerId) {
return customer;
}
}
return null;
}
private void sendEditCustomerForm(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
String url = "/customerManagement.jsp";
request.setAttribute("customers", customers);
request.getRequestDispatcher(url).forward(request,response);
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String uri = request.getRequestURI();
if (uri.endsWith("/addCustomer")) {
addCustomer(response, request);
} else if (uri.endsWith("/addPet")) {
addPet(response, request);
}
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
// update customer
int customerId = 0;
try {
customerId =
Integer.parseInt(request.getParameter("id"));
} catch (NumberFormatException e) {
}
Customer customer = getCustomer(customerId);
if (customer != null) {
customer.setFirstName(request.getParameter("firstName"));
customer.setLastName(request.getParameter("lastName"));
customer.setEmail(request.getParameter("email"));
customer.setPhone(request.getParameter("phone"));
customer.setAddress(request.getParameter("address"));
customer.setCity(request.getParameter("city"));
customer.setZip(request.getParameter("zip"));
}
}
}
It would be easier to use one parameter and check the value than to manually parse the URL:
Add Customer
<br/>Add Pet
In your servlet:
String action = request.getParameter("action");
if("addCustomer".equals(action)) { ... }
else if("addPet".equals(action)) { ... }
if you are using "forms", this could be the solution to send params to servlet.
<form action="ServletName" method="POST">
<input type="text" name="paramName">
<input type="submit" value="Add">
</form>
In Servlet:
String costumerName = request.getParameter("paramName");
If you just use a link like href, you should send the param like:
<a href="ServletName?ID=12345">
In servlet, same.
String costumerName = request.getParameter("ID");

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.

Sending Information Back From Servlet to JSP

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...

Categories