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")
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 am creating a project with JSP & Servlet (and entity beans) and I am trying to create a form where a user registers as a customer and is then redirected to a reservation page.
I want to keep the Id for the Customer that just registered and fill it into a disabled text field and then create a reservation on the next page. But whenever I try to load the customer class through jsp the whole application crashes with a NullPointerException.
It seems like the program crashes when it reaches the jsp-tags to fetch my customer, since it does print out the c.cPnr to the console as well as the test in the JSP-file.
<%# page import = "g24.isp.ejb.Customer" %>
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Welcome to Ski Village!</title>
<link rel="stylesheet" href="new/css/normalize.css">
<link rel="stylesheet" href="new/css/stylesheet.css">
<link href='https://fonts.googleapis.com/css?family=Fjalla+One|Poppins:400,500,600' rel='stylesheet' type='text/css'>
<script src="javascript/script.js" type="text/javascript"></script>
</head>
<body>
<% System.out.println("test"); %>
<% Customer c = (Customer) session.getAttribute("customer"); %>
<div id="container">
<!-- HEADER + MENU -->
<header>
<div class="logo"><!-- Ski Village Logo --></div>
<div class="menu">
<ul>
<li> Home </li>
<li class="left-menu"> About </li>
<li class="right-menu"> Book </li>
<li> <a href="index.html" > Test</a></li>
</ul>
</div>
</header>
<!-- PAGE CONTENT -->
<div id="wrapper">
<div class="center-form">
<form action="/HotelClient/HotelServlet" name="resForm" method="post">
<input type="text" name="cPnr" value="<%= c.getcPnr() %>" >
<input type="number" name="week" min="1" max="52" placeholder="Select week" >
<select name="cno">
<option value="1">Adventure Cabin
</option>
<option value="2">Cozy Cabin
</option>
<option value="3">Snowy Cabin
</option>
<option value="4">Hacker Cabin
</option>
</select>
<input type="submit" name="checkres" value="Check availability">
<input type="submit" name="submitresform" value="Create reservation" type="hidden">
<input name="operation" value="bajskorv" type="hidden">
</form>
</div>
<!-- FOOTER + SOCIAL ICONS -->
<footer>
<img src="img/facebook-logo.png" class="social-icon" alt="facebook logo">
<img src="img/instagram-logo.png" class="social-icon" alt="instagram logo">
<img src="img/twitter-logo.png" class="social-icon" alt="twitter logo">
<p>© 2016 | Ski Village</p>
</footer>
</div>
</div>
</body>
</html>
Servlet code:
package g24.isp.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import g24.isp.ejb.Cabin;
import g24.isp.ejb.Customer;
import g24.isp.ejb.Hotel;
import g24.isp.ejb.Reservation;
import g24.isp.facade.Facade;
import g24.isp.facade.FacadeLocal;
import g24.isp.ejb.MethodClass;
/**
* Servlet implementation class HotelServlet
*/
#WebServlet("/HotelServlet")
public class HotelServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#EJB
private FacadeLocal facade;
/**
* #see HttpServlet#HttpServlet()
*/
public HotelServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
out.println("MainServlet-doGet");
out.close();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
String url = "did not get an url";
// Get hidden field
String operation = request.getParameter("operation");
MethodClass mc = new MethodClass();
if (operation.equals("createcustomer")) {
String cPnr = request.getParameter("txtcPnr");
String cAddress = request.getParameter("txtcAddress");
String cPhone = request.getParameter("txtcPhone");
String cName = request.getParameter("txtcName");
if (facade.findByCpnr(cPnr) == null) {
Customer customer = new Customer();
customer.setcPnr(cPnr);
customer.setcAddress(cAddress);
customer.setcPhone(cPhone);
customer.setcName(cName);
facade.createCustomer(customer);
url = "/new/reservation.jsp";
} else {
url = "new/newcust.jsp";
}
}
else if (operation.equals("createreservation")) {
String cpnr = request.getParameter("txtcPnr");
int week = mc.ParseStringToInt(request.getParameter("week"));
int cno = mc.ParseStringToInt(request.getParameter("cno"));
Customer cs = facade.findByCpnr(cpnr);
Cabin cb = facade.findByCabinNo(cno);
if (cb != null && cs != null) {
Reservation res = new Reservation();
res.setCabin(cb);
res.setCustomer(cs);
res.setrDate(week);
facade.createReservation(res);
url = "/Index.jsp";
} else {
System.out.println("Did not enter if statement");
url = "/Index.jsp";
}
}
else if (operation.equals("newcustomer")) {
url = "/new/newcust.jsp";
}
else if (operation.equals("setcustomer")) {
System.out.println("Servlet - Create reservation");
String cpnr = request.getParameter("txtcPnr");
System.out.println(cpnr);
url = "/new/reservation.jsp";
Customer customer = facade.findByCpnr(cpnr);
if (customer != null) {
System.out.println(customer.getcName());
session.setAttribute("customer", customer);
url = "/reservation.jsp";
}
else {
System.out.println("Customer value is null");
}
}
System.out.println(url);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
}
}
May be it's not setting the session attribute and when c.getcPnr() gets executed, it throws NullPointerException. Can you check whether the attribute is set in the session? You can try printing out 'c' in the jsp.
I solved the problem - i was trying to find the customer by accessing the facade.findBycPnr() method.
The solution was to session.setAttribute(customer, cust) when creating the customer.
I have tried to write a Calculator with JSP and a Servlet
which is working perfect now. (with your help!)
Now I want to write it with MVC.
So I have a JSP:
<?xml version="1.0" encoding="UTF-8" ?>
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>Hello</title>
</head>
<body>
<form action="Process" method="post">
Enter a number: <input type="text" name="num1" />
<input type="text" name="operand" type="submit "value="+" />
<input type="text" name="operand" type="submit "value="-" />
<input type="text" name="operand" type="submit "value="*" />
<input type="text" name="operand" type="submit "value="/" />
Enter a number: <input type="text" name="num2" />
<input type="submit" name="submit" value="OK" />
</form>
</body>
</html>
and I have the Servlet:
package controller;
import model.Calc;
import java.io.IOException;
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 java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
#WebServlet("/servlet")
public class Process extends HttpServlet {
private static final long serialVersionUID = 1L;
public Process() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String num1= request.getParam("num1");
String num2= request.getParam("num2");
request.getParameter("operand");
int num11 = Integer.parseInt(num1);
int num22 = Integer.parseInt(num2);
Calc calc = new Calc();
calc.setNum1(num11);
calc.setNum2(num22);
request.setAttribute("calc", calc);
request.getParameter("operand");
request.setAttribute("operand", operand);
request.setAttribute("calc", calc);
request.setAttribute(calc.getResult());
RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
dispatcher.forward(request, response);
}}
And the JavaBean Class:
package model;
import java.io.Serializable;
public class Calc implements Serializable{
private static final long serialVersionUID = 1L;
private int num1;
private int num2;
private int result;
private String operand;
public Calc() {
super();
}
public Calc(int num1, int num2, int result, String operand) {
super();
this.num1 = num1;
this.num2 = num2;
this.result = result;
this.operand = operand;
}
public int getNum1() {
return num1;
}
public void setNum1(int num1) {
this.num1 = num1;
}
public int getNum2() {
return num2;
}
public void setNum2(int num2) {
this.num2 = num2;
}
public int getResult() {
return result;
}
public void setResult(int result) {
if (operand.equals("+")) {
result = num11 + num22;
} else if (operand.equals("-")){
result = num11 - num22;
} else if (operand.equals("*")){
result = num11 * num22;
} else if (operand.equals("/")){
result = num11 / num22;
this.result = result;
}
public String getOperand() {
return operand;
}
public void setOperand(String operand) {
this.operand = operand;
}}
and this is the result:
it returns a 0 in the result field.
Thanks for your help!
Try changing your input tags to a select tag with options. Something like this
<select id="operand" name="operand" >
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="%">%</option>
</select>
Sometimes JSP tends to confuse, when their is the exact same name.
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.
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.