I am using windows 8.1 64 bit OS, oracle 12c database and netbeans ide.i created a java web project named as WebApplication1 in my netbeans IDE.
in my database I created a user C##abc and password abc having database SID is orcl. In my database I created one table named as city with column name address and inserted one data 'xyz' to the table city. I run the project and in d browser after writing city in text box I am receiving the message- Servlet NewServlet at /WebApplication1 but it should display xyz. Where i am wrong?
I added 2 jar flies ojdbc14.jar and ojdbc_14.jar files.
My new.jsp
<form action="NewServlet" method="post">
<font face="verdana" size="2">
Enter Table Name :<input type="text" name="table">
<input type="submit" value="Display">
</font>
</form>
NewServlet.java
package p;
import java.io.IOException;
import java.io.PrintWriter;
import static java.lang.System.out;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class NewServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet NewServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet NewServlet at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <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 {
String tb=request.getParameter("table");
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:orcl","c##abc","abc");
Statement st=con.createStatement();
out.println("connection established successfully...!!");
ResultSet rs=st.executeQuery("Select * from "+tb);
while(rs.next())
{
out.println(rs); }
}
catch (ClassNotFoundException | SQLException ex){
out.println(ex);
}
Within your doPost() method, the out you are using is System.out, which you have imported (as static). In processRequest() you override that with:
PrintWriter out = response.getWriter()
... which is a bit confusing and I'd choose a different variable name. But you aren't doing that in doPost(). So nothing you write in that method with println is doing to the browser via the HttpServletResponse, it's just going to the JVM console.
From the code you posted it isn't obvious how processRequest() then gets called - which it must be for you to see the output you get. Either you haven't shown a call to doGet()/processRequest() from that method, or the servlet handling is dropping back to doGet() automatically because the response hasn't been initiated, or it's redirecting back to that automatically after an error condition.
Even with a local variable for the response.getWriter() you would need to send proper HTML, not just the plain non-tag messages you have now, otherwise you'd just get a blank page.
Related
I am trying to run this program but it dosent work.I am using net beans 8.2 with jdk 7, rest all works but i end up with this error - "The requested resource is not available" in WelcomeServlet.java.
index.html
```<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="FirstServlet" method="post">
Name:<input type="text" name="username"/><br/><br/>
Password:<input type="password" name="userpass"/><br/><br/>
<input type="submit" value="login"/>
</form>
</body>
```
FirstServlet.java
package newpackage;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author J for Jay
*/
public class FirstServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet FirstServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet FirstServlet at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <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 {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("username");
String p=request.getParameter("userpass");
if(LoginDao.validate(n, p)){
RequestDispatcher rd=request.getRequestDispatcher("WelcomeServlet.java");
rd.forward(request,response);
}
else{
out.print("Sorry username or password error");
RequestDispatcher rd=request.getRequestDispatcher("index.html");
rd.include(request,response);
}
out.close();
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
WelcomeServlet.java
package newpackage;
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;
/**
*
* #author J for Jay
*/
public class WelcomeServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet WelcomeServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet WelcomeServlet at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <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
*/
//#WebServlet(name="",urlPatterns={"/"})
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
try{
PrintWriter out = response.getWriter();
String name=request.getParameter("username");
out.print("Welcome "+name);
out.close();
}
catch( Exception e)
{
System.out.println(e);
}
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
LoginDao.java
package newpackage;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author J for Jay
*/
public class LoginDao extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet LoginDao</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet LoginDao at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <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>
public static boolean validate(String name,String pass){
boolean status=false;
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/bgkv?useSSL=false","root","123456");
PreparedStatement ps=con.prepareStatement("select * from login where username=? and password=?");
ps.setString(1,name);
ps.setString(2,pass);
ResultSet rs=ps.executeQuery();
status=rs.next();
}catch(Exception e){System.out.println(e);}
return status;
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" 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">
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>newpackage.FirstServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>LoginDao</servlet-name>
<servlet-class>newpackage.LoginDao</servlet-class>
</servlet>
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>newpackage.WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/FirstServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>LoginDao</servlet-name>
<url-pattern>/LoginDao</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/WelcomeServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
I am using NetBeans 8.2 with jdk 7, database is already created, sql connetor.jar is also added.
I have created a simple web application.
I need to check, when someone books a room, that the arrival_date is different.
For instance:
Person A: books a room in data: 12/07/2018
Person B: book a room in data: 12/07/2018 ( HE CAN'T because there is the person A yet).
I have this db:
hotel_booking
cid, cname, email, arrival_date, departure_date, person, room, type_room,comment, status, uid.
and this is my code
HotelBooking.java
package hotel;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* #author OOPs
*/
public class Hotelbooking extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String s1 = request.getParameter("id");
String s2 = request.getParameter("name");
String s3 = request.getParameter("email");
String s4 = request.getParameter("arrivaldate");
String s5 = request.getParameter("departuredate");
String s6 = request.getParameter("person");
String s7 = request.getParameter("rooms");
String s8 = request.getParameter("type_room");
String s9 = request.getParameter("comment");
String s10 = request.getParameter("status");
// sesson..........
HttpSession session=request.getSession(true);
String s11 = (String)session.getAttribute("sessname");
out.println(s11);
try {
Class.forName("com.mysql.jdbc.Driver");
// out.println("driver loaded");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/HotelReservation","root" ,"123456789");
// out.println("Connect");
Statement st = con.createStatement();
// out.println("conncetion successfull");
int rs = st.executeUpdate("insert into hotel_booking (cname,email,arrival_date,departure_date,person,room,type_room,comment,status,uid)values ('"+s2+"','"+s3+"','"+s4+"','"+s5+"','"+s6+"','"+s7+"','"+s8+"','"+s9+"','"+s10+"','"+s11+"')");
// out.println(s1);
// out.println(s2);
out.println("<h1> Register sucsefulltttt </h1>");
/* if(rs == 1)
{
out.println("<script type=\"text/javascript\">");
out.println("alert('send successfully');");
out.println("</script>");
//response.sendRedirect("home.jsp");
}else{
}*/
response.sendRedirect("thankyoureg.jsp");
}catch(Exception e){
out.println("nahiiiiiiiiiiiii" +e);
}
finally {
out.close();
}
}
// <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>
}
How can I do in your opinion?? Thanks for the help.
Check if a query like the following returns 0.
SELECT count(*)
FROM hotel_booking
WHERE arrival_date <= $1
AND departure_date > $1,
AND room = $2;
If it returns 0 the room isn't occupied at the day the guest wishes to check in. Otherwise it is.
Substitute $1 with the day the guest wishes to arrive and $2 with the room (number or name or whatever you use).
I assumed that check in/out times are handled like:
Check in at the evening of a given day.
Check out in the morning of a given day. That follows a guest can check in at a day another guest checks out.
If that assumption is wrong, you'd have to tweak the comparison operators accordingly.
Also consider to use parametrized queries instead of string concatenation with unsanitized user input values. The latter is dangerous, your application is vulnerable to SQL injection attacks. Also parametrized queries help to find the right representation for a given data type, thus prevent errors that come from misrepresented values.
registration.java
/*
* 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.
*/
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
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;
/**
*
* #author srini
*/
#WebServlet(urlPatterns = {"/RegisterServlet"})
public class RegisterServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws IOException,ServletException{
processRequset (request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequset (request,response);
}
public void processRequset(HttpServletRequest request,HttpServletResponse response)
throws IOException,ServletException{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String phone =request.getParameter("phone");
String username =request.getParameter("uname");
String password =request.getParameter("pass");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/register","root","toor");
PreparedStatement pstmt=con.prepareStatement(
"insert into headwy(phone,uname,pass) values(?,?,?)");
pstmt.setString(1,phone);
pstmt.setString(2,username);
pstmt.setString(3,password);
int i=pstmt.executeUpdate();
if(i>0)
out.print("You are successfully registered...");
pstmt.close();
con.close();
}
catch (Exception e2) {System.out.println(e2);
}
out.close();
}
}
I am trying to check the existing data in database before inserting the data.
But I don't know how to execute the two SQL statement in servlet program.
Because I am first using sql and servlet.
Please provide the solution or give me the idea for the how to check the aleardy existing data in database.
=> Make store procedure like below sample and then call using java code and get your result in output parameter.
CREATE PROCEDURE InsertName
(
#username varchar(25),
#userpassword varchar(25)
)
AS
IF EXISTS(SELECT 'True' FROM MyTable WHERE username = #username)
BEGIN
--This means it exists, return it to ASP and tell us
SELECT 'This record already exists!'
END
ELSE
BEGIN
--This means the record isn't in there already, let's go ahead and add it
SELECT 'Record Added'
INSERT into MyTable(username, userpassword)
VALUES(#username,#userpassword)
END
I have an interface and a servlet file ,whenever I try to run the application program it gives me following error
SEVERE: Class [ LDir/DirSessionLocal; ] not found. Error while loading [ class DirServlet ]
code for interface
package Dir;
import javax.ejb.Local;
#Local
public interface DirSessionLocal {
String getContact(String name1);
String getDetails(String name2);
void rater(String r);
}
code for servlet
import Dir.DirSessionLocal;
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
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(urlPatterns = {"/DirServlet"})
public class DirServlet extends HttpServlet {
#EJB
private DirSessionLocal dirSession;
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet DirServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet DirServlet at " + request.getParameter("name") + "</h1>");
out.println("<br>");
out.println("<h1>" + request.getParameter("nameD") + "</h1>");
out.println("<br>");
out.println("<h1>" + request.getParameter("rate") + "</h1>");
String a=request.getParameter("nameD");
if(a.equals("abc"))
out.println("<h1>" + dirSession.getContact(a) + "</h1>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
// <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>
}
It means that the JVM running your servlet / webapp cannot find the ".class" file for a class with the name Dir.DirSessionLocal.
Depending on how you are "deploying" your servlet, you either need to add the missing class to a JAR file, an WAR file, the webapp's tree on the web server, etc.
I'm having a hard time with this code, every time I test and run it, I always get the same error but cant seem to fix it. The error I'm getting is, can anyone help? Its the last thing I need to get done to get this project working!
type Exception report
message
description The server encountered an internal error that prevented it from fulfilling this request.
exception
java.lang.NullPointerException
Servlets.addFunds.processRequest(addFunds.java:43)
Servlets.addFunds.doPost(addFunds.java:95)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.34 logs.
/*
* To change this template, choose Tools > Templates
and open the template in the editor.
*/
package Servlets;
import beans.UserBean;
import eventaccess.DatabaseConnector;
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 javax.servlet.http.HttpSession;
/**
*
* #author sberry3
*/
#WebServlet(name = "addFunds", urlPatterns = {"/addFunds"})
public class addFunds extends HttpServlet {
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String url = null;
double addFunds = Double.parseDouble(request.getParameter("addFunds"));
String username = request.getParameter("username");
HttpSession session = request.getSession();
UserBean userSession = (UserBean) session.getAttribute("userSession");
double balance = userSession.getBalance();
balance = balance + addFunds;
userSession.setBalance(balance);
session.setAttribute("userSession", userSession);
DatabaseConnector db = new DatabaseConnector();
String queryString = "UPDATE USERS SET balance=" + balance + " WHERE userID=" + userSession.getUserID();
try {
db.createConnection();
db.pstmt = db.conn.prepareStatement(queryString);
db.pstmt.execute();
db.closeConnection();
url = "/store.jsp";
} catch (Exception e) {
e.printStackTrace();
response.setHeader("dbError", "Coudn't connect to database");
}
request.getRequestDispatcher(url).forward(request, response);
}
// <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>
}
It's hard to tell exactly what line it is where your NullPointerException is happening.
Some possibilities:
Missing request parameters. For example, if you requested the page without including the addFunds parameter, you get a NullPointerException on this line:
double addFunds = Double.parseDouble(request.getParameter("addFunds"));
Missing session attribute:
What does the line
UserBean userSession = (UserBean) session.getAttribute("userSession");
return? Is userSession null? If so then later on:
userSession.setBalance(balance);
would cause a NullPointerException. I thinks that's the most likely problem. Do you something like
session.setAttribute("userSession", new UserSession());
anywhere?
On your first request to this jsp
HttpSession session = request.getSession();
will create a new session since there isn't an existing one. So
UserBean userSession = (UserBean) session.getAttribute("userSession");
will set userSession to null, since no Attribute userSession has been created up to this point.