Can't call doPost() method of servlet in jsp page [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
At beggining. There is a application structure.
I have 3 MySQL tables ( Obiekt, Termin, Rezerwacja). In project i have jsp page (here is code) :
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# page import="java.sql.*"%>
<%# page import="java.io.*"%>
<%# page import="java.util.*"%>
<%# page import="test.Obiekt"%>
<%# page import="test.ListaObiektow"%>
<%# page import="test.Termin"%>
<%# page import="test.ListaTerminow"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>menu główne</title>
<meta name="viewport" content="initial-scale=1, maximum-scale=1">
<meta name="android-mobile-web-app-capable" content="yes">
<meta name="android-mobile-web-app-status-bar-style" content="black">
<link href="css/ratchet.css" rel="stylesheet">
<link href="css/ratchet-theme-android.css" rel="stylesheet">
<script src="js/ratchet.js"></script>
<script type="text/javascript">
function Refresh(idObiekt){
location.href="pilkaNozna.jsp?idObiekt=" + idObiekt;
}
</script>
</head>
<body>
</br>
</br>
</br>
<header class="bar bar-nav">
<a class="icon icon-left-nav pull-left" href="wyszukaj.jsp"></a>
<h1 class="title">Wybierz obiekt</h1>
</header>
<div id="content">
<div class="tabelawybor">
<b>Wybierz obiekt:</b>
<%
ArrayList<Obiekt> list = new ListaObiektow().getObiekty();
%>
<form>
<select name="obiekt" onChange="Refresh(this.value)">
<option value="0" selected>Wybierz Obiekt</option>
<%
String selectedObiekt = request.getParameter("idObiekt");
int counter=0;
for (Obiekt obiekt : list) {
if(selectedObiekt == null && counter==0)
{
selectedObiekt = Integer.toString(obiekt.idObiekt);
}
%>
<option value="<%=obiekt.idObiekt%>"
<%= ((Integer.toString(obiekt.idObiekt)).equals(selectedObiekt))?"selected":""%>><%=obiekt.nazwa%>
<%=obiekt.adres%></option>
<%
}
%>
</select>
</form>
</div>
<div class="tabelawybor">
<td><b>Wpisz liczbę uczestników:</b><input type="text"
name="uczest" /></td>
<% String liczbaUczestnikow = request.getParameter("liczbaUczestnikow"); %>
</div>
<div class="tabelawybor">
<form action="Rezerwacja?action=doPost" method="post">
<table class="center">
<tr>
<td>Nazwa obiektu:</td>
<td>Data:</td>
<td>Godzina</br> rozpoczęcia:
</td>
<td>Godzina</br> zakończenia:
</td>
<td></td>
</tr>
<%
ListaTerminow listaterminow = new ListaTerminow();
listaterminow.setId(selectedObiekt);
ArrayList<Termin> lista =listaterminow.getTerminy();
String idTermin = request.getParameter("idTermin");
for (Termin termin : lista) {
%>
<tr>
<td><%=termin.nazwaObiektu%> <%=termin.adresObiektu%></td>
<td><%=termin.dzien%></td>
<td><%=termin.odKtorej%></td>
<td><%=termin.doKtorej%></td>
<td>
<button class="btn btn-primary">Zarezerwuj</button>
</td>
</tr>
<%
}
%>
</table>
</form>
</div>
</div>
</body>
</html>
In this jsp page i have select form which have List of Obiekt (this list is created in ListaObiektow.java), but it works. I also have table form which contains List of Termin (created in ListaTerminow.java). It works too. But, in this table form there is button to make Rezerwacja.
I made Rezerwuj servlet. Here is code:
package test;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
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 test.ConnectionClass;
import test.Rezerwacja;
import test.Termin;/**
* Servlet implementation class Rezerwuj
*/
#WebServlet("/Rezerwacja")
public class Rezerwuj extends HttpServlet {
private static final long serialVersionUID = 1L;
Connection conn;
private int idTermin;
private int liczbaUczestnikow;
public Rezerwuj() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
conn = ConnectionClass.Polacz();
ArrayList<Rezerwacja> rezerwacje = new ArrayList<Rezerwacja>();
PreparedStatement st = null;
ResultSet rs = null;
String sql = "INSERT INTO rezerwacje (liczbaUczestnikow,idTermin) values ('" + liczbaUczestnikow + "','" + idTermin + "')"
+ "UPDATE termin SET termin.czyZajety=true WHERE termin.idTermin = '"+ idTermin +"'";
try
{
st = conn.prepareStatement(sql);
if(liczbaUczestnikow > 0 && liczbaUczestnikow < 20)
{
rs = st.executeQuery();
}
while(rs.next())
{
Rezerwacja rezerwacja = new Rezerwacja();
rezerwacja.setLiczbaUczestnikow(rs.getInt(1));
rezerwacja.setIdTermin(rs.getInt(2));
rezerwacje.add(rezerwacja);
}
}
catch(SQLException e)
{
System.out.println(e);
}
}
public void setIdTermin(String id)
{
idTermin = Integer.parseInt(id);
}
public void setliczbaUczestnikow(String liczba)
{
liczbaUczestnikow = Integer.parseInt(liczba);
}
}
When i click on the button, it returns error like this:
type Exception report
message
description The server encountered an internal error that prevented it from fulfilling this request.
exception
java.lang.NullPointerException
test.Rezerwuj.doPost(Rezerwuj.java:63)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
What i want:
I select one of option in select form, then type value (0-20) into text input, then click on button and create a record in MySQL table Rezerwacja. Any suggestions ?

