JDBC insert query does not update mysql database - java

The following code does not insert a row into the corresponding table.
I have already tested the db connection and ran the query in the database, both of which have passed however when I add inputs via a .jsp form the values are still not inserting.
public class UserDao {
public String registerUser(User user){
String username = user.getUsername();
String email = user.getEmail();
String password = user.getPassword();
Connection con;
con = DBConnection.createConnection();
PreparedStatement preparedStatement;
try{
con.setAutoCommit(false);
String query = ("INSERT INTO user (username, email, password, user_id) VALUES(?, ?, ?, ?)");
preparedStatement = con.prepareStatement(query);
preparedStatement.setString(1, username);
preparedStatement.setString(2, email);
preparedStatement.setString(3, password);
preparedStatement.setString(4,null);
int i = preparedStatement.executeUpdate();
con.commit();
preparedStatement.close();
con.close();
if(i !=0 ){
return "SUCCESS";
}
}catch(SQLException e){
throw new RuntimeException(e);
}
return "Something is wrong!";
}
}
For reference here is what my servlet class and .jsp file looks also like:
public class UserRegistrationServlet extends HttpServlet {
public UserRegistrationServlet(){}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userName = request.getParameter("username");
String email = request.getParameter("email");
String password = request.getParameter("password");
User user = new User();
user.setUsername(userName);
user.setEmail(email);
user.setPassword(password);
UserDao userDao = new UserDao();
String userRegistered = userDao.registerUser(user);
if(userRegistered.equals("SUCCESS")){
request.getRequestDispatcher("test.jsp").forward(request, response);
}else{
request.setAttribute("error", userRegistered);
request.getRequestDispatcher("/UserRegistration.jsp").forward(request, response);
}
}
}
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Register</title>
<script>
function validate()
{
var username = document.form.username.value;
var email = document.form.email.value;
var password = document.form.password.value;
var conpassword= document.form.conpassword.value;
if (username==null || username=="")
{
alert("Full Name can't be blank");
return false;
}
else if (email==null || email=="")
{
alert("Email can't be blank");
return false;
}
else if(password.length<6)
{
alert("Password must be at least 6 characters long.");
return false;
}
else if (password!=conpassword)
{
alert("Confirm Password should match with the Password");
return false;
}
}
</script>
</head>
<body>
<center><h2>Java Registration application using MVC and MySQL </h2></center>
<form name="form" action="UserRegistrationServlet" method="post" onsubmit="return validate()">
<table align="center">
<tr>
<td>Username</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td>Confirm Password</td>
<td><input type="password" name="conpassword" /></td>
</tr>
<tr>
<td><%=(request.getAttribute("errMessage") == null) ? ""
: request.getAttribute("errMessage")%></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Register"></input><input
type="reset" value="Reset"></input></td>
</tr>
</table>
</form>
</body>
</html>
Not sure where the error in my code, so any advice will be very helpful. Thanks
Updates:
[![After throwing a runtime exception ][2]][2]

