Could anyone fix my delete function in jsp and servlet Please - java

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");

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>

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"});

How can I insert and delete value in a database in derby in JSP? [3]

The history:
History I.
History II.
So the problem is still here. If I select somebody and press the delete button, not to delete from database else a new empty record created.
The client.java:
public class client implements DatabaseConnection{
private static Connection conn = null;
private static void createConnection(){
try {
conn = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (SQLException ex) {
Logger.getLogger(client.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static void closeConnection(){
if (conn != null){
try {
conn.close();
} catch (SQLException ex) {
Logger.getLogger(client.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public List clientList(){
createConnection();
List list=new ArrayList();
try {
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery("SELECT * FROM customer");
while(rs.next()){
**list.add(rs.getString("ID"));**
list.add(rs.getString("CNAME"));
list.add(rs.getString("ADDRESS"));
list.add(rs.getString("PHONENUMBER"));
}
stmt.close();
} catch (Exception e) {
e.printStackTrace(System.err);
}
return list;
}
public void newClient(String name, String address, String phoneNumber)
throws SQLException{
PreparedStatement ps = null;
try {
createConnection();
String insert="INSERT INTO CUSTOMER(CNAME,ADDRESS, PHONENUMBER)
VALUES(?,?,?)";
ps=conn.prepareStatement(insert);
ps.setString(1, name);
ps.setString(2, address);
ps.setString(3, phoneNumber);
ps.executeUpdate();
ps.close();
} catch (Exception e) {
e.printStackTrace(System.err);
}
finally {
ps.close();
closeConnection();
}
}
public void deleteClient(String ID){
try {
createConnection();
String delete="DELETE FROM CUSTOMER WHERE ID=?";
PreparedStatement ps=conn.prepareStatement(delete);
ps.setString(1, ID);
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace(System.err);
}
**finally {
closeConnection();
}**
}
}
The index.jsp:
<jsp:useBean id="client" class="database.client" scope="page" />
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body bgcolor="lightgrey">
<%
String ID=request.getParameter("ID");
String NAME=request.getParameter("CNAME");
String ADDRESS=request.getParameter("ADDRESS");
String PHONENUMBER=request.getParameter("PHONENUMBER");
%>
<form method="post" action="">
<table border="0" align="left">
<th colspan="2" align="center" style="color: brown">Field</th>
<tr>
<td>Name:</td>
<td><input type="text" name="CNAME" style="background-
color:beige"/></td>
</tr>
<tr>
<td>Address?</td>
<td><input type="text" name="ADDRESS" style="background-
color:beige"/></td>
</tr>
<tr>
<td>PhoneNumber:</td>
<td><input type="text" name="PHONENUMBER" style="background-
color:beige"/></td>
</tr>
<input type="submit" name="OK" onclick="
<%
if(NAME!=null && ADDRESS!=null && PHONENUMBER!=null){
client.newClient(NAME, ADDRESS, PHONENUMBER);
}
%>" value="OK"/>
<input type="submit" name="Cancel" onclick="
<%
//nothing
%>" value="Cancel"/>
<input type="submit" name="Delete" onclick="
<%client.deleteClient(ID);%>" value="Delete"/>
</table>
<table border="2">
<th colspan="4" align="center" bgcolor="orange">Clients</th>
<tr bgcolor="silver" align="center">
<td> </td>
**<td>ID</td>**
<td>Name</td>
<td>Address</td>
<td>PhoneNumber</td>
</tr>
<%
List list=client.clientList();
Iterator it=list.iterator();
while(it.hasNext()){
out.print("<tr bgcolor='lightgreen'>");
out.print("<td>");
**ID**=(String)it.next();
out.print("<input type='radio' name='ID' value="+**ID**+"/>");
out.print("</td>");
out.print("<td>");
out.print(**ID**);
out.print("</td>");
for (int i = 0; i < **3**; i++) {
out.print("<td>");
out.print(it.next());
out.print("</td>");
}
out.print("</tr>");
}
%>
</table>
</form>
</body>
</html>
Just create a new Servlet (Delete Servlet) and pass the ID in url and handle it in new jsp page ...You can change your code likethis :
Index JSP:
Delete
Delete Servlet : Updated
#WebServlet(name = "DeleteServlet", urlPatterns = {"/DeleteServlet"})
public class DeleteServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger.getLogger(CurdOperationsImpl.class.getName());
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String ID = request.getParameter("id");
int id = Integer.parseInt(PersonId);
deleteClient(id); // add your own code
out.println("<h2 style='color: green'>Person Deleted Sucessfully.</h2>");
response.sendRedirect("index.jsp");
}else {
}
}
Bonus : get this my ugly Servlet-JSP-Mysql project is ready to use Github link
I hope this help you.

HTTP Status 405 - HTTP method GET is not supported by this URL even with no doget() method

I'm trying to link the register information to database mysql. Everything work fine when i exported the data to the text file but when trying to connect with database, it always get this error. Here is my code I have try so far:
Register.jsp:
enter code here
<form action="./Data">
<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>Date of Birth</td>
<td><select name="Type">
<%for(int i=1;i<=31;i++) {%>
<option><%=i%></option>
<%}%>
</select></td>
<td>
<select name="Type">
<option>January</option>
<option>February</option>
<option>March</option>
<option>April</option>
<option>May</option>
<option>June</option>
<option>July</option>
<option>August</option>
<option>September</option>
<option>October</option>
<option>November</option>
<option>December</option>
</select>
</td>
<td>
<select name="Type">
<% for (int j=1970;j<=2010;j++) {%>
<option><%=j%></option>
<%}%>
</select>
</td>
<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="s4"></td>
<td><input type="reset" value="Reset" name="s5"></td>
</tr>
</table>
</form>
enter code here
Data.java:
enter code here
#WebServlet(urlPatterns = {"/Data"})
public class Data extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String user = request.getParameter("uname");
String pass = request.getParameter("pass");
String email = request.getParameter("mail");
String gender = request.getParameter("Gender");
String end = ("----------------------");
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
String connectionURL = "jdbc:mysql://localhost:8084/userinfo";
Connection con = DriverManager.getConnection(connectionURL,"root","");
Statement st = con.createStatement();
ResultSet rs;
int i = st.executeUpdate("insert into userinfo (Username, email, password) values('" + user + "','" + pass + "','" + email + "')");
if (i > 0) {
response.sendRedirect("welcome.jsp");
out.print("Registration Successfull!"+"<a href='index.jsp'>Go to Login</a>");
} else {
response.sendRedirect("index.jsp");
}
response.sendRedirect("welcome.jsp");
}
}
Your Data class extends HttpServlet which implements the doGet() method.
When the Servlet container receives any request, it will call your Servlet's service() method. In this case, that is the inherited HttpServlet#service() method which calls the HttpServlet#doGet() method. Since you haven't implemented that method, your class inherits it. In the HttpServlet class, it is implemented like so
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String protocol = req.getProtocol();
String msg = lStrings.getString("http.method_get_not_supported");
if (protocol.endsWith("1.1")) {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
} else {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
}
}
Therefore, when you send a GET request, this method will be invoked and you will get the 405 response code.
Implement your own doGet() which delegates to processRequest.
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
processRequest(req, resp);
}

Getting list of strings from servlet to jsp

I have a JSP page in which I have two tags. In first I am trying get input such as Car Maker name such as Tata, Hyundai, Toyota, Audi etc. When user selects any option in first , it should display car models from that maker such as Innova,Land Cruiser etc. So when user selects any option in first tag, I am calling a servlet which gets all the models from database in a list and setting the list as attribute of session and forwarding the request back to JSP. But in jsp when I try to fetch the list it is giving NULL POINTER EXCEPTION. How to solve it?
The code is as below:
DbReviewCar.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection conn= null;
PreparedStatement pstmt= null;
ResultSet rs;
String sql= null;
String maker= request.getParameter("make");
List modellist= new ArrayList();
/*if(maker==null)
{
modellist.add("ferrari");
modellist.add("hummer");
request.getSession().setAttribute("value", modellist);
request.getRequestDispatcher("CarReview.jsp").forward(request,response);
}
else
{*/
try {
Class.forName("com.mysql.jdbc.Driver");
conn= DriverManager.getConnection("jdbc:mysql://localhost/cardetails", "root", "Welcome123");
sql= "select model from cars where make=?;";
pstmt= conn.prepareStatement(sql);
pstmt.setString(1, maker);
rs= pstmt.executeQuery();
while(rs.next())
{
String mod= rs.getString(1);
modellist.add(mod);
System.out.println(mod+">>>>>>>>>>>>>>>>>>.");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
request.getSession().setAttribute("value", modellist);
request.getRequestDispatcher("CarReview.jsp").forward(request,response);
}
CarReview.jsp
Here is my JSP file
<form action="DbReviewCar" method="get" name="myform">
<table>
<tr>
<td>
<tr>
<td>Make:</td>
<td><select name="make" onchange="this.form.submit()"><option>select</option>
<option>Maruti</option>
<option>Ford</option>
<option>Honda</option>
<option>Skoda</option>
<option>Tata</option>
<option>Audi</option>
<option>Toyota</option></select><br></br></td>
</tr>
<%
List list = new ArrayList();
list.addAll((List) (request.getSession().getAttribute("value")));
%>
<tr>
<td>Model:</td>
<td><select name="model">
<%
for (int i = 0; i < list.size(); i++) {
%>
<option value=<%=list.get(i)%>><%=list.get(i)%></option>
<%
}
%>
</select><br></br></td>
</tr>
<tr>
<td>Rating For Style:</td>
<td><input type="text" name="style"><br></br></td>
</tr>
<tr>
<td>Rating for comfort:</td>
<td><input type="text" name="comfort"><br></br></td>
</tr>
<tr>
<td>Rating for Performance:</td>
<td><input type="text" name="performance"><br></br></td>
</tr>
<tr>
<td>Rating for FuelEconomy:</td>
<td><input type="text" name="economy"><br></br></td>
</tr>
<tr>
<td>Review:</td>
<td><textarea cols="18" rows="3"></textarea><br></br></td>
</tr>
<tr>
<td><Button>Save</Button></td>
<td><input type="reset" name="cancel" value="Cancel" /></td>
</tr>
</table>
</form>
When jsp loading for the first time the "value" atribute is not set.
Try to check null for value:
request.getSession().getAttribute("value")

Categories

Resources