Java JSP exception Report - java

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.

Related

Compare element in SQL ( Room Reservation WebApp) Java

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.

Why am I getting an error "class not found .Error while loading class"?

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.

Getting list of countries through a servlet: is it the right way?

I have a problem. In a web page I have a form. In this form there is a select form element which should get from a table in a mysql database all the countries when the page is loaded . Here is it the servlet:
#WebServlet(name = "SignUpServlet", urlPatterns =
{
"/signup"
})
public class SignUpServlet extends HttpServlet
{
#EJB
private SignUpBean signUpBean;
/**
* 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
{
request.setAttribute("CountriesList", signUpBean.getListCountries());
String arg = "/signup.jsp";
RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher(arg);
dispatcher.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>
}
When the servlet it is called it should put on the select element all the countries list.
My question is when I submit the form, which function should I call? I mean A servlet is made to handle only one request. How can I put different function in the same servlet?
EDIT
#Override
public void init()
throws ServletException
{
this.getServletContext().setAttribute("CountriesList", signUpBean.getListCountries());
}

ejb class is not found in glassfish?

I have JAVA EE Application I,m trying to call EJB from servelate but everytime I have this error
HTTP Status 404 - Not Found
type Status report
messageNot Found
descriptionThe requested resource is not available.
I check the glassfish log I see this
SEVERE: Class [ Lejbexercises/StatlessFundManagerBean; ] not found. Error while loading [ class controllers.TestStatelessEJB ]
ejb class
/*
* 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.
*/
package ejbexercises;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
/**
*
* #author
*/
#Stateless
#LocalBean
public class StatlessFundManagerBean {
public double addFunds(double balance, double amount) {
balance += amount;
return balance;
}
public double withdrawFunds(double balance, double amount) {
if (balance < 0) {
return 0.0;
} else {
balance -= amount;
return balance;
}
}
}
/*
* 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.
*/
package controllers;
import ejbexercises.StatlessFundManagerBean;
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;
/**
*
* #author
*/
#WebServlet(name = "TestStatelessEJB", urlPatterns = {"/TestStatelessEJB"})
public class TestStatelessEJB extends HttpServlet {
#EJB(name = "sfm")
private StatlessFundManagerBean sfm;
/**
* 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 {
double balance = 1200;
balance = (double) sfm.addFunds(balance, Double.parseDouble("1200"));
out.println("1st balance=" + balance );
} 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>
}
From EJB Documentation (http://docs.oracle.com/cd/E13222_01/wls/docs100/ejb30/annotations.html#wp1416481):
name - Specifies the name by which the referenced EJB is to be looked up in the environment.
You are using (name = "sfm") and this means that container will lookup bean known to it as "sfm" which is wrong in your case unless you have defined bean name in beans.xml (but you didn't mention it, so I assume, you haven't).
Just remove the (name="sfm ) part and do not forget to redeploy your app.

Java Servlet mapping

Servlet Mapping
I am new to java ee 6.I am trying to get a servlet request.Every other mapping works fine except /category mapping. Here is my ControllerServlet class.I have used #webServlet annotion for mapping.I have tried to do the mapping in web.xml but no luck.Using netbeans IDE 7.2,Server Glassfish opensource.
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 = "ControllerServlet",
loadOnStartup = 1,
urlPatterns = {
"/addToCart",
"/viewCart",
"/updateCart",
"/checkout",
"/purchase",
"/chooseLanguage",
"/category"})
public class ControllerServlet extends HttpServlet {
/**
* 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 {
String userPath = request.getServletPath();
// if cart page is requested
if (userPath.equals("/viewCart")) {
userPath = "/cart";
}
//if category page is requested
else if (userPath.equals("/category")) {
}
// if ckeckout page is requested
else if (userPath.equals("/checkout")){
// System.out.println("check");
}
// if user switches language
else if (userPath.equals("/chooseLanguage")){
}
// use RequestDispatcher to forward request internally
String url = "/WEB-INF/View" + userPath + ".jsp";
System.out.print(url);
try{
request.getRequestDispatcher(url).forward(request, response);
}catch(Exception ex){
ex.printStackTrace();
}
}
/**
* 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 userPath = request.getServletPath();
// if addToCart action is called
if (userPath.equals("/addToCart")) {
// TODO: Implement add product to cart action
// if updateCart action is called
} else if (userPath.equals("/updateCart")) {
// TODO: Implement update cart action
// if purchase action is called
} else if (userPath.equals("/purchase")) {
// TODO: Implement purchase action
userPath = "/confirmation";
}
// use RequestDispatcher to forward request internally
String url = "/WEB-INF/view" + userPath + ".jsp";
try {
request.getRequestDispatcher(url).forward(request, response);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Link to image of web-inf directory
/categories is not mapped in your servlet. /category is mapped however.

Categories

Resources