<form action="Rezerwacja?action=doPost" method="post">
In this line the action is where you are sending the request, so it should be action="Rezerwacja" and method should be method="POST"

I think you have problem with liczbaUczestnikow after initialization is always 0. As result rs always null, therefore exception thrown.

Related

JSP & Servlet & Maven: form attribute "action" redirects to another jsp page, instead of sendRedirect method

I have created a login form in my index.jsp file:
<%# page contentType="text/html; ISO-8859-1" language="java" %>
<html>
<head>
<title>Material Master Data Manager</title>
<meta charset="ISO-8859-1">
<link rel="stylesheet" href="css/login_style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<div id="basicData">
<div id="createMaterialHeader">
<h2><i><b>Material Master Data Manager</b></i></h2>
<div id="newPasswordBar">
<p>New Password</p>
</div>
</div>
<form class="tabcontent" action="MaterialCreator" method="post">
<label for="client">Client</label><br>
<select type="text" name="client" id="client">
<option>Commerzbank AG S.A. Branch in Lodz</option>
<option>Daikin Airconditioning Poland Sp. z o.o.</option>
<option>Infosys Consulting</option>
</select><br>
<label for="userID">User ID</label><br>
<input type="text" id="userID" name="userID"><br>
<label for="userPassword">Password</label><br>
<input type="password" id="userPassword" name="userPassword"><br>
<label for="isAdmin">Admin</label><br>
<input type="text" id="isAdmin" name="isAdmin"><br>
<input type="submit" class="fa fa-check">
</form>
</div>
</div>
<footer>
<p><a>© Created by Lorem Ipsum. 2017</a></p>
</footer>
</body>
<script src='javaScript/loginJs.js'></script>
</html>
That is MaterialCreator servlet:
package com.mmdmanager;
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 java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
#WebServlet("/MaterialCreator")
public class MaterialCreator extends HttpServlet {
Connection dbConnection;
PreparedStatement getCredentialsFromDb;
ResultSet userCredentialsReceived;
String userCredentials = "SELECT USER_ID, FIRST_NAME, LAST_NAME, SEX, COMPANY_NAME, IS_ADMIN, ACC_PASSWORD FROM USERS " +
"WHERE COMPANY_NAME =? AND USER_ID =? AND ACC_PASSWORD =? AND IS_ADMIN =?";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter printWriter = response.getWriter();
doGet(request,response);
String company_name = request.getParameter("client");
String user_id = request.getParameter("userID");
String acc_password = request.getParameter("userPassword");
String is_admin = request.getParameter("isAdmin");
if (company_name.equals("Infosys Consulting") && user_id.equals("ADMIN1") && acc_password.equals("Q#3wertyuiop") && is_admin.equals("Y")) {
response.sendRedirect("MaterialCreator.jsp");
}
else {
response.sendRedirect("");
}
}
}
As You can see in the code above, the main idea is to redirect on condition that a user provides correct credentials (IF statement stores it). Unfortunately, no matter what credentials I provide, every time when I click the input button (class "fa fa-check") I am redirected to MaterialCreator servlet, not to MaterialCreator.jsp file, however the code contains method -> response.sendRedirect("MaterialCreator.jsp");, but it is invisible for the project.
MaterialCreator.jsp file has a very simple html code:
<%# page contentType="text/html; ISO-8859-1" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>Hello User!</h1>
</body>
</html>