You're setting user_id to null and the database complains that the column must not be null. I assume that you haven't passed null to the statement you tested against the DB directly, so that you were setting an empty string instead (or the table is to set a default or automatically generated value in case it's missing).
If there is a default value or a autogenerated one, you can simply leave away user_id in your insert statement and it should work.

Related

How to retrieve data from MySQL database and place in a HTML Form using Soap Web Services using Java ,

I attempted to retrieve user information from the MySQL database, but when I ran my program and searched for the user by name, nothing appeared in the HTML table. I can't figure out what's the issue. Below in my code,
Web Service Code
#WebMethod(operationName = "search")
public List<UserRegister> search(#WebParam(name = "name")String name ) {
Connection connection = DBUtils.getConnection();
List<UserRegister> user = new ArrayList<>();
UserRegister u=null;
try {
String searchQuery = "select * from register where name= ?";
PreparedStatement ps = connection.prepareStatement(searchQuery);
ps.setString(1, name);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
u = new UserRegister();
u.setName(rs.getString("name"));
u.setBranch(rs.getString("branch"));
u.setAge(rs.getString("age"));
u.setPhone(rs.getString("phone"));
user.add(u);
}
}catch(SQLException asd){
System.out.println(asd.getMessage());
}
return user;
}
Java Servlet
#WebServlet("/SearchServlet")
public class SearchServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String Name = request.getParameter("name");
UserRegister userRegister = new UserRegister();
userRegister.setName(Name);
searchClass sclass = new searchClass();
request.setAttribute("name", sclass.search(Name));
RequestDispatcher view = request.getRequestDispatcher("display.jsp");
view.forward(request, response);
}
}
Java Class For Call the Web Service
public class searchClass {
public List<UserRegister> search( String username) {
SerachService_Service service=new SerachService_Service();
SerachService proxy =service.getSerachServicePort();
return (List<UserRegister>) proxy.search(username);
}
}
JSp For Search Bar
<form method="Get" action="SearchServlet">
<table border="0" width="300" align="center" bgcolor="#CDFFFF">
<tr><td colspan=2 align="center">
<h3>Search Employee</h3></td></tr>
<tr><td ><b>User Name</b></td>
<td>: <input type="text" name="name">
<tr><td colspan=2 align="center">
<input type="submit"></td></tr>
</table>
</form>
</body>
JSP Display Data
<table>
<c:forEach var="user" items="${name}">
<tr>
<td>
<c:out value="${user.name}" />
</td>
<td>
<c:out value="${user.branch}" />
</td>
<td>
<c:out value="${user.age}" />
</td>
<td>
<c:out value="${user.phone}" />
</td>
</tr>
</c:forEach>
</body>

Could anyone fix my delete function in jsp and servlet Please

