Java:Null-POINTER异常 - 用服务器中的数据库值替换HTML中的值

发布于 2025-02-08 07:11:49 字数 19212 浏览 2 评论 0 原文

我正在完成一个学校项目 - 用户提交表单后,将创建一个对象,并将其添加到MySQL数据库中。然后,将显示一个由时间戳分类的标题的“列表”。它还必须具有缩略图图片和删除按钮。我正在尝试在HTML页面中替换输入文本值,并以数组的形式使用数据库中的值。 ApplicationDao正在与数据库进行通信,并应该将这些值放在数组中。

我一直在关注教程https://www.linkedin.com/learning/java-ee-servlets-and-javaserver-pages-jsp/search-building-a-servlet-响应?autoplay = true&简历= false& u = 2199673 但是这些值没有被替换,我得到以下例外: ***更新:将日志log = new TextLog更改为log = new TextLog之后,我现在正在收回以下错误!感谢您的帮助!

**我也知道重复一些代码,应该在一个页面上,我只是想找出解决方案!

   Jun. 16, 2022 1:41:41 P.M. org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [com.algonquin.loggy.servlets.deleteServlet] in context with path [/Loggy-Lab3] threw exception
java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
    at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
    at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
    at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
    at java.base/java.util.Objects.checkIndex(Objects.java:372)
    at java.base/java.util.ArrayList.get(ArrayList.java:459)
    at com.algonquin.loggy.servlets.deleteServlet.getHTMLString(deleteServlet.java:65)
    at com.algonquin.loggy.servlets.deleteServlet.doGet(deleteServlet.java:39)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:687)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1722)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:834)



Here is my code:

public  class Log {
    private String uuid;
    private String title;
    private String content;
    private String createTimestamp;
    
  
    
    
    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
       public String getUUID() {
            return uuid;
        }

        public void setUUID(String uuid) {  
            this.uuid = uuid;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }

        public String getCreateTimestamp() {
            return createTimestamp;
        }

        public void setCreateTimestamp(String createTimestamp) {
            this.createTimestamp=createTimestamp;
            
        }
}


import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

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 com.algonquin.loggy.beans.Log;
import com.algonquin.loggy.beans.TextLog;
import com.algonquin.loggy.dao.ApplicationDao;
import com.algonquin.loggy.dao.DBConnection;

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


    /**
     * @see HttpServlet#HttpServlet()
     */
    public LogsServlet() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String htmlResponse = "<html><head><link rel=\"stylesheet\" href=\"style.css\"><title>Loggy Servlet Form</title></head>"
                + "<body><form id=\"logForm\" action=\"LogsServlet\" method=\"post\" >\n"
                + "        <h3>Create A New Log!</h3>\n"
                + "       \n"
                + "        <label id=\"logTitleLabel\" for=\"title\">Title :</label>\n"
                + "        <br>\n"
                + "        <input type=\"text\" id=\"logTitle\" name=\"title\" maxLength=\"60\">\n"
                + "        <br>\n"
                
                + "        <label id=\"logContentLabel\" for=\"content\">Content :</label>\n"
                + "        <br>\n"
                + "        <input type=\"text\" id=\"logContent\" name=\"content\">\n"
                + "        <br>\n"
                + "        <button type=\"submit\" id=\"submitLog\">Submit Log</button>\n"
                + "        \n"
                + "        </form></body></html>";;
        PrintWriter writer = response.getWriter();
        writer.write(htmlResponse);
    }


protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException{
    
    String title = request.getParameter("title");
    String content = request.getParameter("content");
    String output;
    String uuid =UUID.randomUUID().toString();
    String createTimestamp=new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new java.util.Date());
    
    Log log= new TextLog();
    //ApplicationDao dao = new ApplicationDao();
    //List<Log> logs= dao.listLogs();
    

    
    PrintWriter writer = response.getWriter();
    try {
        
        log.setTitle(title);
        log.setContent(content);
        log.setCreateTimestamp(createTimestamp);
        log.setUUID(uuid);
        
        //logsList.add(log);
        
        output="<html><body><h3>Log successfully created</h3></body></html>";
        writer.write(output);
        }
        catch(Exception e) {
            output="<html><body><h3>Log could not be created</h3></body></html>";
            writer.write(output);
        }
    
            

    String indexForm = "<html><head><link rel=\"stylesheet\" href=\"style.css\"><title>Loggy Servlet Form</title></head>"
            + "<body><form id=\"logForm\" action=\"LogsServlet\" method=\"post\" >\n"
            + "        <h3>Create A New Log!</h3>\n"
            + "       \n"
            + "        <label id=\"logTitleLabel\" for=\"title\">Title :</label>\n"
            + "        <br>\n"
            + "        <input type=\"text\" id=\"logTitle\" name=\"title\" maxLength=\"60\">\n"
            + "        <br>\n"
        
            + "        <label id=\"logContentLabel\" for=\"content\">Content :</label>\n"
            + "        <br>\n"
            + "        <input type=\"text\" id=\"logContent\" name=\"content\">\n"
            + "        <br>\n"
            + "        <button type=\"submit\" id=\"submitLog\">Submit Log</button>\n"
            + "        \n"
            + "        </form></body></html>";
    
    writer.write(indexForm);
    
    String insertQuery ="INSERT INTO `logs`(`uuid`, `title`, `content`, `createTimestamp`) VALUES (?,?,?,?)";
    Connection connection =DBConnection.getConnectionToDatabase();
    
    
    java.sql.PreparedStatement statement;
    try {
        statement = connection.prepareStatement(insertQuery);
        statement.setString(1,log.getUUID());
        statement.setString(2,log.getTitle());
        statement.setString(3,log.getContent());
        statement.setString(4,log.getCreateTimestamp());
        
        statement.executeUpdate();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    
    String list ="<div class=\"logContainer\">\n"
            + "        <form>\n"
            + "        \n"
            + "        <div class=\"logContainerItem\">\n"
            + "        <img src=\"images/journal1.png\" height=\"60px\" width=\"60px\">\n"
            + "        <input type=\"text\" name=\"log\" value=\"{0}\">\n"
            + "        <button>Delete Log</button>\n"
            + "        </div>\n"
            + "        \n"
            + "         <div class=\"logContainerItem\">\n"
            + "        <img src=\"images/journal1.png\" height=\"60px\" width=\"60px\">\n"
            + "        <input type=\"text\" name=\"log\" value=\"{1}\">\n"
            + "        <button>Delete Log</button>\n"
            + "        </div>\n"
            + "        \n"
            + "         <div class=\"logContainerItem\">\n"
            + "        <img src=\"images/journal1.png\" height=\"60px\" width=\"60px\">\n"
            + "        <input type=\"text\" name=\"log\" value=\"{2}\">\n"
            + "        <button>Delete Log</button>\n"
            + "        </div>\n"
            + "        \n"
            + "         <div class=\"logContainerItem\">\n"
            + "        <img src=\"images/journal1.png\" height=\"60px\" width=\"60px\">\n"
            + "        <input type=\"text\" name=\"log\" value=\"{3}\">\n"
            + "        <button>Delete Log</button>\n"
            + "        </div>\n"
            + "        \n"
            + "        </form>\n"
            + "        \n"
            + "        \n"
            + "        \n"
            + "        </div>\n"
            + "";
    
    writer.write(list);
    
    
    
    
    //String page = getHTMLString(request.getServletContext().getRealPath("/html/ListLogs.html"), logs);
    //response.getWriter().write(page);

}

//public String getHTMLString(String filePath, List<Log> logs) throws IOException{
//  BufferedReader reader = new BufferedReader(new FileReader(filePath));
//  String line="";
//  StringBuffer buffer = new StringBuffer();
//  while((line=reader.readLine())!=null){
//      buffer.append(line);
//  }
    
//  reader.close();
//  String page = buffer.toString();
    
//  page = MessageFormat.format(page,logs.get(0).getTitle(),
            //logs.get(1).getTitle(),logs.get(2).getTitle(),0);
    
    //return page;
    
    
//}




}