Delete a record from database using servlet

The Remove.java is the servlet and the index.jsp is the jsp file. I am trying to delete the file using email,since it is unique.
Remove.java
package servletPool;
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;
#WebServlet("/Remove")
public class Remove extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String uEmail = request.getParameter("email");
try {
Class.forName("com.mysql.jdbc.Driver");
String user = "root";
String pass = "root";
String query = "delete from user_details where email=?";
Connection con = DriverManager.getConnection("jdbc:mysql://locahost:3306/dbname", user, pass);
PreparedStatement ps = con.prepareStatement("delete from user_details where email=?");
ps.setString(1, uEmail);
int i = ps.executeUpdate();
if(i > 0) {
out.println("User successfully removed...");
}
} catch (Exception e) {
System.out.println(e);
}
}
}
and here is the index.jsp file from which the record will be deleted.
index.jsp
<%# 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>Registration Page.</title>
</head>
<body>
<div>
<div style="padding : 10px;">
<center>
<form action="Remove.servlet" method="get">
<h5>If you want to remove users,</h5>
<input type="email" placeHolder="User's Email" name="email"/>
<input type="button" value="Click" name="remove"/>
</form>
</center>
</div>
</center>
</div>
</body>
</html>
Try changing from:
<form action="Remove.servlet" method="get">
to:
<form action="Remove" method="post">
and from:
<input type="button" value="Click" name="remove"/>
to:
<input type="submit" value="Click" name="remove"/>
In addition, line 26 (</center>) in index.jsp and line 29 (String query = "delete from user_details where email=?";) in Remove.java should be removed because they are unnecessary.

JSP and Servlet NullPointer - display class attribute in text field

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.

Using JSP to store images in Mysql and upload the images online