I have already coded the servlet and the dao part of the delete method.
Once i want to use the method in jsp page, it returned ERROR 500 / ERROR 404.
I am using tomcat 7,Java 7 and windows 10. Running oracle. I tried to use ajax to link the servlet delete method but it still didn't work.
// deleteStaffServelt
public class DeleteStaffServlet extends HttpServlet {
enter code here
/**
*
*/
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String ids = request.getParameter("userId");
int deleteId = Integer.parseInt(ids);
StaffDao staffDao = new StaffDao();
staffDao.delete(deleteId);
response.sendRedirect("deleteStaffServlet?id=" + deleteId);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
// delete method in Dao
public void delete(int id) {
try {
String sql = "delete from ZZZ_EMPLOYEES where ZE_ID = " + id;
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, id);
ps.executeUpdate();
ps.close();
} catch (Exception ex) {
ex.printStackTrace();
}
// jsp
<body>
<form action="listServletTwo">
<table border="0" cellspacing="0">
<tr>
<td>社員No. <input name="noStart" type="text" size="8" />
~ <input name="noEnd" type="text" size="8" /> <input
type="submit" value="検索" />
</td>
<td>社員名. <input name="name" type="text" size="20" /> <input
type="submit" value="検索" />
</td>
</tr>
</table>
</br>
<%
List<Staff> list1 = (List<Staff>) session.getAttribute("list");
if (list1 != null) {
%>
<table border="1" cellspacing="0">
<tr bgcolor="pink">
<td>社員No.</td>
<td>ユーザーID</td>
<td>社員名</td>
<td>削除機能</td>
<td>更新機能</td>
</tr>
<%
for (Staff s : list1) {
%>
<tr>
<td id="<%=s.getId()%>"><%=s.getId()%></td>
<td><%=s.getNo()%></td>
<td><%=s.getName()%></td>
<td>Delete</td>
<td>名前:<input name="name" type="text" size="10" /> ユーザーID:<input
name="name" type="text" size="10" />
<input type="submit" value="Edit" name="edit" onclick="editRecord(<%=s.getId()%>);">
</td>
</tr>
<%
}
}
session.removeAttribute("list");
%>
</table>
</form>
result is HTTP Status 500 – Internal Server Error
java.lang.NumberFormatException: null
Here ,Delete,you have used id=<%=s.getId()%> i.e : you are getting value <%=s.getId()%> in parameter id but in your servlet ,you are getting parameter using request.getParameter("userId"); just change this to request.getParameter("id");.
Also, your delete query is wrong it should like below :
// delete method in Dao
public void delete(int id) {
try {
//you have to give placeholder(?) in query not the value
String sql = "delete from ZZZ_EMPLOYEES where ZE_ID =?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, id);
ps.executeUpdate();
ps.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
I am not sure what you are doing here :
response.sendRedirect("deleteStaffServlet?id=" + deleteId);
But, I think you have already deleted required row from table ,so there is no need to do that again. So, just change that to below :
response.sendRedirect("yourjsppage");

Java DB Inserting Data Into Table

I am having trouble trying to insert data into a table in my database in netbeans, below is my code:
public class NewUser extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
HttpSession session = request.getSession(false);
String [] query = new String[5];
query[0] = (String)request.getParameter("username");
query[1] = (String)request.getParameter("password");
query[2] = (String)request.getParameter("confPassword");
query[3] = (String)request.getParameter("name");
query[4] = (String)request.getParameter("address");
Jdbc jdbc = (Jdbc)session.getAttribute("dbbean");
if (jdbc == null)
request.getRequestDispatcher("/WEB-INF/conErr.jsp").forward(request, response);
else {
jdbc.insert(query);
request.setAttribute("message", query[0]+" has been registered successfully!");
}
This is in a class "NewUser.java". The insert method is in a class "jdbc" and is as follows:
public void insert(String[] str){
PreparedStatement ps = null;
try {
ps = connection.prepareStatement("INSERT INTO CUSTOMER VALUES (?,?,?,?)",PreparedStatement.RETURN_GENERATED_KEYS);
ps.setString(1, str[0].trim());
ps.setString(2, str[1]);
ps.setString(3, str[3]);
ps.setString(4, str[4]);
ps.executeUpdate();
ps.close();
System.out.println("1 row added.");
} catch (SQLException ex) {
Logger.getLogger(Jdbc.class.getName()).log(Level.SEVERE, null, ex);
}
}
The "CUSTOMER" table looks as follows:
# | Username | Password | Name | Address | ID
('ID' is the primary key which is auto incremented)
The JSP where the user inputs the information is as follows:
<%#page import="model.Jdbc"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>User</title>
</head>
<body>
<h2>User's details:</h2>
<%! int i = 0;
String str = "Register";
String url = "NewUser.do";
%>
<%
if ((String) request.getAttribute("msg") == "del") {
str = "Delete";
url = "Delete.do";
}
else
{
str = "Register";
url = "NewUser.do";
}
%>
<form method="POST" action="<%=url%>">
<table>
<tr>
<th></th>
<th>Please provide your following details</th>
</tr>
<tr>
<td>Username:</td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password"/></td>
</tr>
<tr>
<td>Confirm Password:</td>
<td><input type="password" name="confPassword"/></td>
</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> <input type="submit" value="<%=str%>"/></td>
</tr>
</table>
</form>
<%
if (i++ > 0 && request.getAttribute("message") != null) {
out.println(request.getAttribute("message"));
i--;
}
%>
</br>
<jsp:include page="foot.jsp"/>
</body>
</html>
The SQL statement used to create the database:
CREATE TABLE Customer (
username varchar(20),
password varchar(20),
name varchar(20),
address varchar(60),
id INT primary key GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1)
);
The code doesn't throw any errors however, when I check the database to see if the data has been added it never gets added and I cannot figure out why (I think it's something to do with the "insert" method?). I have looked around for solutions however, I still get the same outcome and could really use some help.
Cheers,
For Oracle you need to specify column for auto generated columns:
ps = connection.prepareStatement("INSERT INTO CUSTOMER VALUES (?,?,?,?)", new String[]{"ID"})
For ID column
You forgot to replace prepareStatement.return.. to Statement.return..ps = connection.prepareStatement("INSERT INTO CUSTOMER VALUES (?,?,?,?)",Statement.RETURN_GENERATED_KEYS,new String[]{"ID"});

Servlet code dispatching to JSP shows error

I have the following code which validates a Sign up form. I have two methods which validate if "Password" and "Confirm password" are the same and sends an error message if not and also checkEmail() which checks the DB if the email already exists. When I don't include the checkEmail() method the other one works fine (even the error message). But when I include the checkEmail() it gives an error message of NullPointerException. I believe it has to do with the incorporation of the checkEmail() method in my code but I am not sure where to put it. I would be grateful if anyone could help me.
//SERVLET doPost METHOD
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession s = request.getSession();
UserInfo ud = new UserInfo();
ud.createTable();
UserBean u = new UserBean();
ServletContext ctx = s.getServletContext();
u.setEmail(request.getParameter("email"));
u.setName(request.getParameter("name"));
u.setLname(request.getParameter("sname"));
u.setPassword(request.getParameter("password"));
s.setAttribute("User", u);
String e = u.getEmail();
String p1 = u.getPassword();
String p2 = request.getParameter("password2");
if(User.confirmPassword(p1, p2) && !User.checkEmail(e)) {
//Save data to DB
u = (User)s.getAttribute("User");
s.invalidate();
ud.insert(u);
forwardTo(ctx, request, response, "/Somepage.jsp");
} else {
if(User.checkEmail(e)) {
request.setAttribute("name",request.getParameter("name"));
request.setAttribute("sname",request.getParameter("sname"));
request.setAttribute("email",request.getParameter("email"));
request.setAttribute("pass", request.getParameter("password"));
request.setAttribute("pass2", request.getParameter("password2"));
request.setAttribute("errorMessage", "Email already exists!");
request.getRequestDispatcher("/SignUp.jsp").forward(request, response);
}
if(!User.confirmPassword(p1, p2)) {
request.setAttribute("name",request.getParameter("name"));
request.setAttribute("sname",request.getParameter("sname"));
request.setAttribute("email",request.getParameter("email"));
request.setAttribute("pass", request.getParameter("password"));
request.setAttribute("pass2", request.getParameter("password2"));
request.setAttribute("errorMessage", "Passwords do not match!");
request.getRequestDispatcher("/SignUp.jsp").forward(request, response);
}
}
}
//SIGN UP FORM
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>User Registration</title>
</head>
<body>
<form action = "UserServ" method ="POST">
<h5 >Enter the details below to Sign Up</h5><br>
Name: <input type="text" name="name" required placeholder="Firstname" value="${name}"><br>
Surname: <input type="text" name="sname" required placeholder="Surname" value="${sname}"><br>
Email: <input type="text" value="${email}" name="email" placeholder="Email"><br>
Password:
<input type="password" value="${pass}" name="password" placeholder="Password" required><br>
Confirm password:
<input type="password" name="password2" value="${pass2}" placeholder="Confirm password" required><br>
<div style="color: #FF0000;">${errorMessage}</div><br>
<input type="submit" value="Sign Up">
</form>
</body>
</html>
</body>
</html>
//METHODS
public static boolean confirmPassword(String p1, String p2){
boolean status = false;
if(p1.equals(p2)) {
status =true;
}
return status;
}
public static boolean checkEmail(String email) {
boolean check = false;
PreparedStatement pst = null;
ResultSet rs = null;
try(Connection conn= ConnectionConfiguration.getConnection()){
pst = conn.prepareStatement("SELECT * FROM users WHERE email=?;");
pst.setString(1, email);
check = rs.next();
} catch (SQLException e) {
e.printStackTrace();
}
return check;
}
}
The ResultSet is never calculated as the prepared statement is never executed. This results in the NPE while executing rs.next().
Add sth like this after setting the email:
rs = preparedStatement.executeQuery();
This will execute the prepared statement with the given parameters and return the ResultSet you're looking for.
BTW:
Please consider using rs.isBeforeFirst() instead of rs.next() for checking if there is any result. In your case it will work, because you're not reading any row, but if, you'll need to reset the cursor as rs.next() moves the cursor to the next row if present.