import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import com.algonquin.loggy.beans.Log;
import com.algonquin.loggy.beans.TextLog;
import com.algonquin.loggy.services.ApplicationService;

public class ApplicationDao implements ApplicationService {


        @SuppressWarnings("null")
        public List<Log> listLogs() {
                
            Log log=null;
            List<Log> logs = new ArrayList<>();
            
            
            try{
                Connection connection = DBConnection.getConnectionToDatabase();
                
                String sql = "SELECT title FROM `logs` ORDER BY createTimestamp";
                
                Statement statement = connection.createStatement();
                
                ResultSet set = statement.executeQuery(sql);
                
                while(set.next()){
                    
                    log = new Log();
                    log.setTitle(set.getString("title"));
                    log.setContent(set.getString("content"));
                    log.setCreateTimestamp(set.getString("createTimestamp"));
                    log.setUUID(set.getString("UUID"));
                    
            
                    logs.add(log);
                    
                }

            }
            catch(SQLException exception){
                exception.printStackTrace();
            }
            return logs;

            }
    }


package com.algonquin.loggy.servlets;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.List;

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 com.algonquin.loggy.beans.Log;
import com.algonquin.loggy.dao.ApplicationDao;




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

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
        
        
        
        //call DAO layer and get all products for search criteria
        ApplicationDao dao = new ApplicationDao();
        List<Log> logs = dao.listLogs();
        
        //write the products data back to the client browser
        String page = getHTMLString(req.getServletContext().getRealPath("/ListLogs.html"), logs);
        resp.getWriter().write(page);
        
        
    }
    
    /**
     * this methods reads the HTML template as a String, replaces placeholders
     * with the values and returns the entire page as a String
     * @param filePath
     * @param products
     * @return
     * @throws IOException
     */
    
    public String getHTMLString(String filePath, List<Log> logs) throws IOException{
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        String line="";
        StringBuffer buffer = new StringBuffer();
        while((line=reader.readLine())!=null){
            buffer.append(line);
        }
        
        reader.close();
        String page = buffer.toString();
        
        page = MessageFormat.format(page, logs.get(0).getTitle(),
                logs.get(1).getTitle(),logs.get(2).getTitle(),logs.get(3).getTitle());
        
        return page;
        
        
    }
}


<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>List Of Submitted Logs</title>
</head>
<body>
   <div class="logContainer">
        <form method="get" action="deleteServlet">
        
        <div class="logContainerItem">
        <img src="images/journal1.png" height="60px" width="60px">
        <input type="text" name="log" value="{0}">
        <button>Delete Log</button>
        </div>
        
         <div class="logContainerItem">
        <img src="images/journal1.png" height="60px" width="60px">
        <input type="text" name="log" value="{1}">
        <button>Delete Log</button>
        </div>
        
         <div class="logContainerItem">
        <img src="images/journal1.png" height="60px" width="60px">
        <input type="text" name="log" value="{2}">
        <button>Delete Log</button>
        </div>
        
         <div class="logContainerItem">
        <img src="images/journal1.png" height="60px" width="60px">
        <input type="text" name="log" value="{3}">
        <button>Delete Log</button>
        </div>
        
        </form>
        
        
        
        </div>

</body>
</html>


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnection {

    // Database Schema
    // CREATE DATABASE loggy DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
    // CREATE TABLE logs (uuid CHAR(40) NOT NULL PRIMARY KEY, title CHAR(128),
    // content TEXT, createTimestamp Date);

     private static final String dbUser = "user";
        private static final String dbPassword = "password";
        private static Connection connection = null;
        

        public static Connection getConnectionToDatabase() {
            

            try {

                // load the driver class
                Class.forName("com.mysql.jdbc.Driver");
                System.out.println("MySQL JDBC Driver Registered!");

                // get hold of the DriverManager
                connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/loggy",dbUser,dbPassword);
            } catch (ClassNotFoundException e) {
                System.out.println("Where is your MySQL JDBC Driver?");
                e.printStackTrace();

            }

            catch (SQLException e) {
                System.out.println("Connection Failed! Check output console");
                e.printStackTrace();

            }

            if (connection != null) {
                System.out.println("Connection made to DB!");
            }
            return connection;
            
        }
        

          
    }