I am still wondering what it is that i am doing wrong,my problem is i dont know if it is my entire sample code which has na error or my connection to the database which has an issues, as of where i stand i am not sure what is making me get this error. (displayed below).I have tried to look here at stack overflow but all i get is loading images using JSP but not adding them to the database. If we have one i couldnt trace please help me with the link. I have included all the libraries needed and my code has no error apart from this output. I came here because i am stranded and need a short review of what you proffesionals think is wrong with my code as done below. I will really appreciate anyhelp given as i am working on a deadline.
my Database name is
AppDB
I was wondering should i use the name of the table? to INSERT INTO? which is
'contacts'
Error Message
HTTP Status 404 - /UploadImageOnWeb/uploadServlet type Status report
message /UploadImageOnWeb/uploadServlet description The requested
resource is not available. Apache Tomcat/8.0.23
Thank you
Java Servlet Code
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
/**
* Servlet implementation class FileUploadDBServlet
*/
#MultipartConfig(maxFileSize = 16177215)
#WebServlet("/FileUploadDBServlet")
public class FileUploadDBServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
// database connection settings
/*private String dbURL = "jdbc:mysql://localhost/AppDB";
private String dbUser = "root";
private String dbPass = "mypassword";*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
InputStream inputStream = null;
Part filePart = request.getPart("photo");
if (filePart != null) {
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
inputStream = filePart.getInputStream();
}
Connection conn = null;
String message = null;
try {
// connects to the database
/*DriverManager.registerDriver("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(dbURL, dbUser, dbPass);*/
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/AppDB","root","mypassword");
// constructs SQL statement
String sql = "INSERT INTO contacts (first_name, last_name, photo) values (?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, firstName);
statement.setString(2, lastName);
if (inputStream != null) {
// fetches input stream of the upload file for the blob column
statement.setBlob(3, inputStream);
}
int row = statement.executeUpdate();
if (row > 0) {
message = "File uploaded and saved into database";
}
} catch (SQLException ex) {
message = "ERROR: " + ex.getMessage();
ex.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (conn != null) {
// closes the database connection
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
// sets the message in request scope
request.setAttribute("Message", message);
// forwards to the message page
getServletContext().getRequestDispatcher("/Message.jsp").forward(request, response);
}
}
}
My .Jsp class
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>File Upload to Database Demo</title>
</head>
<body>
<center>
<h1>File Upload to Database Demo</h1>
<form method="post" action="uploadServlet" enctype="multipart/form-data">
<table border="0">
<tr>
<td>Enter First Name: </td>
<td><input type="text" name="firstName" size="20"/></td>
</tr>
<tr>
<td>Enter Last Name: </td>
<td><input type="text" name="lastName" size="20"/></td>
</tr>
<tr>
<td>Portrait Photo: </td>
<td><input type="file" name="photo" size="20"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save">
</td>
</tr>
</table>
</form>
</center>
</body>
</html>
Display Jsp
<%# 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>Message</title>
</head>
<body>
<center>
<h3><%=request.getAttribute("Message")%></h3>
</center>
</body>
</html>
The 404 error indicates that the form is not even getting to the servlet.
You defined the action attribute in the form as uploadServlet which doesn't seem to be a valid URL for your application.
The servlet's URL is defined in the #WebServlet annotation as FileUploadDBServlet.
So you can fix it by changing the action in the form or changing the URL for the servlet.

unable to update table using JSP/DAO/Servlet

