HTTP Status 404 - Not Found in Servlet crud - java

i am creating a simple crud system in Java Servlet. I am beginner of Servlet.I filled the form and clicked submit button and got the error - HTTP Status 404 - Not Found. I have attached the screen shot image below along with the code.
folder structure
Form
<form method = post action = "employee/employee.java">
<table class="table table-borederd">
<tr>
<td>Enter Employee ID:</td>
<td ><input class="form-control" type = "text" name = "txtEmpId"/></br></td>
</tr>
<tr>
<td>Enter Employee FirstName:</td>
<td ><input class="form-control" type = "text" name = "txtFName"/></td>
</tr>
<tr>
<td>Enter Employee LastName:</td>
<td ><input class="form-control" type = "text" name = "txtLName"/></td>
</tr>
<td><input type = "submit" value = "submit"/></td>
</form>
employee.java
public class employee extends HttpServlet
{
Connection con;
int row;
public void doPost(HttpServletRequest req, HttpServletResponse rsp) throws IOException, ServletException
{
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/empp","root","");
System.out.println("Connection Established");
}
catch(Exception e)
{
System.out.println("Sorry...........");
}
rsp.setContentType("text/html");
PrintWriter out = rsp.getWriter();
String empId = req.getParameter("txtEmpId");
String empFName = req.getParameter("txtFName");
String empLName = req.getParameter("txtLName");
try
{
PreparedStatement stat = con.prepareStatement("insert into record (id,fname,lname) Values(?,?,?)");
stat.setString(1,empId);
stat.setString(2,empFName);
stat.setString(3,empLName);
row = stat.executeUpdate();
}
catch(Exception e)
{
}
out.println("<html>");
out.println("<font color = 'red'>Sucessfully registered!</font>");
out.println("</body>");
out.println("<h2>");
out.println(row);
out.println("</h2>");
out.println("</body>");
}
}

Related

retrieve id and Delete the line using button JSP

I am new to jsp.
In my example I retrieve data from a table and I am looking to have a button that can delete the row using the id , it does not work, but when I inspect the button I see that it retrieves the id correctly but the deletion does not run .
I work for the moment with the servlet class, and I pass the delete method in dopost
Code jsp :
<%
try {
ArrayList<Dossier> dossiers = (ArrayList<Dossier>) request.getAttribute("list_dossiers");
for (Dossier c : dossiers) {%>
<tr>
<td> <%=c.getId()%> </td>
<td> <%=c.getTitre()%> </td>
<td> <%=c.getDate_creation()%></td>
<td> <form action="Controller" method="post">
<input type="hidden" name="type" value="supprimerDossier"/>
<input type="hidden" name="id" value="<%=c.getId()%>"/>
<button type="submit" class="btn btn-primary">Supprimer</button>
</form>
</td>
<td> <button type="button" class="btn btn-primary">Modifier</button> </td>
</tr>
<% }
} catch (Exception e) {
e.printStackTrace();
}%>
Method delete :
private void deleteDossier(int id) throws Exception {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/avocat", "root", "");
PreparedStatement ps = con.prepareStatement("DELETE FROM dossier WHERE ID=?");
ps.setInt(1, id);
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
Dopost:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String hiddenParam=request.getParameter("type");
try {
if (hiddenParam.equals("addClient")) {
addClients(request, response);
request.setAttribute("success", "Client ajouté avec succès");
getServletContext().getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response);
} else if (hiddenParam.equals("addDossier")) {
addDossiers(request, response);
request.setAttribute("success", "Dossier ajouté avec succès");
getServletContext().getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response);
} else if (hiddenParam.equals("supprimerDossier")){
String id= request.getParameter("id");
deleteDossier(Integer.parseInt(id));
request.setAttribute("success", "Dossier supprimer");
getServletContext().getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}

Java error when using two submit buttons on two different forms in a jsp

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

Delete entire Row from Table in database and display all data in table(i.e., auto update the table in same page)

In table 10 rows are there..selected data has to delete (using check box) and display all the content in table....Here newsid in JSP file is auto incremented value....
This is DeleteSuccess.java File
public class DeleteSuccess extends HttpServlet {
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession();
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/MyDataBase","root","root");
PreparedStatement ps = con.prepareStatement("delete from ROOT.NEWSTABLE where newsid='" + (* here what i have 2 write *) +"'");
int i= ps.executeUpdate();
PreparedStatement pss = con.prepareStatement("select NEWSID,NEWS from ROOT.NEWSTABLE");
ResultSet rs =pss.executeQuery();
ArrayList<News> listnewsobj = new ArrayList<News>();
while(rs.next())
{
News obj=new News();
obj.setNewsId(rs.getInt(1));
obj.setNews(rs.getString(2));
listnewsobj.add(obj);
}
session.setAttribute("listnewskey",listnewsobj);
System.out.println(listnewsobj);
if (i > 0)
{
System.out.println("Venkatesh");
//out.print("You are successfully registered...");
//RequestDispatcher rs = request.getRequestDispatcher("Login.html");
// RequestDispatcher rd = request.getRequestDispatcher("JSP/AddNews.jsp");
// rd.include(request, response);
response.sendRedirect("JSP/AddNews.jsp");
}
} catch (Exception e2) {
System.out.println(e2);
}
out.close();
}
}
This is JSP file
<form method="post" action="../newsdelete">
<fieldset class="rt">
<legend> <b> Manage News </b> </legend>
<table>
<tr>
<th>News Id</th>
<th>News Name</th>
<th>Action</th>
</tr>
<c:forEach items="${listnewskey}" var="listnews">
<tr>
<td class="first_col">${listnews.newsId}</td>
<td>${listnews.news}</td>
<td class="third_col">
<input id="" type="checkbox" name="check" value="action"><label for="radio1"><span><span></span></span></label>
</td>
</tr>
</c:forEach>
</table>
<div> <br><input type="submit" value="Delete" name="delete"></div>
</fieldset>
</form>
This is web.xml
<servlet>
<servlet-name>Delete</servlet-name>
<servlet-class>com.venkatesh.DeleteSuccess</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Delete</servlet-name>
<url-pattern>/newsdelete</url-pattern>
</servlet-mapping>
Can anyone tell me how to delete the row which is checked and automatically display the information from the table in same JSP file which i have written the table in Loop...