谢谢您,希望我的问题有意义!

I am completing a school project- After the user submits the form, an object is to be created, and it is added to MySQL database. Then a "list" is to be shown of the title sorted by the timestamp. It also must have a thumbnail picture and delete button. I am trying to replace the input text values in the html page, with values from the database in the form of an array. The ApplicationDao is communicating with the database and is suppose to place those values in the array.

I have been following the tutorial https://www.linkedin.com/learning/java-ee-servlets-and-javaserver-pages-jsp/search-building-a-servlet-response?autoplay=true&resume=false&u=2199673
but the values are not being replaced and I am getting the following exception:
***Updated:After changing the Log log= new textLog to log= new TextLog, I am now recieving the below error! Thanks for all your help!

** also I know some code is repeated, it is suppose to be on one page I was just trying to figure out a solution!

   Jun. 16, 2022 1:41:41 P.M. org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [com.algonquin.loggy.servlets.deleteServlet] in context with path [/Loggy-Lab3] threw exception
java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
    at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
    at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
    at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
    at java.base/java.util.Objects.checkIndex(Objects.java:372)
    at java.base/java.util.ArrayList.get(ArrayList.java:459)
    at com.algonquin.loggy.servlets.deleteServlet.getHTMLString(deleteServlet.java:65)
    at com.algonquin.loggy.servlets.deleteServlet.doGet(deleteServlet.java:39)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:687)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1722)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:834)



Here is my code:

public  class Log {
    private String uuid;
    private String title;
    private String content;
    private String createTimestamp;
    
  
    
    
    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
       public String getUUID() {
            return uuid;
        }

        public void setUUID(String uuid) {  
            this.uuid = uuid;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }

        public String getCreateTimestamp() {
            return createTimestamp;
        }

        public void setCreateTimestamp(String createTimestamp) {
            this.createTimestamp=createTimestamp;
            
        }
}


import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

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 com.algonquin.loggy.beans.Log;
import com.algonquin.loggy.beans.TextLog;
import com.algonquin.loggy.dao.ApplicationDao;
import com.algonquin.loggy.dao.DBConnection;

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


    /**
     * @see HttpServlet#HttpServlet()
     */
    public LogsServlet() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String htmlResponse = "<html><head><link rel=\"stylesheet\" href=\"style.css\"><title>Loggy Servlet Form</title></head>"
                + "<body><form id=\"logForm\" action=\"LogsServlet\" method=\"post\" >\n"
                + "        <h3>Create A New Log!</h3>\n"
                + "       \n"
                + "        <label id=\"logTitleLabel\" for=\"title\">Title :</label>\n"
                + "        <br>\n"
                + "        <input type=\"text\" id=\"logTitle\" name=\"title\" maxLength=\"60\">\n"
                + "        <br>\n"
                
                + "        <label id=\"logContentLabel\" for=\"content\">Content :</label>\n"
                + "        <br>\n"
                + "        <input type=\"text\" id=\"logContent\" name=\"content\">\n"
                + "        <br>\n"
                + "        <button type=\"submit\" id=\"submitLog\">Submit Log</button>\n"
                + "        \n"
                + "        </form></body></html>";;
        PrintWriter writer = response.getWriter();
        writer.write(htmlResponse);
    }


protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException{
    
    String title = request.getParameter("title");
    String content = request.getParameter("content");
    String output;
    String uuid =UUID.randomUUID().toString();
    String createTimestamp=new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new java.util.Date());
    
    Log log= new TextLog();
    //ApplicationDao dao = new ApplicationDao();
    //List<Log> logs= dao.listLogs();
    

    
    PrintWriter writer = response.getWriter();
    try {
        
        log.setTitle(title);
        log.setContent(content);
        log.setCreateTimestamp(createTimestamp);
        log.setUUID(uuid);
        
        //logsList.add(log);
        
        output="<html><body><h3>Log successfully created</h3></body></html>";
        writer.write(output);
        }
        catch(Exception e) {
            output="<html><body><h3>Log could not be created</h3></body></html>";
            writer.write(output);
        }
    
            

    String indexForm = "<html><head><link rel=\"stylesheet\" href=\"style.css\"><title>Loggy Servlet Form</title></head>"
            + "<body><form id=\"logForm\" action=\"LogsServlet\" method=\"post\" >\n"
            + "        <h3>Create A New Log!</h3>\n"
            + "       \n"
            + "        <label id=\"logTitleLabel\" for=\"title\">Title :</label>\n"
            + "        <br>\n"
            + "        <input type=\"text\" id=\"logTitle\" name=\"title\" maxLength=\"60\">\n"
            + "        <br>\n"
        
            + "        <label id=\"logContentLabel\" for=\"content\">Content :</label>\n"
            + "        <br>\n"
            + "        <input type=\"text\" id=\"logContent\" name=\"content\">\n"
            + "        <br>\n"
            + "        <button type=\"submit\" id=\"submitLog\">Submit Log</button>\n"
            + "        \n"
            + "        </form></body></html>";
    
    writer.write(indexForm);
    
    String insertQuery ="INSERT INTO `logs`(`uuid`, `title`, `content`, `createTimestamp`) VALUES (?,?,?,?)";
    Connection connection =DBConnection.getConnectionToDatabase();
    
    
    java.sql.PreparedStatement statement;
    try {
        statement = connection.prepareStatement(insertQuery);
        statement.setString(1,log.getUUID());
        statement.setString(2,log.getTitle());
        statement.setString(3,log.getContent());
        statement.setString(4,log.getCreateTimestamp());
        
        statement.executeUpdate();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    
    String list ="<div class=\"logContainer\">\n"
            + "        <form>\n"
            + "        \n"
            + "        <div class=\"logContainerItem\">\n"
            + "        <img src=\"images/journal1.png\" height=\"60px\" width=\"60px\">\n"
            + "        <input type=\"text\" name=\"log\" value=\"{0}\">\n"
            + "        <button>Delete Log</button>\n"
            + "        </div>\n"
            + "        \n"
            + "         <div class=\"logContainerItem\">\n"
            + "        <img src=\"images/journal1.png\" height=\"60px\" width=\"60px\">\n"
            + "        <input type=\"text\" name=\"log\" value=\"{1}\">\n"
            + "        <button>Delete Log</button>\n"
            + "        </div>\n"
            + "        \n"
            + "         <div class=\"logContainerItem\">\n"
            + "        <img src=\"images/journal1.png\" height=\"60px\" width=\"60px\">\n"
            + "        <input type=\"text\" name=\"log\" value=\"{2}\">\n"
            + "        <button>Delete Log</button>\n"
            + "        </div>\n"
            + "        \n"
            + "         <div class=\"logContainerItem\">\n"
            + "        <img src=\"images/journal1.png\" height=\"60px\" width=\"60px\">\n"
            + "        <input type=\"text\" name=\"log\" value=\"{3}\">\n"
            + "        <button>Delete Log</button>\n"
            + "        </div>\n"
            + "        \n"
            + "        </form>\n"
            + "        \n"
            + "        \n"
            + "        \n"
            + "        </div>\n"
            + "";
    
    writer.write(list);
    
    
    
    
    //String page = getHTMLString(request.getServletContext().getRealPath("/html/ListLogs.html"), logs);
    //response.getWriter().write(page);

}

//public String getHTMLString(String filePath, List<Log> logs) throws IOException{
//  BufferedReader reader = new BufferedReader(new FileReader(filePath));
//  String line="";
//  StringBuffer buffer = new StringBuffer();
//  while((line=reader.readLine())!=null){
//      buffer.append(line);
//  }
    
//  reader.close();
//  String page = buffer.toString();
    
//  page = MessageFormat.format(page,logs.get(0).getTitle(),
            //logs.get(1).getTitle(),logs.get(2).getTitle(),0);
    
    //return page;
    
    
//}




}



import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import com.algonquin.loggy.beans.Log;
import com.algonquin.loggy.beans.TextLog;
import com.algonquin.loggy.services.ApplicationService;

public class ApplicationDao implements ApplicationService {


