Here i come up with problem while performing some operation like update,delete and insert but its return some null value with exception kindly some one could look at the code if its wrong:
Error:
HTTP Status 500 - null
type Exception report
message null
description The server encountered an internal error that prevented it from fulfilling this request.
exception
java.lang.NumberFormatException: null
java.lang.Integer.parseInt(Integer.java:454)
java.lang.Integer.parseInt(Integer.java:527)
Controller.ControllerTest.doGet(ControllerTest.java:48)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
note The full stack trace of the root cause is available in the Apache Tomcat/6.0.37 logs.
Apache Tomcat/6.0.37
user.jsp:
<form method="POST" action='ControllerTest' name="frmAddUser">
<jsp:useBean id="users" class="java.util.ArrayList" scope="request" />
<% for(int i = 0; i < users.size(); i+=1)
{
UseBean user = (UseBean)users.get(i);
%>
id:<input type="text" name="ID" value="<%=user.getID() %>"><br/>
Name:<input type="text" name="Name" value="<%= user.getName() %>"><br/>
Password:<input type="text" name="password" value="<%= user.getPassword() %>"><br/>
phoneno:<input type="text" name="Phoneo" value="<%= user.getPhoneo() %>"><br/>
Emailid:<input type="text" name="Emailid" value="<%= user.getEmailID() %>"> <br/>
<%} %>
<input type="submit" value="Submit" />
</form>
listuser.jsp
<body>
<table border=1>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>password</th>
<th>phoneno</th>
<th>emailid</th>
<th colspan=2>Action</th>
</tr>
</thead>
<tbody>
<jsp:useBean id="users" class="java.util.ArrayList" scope="request" />
<% for(int i = 0; i < users.size(); i+=1)
{
UseBean user = (UseBean)users.get(i);
%>
<tr>
<td><%= user.getID() %></td>
<td><%= user.getName() %></td>
<td><%= user.getPassword() %></td>
<td><%= user.getEmailID() %></td>
<td><%= user.getPhoneo() %></td>
<td><a href="ControllerTest?action=edit&userId=<%= user.getID() %>" >Update</a></td>
<td>Delete</td>
</tr>
<% } %>
</tbody>
</table>
<p>
Add User
</p>
Controllertest.java:
package Controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.UserDao;
import dbBean.UseBean;
public class ControllerTest extends HttpServlet
{
private static final long serialVersionUID = 1L;
private static String INSERT_OR_EDIT = "/user.jsp";
private static String LIST_USER = "/listUser.jsp";
private UserDao dao;
public ControllerTest()
{
super();
dao = new UserDao();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
String forward = "";
String action = request.getParameter("action");
if (action.equalsIgnoreCase("delete"))
{
try
{
int userId = Integer.parseInt(request.getParameter("userId"));
dao.deleteUser(userId);
forward = LIST_USER;
request.setAttribute("users", dao.getAllUsers());
}
catch (NumberFormatException ex)
{
System.out.println("Error occured with during conversion delete");
}
}
else if (action.equalsIgnoreCase("edit"))
{
forward = INSERT_OR_EDIT;
try
{
int userId = Integer.parseInt(request.getParameter("userId"));
UseBean bean = dao.getUserById(userId);
request.setAttribute("user", bean);
} catch (NumberFormatException ex)
{
System.out.println("Error occured with during conversion edit");
}
}
else if (action.equalsIgnoreCase("listUser"))
{
forward = LIST_USER;
request.setAttribute("users", dao.getAllUsers());
} else
{
forward = INSERT_OR_EDIT;
}
RequestDispatcher view = request.getRequestDispatcher(forward);
view.forward(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
try
{
UseBean bean = new UseBean();
bean.setName(request.getParameter("Name"));
bean.setPassword(request.getParameter("password"));
bean.setPhoneo(request.getParameter("Phoneo"));
bean.setEmailID(request.getParameter("Emailid"));
String userid = request.getParameter("ID");
if (userid == null || userid.isEmpty())
{
dao.addUser(bean);
} else
{
bean.setID(Integer.parseInt(userid));
dao.updateUser(bean);
}
RequestDispatcher view = request.getRequestDispatcher(LIST_USER);
request.setAttribute("users", dao.getAllUsers());
view.forward(request, response);
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("erro occuring in update code");
}
}
}
You're getting a NumberFormatException when trying to convert the empty string "" into an Integer...
You get a NumberFormatException, if you do not pass a valid number to Integer.parseInt()
int userId = Integer.parseInt(request.getParameter("userid"));
Try to print the value of request.getParameter("userid") and check.
The page you are forwarding on might have some string to integer conversions that might be creating the error
Before parsing a string you should do null check and trim then parse. If NumberFormatException occurs handle it.
Whenever you get into trouble like this, put debug statements and analyse
what actually causing exception. null or empty or whitespace or string? Then you can handle it easily.
Integer userId= parseToNumber(request.getParameter("userId"));
//check for not null and proceed
// returns null if receivedParam = "", "some string", null or number with space
private Integer parseToNumber(String receivedParam)
{
System.out.println("received param:"+receivedParam);
if (receivedParam != null && !receivedParam.trim().isEmpty())
{
try
{
return Integer.parseInt(receivedParam.trim());
}
catch (NumberFormatException nfe)
{
System.out.println("received param is not a number");
return null;
}
}
else
{
System.out.println("received param is null or empty");
return null;
}
}
In file user.jsp and listuser.jsp. you used space for URL Rewriting.
you should use
<tr>
<td><%=user.getID()%></td>
<td><%=user.getName()%></td>
<td><%=user.getPassword()%></td>
<td><%=user.getEmailID()%></td>
<td><%=user.getPhoneo()%></td>
<td><a href="ControllerTest?action=edit&userId=<%=user.getID()%>" >Update</a></td>
<td>Delete</td>
</tr>
Related
i am creating a simple crud system in Java Servlet. I am beginner of Servlet.I filled the form and clicked submit button and got the error - HTTP Status 404 - Not Found. I have attached the screen shot image below along with the code.
folder structure
Form
<form method = post action = "employee/employee.java">
<table class="table table-borederd">
<tr>
<td>Enter Employee ID:</td>
<td ><input class="form-control" type = "text" name = "txtEmpId"/></br></td>
</tr>
<tr>
<td>Enter Employee FirstName:</td>
<td ><input class="form-control" type = "text" name = "txtFName"/></td>
</tr>
<tr>
<td>Enter Employee LastName:</td>
<td ><input class="form-control" type = "text" name = "txtLName"/></td>
</tr>
<td><input type = "submit" value = "submit"/></td>
</form>
employee.java
public class employee extends HttpServlet
{
Connection con;
int row;
public void doPost(HttpServletRequest req, HttpServletResponse rsp) throws IOException, ServletException
{
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/empp","root","");
System.out.println("Connection Established");
}
catch(Exception e)
{
System.out.println("Sorry...........");
}
rsp.setContentType("text/html");
PrintWriter out = rsp.getWriter();
String empId = req.getParameter("txtEmpId");
String empFName = req.getParameter("txtFName");
String empLName = req.getParameter("txtLName");
try
{
PreparedStatement stat = con.prepareStatement("insert into record (id,fname,lname) Values(?,?,?)");
stat.setString(1,empId);
stat.setString(2,empFName);
stat.setString(3,empLName);
row = stat.executeUpdate();
}
catch(Exception e)
{
}
out.println("<html>");
out.println("<font color = 'red'>Sucessfully registered!</font>");
out.println("</body>");
out.println("<h2>");
out.println(row);
out.println("</h2>");
out.println("</body>");
}
}
I am having some trouble figuring out why I am getting an error with my code. Below is my JSP file (the problem is with the second form):
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Book Drivers</title>
</head>
<body>
<h1>Book Demands</h1>
<form method="POST" action="BookDriver.do">
<br>View a table </br>
<input type="radio" name="tbl" value="ListTodaysDemands">List Todays Demands<br />
<input type="radio" name="tbl" value="ListAllDemands">List All Demands<br />
<input type=submit value="Go!"> <br />
</form>
</body>
<body>
<h2>Demands</h2>
<%=(String)(request.getAttribute("query"))%>
</body>
<body>
<h2>Journeys</h2>
<%=(String)(request.getAttribute("query1"))%>
</body>
<body>
<h2>Drivers</h2>
<%=(String)(request.getAttribute("query2"))%>
</body>
<body>
<h2>Book taxi</h2>
<form method="POST" action="BookDriver.do">
<table>
<tr>
<th></th>
<th>Please provide your following details</th>
</tr>
<tr>
<td>Name:</td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>Address:</td>
<td><input type="text" name="address"/></td>
</tr>
<tr>
<td>Destination:</td>
<td><input type="text" name="destination"/></td>
</tr>
<tr>
<td>Date:</td>
<td><input type="text" name="date"/></td>
</tr>
<tr>
<td>Time:</td>
<td><input type="text" name="time"/></td>
</tr>
<tr>
<td> <input type="submit" value="Book"/></td>
</tr>
</table>
</form>
</body>
Below is my controller:
public class BookDriver extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
LocalDate date = LocalDate.now();
String qry1 = "select * from CUSTOMER";
String qry2 = "select * from DRIVERS";
String qry3 = "select * from DEMANDS where date = '"+date+"'";
String qry4 = "select * from DEMANDS";
String qry5 = "select * from JOURNEY";
//String qry4 = "SELECT Drivers.Name, Drivers.Registration FROM Drivers LEFT JOIN Journey ON Journey.Registration = Drivers.Registration LEFT JOIN Demands ON Demands.Time = Journey.Time WHERE Demands.id IS NULL";
//String qry4 = "SELECT Drivers.Name, Drivers.Registration FROM Drivers LEFT JOIN Journey ON Journey.Registration = Drivers.Registration LEFT JOIN Demands ON Demands.Date = Journey.Date LEFT JOIN Demands ON Demands.Time = Journey.Time WHERE Demands.id IS NULL";
response.setContentType("text/html;charset=UTF-8");
HttpSession session = request.getSession(false);
Jdbc dbBean = new Jdbc();
dbBean.connect((Connection)request.getServletContext().getAttribute("connection"));
session.setAttribute("dbbean", dbBean);
if((Connection)request.getServletContext().getAttribute("connection")==null)
request.getRequestDispatcher("/WEB-INF/conErr.jsp").forward(request, response);
else if (request.getParameter("tbl").equals("ListTodaysDemands")){
String msg="No current demands";
String msg2="No current journeys";
String msg3="No current journeys";
try {
msg = dbBean.retrieve(qry3);
msg2 = dbBean.retrieve(qry5);
msg3 = dbBean.retrieve(qry2);
} catch (SQLException ex) {
Logger.getLogger(BookDriver.class.getName()).log(Level.SEVERE, null, ex);
}
request.setAttribute("query", msg);
request.setAttribute("query1", msg2);
request.setAttribute("query2", msg3);
request.getRequestDispatcher("/WEB-INF/bookDemands.jsp").forward(request, response);
}
else if (request.getParameter("tbl").equals("ListAllDemands")){
String msg="No current demands";
String msg2="No current journeys";
String msg3="No current drivers";
try {
msg = dbBean.retrieve(qry4);
msg2 = dbBean.retrieve(qry5);
msg3 = dbBean.retrieve(qry2);
} catch (SQLException ex) {
Logger.getLogger(BookDriver.class.getName()).log(Level.SEVERE, null, ex);
}
request.setAttribute("query", msg);
request.setAttribute("query1", msg2);
request.setAttribute("query2", msg3);
request.getRequestDispatcher("/WEB-INF/bookDemands.jsp").forward(request, response);
}
///////////THIS PART NOT WORKING//////////////////////////
String [] query = new String[5];
query[0] = (String)request.getParameter("name");
query[1] = (String)request.getParameter("address");
query[2] = (String)request.getParameter("destination");
query[3] = (String)request.getParameter("date");
query[4] = (String)request.getParameter("time");
Jdbc jdbc = (Jdbc)session.getAttribute("dbbean");
if (jdbc == null)
request.getRequestDispatcher("/WEB-INF/conErr.jsp").forward(request, response);
if(query[0].equals("") ) {
request.setAttribute("msg", "Username cannot be NULL");
}
request.getRequestDispatcher("/WEB-INF/bookDemands.jsp").forward(request, response);
}
The first form in the JSP works absolutely fine, the issue is with the second form. Whenever I use the button "Book" I get a null pointer exception and I cannot figure out why and if I comment out all of the code to due with the first form in the servlet, then it no longer throws the exception and it works fine.
I would really appreciate some help with this as I have now spent hours searching for a solution online and i'm still very much struggling to solve the problem.
Cheers,
Use request.getParameterValues("name").. and same for others too maybe the current value be null
I was trying to make a simple E-Commerce website using MVC architecture in java. Initially I made a controller servlet which is named TestingServlet,a web.xml file,a bean class in the package com.bean under classes folder named DbBean and a Default.jsp,Header.jsp,Menu.jsp to start with. I compiled bean and the servlet classes. Then finally when I deployed the application on WebLogic server and run it, I got the following error-
As you can see in the log that it says it failed to compile JSP JSP/Menu.jsp which means the problem must be with Menu.jsp. Moreover, it says that in line 28 bean cannot be resolved. So, I checked that part of the code but it looks fine to me. What is causing the problem?
Following are all the files that I made-
TestingServlet.java
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import com.bean.DbBean;
public class TestingServlet extends HttpServlet
{
public void init(ServletConfig conf)
{
System.out.println("Initiallizing ControllerServlet");
ServletContext ctx = conf.getServletContext();
ctx.setAttribute("base",conf.getInitParameter("base"));
System.out.println("base = " +conf.getInitParameter("base"));
ctx.setAttribute("imageUrl",conf.getInitParameter("imageUrl"));
System.out.println("imageUrl = " +conf.getInitParameter("imageUrl"));
DbBean bean = new DbBean();
bean.setDbUrl(conf.getInitParameter("dbUrl"));
bean.setDbUserName(conf.getInitParameter("userName"));
bean.setDbPassword(conf.getInitParameter("password"));
ctx.setAttribute("bean",bean);
System.out.println("bean object successfully made,its properties set
and set in app scope..");
try
{
Class.forName(conf.getInitParameter("jdbcDriver"));
System.out.println("Driver Class Loaded Successfully");
}
catch(Exception e)
{
System.out.println("Could not load the driver class");
}
}
protected void doGet(HttpServletRequest req , HttpServletResponse res)
throws ServletException,IOException
{
doPost(req,res);
System.out.println("in doGet method");
}
protected void doPost(HttpServletRequest req , HttpServletResponse res)
throws ServletException,IOException
{
System.out.println("in doPost method");
String base = "/jsp/";
String url = base + "Default.jsp";
String action = req.getParameter("action");
if(action!=null)
{
if(action.equals("search"))
url = base + "SearchResults.jsp";
else if(action.equals("browseCatalog"))
url = base + "BrowseCatalog.jsp";
if(action.equals("productDetails"))
url = base + "ProductDetails.jsp";
if(action.equals("addShoppingItem") ||
action.equals("updateShoppingItem") ||
action.equals("deleteShoppingItem") ||
action.equals("displayShoppingCart"))
url = base + "ShoppingCart.jsp";
if(action.equals("checkOut"))
url = base + "CheckOut.jsp";
if(action.equals("order"))
url = base + "Order.jsp";
}
System.out.println("if part successfully executed");
RequestDispatcher rd = req.getRequestDispatcher(url);
System.out.println("RD object made successfully..");
rd.forward(req,res);
System.out.println("forward successfully executed..");
}
}
DbBean.java
package com.bean;
import java.sql.*;
import java.util.Hashtable;
public class DbBean
{
public String dbUrl = "";
public String dbUserName = "";
public String dbPassword = "";
public void setDbUrl(String url)
{
dbUrl = url;
}
public void setDbUserName(String userName)
{
dbUserName = userName;
}
public void setDbPassword(String password)
{
dbPassword = password;
}
public Hashtable getCategories()
{
Hashtable categories = new Hashtable();
try
{
Connection conn =
DriverManager.getConnection(dbUrl,dbUserName,dbPassword);
Statement stmt = conn.createStatement();
String sql = "select CategoryId,Category from Categories" +" ";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next())
{
categories.put(rs.getString(1),rs.getString(2));
}
rs.close();
stmt.close();
conn.close();
}
catch(SQLException e)
{}
return categories;
}
}
Default.jsp
<html>
<head>
<title>Welcome</title>
</head>
<body>
<table>
<tr>
<td colspan="2">
<jsp:include page="Header.jsp" flush = "true"/>
</td>
</tr>
<tr>
<td>
<jsp:include page="Menu.jsp" flush="true"/>
</td>
<td valign="top">
<H2>WELCOME TO MY E-MALL.</H2>
</td>
</tr>
</table>
</body>
</html>
Menu.jsp
<%# page import="java.util.*" %>
<jsp : useBean id = "bean" scope = "application" class="com.bean.DbBean" />
<%
String base = (String)application.getAttribute("base");
%>
<table cellspacing="0" cellpadding="5" width="150" border="0">
<tr>
<td bdcolor="F6F6F6">
<font face="Verdana">Search</font>
<form>
<input type="hidden" name="action" value="search">
<input type="text" name="keyword" size="10">
<input type="submit" value="Go">
</form>
</td>
</tr>
<tr >
<td bgcolor="F6F6F6">
<font face="Verdana">
Categories:
</font>
</td>
</tr>
<tr valign="top">
<td bgcolor="F6F6F6">
<%
Hashtable categories = bean.getCategories();
Enumeration categoryIds = categories.keys();
while(categoryIds.hasMoreElements())
{
Object categoryId = categoryIds.nextElement();
out.println("<a href=" +base +"?
action=browseCatalog&categoryId=" +categoryId.toString()
+">" +categories.get(categoryId) +"</a><br>");
}
%>
</td>
</tr>
</table>
The jsp : useBean is for use with Objects that are Java Beans.
Is it the case that DbBean does not adhere to the JavaBeans conventions i.e. have a look at What is a JavaBean exactly? and maybe you could change DBean to adhere to the conventions or you could just drop the use of jsp : useBean and just instansiate and manipulate it in the scriptlet?
I'm having some trouble returning a string to a component on a JSP page. I have built a very simple page as follows:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
...
<div id="logindiv" class="centered">
<h1>DB Schema status</h1>
<form action="DBConnectionTester" method="post">
<input type="text" name="usr" placeholder="DB Username" style="text-align: center;">
<br>
<input type="password" name="pwd" placeholder="DB Password" style="text-align: center;">
<br>
<input type="submit" value="Get Schema" class="btn btn-default btn-xs">
<br>
<br>
<c:if test="${not empty rtnmsg}">
<h6>${message}</h6>
</c:if>
</form>
</div>
And the class behind it is as follows:
#WebServlet("/DBConnectionTester")
public class DBConnectionTester extends HttpServlet {
String rtnmsg = "";
DBConnection dbcon = new DBConnection();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
dbcon.usr = request.getParameter("usr");
dbcon.pwd = request.getParameter("pwd");
dbcon.sampletest();
rtnmsg = dbcon.rtnstr;
}
}
For clarification, DBConnection is as follows:
public class DBConnection {
public String usr;
public String pwd;
private static String mySQLCon = "jdbc:mysql://<REDACTED>zeroDateTimeBehavior=convertToNull";
public String err;
public String stmt;
public String rtnstr;
void sampletest()
{
try
{
Connection mCon = DriverManager.getConnection(mySQLCon, usr, pwd);
mCon.getSchema();
err = "No connection issues";
}
catch (SQLException e)
{
err = e.toString();
}
Date date = new Date();
rtnstr = err + date.toString();
}
}
Now, whenever I hit that submit button, my browser appears to access the class itself - that is to say, the URL in the browser is as follows: http://<REDACTED>elasticbeanstalk.com/DBConnectionTester
What am I missing here?
Friends i have a jsp page which retrieves data from mysql table and displays them in form of table. I will also display another column consisting of a button to give Status to 1 . i need to update the database table when i click the status button.
following is the code for jsp
<form action="Edit" method="post">
<table cellspacing="8">
<tr>
<td><b>Name</b>
</td>
<td><b>Place</b>
</td>
<td><b>Gender</b>
</td>
<td><b>UserName</b>
</td>
<td><b>Password</b>
</td>
<td><b>Status</b>
</td>
<td></td>
</tr>
<%
ViewService vs = new ViewService();
ResultSet rs = vs.getRecords();
while(rs.next())
{
%>
<tr>
<td><%=rs.getString(2) %></td>
<td><%=rs.getString(3) %></td>
<td><%=rs.getString(4) %></td>
<td><%=rs.getString(5) %></td>
<td><%=rs.getString(6) %></td>
<td><%=rs.getString(7) %></td>
<td></td>
<td><input type="text" name="userid" value="<%=rs.getString(2) %>"
style="visibility: hidden;" > <input type="submit" value="Active"></td>
</tr>
<% }
%>
</table>
</form>
And my edit servlet is
package Admin;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
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 DBcon.Dbcon;
#WebServlet("/Edit")
public class Edit extends HttpServlet {
private static final long serialVersionUID = 1L;
public Edit() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Connection con;
PreparedStatement ps;
Dbcon db = new Dbcon();
con = db.getCon();
int status=1;
int userid =Integer.parseInt(request.getParameter("userid"));
try {
ps=con.prepareStatement("update tbluser set status = ? where userid
= ?");
ps.setInt(7,status);
ps.setInt(1, userid);
ps.executeUpdate();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.sendRedirect("ViewUser.jsp");
}
}
inside while loop
put the form tag inside while loop ( < td > ) not around the < table >
....
<td><%=rs.getString(7) %></td>
<td></td>
<td>
<form action="Edit" method="post">
<input type="text" name="userid" value="<%=rs.getString(2) %>" style="visibility: hidden;" > <input type="submit" value="Active">
</form>
</td>
</tr>
<% }
%>
</table>
OR
Use Hyperlink instead of form and button
<td>
Activate
<td>
try this bro i modified your codes.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Connection con;
PreparedStatement ps;
Dbcon db = new Dbcon();
con = db.getCon();
int status=1;
int userid =Integer.parseInt(request.getParameter("userid"));
try {
ps=con.prepareStatement("update tbluser set status = '"+status+"' where userid = '"+userid+"'");
ps.executeUpdate();
int updateQuery = ps.executeUpdate();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.sendRedirect("ViewUser.jsp");
}
}