1

I am learning Java CRUD Operation . I am trying to insert ,update and delete records from sql database.The insert and displaying all records methods is working but the problem is when I click edit and delete links ,its throw http 404 not found exception

Here is my HTML code display all the records .

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>All Posts</title>
    </head>
    <body>
        <div style="width: 1200px; margin-left: auto; margin-right: auto;">
            <table cellpadding="10">
                <tr>
                    <th>Id</th>
                    <th>Title</th>
                    <th>Description</th>
                    <th>Detail</th>
                    <th>Category</th>
                    <th>Date</th>
                    <th>Image</th>
                    <th></th>
                </tr>
                <c:forEach items="${AllPost}" var="p">
                    <tr>
                        <td>${p.id}</td>
                        <td>${p.title}...</td>
                        <td>${p.description}...</td>
                        <td>${p.detail}...</td>
                        <td>${p.category}</td>
                        <td>${p.date}...</td>
                        <td>${p.image}...</td>
                        <td>
                            <a href="EditPost?id=${p.id}">Edit</a>
                            <a href="DeletePost?id=${p.id}">Delete</a>
                        </td>
                    </tr>
                </c:forEach>
            </table>
        </div>
    </body>
</html>

Here is the HTML for EidtPost.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Edit</title>
    </head>
    <body>
        <h1>Edit News</h1>
        <div style="width: 900px; margin-left: auto; margin-right: auto">
            <c:forEach items="${getNewsById}" var="p">
                <form action="JSP/ManagerEditPost.jsp" method="post">
                    <input type="hidden" name="id" value="${p.id}">
                    Title:<br>
                    <input type="text" value="${p.title}" name="title" style="width: 200px"><br>
                    Description:<br>
                    <input type="text" value="${p.description}" name="description" style="width: 200px"><br>
                    Detail:<br>
                    <textarea name="detail" style="width: 400px; height: 200px">${p.detail}</textarea><br>
                    Category: 
                    <select name="category">
                        <option value="${p.category}">${p.category}</option>
                        <option value="World">World</option>
                        <option value="Tech">Tech</option>
                        <option value="Sport">Sport</option>
                    </select><br>
                    Image:<br>
                    <input type="text" value="${p.image}" name="image" style="width: 200px"><br>
                    <input type="submit" value="Submit">
                </form>
            </c:forEach>

        </div>
    </body>
</html>

Here is the Data Access code for CRUD operation.

    public void edit(int id, String title, String description, String detail, String category, String image){
        try {
            String sql = "update News SET title = ?, description = ?, detail = ?, category = ?, image = ?" + " where id = ?";
            PreparedStatement ps= DBUtils.getPreparedStatement(sql);
            ps.setString(1, title);
            ps.setString(2, description);
            ps.setString(3, detail);
            ps.setString(4, category);
            ps.setString(5, image);
            ps.setInt(6, id);
            ps.executeUpdate();
        } catch (ClassNotFoundException | SQLException ex) {
            Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE, null, ex);
        }

    }


}

Here is the servlet code .

@WebServlet(name = "EditPost", urlPatterns = {"/EditPost"})
public class EditPost extends HttpServlet {


    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
             {
        String idTemp = request.getParameter("id");
        int id = Integer.parseInt(idTemp);
        request.setAttribute("getNewsById", DataAccess.getNewById(id));
        RequestDispatcher rd = request.getRequestDispatcher("CRUD/EditPost.jsp");
        try {
            rd.forward(request, response);
        } catch (ServletException | IOException ex) {
            Logger.getLogger(EditPost.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

Here is the code web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet>
        <servlet-name>EditPost</servlet-name>
        <servlet-class>servlet.EditPost</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>DeletePost</servlet-name>
        <servlet-class>servlet.DeletePost</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>AllPost</servlet-name>
        <servlet-class>servlet.AllPost</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>EditPost</servlet-name>
        <url-pattern>/EditPost</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>DeletePost</servlet-name>
        <url-pattern>/DeletePost</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>AllPost</servlet-name>
        <url-pattern>/AllPost</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>faces/index.xhtml</welcome-file>
    </welcome-file-list>
</web-app>

Here is the screen shot of the error when i click the edit and delete link .

enter image description here

Rasel
  • 239
  • 4
  • 15
  • In the .html page, the reference is to `delete` and `edit`, but the URL pattern is `/DeletePost`. I might have missed a mapping somewhere. But a 404 is the page/servlet wasn't found at the specified path. – KevinO May 05 '18 at 01:13
  • There is too much posted here -- you need to reduce the post to only the essentials (e.g., the `DataAccess` is not likely to be involved with a 404 error). Again, there might be a mapping somewhere in all of this. However, at first glance, this code in the .html file `Edit` wants a page/servlet called `edit`, but you have your servlet path declared as `/EditPost`. These are not the same path. – KevinO May 05 '18 at 01:22
  • In other words, remove the absolute reference from the href. See [some discussion here](https://stackoverflow.com/questions/2005079/absolute-vs-relative-urls) (or you can do `href="EditPost"`) – KevinO May 05 '18 at 02:22
  • Thanks you Kavin .Can you please post your answer . I just delete all the servlet and added it again .Now Its working according your suggestion – Rasel May 05 '18 at 02:28
  • I'm very glad it is working for you! I gave a quick answer below that I think covers the bulk of the issues. Have a great day! – KevinO May 05 '18 at 02:34

1 Answers1

1

The following shows the minimum necessary to create the desired functionality. Obviously everything about the true implementation needs to be added.

Ultimately, the path in the .jsp needs to match to the @WebServlet path. Though the specific forwarding depends a bit on absolute vs. relative URLs.

This works in tomcat 9.0, but is likely applicable to other such servers such as glassfish, etc.

web.xml

This provides the basic information.

<web-app>
  <welcome-file-list>
    <welcome-file>welcome.jsp</welcome-file>
  </welcome-file-list>
</web-app>

welcome.jsp

This is just an example .jsp that provides an href.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
  </head>
  <body>

    <h1>Hello World!</h1>
    <!-- note this can also be ./EditPost -->
    <!-- also note that not passing any query here -->
    <a href="EditPost">Edit Post</a>
  </body>
</html>

EditPost.java

This is a quick example of an annotated servlet.

@WebServlet("/EditPost")
public class EditPost extends HttpServlet {
  private static final long serialVersionUID = 1L;

  /**
   * Default constructor. 
   */
  public EditPost() {
  }

  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.getWriter().append("Served at: ").append(request.getContextPath());
  }

  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    doGet(request, response);
  }

}
KevinO
  • 4,303
  • 4
  • 27
  • 36