I am working on a simple home library web application using Java EE, Servlets, JSP, and MySQL. My Create, Read, and Delete are working fine but Update is not working. I am not using any form of design patterns, just servlets and POJO. All examples i try to learn from seem to have used MVC and DAO design patterns. Is there any way to achieve the CRUD application without using MVC and DAO patterns? What is the recommended and best practice for such a simple application?
here is code:
UpdateBook.jsp
<%# page language="java" contentType="text/html; charset=gbk"
pageEncoding="gbk"%>
<%# page import ="java.util.ArrayList"%>
<%#page import="book.Book"%>
<!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=gbk">
<link rel="stylesheet" type="text/css" href="../css/styles.css" />
<title>Updated Library Collection</title>
</head>
<body>
<div id="container">
<div id="header"><h1 align="center" style="color:blue">Edit Library Collection</h1></div>
<div id="wrapper">
<div id="content" align="center">
<%
request.setCharacterEncoding("gbk");
String ISBN=request.getParameter("Isbn");
String BookTitle=request.getParameter("Title");
String BookAuthor=request.getParameter("Author");
String Category=request.getParameter("Category");
String Description=request.getParameter("Description");
%>
<table width="100%" border="0" cellspacing="0" cellpadding="4" align="center" >
<tr>
<td width="100%" bgcolor="#EAEAEA" colspan="2">
<form name="bookUpdate" action="/homelibrary/UpdateBookServlet" method="POST">
<p>
<label for="Isbn">ISBN: </label>
<input type="text"readonly name="Isbn" id="Isbn" value=<%=ISBN%> >
<br><br>
<label for="Title">Title: </label>
<input type="text" name="Title" id="Title" value=<%=BookTitle%>>
<br><br>
<label for="Author">Author: </label>
<input type="text" name="Author" id="Author" value=<%=BookAuthor%>>
<br><br>
<label for="Category">Category: </label>
<input type="text" name="Category" id="Category" value=<%=Category%>>
<br><br>
<label for="Description">Description: </label>
<input type="text" name="Description" id="Description" value=<%=Description%>>
<br><br>
<p>
<input type="submit" name="Submit" value="Submit" onclick="goto">
<input type="button" name="Cancel" value="Cancel" onclick="javascript:history.go(-1);">
</p>
</form>
</td>
</tr>
</table>
</div>
</div>
<div id="footer" align="center">
<p>© Home Library</p>
</div>
</body>
</html>
UpdateBookServlet.java
package book;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
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;
#WebServlet("/UpdateBookServlet")
public class UpdateBookServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public UpdateBookServlet(){
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//String forward="";
String action = request.getParameter("action");
if (action == ("edit")){
String Isbn = request.getParameter("Isbn");
Book book = null;
try {
book = this.getBookByIsbn(Isbn);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.setAttribute("book", book);
}
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/Book/UpdateBook.jsp");
dispatcher.forward(request,response);
}
//#SuppressWarnings("unused")
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Book book = new Book();
response.setContentType("text/html");
request.setCharacterEncoding("gbk");
//Get data from form data
String ISBN = request.getParameter("Isbn");
String BookTitle = request.getParameter("Title");
String BookAuthor = request.getParameter("Author");
String Category = request.getParameter("Category");
String Description = request.getParameter("Description");
//#SuppressWarnings("unused")
//PreparedStatement preStmt = null;
//Connection cn =null;
try {
//Create a java MySQL database connection
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/ebookstore";
Connection cn = DriverManager.getConnection(url, "admin", "admin");
PreparedStatement prepStmt= null;
if(ISBN != null)
// create the java MySQL update PreparedStatement
prepStmt = cn.prepareStatement("UPDATE book SET Title=?,Author=?,Category=?,Description=? "+" where Isbn=?");
//String update = "UPDATE book SET Title=?,Author=?,Category=?,Description=? "+" where Isbn=1111";
//prepStmt = cn.prepareStatement(update);
prepStmt.setString(1, book.getTitle());
prepStmt.setString(2, book.getAuthor());
prepStmt.setString(3, book.getCategory());
prepStmt.setString(4, book.getDescription());
prepStmt.setInt(5, Integer.parseInt(book.getISBN()));
//execute the java preparedStatment
prepStmt.executeUpdate();
cn.close();
prepStmt.close();
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
//forwarding from Servlet to a JSP
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/Book/QueryBook.jsp");
dispatcher.forward(request,response);
}
public Book getBookByIsbn(String isbn) throws ClassNotFoundException {
Book book = new Book();
try {
//Create a java MySQL database connection
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/homelib";
Connection cn = DriverManager.getConnection(url, "root", "admin");
PreparedStatement preparedStatement = cn.
prepareStatement("SELECT * FROM book where Isbn=?");
preparedStatement.setString(1, isbn);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) {
book.setISBN(rs.getString("Isbn"));
book.setTitle(rs.getString("Title"));
book.setAuthor(rs.getString("Author"));
book.setCategory(rs.getString("Category"));
book.setDescription(rs.getString("Description"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return book;
}
}
Button in QueryBook.jsp
<td>Update</td>
This example is for updating a book's information when a user is logged in on the session
Insert this at the top of your JSP to identify the user on the session
if (session!=null && request.getSession().getAttribute("loggedin") != null) {
if (request.getSession().getAttribute("role").equals("Student")) {
response.sendRedirect("index.jsp");
return;
}
} else {
response.sendRedirect("index.jsp");
return;
} %>
<% if (request.getSession().getAttribute("loggedin") == null) {
response.sendRedirect("index.jsp");
return;
}
BookDTO dto = (BookDTO) request.getSession().getAttribute("book");
Then insert this code below in the JSP to post new data to the servlet
<form method="POST" action="EditBookServlet">
<div class="form-submit">
My Information
<div class="submit">
<div class="form-row">
<div class="x">
<label>Name</label>
<input type="text" class="form" value="<%= dto.getName()%>" name="name">
</div>
<div class="x">
<label>Author</label>
<input type="author" class="form" value="<%= dto.getAuthor()%>" name="author">
</div>
<div class="form x">
<button class="btn" type="submit">Save Changes</button>
</div>
</div>
</div>
</form>
In the EditBookServlet, insert this code
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
BookDB db = new BookDB();
BookDTO dto = db.getBookByID(((BookDTO)
request.getSession().getAttribute("book")).getId());
dto.setName(request.getParameter("name"));
dto.setAuthor(request.getParameter("author"));
db.updateBook(dto);
request.getSession().setAttribute("book", dto);
In the StudentDB java file insert this to find the book by Id and then to update the book sql file
public BookDTO getBookByID(int id) {
BookDTO obj = null;
String query = "Select * from book where id=?";
PreparedStatement pst = null;
ResultSet rs = null;
try {
pst = conn.prepareStatement(query);
pst.setInt(1,id);
rs = pst.executeQuery();
if (rs != null) {
if (rs.next()) {
obj = new BookDTO();
obj.setId(rs.getInt(1));
obj.setName(rs.getString(2));
obj.setAuthor(rs.getAuthor(3));
} catch (SQLException ex) {
Logger.getLogger(BookDB.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
Logger.getLogger(BookDB.class.getName()).log(Level.SEVERE, null, ex);
}
}
public boolean updateBook(BookDTO obj) {
int affectedRows = 0;
String query = "update `book` set name=? , author=lower(?) where id=?";
PreparedStatement pst = null;
try {
pst = conn.prepareStatement(query);
pst.setString(1,obj.getName());
pst.setString(2,obj.getAuthor());
pst.setInt(10, obj.getId());
System.out.println(pst);
affectedRows = pst.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(Book.class.getName()).log(Level.SEVERE, null, ex);
}
return affectedRows > 0;
}
You said in your comment:
The update page return with null for all the values.
That is, because you intantiate the Book object In UpdateBookServlet.java
Book book = new Book();
but you set the request parameters into separate string objects:
String ISBN = request.getParameter("Isbn");
String BookTitle = request.getParameter("Title");
String BookAuthor = request.getParameter("Author");
String Category = request.getParameter("Category");
String Description = request.getParameter("Description");
But never use them. Instead you add data from the empty Book object:
prepStmt.setString(1, book.getTitle());
prepStmt.setString(2, book.getAuthor());
prepStmt.setString(3, book.getCategory());
prepStmt.setString(4, book.getDescription());
prepStmt.setInt(5, Integer.parseInt(book.getISBN()));
Related
I am currently working on my login and registration page using sublime text. When I try to register users for my registration page or try to login, the error message will pop up shown below.
This is the format for my code shown below:
login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="loginRegister" method="post">
<table
style="background-image: url('https://static.abbottnutrition.com/cms-prod/abbottfamily.com.sg/img/Article%201%20banner_tcm150-71042.jpg'); width: 500px; height: 200px; margin-left: 20px; margin-left: 20px;">
<tr>
<td><h3 style="color: red;">${message}</h3>
<h3 style="color: green;">${SuccessMessage}</h3></td>
</tr>
<tr>
<td><h3 style="color: Red;">Recipe Login Page</h3></td>
<td></td>
</tr>
<tr>
<td>Email :</td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td>Password :</td>
<td><input type="password" name="pwd"></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="login"></td>
<td>Registration</td>
</tr>
</table>
</form>
</body>
</html>
register.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="loginRegister" method="post">
<table
style="background-image: url('https://static.abbottnutrition.com/cms-prod/abbottfamily.com.sg/img/Article%201%20banner_tcm150-71042.jpg'); width: 500px; height: 200px; margin-left: 20px; margin-left: 20px;">
<tr>
<td><h3 style="color: Black;">Recipe Registration Page</h3></td>
<td></td>
</tr>
<tr>
<td><h3 style="color: red;">${message}</h3>
<h3 style="color: green;">${SuccessMessage}</h3></td>
</tr>
<tr>
<td>Email :</td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td>Password :</td>
<td><input type="password" name="pwd"></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="register"></td>
<td>Login</td>
</tr>
</table>
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>MyRecipeProject</display-name>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
</web-app>
CustomerDAO.java
public interface CustomerDAO {
public int insertCustomer(Customer c);
public Customer getCustomer(String email,String pwd);
}
Customer.java
public class Customer {
private String email;
private String pwd;
public String getemail() {
return email;
}
public void setemail(String email) {
this.email = email;
}
public String getpwd() {
return pwd;
}
public void setpwd(String pwd) {
this.pwd = pwd;
}
}
LoginRegister.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LoginRegister
*/
#WebServlet("/loginRegister")
public class LoginRegister extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginRegister() {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
CustomerDAOImpl cd = new CustomerDAOImpl();
String email = request.getParameter("email");
String pwd = request.getParameter("pwd");
String submitType = request.getParameter("submit");
Customer c = cd.getCustomer(email, pwd);
//if (submitType.equals("login") && c!=null && c.getName()!=null)
if (submitType.equals("login") && c!=null && c.getName()!=null) {
request.setAttribute("message", c.getemail());
request.getRequestDispatcher("welcome.jsp").forward(request, response);
} else if (submitType.equals("register")) {
c.setemail(request.getParameter("email"));
c.setpwd(pwd);
cd.insertCustomer(c);
int t = 0;
/*if(cd.insertCustomer(c) > t) {
request.setAttribute("Successmessage", "Registration Done, please login to continue!!!!");
}
else {
request.setAttribute("not successful", "try again");
}
*/
request.setAttribute("SuccessMessage", "Registration Done, please login to continue!!!!");
request.getRequestDispatcher("register.jsp").forward(request, response);
} else {
request.setAttribute("message", "Data Not Found, click on Register !!!");
request.getRequestDispatcher("login.jsp").forward(request, response);
System.out.println(c.getemail());
}
}
}
CustomerDAOImpl.java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class CustomerDAOImpl implements CustomerDAO {
static Connection con;
static PreparedStatement ps;
public int insertCustomer(Customer c) { //put from frontend data to database
int status = 0;
try {
con = MyConnectionProvider.getConnection();
ps = con.prepareStatement("insert into accountInfo values(?,?)"); // putting data in sql
ps.setString(1, c.getemail()); // before putting into sql, must put user data from frontend to customer object in servlet
ps.setString(2, c.getpwd()); //and then call from here using customer object call and push to database
status = ps.executeUpdate(); //if want to put data, always update
con.close();
} catch (Exception e) {
System.out.println(e);
}
return status;
}
public Customer getCustomer(String email, String pwd) { //call data from database
Customer c = new Customer();
try {
con = MyConnectionProvider.getConnection();
ps = con.prepareStatement("select * from accountInfo where email=? and pwd=?"); //prepare statement to just call all data containing username and password
ps.setString(1, email); //input
ps.setString(2, pwd);
ResultSet rs = ps.executeQuery(); //call from database
while (rs.next()) {
c.setemail(rs.getString(1));
c.setpwd(rs.getString(2)); //get data from database then put into the customer object
}
} catch (Exception e) {
System.out.println(e);
}
return c;
}
}
welcome.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body style="color: yellow;">
<h1>Hi ${message} !!! We welcome you !!!</h1>
</body>
</html>
MyProvider.java
public interface MyProvider {
String username="root"; //password of database
String pwd="xxxx";
String connUrl = "jdbc:mysql://localhost:3306/userinfo?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC"; //postgresql==.mysql
}
MyConnectionProvider.java
import java.sql.*;
public class MyConnectionProvider implements MyProvider {
private static final String DRIVER_NAME = "com.mysql.cj.jdbc.Driver";
// private static final String URL = "jdbc:mysql://localhost:3306/appdb";
// local machine
private static final String URL = "jdbc:mysql://localhost:3306/userinfo?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
static {
try {
Class.forName(DRIVER_NAME).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
// Establish connection
/**
* Establish connection
*
* #return Connection object
* #throws SQLException throws SQLException
*/
public static Connection getConnection() throws SQLException {
// return DriverManager.getConnection(URL, "root", "yJfcXQETOLH1");
// local machine
System.out.println(DriverManager.getDriver("jdbc:mysql://localhost:3306/userinfo?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC").toString());
return DriverManager.getConnection(URL, "root", "xxxx");
}
// Close connection
/**
* Close connection
*
* #param conn Connection object
* #param stmt Statement object
* #param rs ResultSet object
*/
public static void close(Connection conn, Statement stmt, ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
So basically, I create a folder called myWebProject, and I saved all my codings and pages under a sub-folder called DIPProject as shown below and I run using Tomcat[![][6]
I would appreciate if someone can help me on that. Thanks so much!
I am trying to create a register page for users to register new accounts.
I am using signup.jsp page with the register form
Which is then connected to RegisterServlet.java (gets form parameters and inserts parameters into database after connecting to DBConnection.java)
DBConnection contains the try{} of connecting to the mysql database.
I have tried multiple ways of registering a user, but the users information never inserts into database.
signup.jsp:
<form action="RegisterServlet" method="post" onsubmit="return validate()">
<div class="row">
<div class="col-lg-6 col-md-6">
<input type="text" placeholder="First Name" name="fname" class="form-control" />
</div>
<div class="col-lg-6 col-md-6">
<input type="text" placeholder="Last Name" name="lname" class="form-control" />
</div>
</div>
<div>
<input type="text" placeholder="User Name" name="username" class="form-control" />
</div>
<div class="row">
<div class="col-lg-6 col-md-6">
<input type="password" placeholder="Password" name="password" class="form-control" id="pass" name="pass" />
</div>
<div class="col-lg-6 col-md-6">
<input type="password" placeholder="Retype Password" name="confirm_password" class="form-control" id="pass2" name="pass2" />
</div>
<div class="col-lg-6 col-md-6">
<%=(request.getAttribute("errMessage") == null) ? ""
: request.getAttribute("errMessage")%>
</div>
</div>
<div class="pull-left"><button type="submit" class="btn btn-primary">Sign Up</button></div>
</form>
RegisterServlet.java:
#WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public RegisterServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.sendRedirect("login.jsp");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try
{
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
String username = request.getParameter("username");
String password = request.getParameter("password");
DBConnection db = new DBConnection();
Connection con = db.getCon();
Statement stmt = con.createStatement();
stmt.executeUpdate("insert into user (fname, lname, username, password)values('"+fname+"','"+lname+"','"+username+"','"+password+"')");
System.out.println("data inserted sucessfully");
response.sendRedirect("login.jsp");
} catch (SQLException e)
{
e.printStackTrace();
}
}
}
DBConnection.java
public class DBConnection {
public Connection con;
public Connection getCon(){
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/cultureexchange", "root", "");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
}
Sql user table:
fname lname username password
varchar varchar varchar varchar
My login.jsp works so the connection to database must work,
appreciate the help in advance.
try Changing these line
Statement stmt = con.createStatement();
stmt.executeUpdate("insert into user (fname, lname, username, password)values('"+fname+"','"+lname+"','"+username+"','"+password+"')");
to
PreparedStatement stmt = con.prepareStatement("insert into user (fname, lname, username, password)values(?,?,?,?)");
ps.setString(1, fname);
ps.setString(2, lname);
ps.setString(3, username);
ps.setString(4, password);
ps.executeUpdate();
And make sure that you have mysql-j-connector in your lib folder under WEB-INF.
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 am trying to save data from my registration page to my database but it is not working some how. Does anyone have advise on how I can fix it?
This is my jsp page form.
I am using an embedded derby database.
Any advise would be greatly appreciated.
<form class="form-signin" method="POST" action="newuserservlet">
<input type="text" class="input-block-level" name="firstName" placeholder="First Name">
<input type="text" class="input-block-level" name="lastName" placeholder="Last Name">
<button class="btn btn-large btn-primary" >Sign up</button>
This my servlet:
public class newuserservlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String firstname = request.getParameter("firstName");
String lastname = request.getParameter("lastName");
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
Connection dbConnection = null;
String strUrl = "jdbc:derby:billsdb;create=true";
dbConnection = DriverManager.getConnection(strUrl);
PreparedStatement stmt = dbConnection.prepareStatement("insert into USERDATA values(?,?)");
stmt.setString(1, firstname);
stmt.setString(2, lastname);
int i = stmt.executeUpdate();
if (i > 0) {
out.println("You are successfully registered.....");
}
} catch (Exception ey) {
System.out.println(ey);
}
out.close();
}
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?