Hello i'm trying to create a page to update a row in my database table i'm using DAO/Servlet with JSP page
DAO code:
public static AnimalUpdateBean updateAnimal(AnimalUpdateBean bean) {
//preparing some objects for connection
PreparedStatement up = null;
Statement stmt = null;
String id = bean.getAnimalId();
String aname = bean.getAnimalName();
String dob = bean.getAnimalDob();
String gender = bean.getAnimalGender();
String breedid = bean.getAnimalBreed();
String remark = bean.getAnimalRemark();
try
{
//connect to DB
currentCon = dbConnection.getConnection();
up = currentCon.prepareStatement("update animal set aname = '"+aname+"' , gender = '"+gender+"', specie_id = '"
+breedid+"' , remark = '"+remark+"' where animal_id = '"+id+"'");
up.executeUpdate();
if (up.executeUpdate()>=1){
stmt=currentCon.createStatement();
rs = stmt.executeQuery("select aname , dob, gender, specie_id , remark from animal where animal_id = '"+id+"'");
}
System.out.println("done");
}
catch (Exception ex)
{
System.out.println("Log In failed: An Exception has occurred! " + ex);
}
//some exception handling
finally
{
if (rs != null) {try {rs.close();} catch (Exception e) {} rs = null;}
if (stmt != null) {try {stmt.close();} catch (Exception e) {}stmt = null;}
if (currentCon != null) {try {currentCon.close();} catch (Exception e) {}currentCon = null;}
}
return bean;
}
}
UpdateAnimal.jsp code:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# page import="java.util.ArrayList" %>
<%#page import="content.*"%>
<%#page import="java.sql.*"%>
<%#page import="java.util.*"%>
<%# page session="true"%>
<%#page import="java.io.*"%>
<%#page import="java.net.*"%>
<%#page import="javax.servlet.*"%>
<%# page language="java"
contentType="text/html; charset=windows-1256"
pageEncoding="windows-1256" %>
<!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=windows-1256">
<title>Update Animal</title>
<link rel="stylesheet"
href="./css/styles.css"
type="text/css"/>
</head>
<body>
<table class="title">
<tr><th>Zoo keeper</th></tr>
</table>
<h1>Update Animal</h1>
<form action="Relay" >
<fieldset>
Animal new name: <input type= "text" name = "aname"><br>
Animal new DOB: <input type= "text" name = "dob"><br>
<br>
Animal new gender:
<select name="gender" id="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<br>
Animal new Breed: <input type= "text" name = "breedid" ><br>
Animal new remarks: <textarea name = "remark" rows="4" cols="20">
</textarea> <br /> <br/>
<input type="submit" value="submit">
<input type="hidden" name="animal_id" value="<%= request.getParameter("animal_id") %>">
<input type="hidden" name="command" value="UpdateAnimalServlet" >
</fieldset>
</form>
</body></html>
the record being updated come from a select page to view the records when the user click on the name he will be redirected to update page CheckAnimal.jsp
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# page import="java.util.ArrayList" %>
<%#page import="content.*"%>
<%#page import="java.sql.*"%>
<%#page import="java.util.*"%>
<%# page session="true"%>
<%#page import="java.io.*"%>
<%#page import="java.net.*"%>
<%#page import="javax.servlet.*"%>
<%# page language="java"
contentType="text/html; charset=windows-1256"
pageEncoding="windows-1256" %>
<!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=windows-1256">
<title>Animal list</title>
<link rel="stylesheet"
href="./css/styles.css"
type="text/css"/>
</head>
<body>
<table class="title">
<tr><th>Zoo keeper</th></tr>
</table>
<h1>Animal list</h1>
Click on animal name to update it!
<center>
<table width="100 % " id='table1' border="1" cellspacing="2" cellpadding="2">
<tr class="tab-highlighted-2">
<td class="tab-highlighted-2" width="15">
<div align="left">Name</div>
</td>
<td class="tab-highlighted-2" width="13">
<div align="left">Age</div>
</td>
<td class="tab-highlighted-2" width="13">
<div align="left">Gender</div>
</td>
<td class="tab-highlighted-2" width="13">
<div align="left">Status</div>
</td>
<td class="tab-highlighted-2" width="13">
<div align="left">Breed</div>
</td>
<td class="tab-highlighted-2" width="13">
<div align="left">Pen #</div>
</td>
<td class="tab-highlighted-2" width="15">
<div align="left">Zoo</div>
</td>
<td class="tab-highlighted-2" width="20">
<div align="left">Remarks</div>
</td>
</tr>
<c:forEach items="${beans}" var="view">
<tr>
<td>${view.animalName}</td>
<td>${view.animalDob}</td>
<td>${view.animalGender}</td>
<td>${view.animalSource}</td>
<td>${view.animalBreed}</td>
<td>${view.sectionId}</td>
<td>${view.zooId}</td>
<td>${view.animalRemark}</td>
</tr>
</c:forEach>
</table>
</center>
</body></html>
AnimalUpdateBean.java code:
package content;
public class AnimalUpdateBean {
private String animalId;
private String animalName;
private String animalDob;
private String animalGender;
private String animalBreed;
private String animalRemark;
public String getAnimalId() {return animalId;}
public String getAnimalName() {return animalName;}
public String getAnimalDob() {return animalDob;}
public String getAnimalGender() {return animalGender;}
public String getAnimalBreed() {return animalBreed;}
public String getAnimalRemark() {return animalRemark;}
public void setAnimalId(String animalId) {this.animalId = animalId;}
public void setAnimalName(String animalName) {this.animalName = animalName;}
public void setAnimalDob(String animalDob) {this.animalDob = animalDob;}
public void setAnimalGender(String animalGender) {this.animalGender = animalGender;}
public void setAnimalBreed(String animalBreed) {this.animalBreed = animalBreed;}
public void setAnimalRemark(String animalRemark) {this.animalRemark = animalRemark;}
}
the servlet responsible to start the update is UpdateAnimalServlet:
package content;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class LoginServlet
*/
public class UpdateAnimalServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
try
{
AnimalUpdateBean animal = new AnimalUpdateBean();
animal.setAnimalId(request.getParameter("animal_id"));
animal.setAnimalName(request.getParameter("aname"));
// animal.setAnimalDob(request.getParameter("dob"));
animal.setAnimalGender(request.getParameter("gender"));
animal.setAnimalBreed(request.getParameter("breedid"));
animal.setAnimalRemark(request.getParameter("remark"));
String test = request.getParameter("animal_id");
System.out.println(test);
System.out.println(animal);
animal = DAO.updateAnimal(animal);
response.sendRedirect("/oosd/member.jsp");
}
catch (Throwable theException)
{
System.out.println(theException);
}
}
}
I'm using a Relay servlet that calls AnimalUpdateServlet for execution:
package content;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LoginServlet
*/
public class Relay extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
try
{
String command = request.getParameter("command");
if (command.equals("LoginServlet")){
RequestDispatcher rd =request.getRequestDispatcher("/"+command);
rd.forward(request, response);
//for testing
System.out.println("Request forwarded to " + command + " servlet");
} else if (command.equals("UpdateAnimalServlet")){
RequestDispatcher rd =request.getRequestDispatcher("/"+command);
rd.forward(request, response);
//for testing
System.out.println("Request forwarded to " + command + " servlet");
}
else
System.out.println("=> command='" + command + "'");
String url = "/oosd/" + command;
String encodedUrl = response.encodeRedirectURL(url);
System.out.println(" url=" + url);
System.out.println(" encodedUrl=" + encodedUrl);
response.sendRedirect(encodedUrl);
}
catch (Throwable theException)
{
System.out.println(theException);
}
}
}
and last thing is the web.xml page:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:javaee="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>content.LoginServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>UpdateAnimalServlet</servlet-name>
<servlet-class>content.UpdateAnimalServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>SelectAnimalServlet</servlet-name>
<servlet-class>content.SelectAnimalServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>Relay</servlet-name>
<servlet-class>content.Relay</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SelectAnimalServlet</servlet-name>
<url-pattern>/SelectAnimalServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>UpdateAnimalServlet</servlet-name>
<url-pattern>/UpdateAnimalServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Relay</servlet-name>
<url-pattern>/Relay</url-pattern>
</servlet-mapping>
</web-app>
I keep getting these errors:
Log In failed: An Exception has occurred! java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Data type mismatch in criteria expression.
java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed
I have checked the data entry and all correct name text, gender text, specie_id number, remark text i even put the dob on hold until this work i'm using access database and here is the connection code:
package content;
import java.sql.*;
public class dbConnection {
static Connection con;
static String url;
public static Connection getConnection()
{
try
{
String url = "jdbc:odbc:oosd";
// assuming "DataSource" is your DataSource name
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
try
{
con = DriverManager.getConnection(url,"","");
// assuming your SQL Server's username is "username"
// and password is "password"
}
catch (SQLException ex)
{
ex.printStackTrace();
}
}
catch(ClassNotFoundException e)
{
System.out.println(e);
}
return con;
}
}
Any idea where is my mistake here ?
as specie_id is a number and that's what the thrown exception is stating "Data type mismatch in criteria expression." and because of this exception sendRedirect error is occuring as because of the SQLException data has been already written to the response.
your query should be something like
"update animal set aname = '"+aname+"' , gender = '"+gender+"', specie_id = "
+Integer.parseInt(breedid)+" , remark = '"+remark+"' where animal_id = '"+id+"'"
same would be required if animal_id is also a number.
The sendRedirect error happens when you've already written data to the response (like with a forward, or to the JSP writer directly) then try to redirect.
The SQL error is likely due to you using a string IDs in the SQL (surrounded by single-quotes) whereas the IDs in the DB are most likely defined as an integer.
Also, after you update the animal, you perform a query, but do nothing with the results.

Categories