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;
}
}
Related
I have a problem with my web server. i need to introducing parametre and after introducing use that value in calcule in class. after calculate i need to show that value after press ok button
package CalculatorOnline;
import java.io.IOException;
import java.io.PrintWriter;
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("/TestCalc")
public class TestCalc extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
int Prescale = Integer.parseInt(request.getParameter("prescaler"));
int TimerMO = Integer.parseInt(request.getParameter("timermode"));
long TTTicks = Integer.parseInt(request.getParameter("ttticks"));
double Freq = Integer.parseInt(request.getParameter("freq"));
System.out.println("Frecventa:"+ Freq);
System.out.println("Prescaler:"+ Prescale);
System.out.println("TimerMod:"+ TimerMO);
System.out.println("TotalTimerTicks"+ TTTicks);
TestLabclass temp = new TestLabclass();
temp.setFreq(Freq);
temp.setPrescaler(Prescale);
temp.setTTTicks(TTTicks);
PrintWriter out = response.getWriter();
double TimeU2 = temp.getTimeU();
double RealT = temp.getRealT();
out.println("Timpului pina la umplere : "+ TimeU2);
out.println("Real time per tick : "+ RealT);
}
}
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form name="Frec input" action="TestLab">
<p> <label>FREQUENCY</label>
<input type="number" name="freq" id="quantity" />
<label>Total Timer Ticks</label>
<input type="number" name="ttticks" id="quantity" />
<label>Prescaler</label>
<select name="prescaler">
<option value="0">No clock source</option>
<option value="1">No Prescaling</option>
<option value="8">clkI/O/8</option>
<option value="64">clkI/O/64</option>
<option value="256">clkI/O/256</option>
<option value="1024">clkI/O/1024</option>
</select>
<label>Mode</label>
<select name="timermode">
<option value="0">Normal</option>
<option value="1">PWM</option>
<option value="2">CTC</option>
<option value="3">Fast PWM</option>
</select>
<input type="submit" value="ok" />
</p>
</form>
</body>
</html>
enter image description here
I am introducing all data i need and after press ok button i have 404 error. My out parametre was not showing
classfile
package CalculatorOnline;
class TestLabclass {
double Freq; // frequency
double TimeU; // overflow time
double RealT; //real time per tick
int Prescaler;
long TTTicks;
long OverFlowCount;
public TestLabclass()
{
Freq = 0;
TimeU = 0;
RealT = 0;
Prescaler = 0;
TTTicks = 0;
OverFlowCount = 0;
}
public double getFreq()
{
return Freq;
}
public void setFreq(double Freq)
{
this.Freq = Freq;
}
public int getPrescaler()
{
return Prescaler;
public void setPrescaler(int Prescaler)
{
this.Prescaler = Prescaler;
}
public long getTTTicks()
{
return TTTicks;
}
public void setTTTicks(long TTTicks)
{
this.TTTicks = TTTicks;
}
public double getRealT() {
return TTTicks/(Freq/Prescaler);
}
public void setRealT(double RealT)
{
this.RealT = RealT;
}
public void setOverFlowCount(long OverFlowCount)
{
this.OverFlowCount = OverFlowCount;
}
public long getOverFlowCount()
{
return TTTicks/256;
}
public double getTimeU()
{
return RealT*(TTTicks - (OverFlowCount * 256));
}
public void setTimeU(double TimeU)
{
this.TimeU = TimeU;
}
}
The form action should match the name declared in #WebServlet("/TestCalc")
Replace
<form name="Frec input" action="TestLab">
with
<form name="Frec input" action="TestCalc">
-OR-
Replace #WebServlet("/TestCalc") with #WebServlet("/TestLab")
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 );
}
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.
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.
I am a starter in java.
I am trying to develop a web application to validate user name and password in mysql database.
When i run the program i am getting exception. can anyone help me to find out what is wrong in the below code.
index.jsp
*********
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<form method="post" action="database">
<body>
<h1>Enter user details</h1>
<h2>Name</h2>
<input type="text" name="t1" /><br>
<h2>Password</h2>
<input type="password" name="p1" /><br><br>
<input type="submit" value="Submit" name="b1">
</body>
</form>
</html>
c1.java
********
package model;
public class c1 {
String name,password;
public c1(String name, String password) {
this.name = name;
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
database.java
*************
package controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
public class database extends HttpServlet {
#Resource(name = "db1")
private DataSource db1;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String name=request.getParameter("t1").trim();
String password=request.getParameter("p1").trim();
int value=select(name,password);
if(value==1)
{
out.println("User details present in database");
}
else
{
out.println(value);
out.println("ERROR Invalid user");
}
}
catch(Exception e2)
{
out.println("error");
}
finally {
out.close();
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);`
}
#Override
public String getServletInfo() {
return "Short description";``
}// </editor-fold>
public int select(String UserName,String Password) throws SQLException
{
DataSource d= db1;
Connection c=d.getConnection();
PreparedStatement p=c.prepareStatement
("select * from Employee where name='"+UserName+"' and password='"+Password+"'");
ResultSet rs=p.executeQuery();
int a= rs.getRow();
return a;
}
}
You have several errors in your code:
JSP. Incorrect position of body tags:
Correct code:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form method="post" action="database">>
<h1>Enter user details</h1>
<h2>Name</h2>
<input type="text" name="t1" />
<br>
<h2>Password</h2>
<input type="password" name="p1" />
<br>
<br>
<input type="submit" value="Submit" name="b1">
</form>
</body>
</html>
JAVA. You have a couple of errors in your controller. Some ` characters producing errors.
Correct code:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
processRequest(request, response); // ERROR Removed last `
}
#Override
public String getServletInfo() {
return "Short description"; // ERROR removed lasts ``
}// </editor-fold>
WEB.XML: Check your web.xml and verify that you have the next lines:
<servlet>
<servlet-name>Database-servlet</servlet-name>
<servlet-class>controller.database</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Database-servlet</servlet-name>
<url-pattern>/database</url-pattern>
</servlet-mapping>