text field in file upload servlet, Java

In my java application i am uploading multiple files using java servlet.
All things works fine until i added extra text field in my form.
I am getting null document when i add text field.
Here is my code:-
JSP Form:-
<form action="upload/servlet" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>Upload File: </td>
<td><input type="file" name="file" multiple/>
</td>
<td style="color: red; font-style: italic;"><form:errors
path="file" />
</td>
</tr>
<tr>
<td>Generate Key</td><td> </td>
<td><input type="button" value="Change Key"/>
</td>
<td>${key}</td>
</tr>
<tr>
<td>Zip Code</td><td> </td>
<td><input type="text" value="100001" name="zipcode"/>
</td>
<td> </td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Upload" />
</td>
<td> </td>
</tr>
</table>
</form>
Here is my servlet:-
#Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (!ServletFileUpload.isMultipartContent(req)) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST,"Multipart content expected!");
}
ModelMap model = new ModelMap();
try {
#SuppressWarnings("unchecked")
List<FileItem> files = this.upload.parseRequest(req);
String userName=req.getSession().getAttribute("username").toString();
String fileName;
String contentType;
byte[] content;
System.out.print("Zipcode is "+req.getParameter("zipcode"));
for(FileItem item : files) {
if(item.isFormField()){
fileName = item.getName();
contentType = item.getContentType();
content = item.get();
String id=this.indexDocument(fileName, contentType, content,userName,req);
model.put(id, fileName);
System.out.println("Done for "+fileName+ " id "+id);
}
}
} catch (FileUploadException e) {
System.out.println("Error FileUploadException: "+e.getMessage());
throw new ServletException(e);
}
catch (Exception e) {
e.printStackTrace();
System.out.println("Error "+e.getMessage());
}
req.setAttribute("message", model);
req.getSession().setAttribute("tmpRetMessage", model);
// RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/success.do");
//dispatcher.forward(req, resp);
resp.sendRedirect("../success.do");
}
If i add two text fields then getting null document error two times. If i add three times then getting error three times.
Here form enctype type multipart (enctype="multipart/form-data"). So request.getParameter() value will be null. So you need to process file field and regular fields means other than file like text, radio, etc separately.
see for more how to get request parameters

Update mySql table Based on jsp page

Friends i have a jsp page which retrieves data from mysql table and displays them in form of table. I will also display another column consisting of a button to give Status to 1 . i need to update the database table when i click the status button.
following is the code for jsp
<form action="Edit" method="post">
<table cellspacing="8">
<tr>
<td><b>Name</b>
</td>
<td><b>Place</b>
</td>
<td><b>Gender</b>
</td>
<td><b>UserName</b>
</td>
<td><b>Password</b>
</td>
<td><b>Status</b>
</td>
<td></td>
</tr>
<%
ViewService vs = new ViewService();
ResultSet rs = vs.getRecords();
while(rs.next())
{
%>
<tr>
<td><%=rs.getString(2) %></td>
<td><%=rs.getString(3) %></td>
<td><%=rs.getString(4) %></td>
<td><%=rs.getString(5) %></td>
<td><%=rs.getString(6) %></td>
<td><%=rs.getString(7) %></td>
<td></td>
<td><input type="text" name="userid" value="<%=rs.getString(2) %>"
style="visibility: hidden;" > <input type="submit" value="Active"></td>
</tr>
<% }
%>
</table>
</form>
And my edit servlet is
package Admin;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import DBcon.Dbcon;
#WebServlet("/Edit")
public class Edit extends HttpServlet {
private static final long serialVersionUID = 1L;
public Edit() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Connection con;
PreparedStatement ps;
Dbcon db = new Dbcon();
con = db.getCon();
int status=1;
int userid =Integer.parseInt(request.getParameter("userid"));
try {
ps=con.prepareStatement("update tbluser set status = ? where userid
= ?");
ps.setInt(7,status);
ps.setInt(1, userid);
ps.executeUpdate();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.sendRedirect("ViewUser.jsp");
}
}
inside while loop
put the form tag inside while loop ( < td > ) not around the < table >
....
<td><%=rs.getString(7) %></td>
<td></td>
<td>
<form action="Edit" method="post">
<input type="text" name="userid" value="<%=rs.getString(2) %>" style="visibility: hidden;" > <input type="submit" value="Active">
</form>
</td>
</tr>
<% }
%>
</table>
OR
Use Hyperlink instead of form and button
<td>
Activate
<td>
try this bro i modified your codes.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Connection con;
PreparedStatement ps;
Dbcon db = new Dbcon();
con = db.getCon();
int status=1;
int userid =Integer.parseInt(request.getParameter("userid"));
try {
ps=con.prepareStatement("update tbluser set status = '"+status+"' where userid = '"+userid+"'");
ps.executeUpdate();
int updateQuery = ps.executeUpdate();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.sendRedirect("ViewUser.jsp");
}
}

Categories