register page with MVC model

I am trying to build a website with a register page with MVC model, but when i clicked a register button to submit, it pointed to the controller but with a blank page. Here's my MVC i've tried so far
View:
register.jsp
<form action="controller" method="post">
<table>
<tr>
<td> Username </td>
<td><input type ="text" name="uname" size="30"required></td>
</tr>
<tr>
<td>Your email address </td>
<td><input type ="text" name="mail" size="30"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="pass" size="20"required></td>
</tr>
<tr>
<td>Please re-type your password</td>
<td><input type="password" name="p2" size="20"required></td>
</tr>
<table>
<tr>
<td>Gender</td>
<td><input type ="radio" value="r1" checked name="Gender">Male</td>
<td><input type ="radio" value="r2" checked name="Gender">Female</td>
</tr>
<tr>
<td>
</tr>
<tr>
<td><input type="submit" value="Register" name="submit"></td>
<td><input type="reset" value="Reset" name="s5"></td>
</tr>
</table>
</form>
My Model is
public class signin extends HttpServlet {
public void register(String uname, String pass, String email) throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
String driver = "com.mysql.jdbc.Driver";
Class.forName(driver).newInstance();
String url = "jdbc:mysql://localhost:3306/";
String dbName = "webauth";
String userName = "root";
String passWord = "";
Connection conn = DriverManager.getConnection(url + dbName, userName, passWord);
PreparedStatement statement;
statement = conn.prepareStatement("insert into data(username, email, password)" + " values (?,?,?,?)");
statement.setString(1,uname );
statement.setString(2, pass);
statement.setString(3, email);
statement.executeUpdate();
statement.clearParameters();
statement.close();
conn.close();
}
and my Controller :
try {
String action = request.getParameter("submit");
if (action.equals("Register")){
String Uname = request.getParameter("uname");
String Pword = request.getParameter("pass");
String Email = request.getParameter("mail");
boolean check = false;
try {
signin signin = new signin();
check = signin.takeuser(Uname);
if (check)
request.setAttribute("error","This user has already been registered");
}
catch(Exception e){
System.out.println("Exception");
}
if (check){
RequestDispatcher dispatch = request.getRequestDispatcher("signin.jsp");
dispatch.forward(request, response);
}
else{
try{
signin signin = new signin();
signin.checkLogin(Uname, Email, Pword);
response.sendRedirect("registersuccess.jsp");
}
catch(Exception e)
{
System.out.println("Exception");
}
}
}
} finally {
out.close();
}
}
e,I think your "Controller" should extends HttpServlet..not the "Signin", Or you can modify the form's action ,it's Signin. The last,configurate your web.xml.
if (check){
RequestDispatcher dispatch = request.getRequestDispatcher("signin.jsp");
dispatch.forward(request, response);
}
else{
try{
signin signin = new signin();
signin.checkLogin(Uname, Email, Pword);
response.sendRedirect("registersuccess.jsp");
}
catch(Exception e)
{
System.out.println("Exception");
}
}
in this code if you consider else part if try block executed successfully then you will be redirected to registersuccess.jsp but if some exception occurs then you are just printing exception but not redirecting anywhere.
This could be a reason like you are getting exception in the mentioned try block so you are not getting redirected anywhere. just check your console is printing "Exception"?
Or better you debug your code so that you can figure out in which block it goes.

Categories

Resources