        @SuppressWarnings("null")
        public List<Log> listLogs() {
                
            Log log=null;
            List<Log> logs = new ArrayList<>();
            
            
            try{
                Connection connection = DBConnection.getConnectionToDatabase();
                
                String sql = "SELECT title FROM `logs` ORDER BY createTimestamp";
                
                Statement statement = connection.createStatement();
                
                ResultSet set = statement.executeQuery(sql);
                
                while(set.next()){
                    
                    log = new Log();
                    log.setTitle(set.getString("title"));
                    log.setContent(set.getString("content"));
                    log.setCreateTimestamp(set.getString("createTimestamp"));
                    log.setUUID(set.getString("UUID"));
                    
            
                    logs.add(log);
                    
                }

            }
            catch(SQLException exception){
                exception.printStackTrace();
            }
            return logs;

            }
    }


package com.algonquin.loggy.servlets;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.List;

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 com.algonquin.loggy.beans.Log;
import com.algonquin.loggy.dao.ApplicationDao;




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

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
        
        
        
        //call DAO layer and get all products for search criteria
        ApplicationDao dao = new ApplicationDao();
        List<Log> logs = dao.listLogs();
        
        //write the products data back to the client browser
        String page = getHTMLString(req.getServletContext().getRealPath("/ListLogs.html"), logs);
        resp.getWriter().write(page);
        
        
    }
    
    /**
     * this methods reads the HTML template as a String, replaces placeholders
     * with the values and returns the entire page as a String
     * @param filePath
     * @param products
     * @return
     * @throws IOException
     */
    
    public String getHTMLString(String filePath, List<Log> logs) throws IOException{
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        String line="";
        StringBuffer buffer = new StringBuffer();
        while((line=reader.readLine())!=null){
            buffer.append(line);
        }
        
        reader.close();
        String page = buffer.toString();
        
        page = MessageFormat.format(page, logs.get(0).getTitle(),
                logs.get(1).getTitle(),logs.get(2).getTitle(),logs.get(3).getTitle());
        
        return page;
        
        
    }
}


<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>List Of Submitted Logs</title>
</head>
<body>
   <div class="logContainer">
        <form method="get" action="deleteServlet">
        
        <div class="logContainerItem">
        <img src="images/journal1.png" height="60px" width="60px">
        <input type="text" name="log" value="{0}">
        <button>Delete Log</button>
        </div>
        
         <div class="logContainerItem">
        <img src="images/journal1.png" height="60px" width="60px">
        <input type="text" name="log" value="{1}">
        <button>Delete Log</button>
        </div>
        
         <div class="logContainerItem">
        <img src="images/journal1.png" height="60px" width="60px">
        <input type="text" name="log" value="{2}">
        <button>Delete Log</button>
        </div>
        
         <div class="logContainerItem">
        <img src="images/journal1.png" height="60px" width="60px">
        <input type="text" name="log" value="{3}">
        <button>Delete Log</button>
        </div>
        
        </form>
        
        
        
        </div>

</body>
</html>


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnection {

    // Database Schema
    // CREATE DATABASE loggy DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
    // CREATE TABLE logs (uuid CHAR(40) NOT NULL PRIMARY KEY, title CHAR(128),
    // content TEXT, createTimestamp Date);

     private static final String dbUser = "user";
        private static final String dbPassword = "password";
        private static Connection connection = null;
        

        public static Connection getConnectionToDatabase() {
            

            try {

                // load the driver class
                Class.forName("com.mysql.jdbc.Driver");
                System.out.println("MySQL JDBC Driver Registered!");

                // get hold of the DriverManager
                connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/loggy",dbUser,dbPassword);
            } catch (ClassNotFoundException e) {
                System.out.println("Where is your MySQL JDBC Driver?");
                e.printStackTrace();

            }

            catch (SQLException e) {
                System.out.println("Connection Failed! Check output console");
                e.printStackTrace();

            }

            if (connection != null) {
                System.out.println("Connection made to DB!");
            }
            return connection;
            
        }
        

          
    }

Thankyou in advance, and hope my question makes sense!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文