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"});
Related
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>
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");
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.
Here is my code.
<%--
Document : index
Created on : Jan 16, 2016, 2:49:24 PM
Author : Manoj
--%>
<%#page import="java.sql.*"%>
<% Class.forName("org.apache.derby.jdbc.ClientDriver"); %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Inserting Data</title>
</head>
<body>
<h1>Inserting Data</h1>
<%!
public class Contact {
String URL = "jdbc:derby://localhost:1527/contact";
String USERNAME = "nbuser";
String PASSWORD = "nbuser";
Connection conn = null;
PreparedStatement pst = null;
Statement stm = null;
ResultSet rst = null;
public Contact(){
try{
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
pst = conn.prepareStatement(
"INSERT INTO contactinfo (name, address, mobile)"+" VALUES (?, ?, ?)");
}
catch(SQLException e)
{
e.printStackTrace();
}
}
public int setContact(String name, String address, String mobile)
{
int result =0;
try{
pst.setString(1, name);
pst.setString(2, address);
pst.setString(3, mobile);
result = pst.executeUpdate();
}
catch(SQLException e)
{
e.printStackTrace();
}
return result;
}
}
%>
<%
int result = 0;
if(request.getParameter("submit") != null){
String name = new String();
String address = new String();
String mobile = new String();
if (request.getParameter("name")!= null)
{
name = request.getParameter("name");
}
if (request.getParameter("address")!= null)
{
address = request.getParameter("address");
}
if (request.getParameter("mobile")!= null)
{
mobile = request.getParameter("mobile");
}
Contact contact = new Contact();
result = contact.setContact(name, address, mobile);
}
%>
<form name="myform" action="index.jsp" method="POST">
<table border="0">
<tbody>
<tr>
<td>Name</td>
<td><input type="text" name="name" value="" size="30" /></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="address" value="" size="50" /></td>
</tr>
<tr>
<td>Mobile</td>
<td><input type="text" name="mobile" value="" size="10" /></td>
</tr>
</tbody>
</table>
<input type="reset" value="Clear" name="clear" />
<input type="submit" value="Submit" name="submit" />
</form>
</body>
</html>
Kindly help me. This is the first time I am writing a JSP code.
The database I am using is Apache derby within Neatbeans 8.1. I tried all alternatives but could not find a solution. When I manually insert a row into the database it is inserting the values.
You can try to debug your code and check whether if(request.getParameter("submit") != null) is returning TRUE or FALSE.
As I doubt because you have used a
<input type="submit" value="Submit" name="submit" />
where value is with capital S
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I write an Java Web Application and I want to write data into DB but when I fill information in Text Fields and Click on Submit I do not get any thing to write in DB? what is the Problem.
Here is my Code so far:
<%#page import="java.sql.*"%>
<% Class.forName("com.mysql.jdbc.Driver"); %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body onload="displayResult()">
<%!
public class User {
String URL = "jdbc:mysql://localhost:3306/studetnInfo";
String USERNAME = "root";
String PASSWORD = "root";
Connection myConnection = null;
Statement statement=null;
PreparedStatement insertUsers = null;
ResultSet resultSet = null;
public User(){
try{
myConnection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
insertUsers = myConnection.prepareStatement(
"INSERT INTO user(name, email) VALUES (?, ?, ?)");
} catch(SQLException e){
e.printStackTrace();
}
}
public int setUsers (String userName, String userEmail){
int result=0;
try{
insertUsers.setString(1, userName);
insertUsers.setString(2, userEmail);
result = insertUsers.executeUpdate();
}catch(SQLException e){
e.printStackTrace();
}
return result;
}
}
%>
<%
int result=0;
// If Submit buttin is clicked.
if (request.getParameter("submit") != null){
String firstName = new String();
String emailAddress = new String();
if (request.getParameter("first") != null){
firstName = request.getParameter("first");
}
if (request.getParameter("email") != null){
emailAddress = request.getParameter("email");
}
User user = new User();
result = user.setUsers(firstName, emailAddress);
}
%>
<form name="myform" action="index.jsp" method="POST">
<table border="0">
<tbody>
<tr>
<td>Enter First Name: </td>
<td><input type="text" name="first" value="" size="50" /></td>
</tr>
<tr>
<td>Enter E-mail Address: </td>
<td><input type="text" name="email" value="" size="50" /></td>
</tr>
</tbody>
</table>
<input type="hidden" name="hidden" value="<%= result %>" />
<input type="reset" value="Clear" name="clear" />
<input type="submit" value="Submit" name="submit" />
</form>
<script lang="JavaScript">
<!--
function displayResult()
{
if(doccument.myform.hidden.value == 1){
alert("Data Inserted");
}else{
alret("Data Not Inserted");
}
}
//-->
</script>
</body>
</html>
You are doing it wrong. First of all the query needs only 2 values not 3, one for name and another for email. And secondly, you have to set the 2 values after the query for the two (?, ?). Which you are missing here.
for Ex : write something like this :
insertUsers = myConnection.prepareStatement(
"INSERT INTO user(name, email) VALUES (?, ?)");
insertUsers.setString("name");
insertUsers.setString("email");
in place of "name" and "email" place the values you got from the UI.
For getting values from the UI you can use something like :
request.getParameter("name of the form element");
Because you did not send any values to your INSERT script.