-2

i am trying to create CRUD application from tutorials but i am stuck in problem without errors in the AllPost.jsp it displays only the the titles of the elements without data and i checked my mysql database and it did not insert anything here is my code

AllPost.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib  uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>JSP Page</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="edit?id=${p.id}">Edit</a>
                            <a href="delete?id=${p.id}">Delete</a>
                        </td>

                    </tr>

                </c:forEach>
            </table>

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

AllPost.java

package servlet;

import dao.DataAccess;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name="AllPost", urlPatterns={"/AllPost"})
public class AllPost extends HttpServlet {
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException, SQLException {
        request.setAttribute("AllPost", DataAccess.getAll());
        RequestDispatcher rd = request.getRequestDispatcher("AllPost.jsp");
        rd.forward(request, response);

    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        // processRequest(request, response);
        request.setAttribute("AllPost", DataAccess.getAll());
        RequestDispatcher rd = request.getRequestDispatcher("AllPost.jsp");
        rd.forward(request, response);

    }
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         id="WebApp_ID"
         version="3.0">
    <servlet>
        <servlet-name>AllPost</servlet-name>
        <jsp-file>/AllPost.jsp</jsp-file> 
    </servlet>
    <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>AddNew.html</welcome-file>
    </welcome-file-list>
</web-app>

DataAccess.java

package dao;

public class DataAccess {

    public void addNew(News n){    
        try {
            PreparedStatement ps = DButil.getPreparedStatement("insert into   news values(?,?,?,?,?,?)");
            ps.setString(1,n.getTitle());
            ps.setString(2,n.getDate());
            ps.setString(3,n.getDescription());
            ps.setString(4,n.getDetail());   
            ps.setString(5,n.getCategory());
            ps.setString(6,n.getImage());
            ps.executeUpdate();
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE, null, ex);   
        } catch (SQLException ex) {
            Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static List<News> getAll()  {

        List<News> ls = new LinkedList<News>();
        try {
            ResultSet rs = DButil.getPreparedStat  ement("select * from news").executeQuery();

        } catch (ClassNotFoundException ex) {
            Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE,null,ex);
        }catch (SQLException ex){
            Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE,null,ex);
        }

        return ls;
    }
}

and DButil.java

package db;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import java.sql.DriverManager;
import java.sql.SQLException;


public class DButil {
    public static PreparedStatement getPreparedStatement(String sql) throws   ClassCastException, ClassNotFoundException, SQLException{

        PreparedStatement ps=null;
        Class.forName("com.mysql.jdbc.Driver");
        String url="jdbc:mysql://localhost/crud";
        String user="root";
        String password="";
        Connection    con=   (Connection) DriverManager.getConnection (url,   user, password);
        ps=(PreparedStatement) con.prepareStatement(sql);
        return ps;
    }
}

ManagerAddNew.jsp


    <%@page import="dao.DataAccess"%>
    <%@page import="model.News"%>
    <%@page import="java.text.SimpleDateFormat"%>
    <%@page import="java.sql.Date"%>
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
       "http://www.w3.org/TR/html4/loose.dtd">

    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <title>JSP Page</title>
        </head>
        <body>
            <%
                String title=request.getParameter("title");
                Date dateTmp = new Date(System.currentTimeMillis());
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
                String date = dateFormat.format(dateTmp.getTime());
                String description=request.getParameter("description");
                String detail=request.getParameter("detail");
                String category=request.getParameter("category");
                String image=request.getParameter("image");

                News n = new News(0, title, date, description, detail, category, image);
                DataAccess da = new DataAccess();
                da.addNew(n);
                response.sendRedirect("/CRUD_NEWS/AllPost");
          %>

        </body>
    </html>

1 Answers1

1

First of all, I suggest/recommend/propose that you use only JDBC API specific interface classes instead of MySQL only classes.

Instead of:

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

Use

import java.sql.Connection;
import java.sql.PreparedStatement;

And throw only SQLException.

Secondly, I wrote in this SO Post on how to correctly execute a SQL statement (excluding transactions, of course).

Thirdly, I have not see in your post where the DataAccess.addNew() method is ever called.

Few things I've picked up:

  1. Why do you create a News object passing 0 as first parameter?
  2. The getAll() method has a List<News> that is empty. You do a request on it but you NEVER iterate the ResultSet to create a News object and add it into the ls list. That is your problem there.
Community
  • 1
  • 1
Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228