My JSP page has 2 input boxes:
1) Amount to deposit.
2) Amount to withdraw.
Due to Javascript validation, the user can input in either of the boxes. Based on the inputs from the jsp page, I'm trying to call the appropriate servlet method. However, its been a frustrating experience, so far.
The challenge I'm facing is, if I enter deposit amount I get a NumberFormatException for the withdraw amount and vice-versa. How do I eliminate this?
.jsp page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>
<link rel="stylesheet" href="colorShades.css">
<script type="text/javascript">
function myfunc1(){
var deposit = document.getElementById("deposit");
if(deposit.value.length >0){
document.getElementById("withdraw").disabled = true;
}
else{
document.getElementById("deposit").disabled = false;
}
}
function myfunc2(){
var withdraw = document.getElementById("withdraw");
if(withdraw.value.length >0){
document.getElementById("deposit").disabled = true;
}
else{
document.getElementById("withdraw").disabled = false;
}
}
</script>
</head>
<body>
<form action="DepositWithdrawServlet" method="post">
<div>
<label>Account No:</label>
<input type="text" name="accountNo" class="input_boxAdj" id="account" />
</div>
<div style="clear:both;"> </div>
<div>
<label>Enter amount to deposit:</label>
<input type="text" name ="depositAmt" values="deposit" class="input_boxAdj" id="deposit" onblur="myfunc1()" />
</div>
<div style="clear:both;"> </div>
<div>
<label>Enter amount to withdraw:</label>
<input type="text" name ="withdrawAmt" values="withdraw" class="input_boxAdj" id="withdraw" onblur="myfunc2()"/>
</div>
<div style="clear:both;"> </div>
<div>
<button class="button">Submit »</button>
<span><button class="button">Reset »</button></span>
</div>
</form>
</body>
</html>
Servlet code:
package com.banking.servlet;
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;
import com.banking.dao.WebBankProjectDao;
import com.banking.dao.WebBankProjectDaoImpl;
import com.banking.pojo.WebBankTemporaryPojo;
/**
* Servlet implementation class DepositWithdrawServlet
*/
#WebServlet("/DepositWithdrawServlet")
public class DepositWithdrawServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public DepositWithdrawServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Reached inside servlet");
WebBankTemporaryPojo tempPojo = new WebBankTemporaryPojo();
WebBankProjectDao bankdao = new WebBankProjectDaoImpl();
int initialBalance = 0;
int finalBalance = 0;
int depositAmt = Integer.parseInt(request.getParameter("depositAmt"));
System.out.println("Deposit Amt: " +depositAmt);
System.out.println("Value" + (depositAmt>=0));
if((depositAmt>=0 && request.getParameter("withdrawAmt")==null)){
if(initialBalance==0){
out.print("<body style='color:red; font-family:Times New Roman; font-style:italic; font-size:25px'>");
initialBalance = depositAmt - 1000;
out.print("Amount of Rs.1000 will go as MINIMUM BALANCE to be maintained");
}
else{
finalBalance = depositAmt + initialBalance;
}
}
tempPojo.setDepositAmt(request.getParameter("depositAmount"));
bankdao.depositAmt(finalBalance);
int withdrawAmt = 0;
int withdrawAmount = Integer.parseInt(request.getParameter("withdrawAmt"));
System.out.println("Withdraw Amt: " +withdrawAmount);
if(withdrawAmount>0 && request.getParameter("depositAmt")==null){
if(Integer.parseInt(request.getParameter("withdrawAmount"))>finalBalance){
out.print("<body style='color:red; font-family:Times New Roman; font-style:italic; font-size:25px'>");
out.print("Oops !! Please deposit some funds before you can withdraw"); }
else if(Integer.parseInt(request.getParameter("withdrawAmount"))<0 || Integer.parseInt(request.getParameter("withdrawAmount"))==0){
out.print("<body style='color:red; font-family:Times New Roman; font-style:italic; font-size:25px'>");
out.print("The minimum amount you can withdraw is Rs. 100");
}
else if(Integer.parseInt(request.getParameter("withdrawAmount"))%100==0){
out.print("<body style='color:red; font-family:Times New Roman; font-style:italic; font-size:25px'>");
out.print("You should enter in the multiples of 100 to withdraw money");
}
else if(Integer.parseInt(request.getParameter("withdrawAmount"))>finalBalance){
out.print("Sorry, you have insufficient funds !!"); }
else{
withdrawAmt = finalBalance - Integer.parseInt(request.getParameter("withdrawAmount"));
}
}
tempPojo.setWithdrawAmt(request.getParameter("withdrawAmount"));
bankdao.depositAmt(withdrawAmt);
}
}
#Override
public boolean withdrawAmt(int accountNo) {
Connection con = DBUtility.getConnection();
String sql="update temporarytransaction set withdrawAmt=? where
accountNo=?";
WebBankTemporaryPojo tempPojo = new WebBankTemporaryPojo();
try {
PreparedStatement stmt=con.prepareStatement(sql);
stmt.setString(1, tempPojo.getWithdrawAmt());
stmt.setString(2, tempPojo.getAccountNo());
int no=stmt.executeUpdate();
if(no>0){
System.out.println("amount withdraw successfull");
}
}catch (Exception e){
e.printStackTrace();
}
return false;
}
#Override
public boolean depositAmt(int accountNo) {
Connection con = DBUtility.getConnection();
String sql="update temporarytransaction set depositAmt =? where accountNo=?";
WebBankTemporaryPojo tempPojo = new WebBankTemporaryPojo();
try {
PreparedStatement stmt=con.prepareStatement(sql);
stmt.setString(1, tempPojo.getDepositAmt());
stmt.setString(2, tempPojo.getAccountNo());
int no=stmt.executeUpdate();
if(no>0){
System.out.println("amount deposit successful");
}
}catch (Exception e){
e.printStackTrace();
} return false;
}
You could simply wrap this in a null check:
int depostAmt = 0;
if(request.getParameter("depositAmt") != null){
depositAmt = Integer.parseInt(request.getParameter("depositAmt"));
}
You should use the BigDecimal class to do monetary calculations. Simply sanitise the input from your clients then call new BigDecimal passing in the amounts i.e BigDecimal depositAmt = new BigDecimal("22.50"); To ensure you are receiving valid amount to process log the amounts passed in to the screen i.e Logger.getLogger(name.of.your.class).log(Level.info,"Amount passed in was {0}",amountPassedIn); That was you can be certain only numeric values are provided.
use request.getParameter("withdrawAmount")!=null and
request.getParameter("depositAmt")!=null before parseInt.
because it may be possible that either of you will get null.
Related
I'm making an application that has two values and it returns a lot of different function answers (addition, subtraction, div, multiplication, etc). It's made using JSP and I have an Index and an error JSPs. When I try to run the app with the error.jsp enabled, it always returns that page no matter what I try, because there's something wrong in my code but I don't understand what. The application also has a prime number section, in which you can enter a number, pressing ok and if the number is a prime nothing happens, but if it isnt then you will get an error message. Next prime and previous prime just returns next and previous prime numbers from the number you entered.
index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page errorPage="error.jsp"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Home Page</title>
</head>
<body>
<h1>Calculations using JSP pages</h1>
<jsp:useBean id="math" scope="session" class="beans.MathBean" />
<jsp:useBean id="primenumber" scope="session" class="beans.PrimeBean" />
<jsp:setProperty name="math" property="*" />
<jsp:setProperty name="primenumber" property="prime" />
<form name="form1" method="post">
<table>
<tr>
<td>Number 1: </td>
<td><input type="text" name="numberA" value="${math.numbera}" style="width: 130px"</td>
</tr>
<tr>
<td>Number 2: </td>
<td><input type="text" name="numberB" value="${math.numberb}" style="width: 130px"</td>
</tr>
<tr>
<td colspan="2" style="text-align: right"><input type="submit" value="OK"</td>
</tr>
</table>
</form>
<table>
<tr>
<td>Add</td><td>${math.add()}</td>
</tr>
<tr>
<td>Subtract</td><td>${math.subtract()}</td>
</tr>
<tr>
<td>Multiply</td><td>${math.multiply()}</td>
</tr>
<tr>
<td>Divide</td><td>${math.divide()}</td>
</tr>
</table>
<form name="form2" method="post">
<input type="text" name="prime" value="${primenumber.prime}"/>
<input type="submit" value="OK"/>
</form>
<p>Next Prime
<p>Previous Prime
</body>
</html>
Error.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page isErrorPage="true"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Error page</title>
</head>
<body>
<h1>Error!</h1>
<p>back 2 menu</p>
</body>
</html>
web.xml file is just default with added welcome-file-list, welcome-file with the index.jsp in it.
MathBean:
package beans;
import java.io.Serializable;
public class MathBean implements Serializable{
private long numbera, numberb;
public MathBean(long numbera, long numberb) {
this.numbera = numbera;
this.numberb = numberb;
}
public long getNumbera() {
return numbera;
}
public void setNumbera(long numbera) {
this.numbera = numbera;
}
public long getNumberb() {
return numberb;
}
public void setNumberb(long numberb) {
this.numberb = numberb;
}
public long add() {
return numbera + numberb;
}
public long subtract() {
return numbera - numberb;
}
public long divide() {
if (numberb == 0) {
return 0;
}
return numbera / numberb;
}
public long multiply() {
return numbera * numberb;
}
}
PrimeBean:
package beans;
public class PrimeBean {
private static final long max = 9223372036854775783L;
private long prime = 2;
public PrimeBean() {
}
public long getPrime() {
return prime;
}
public void setPrime(long p) throws Exception {
if(!isPrime(p)) throw new Exception("Illegal number");
prime = p;
}
private static boolean isPrime(long p) {
if (p == 2 || p == 3 || p == 5 || p == 7) return true;
if(p<11||p%2 == 0 ) return false;
for(long t = 3, m = (long)Math.sqrt(p) + 1; t <= m; t+=2) if(p % t == 0) return false;
return true;
}
public boolean next() {
if (prime < max) {
if (prime == 2) prime = 3;
else for(prime += 2; !isPrime(prime); prime += 2);
return true;
}
return false;
}
public boolean previous() {
if (prime > 2) {
if(prime == 3) prime = 2;
else for(prime -= 2; !isPrime(prime); prime -= 2);
return true;
}
return false;
}
}
PrimeServlet:
package servlets;
import beans.PrimeBean;
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(name = "Primes", urlPatterns = {"/Primes"})
public class PrimeServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException{
PrimeBean bean = (PrimeBean) request.getSession().getAttribute("primenumber");
String number = request.getParameter("number");
if (number.equals("next")) bean.next(); else bean.previous();
response.sendRedirect("index.jsp");
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Sorry for posting all the code, but I'm truly lost and I don't understand why it doesn't work. All help appreciated.
Thank you!
There are at least 2 problems in the implementation:
Beans must have public default constructor with no arguments:
public MathBean() { ...
You have
public MathBean(long numbera, long numberb) { ...
HTML input tags numberA, numberB and submit on index.jsp are missing closing >.
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")
I have a very beginner question as I'm just learning to work with DBs. I have a very simple HTML form with a textField for a name, an add button to add a name to a MySQL database, and a sort button to sort the names in the database and display them. I almost have it working, however when I hit the "add" or "sort" buttons I get the same messages that appear after a user clicks those buttons along with the sorted list of names. It looks like this when clicking the add button:
Please go back and add a name or sort
Bill Jones
David G
Debbie Downer
Jane Doe
Would someone be able to advise me on what I have to change on my code to make just the list show up by itself when the user clicks sort? I am not a programmer just someone trying to learn.
Servlet code:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
#WebServlet("/Main")
public class Main extends javax.servlet.http.HttpServlet implements
javax.servlet.Servlet {
static final long serialVersionUID = 1L;
public Main() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager
.getConnection("jdbc:mysql://localhost:3306/test?user=root&password=root");
Statement stmt = con.createStatement();
try {
//stmt.execute("DROP TABLE simple");
stmt.execute("CREATE TABLE IF NOT EXISTS simple( name char(30))");
} catch (Exception e) {
}
if (name == "" || name == null) {
out.print("<h1>Please enter a name.<h1>");
}
else if (name != null) {
String s = "Insert into simple values(\'" + name + "\')";
stmt.execute(s);
out.print("<h1>Please go back and add a name or sort.<h1>");
}
ResultSet rs = stmt.executeQuery("Select * FROM simple ORDER BY name");
while (rs.next())
out.println("<h1>" + rs.getString(1) + "</h1>");
} catch (Exception ex) {
System.out.println(ex);
}
System.out.println("Program terminated with no error.");
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
HTML code:
<!-- Main.html -->
<!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>DB Sort</title>
</head>
<body>
<form action="http://localhost:8080/DB_Sorts/Main">
<center>
<br><br>
User Name:
<input name="name" type="text" value="">
<br><br>
<input name="add" type="Submit" value="Add">
<input name="sort" type="Submit" value=" Sort ">
</center>
</form>
</body>
</html>
Each submit button calls the same servlet with slightly different parameters.
If you wish to have different behaviour based on the button that is pressed you need to test which button was pressed.
If you click the add button the parameters name=???? and add=Add will be submitted. So if you add some code along the lines of.
if (request.getParameter("add") != null){
// do add
} else if (request.getParameter("sort") != null){
// do sort
}
you should get what you want.
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.