unable to update table using JSP/DAO/Servlet - java

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.

Related

Servlet returning blank page not redirecting to jsp page

I am working on a Login and registration form. I have successfully created the Login and Registration form and linked them together. Now I created a separate page for admin where I want to display my database. But I am not able to move to the admin page. Whenever i input my admin credentials it always shows a blank page. I am a newbie both to Java and stackoverflow so I dont know how to ask proper questions. I pasted all my code here. My main problem is in Login.java . I am using eclipse and tomcat 8.5.
Things I have tried till now:-
1) RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/admin.jsp");
rd.forward(request, response);
2)HttpServletResponse.sendRedirect("/WEB-INF/admin.jsp")
3)response.sendRedirect("WEB_INF/admin.jsp");
Registeration.java
public class Registeration extends HttpServlet {
private static final long serialVersionUID = 1L;
public Registeration(){
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException{
try {
String usernam = request.getParameter("usernam");
String password = request.getParameter("password");
String age = request.getParameter("age");
String gender = request.getParameter("gender");
String event = request.getParameter("event");
String sql = "insert into
registeration(usernam,password,age,gender,event) values(?,?,?,?,?)";
Class.forName("com.mysql.jdbc.Driver");
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/portal",
"root", "");
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,usernam);
ps.setString(2,password);
ps.setString(3,age);
ps.setString(4,gender);
ps.setString(5,event);
ps.executeUpdate();
PrintWriter out = response.getWriter();
out.println("You have successfully registered!");
out.flush();
RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
rd.include(request, response);
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
Registeration.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=UTF-8">
<title>JSP Page</title>
<style>
img {
display: block;
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<img src="unilogo.PNG" style="width:40%">
<body>
<div align="center">
<form action="Registeration" method="POST">
User Name:<input type="text" name="usernam" required="required">
<br>
Password : <input type="password" name="password"
required="required"><br>
Age : <input type="text" name="age" required="required" /><br>
Gender : <select name="gender">
<option>Male</option>
<option>Female</option>
<option>Transgender</option>
</select><br>
Event : <select name="event" multiple="multiple">
<option>Mr.Tanwar Body Building</option>
<option>Fashion Show</option>
<option>Dance</option>
<option>Singing</option>
<option>Coding</option>
</select><br>
<input type="submit" value="REGISTER" />
<input type="reset" value="RESET" /><br>
<a href="${pageContext.request.contextPath}/login.jsp">Click
here
to go to the login page</a>
</form>
</div>
</body>
</html>
Login.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=UTF-8">
<title>Login Page</title>
</head>
<body>
<div align="center">
<form action="Login" method="POST">
User Name:<input type="text" name="usernam" required="required">
<br>
Password : <input type="password" name="password"
required="required"><br>
<input type="submit" value="Login" />
<input type="reset" value="RESET" /><br>
<a
href="${pageContext.request.contextPath}/registeration.jsp">Click here
to
go to the Registration page</a>
</form>
</div>
</body>
</html>
Login.java
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
public Login() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
try {
String usernam = request.getParameter("usernam");
String password = request.getParameter("password");
String dbName = null;
String dbPassword = null;
String sql = "select * from registeration where usernam =
? and password = ?";
Class.forName("com.mysql.jdbc.Driver");
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/portal",
"root",
"");
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,usernam);
ps.setString(2,password);
ResultSet rs = ps.executeQuery();
PrintWriter out = response.getWriter();
while(rs.next()){
dbName = rs.getString(2);
dbPassword = rs.getString("password");
if(usernam.equals("admin") &&
password.equals("password")){
RequestDispatcher rd =
request.getRequestDispatcher("/WEB-INF/admin.jsp");
rd.forward(request, response);
}
if(usernam.equals(dbName) &&
password.equals(dbPassword)) {
out.println("You have successfully logged
in!");
out.println("Age:"+rs.getString(4)+"
Gender:"+rs.getString(5)+" Event:"+rs.getString(6));
}
else {
RequestDispatcher rd =
request.getRequestDispatcher("/WEB-INF/registeration.jsp");
rd.forward(request, response);
}
}
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID"
version="3.1">
<display-name>Registeration</display-name>
<servlet>
<servlet-name>reg</servlet-name>
<servlet-class>jdbc.registeration</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>reg</servlet-name>
<url-pattern>/regServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>jdbc.Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/loginServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
My login page is supposed to redirect me to admin.jsp when i enter my admin details. But all i get is a blank page. My url after entering admin details"http://localhost:8080/Registeration/Login". I am getting the required output when enter the login id which are stored in DB.

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.

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

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.

Error on login form

I am new to java servlets.
I googled for how to build simple login form with validation against mysql database. I have made so much changes and still have the following error for some reason.
The following error type:
HTTP Status 404 - /LoginServlet
type Status report
message /LoginServlet
description The requested resource is not available.
Apache Tomcat/7.0.57
Here all my jsp pages and java objects and web.xml:
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>Login Page</title>
</head>
<body>
<center>
<h1>Login Details</h1>
<form action="/LoginServlet" method="POST">
<br/>Username:<input type="text" name="username">
<br/>Password:<input type="password" name="password">
<br/><input type="submit" value="Submit">
</form>
</center>
</body>
</html>
Welcome.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome <%=session.getAttribute("name")%></title>
</head>
<body>
<h3>Login successful!!!</h3>
<h4>
Hello,
<%= session.getAttribute("name")%>
</h4>
</body>
</html>
LoginServlet.java
package com.servlet;
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;
import javax.servlet.http.HttpSession;
import com.logindao.LoginDao;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public 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("password");
HttpSession session = request.getSession(false);
if(session!=null)
session.setAttribute("username", n);
if(LoginDao.validate(n, p)){
RequestDispatcher rd=request.getRequestDispatcher("welcome.jsp");
rd.forward(request,response);
}
else{
out.print("<p style=\"color:red\">Sorry username or password error</p>");
RequestDispatcher rd=request.getRequestDispatcher("index.jsp");
rd.include(request,response);
}
out.close();
}
}
LoginDao.java
package com.logindao;
import java.sql.*;
public class LoginDao {
public static boolean validate(String name, String pass) {
boolean status = false;
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "form";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "password";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url + dbName, userName, password);
pst = conn.prepareStatement("select * from login where user=? and password=?");
pst.setString(1, name);
pst.setString(2, pass);
rs = pst.executeQuery();
status = rs.next();
} catch (Exception e) {
System.out.println(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pst != null) {
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return status;
}
}
Web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Unless your application is deployed as the root application, all the URLs to resources of the application should start with the context path of the application (the root application's context path is the empty string).
Typically, if your war file is myWebApp.war, the app is living under /myWebApp, and all the URLs should thus start with /myWebApp.
Your form action is /LoginServlet, so it fails to fill this constraint.
Use the JSTL, and define the action as
<form action="<c:url value='/LoginServlet' />"
The c:url tag will prepend the context path, whatever it is.
The problem is here:
<form action="/LoginServlet" method="POST">
^ means absolute path
Change it to a proper form using EL:
<form action="${request.contextPath}/LoginServlet" method="POST">
In your doPost method, if you're already using this:
RequestDispatcher rd=request.getRequestDispatcher("...");
rd.forward(request,response);
There's no need to use the writer of the response:
PrintWriter out = response.getWriter();
//...
out.print("<p style=\"color:red\">Sorry username or password error</p>");
//...
out.close();
These lines using out should be removed from your code.
Also, please stop using scriptlets. Use EL + JSTL to achieve the same result:
<!-- <title>Welcome <%=session.getAttribute("name")%></title> -->
<!-- Retrieve it directly from any scope -->
<!-- <title>Welcome ${name}</title> -->
<!-- If you want to make sure it is retrieved from session scope -->
<title>Welcome <c:out value="${sessionScope.name}" /></title>
</head>
<body>
<h3>Login successful!!!</h3>
<h4>
<!-- similar here -->
<!--
Hello, <%= session.getAttribute("name")%>
-->
Hello, <c:out value="${sessionScope.name}" />
You servlet is not found in the absolute path you requested the <form action> attribute . I suggest you to get the path using contextPath as suggessted by #Luggi.
This temporary soultion should work ,
<form action="<c:url value='./LoginServlet'>"
as it will search for the servlet in the packages that are created under the src package.
And also avoid using the scriplets as they are not suggested over the decade. Please see How to avoid Java code in JSP files?
Hope this helps

passing value to a jsp page from a java class using DAO

I wanted to pass the value retrieved on a java class to a page.I am using DAO classes.
I have retrieved the values from the database and stored them on String variables.Now I want to set them to the text boxes in my view.jsp page.I am new to this area,can anyone help me out??
View.jsp is as
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="process.jsp">
Enter Name <br/> <br> <input type="text" name="uname" onclick="this.value=''"/><br/><br/>
<input type="submit" value="view details"/><br/><br/>
Email id: <br/> <input type="text" name="email" id="email" > <br/><br/>
password: <br/> <input type="text" name="passw" id="passw"><br/><br/>
</form>
</body>
</html>
and My Activity ViewDAO.java is as
public static void view(user u) {
Connection con=ConnectionProvider.getCon();
String uname=u.getUname();
try {
PreparedStatement ps=con.prepareStatement("select email,pass from S1.USER432 where name='"+uname+"'");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String email = rs.getString("EMAIL");
String pass = rs.getString("PASS");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Thanks...
If you are using a front controller[spring mvc] then you can pass the data by doing,
model.addAttribute("variable_name ", data);
and in the jsp you can access it by doing this ${variable_name};
You need to call the DAO method from your servlet like below:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// call DAO method to get the email and password
HashMap<String,String> map=ViewDAO.getDetails();
//from the map you will get the email and password.then you need to set them in the attributes and get them in your jsp
request.setAttribute("email", map.get("email"));
request.setAttribute("password", map.get("password"));
}
your DAO method should be like the below:
public static HashMap<String,String> getDetails(user u) {
Connection con=ConnectionProvider.getCon();
String uname=u.getUname();
Map<String,String> map=new HashMap<>();
try {
PreparedStatement ps=con.prepareStatement("select email,pass from S1.USER432 where name='"+uname+"'");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String email = rs.getString("EMAIL");
String pass = rs.getString("PASS");
}
map.put("email",email);
map.put("password",pass);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return map;
}
}
Hope this will help you.
if you are using simple jsp and servelt, then make one ViewController.java.
You can two methods one for handling GET and other for POST
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String email = request.getParameter("email");
String password = request.getParameter("password");
request.setAttribute("email", email);
request.setAttribute("password", password);
request.getRequestDispatcher("view.jsp").forward(request, response);
}
catch(Exception e){
}
View.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>Insert title here</title>
</head>
<body>
<form action="process.jsp">
Enter Name <br/> <br> <input type="text" name="uname" onclick="this.value=''"/><br/><br/>
<input type="submit" value="view details"/><br/><br/>
Email id: <br/> <input type="text" name="email" id="email" value="<%=email%>" > <br/><br/>
password: <br/> <input type="text" name="passw" id="passw" value="<%=password%>"><br/><br/>
</form>
</body>
</html>
The Servlet decides which page must be loaded. So whatever you get from the DAO must go to the Servlet and through that, to the jsp. You can use a bean class to send values from DAO to Servlet.
Like this,
public class Details{
private String email;
private String password;
public void setEmail(String email){
this.email = email;
}
public void setPassword(String password){
this.password= password;
}
public String getEmail(){
return this.email;
}
public String getPassword(){
return this.password;
}
}
And you can make the following changes in DAO after getting the query results in the String. Add these
Details d = new Details();
d.setEmail(email);
d.setPassword(pass);
return d;
You can pass this object d to the servlet and retrieve the values using the getter methods of the bean. Also, the DAO must be called from the Servlet.
And now on the Servlet side.
On the Servlet you can put your code in the get or post method depending on your need. It may be like
public class ExampleServlet extends HttpServlet{
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String email = request.getParameter("email"); //got from the jsp where "email" is the name attribute of the input field
Details d = new Details();
d = ViewDao.view(user_object); //the bean sent by DAO. "user_object" is parameter that your DAO method is taking in your code
if(d.getEmail()!=null){ //just an example
// your code that redirects desired page
}
}
}
Based on d returned by the DAO you may redirect to any page you want.
Something like that
Observe this import
dao.UserDao,bean.*,
dao is the package
UserDao is the class
bean is the method you want or is could an attribute from dao
remember that
jsp
<body>
<%#page import="dao.UserDao,bean.*,java.util.*"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h1>Users List</h1>
<%
List<User> list=UserDao.getAllRecords();
request.setAttribute("list",list);
%>
<div class="table-responsive">
<table class="table">
<thread class="bg-info">
<th>Id</th><th>Name</th><th>Password</th><th>Edit</th><th>Delete</th>
</thread>
<c:forEach items="${list}" var="u">
<tr>
<td>${u.getId()}</td><td>${u.getUsername()}</td><td>${u.getPassword()}</td>
<td>Edit</td>
<td>Delete</td>
</tr>
</c:forEach>
</table>
</div>
<br/>Add New User
<br>
<br>
<form action="index.jsp">
<button type="submit">IndexUsers</button>
</form>
</body>
Bean or model
package bean;
// classe para as tables
public class User {
private int id;
private String username,password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
dao
public class UserDao {
public static Connection getConnection(){
Connection con=null;
try{
Class.forName("com.mysql.cj.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql_database","root","14570");
}catch(Exception e){System.out.println(e);}
return con;
}
public static int save(User u){
int status=0;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement(
"insert into login(username,password) values(?,?)");
ps.setString(1,u.getUsername());
ps.setString(2,u.getPassword());
status=ps.executeUpdate();
}catch(Exception e){System.out.println(e);}
return status;
}
public static int update(User u){
int status=0;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement(
"update login set username=?,password=? where id=?");
ps.setString(1,u.getUsername());
ps.setString(2,u.getPassword());
ps.setInt(3,u.getId());
status=ps.executeUpdate();
}catch(Exception e){System.out.println(e);}
return status;
}
public static int delete(User u){
int status=0;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("delete from login where id=?");
ps.setInt(1,u.getId());
status=ps.executeUpdate();
}catch(Exception e){System.out.println(e);}
return status;
}
public static List<User> getAllRecords(){
List<User> list=new ArrayList<User>();
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("select * from login");
ResultSet rs=ps.executeQuery();
while(rs.next()){
User u=new User();
u.setId(rs.getInt("id"));
u.setUsername(rs.getString("username"));
u.setPassword(rs.getString("password"));
list.add(u);
}
}catch(Exception e){System.out.println(e);}
return list;
}
public static User getRecordById(int id){
User u=null;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("select * from login where id=?");
ps.setInt(1,id);
ResultSet rs=ps.executeQuery();
while(rs.next()){
u=new User();
u.setId(rs.getInt("id"));
u.setUsername(rs.getString("username"));
u.setPassword(rs.getString("password"));
}
}catch(Exception e){System.out.println(e);}
return u;
}
}
Another Example this import import="dao.*"% makes available any methods from package dao, Bellow you see how to get the result of the method countid() in the dao.
<%#page import="dao.*"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Connection"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<% int id = 0; %>
<%
DaoEvento daoEvento = new DaoEvento();
id = daoEvento.countId();
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">
<body>
<br><br>
<form action="add_event_servletnew" method="POST">
<div class="form-group">
<td>
<font color='green' face = "Arial" size = "4">
<%= request.getParameter("message") %>
</font>
view
<td>
</div>
<div class="form-group">
<label>id</label>
<input type="text" name="id" value="<%= id%>" readonly="readonly" class="form-control"/>
</div>
<div class="form-group">
<label>Title</label>
<input type="text" name="title" value="" class="form-control" />
</div>
<div class="form-group">
<label>Start</label>
<input type="date" name="start" value="" class="form-control"/>
</div>
<div class="form-group">
<label>End</label>
<input type="date" name="end" value="" class="form-control" />
</div>
<div class="form-group">
<td><input type="submit" value="submit" class="btn btn-success btn-block"/></td>
</div>
</form>
</body>
<script src="https://cdn.jsdelivr.net/npm/jquery#3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-fQybjgWLrvvRgtW6bFlB7jaZrFsaBXjsOMm/tB9LTS58ONXgqbR9W8oWht/amnpF" crossorigin="anonymous"></script>
<script src="jquery.mask.min.js"> </script>
</html>

Categories