0
votes

For a school project we are trying to create a very basic version of MVC pattern using a servlet and JSP page. It is basically an online journal, which saves information to the Database. Beside each entry are three buttons : read, update, and delete. The issue that I am having is that once I select a log, its ID is stored in the servlet, so when I choose a different logs button, the previous logs information is coming up instead.

I have tried requesting the parameters within each if statement, as well as creating a servlet method for each button, but the result is the same.

Any suggestions would be great!

INDEX.JSP

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<%@ page import="java.util.*" %>
<%@ page import="com.algonquin.loggy.beans.Log"%>
<html>
<head>
<meta charset="ISO-8859-1">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Loggy Home Page</title>
</head>
<body>
<%@ include file="header.jsp" %>

<div id="logFormCon">
<form id="logForm" action="LogsServlet" method="post">
<h3 id="formTitle">Create a new log:</h3>
<label for="title"id="titleLabel">Title: </label><!----><input id="titleInput" type="text" name="title" maxlength="60">
<br>
<label id="contentLabel" for="content">Log Content:</label>
<br>
<input type="text" id="contentInput" name="content">
<br>
<button type="submit" id="submit" name="button" value="create">Upload Log</button>
</form>
</div>


<form id="logsList" action="LogsServlet" method="post">
<div id="listTop">
<h1 id="listHead" >My Logs</h1>
</div>


<%

List<Log> logs = (ArrayList<Log>) request.getAttribute("logs");
Iterator<Log> iterator = logs.iterator();
while (iterator.hasNext()) {
    Log log = iterator.next();
    
%>
<div id="logItem">
<div id="thumbnailHolder">
<img src="images/thumbnailOrange.png" width="80px" height="80px">
</div>
<div id="infoHolder">

<label for="uuid" id="lbl">ID: </label><input id="uuidPlace" class="info" type="text" name="uuid" value="<%=log.getId()%>" readonly="readonly">
<br>
<label for="title" id="lbl">Title: </label><input id="titlePlace" class="info" type="text" name="title" value="<%=log.getTitle()%>" readonly="readonly">


<button id="readBtn" class="btn" type="submit" name="button" value="read">Read</button>
<button id="updateBtn" class="btn" type="submit" name="button" value="update">Update</button>
<button id="deleteBtn" class="btn" type="submit" name="button" value="delete">Delete</button>
</div>
<% } %>


</div>

</form>
</body>
</html>

UPDATE.JSP

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<%@ page import="java.util.*" %>
<%@ page import="com.algonquin.loggy.beans.Log"%>
<html>
<head>
<meta charset="ISO-8859-1">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Update Log</title>
</head>
<body>
<%@ include file="header.jsp" %>
<%
Log log= (Log)request.getAttribute("log");
%>
<div id="logFormCon">
<form id="logForm" action="LogsServlet" method="post">
<h3 id="formTitle">Update log:</h3>
<label for="uuid" id="titleLabel">ID: </label><input id="uuidPlaceUpdate" class="info" type="text" name="uuid" value="<%=log.getId() %>" readonly="readonly">
<br>
<label for="title"id="titleLabel">Title: </label><!----><input id="titleInput" type="text" name="title" value="<%=log.getTitle() %>" maxlength="60">
<br>
<label id="contentLabel" for="content">Log Content:</label>
<br>
<input type="text" id="contentInput" name="content" value="<%=log.getContent()%>">
<br>
<button type="submit" id="submit" name="button" value="confirmUpdate">Update Log</button>
</form>
</div>
</body>
</html>

SERVLET

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Map;
import java.util.UUID;

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;

import com.algonquin.loggy.beans.Log;
import com.algonquin.loggy.beans.TextLog;
import com.algonquin.loggy.dao.ApplicationDao;
import com.algonquin.loggy.inmemory.ApplicationInMemory;
import com.algonquin.loggy.services.ApplicationService;

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

    ApplicationDao dao = new ApplicationDao();
 
    public LogsServlet() {
        super();
      
    }

  
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        // Read all logs, assign to local variable and sent to printOutBodyList
        
        ArrayList<Log> logs =  dao.readLogs(); 
      
        request.setAttribute("logs", logs);
        RequestDispatcher dispatcher = getServletContext()
                  .getRequestDispatcher("/index.jsp");
            dispatcher.forward(request, response);
    }

    
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    
      String action = request.getParameter("button");
         
      
    if("create".equals(action)) {
        create(request,response);
      }
        else if("delete".equals(action)) {
           delete(request,response);
       }
        else if("update".equals(action)) {
            openUpdate(request,response);
        }
    
      
    
        // Process GET for rendering the page with updates.
       //doGet(request, response);
       
       doGet(request,response);
    }

 
  
   //Delete Method

  private void delete(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException{
    String id=  request.getParameter("uuid");
      dao.deleteLog(id);
  }
  
  private void openUpdate(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException{
      String id=  request.getParameter("uuid");
       Log log = dao.readLogUUID(id);
       request.setAttribute("log", log);
        RequestDispatcher dispatcher = getServletContext()
                  .getRequestDispatcher("/update.jsp");
            dispatcher.forward(request, response);  

  }
  private void updateLog(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
      
      String title = request.getParameter("title");
      String content = request.getParameter("content");
      String id=  request.getParameter("uuid");
      UUID uuid = UUID.fromString(id);
      
      Log log = new TextLog();
      log.setId(uuid);
      log.setTitle(title);
      log.setContent(content);
      
      dao.updateLog(log);     
      
  }
  //Create Method
  private void create(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException{
      String title = request.getParameter("title");
      String content = request.getParameter("content");
      
      Log log = new TextLog(title,content);
      dao.createLog(log);
      
  }
  
}

APPLICATIONDAO

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

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

public class ApplicationDao {

    public ArrayList<Log> readLogs() {
        Log log = null;
        ArrayList<Log> logs = new ArrayList<Log>();

        try {
            // get connection to database
            Connection connection = DBConnection.getConnectionToDatabase();

            // write select query to get all the log
            String sql = "SELECT * FROM `logs` ORDER BY 'creationTimestamp';";
            PreparedStatement statement = connection.prepareStatement(sql);

            // execute query, get resultset and return User info
            ResultSet set = statement.executeQuery();
            while (set.next()) {
                log = new TextLog();
                log.setId(UUID.fromString(set.getString("uuid")));
                log.setTitle(set.getString("title"));
                log.setContent(set.getString("content"));
                // log.setCreateTimestamp(Date.parse(set.getDate("createTimestamp")));
                logs.add(log);
            }
        } catch (SQLException exception) {
            exception.printStackTrace();
        }
        return logs;
    }

    public Log readLogUUID(String id) {
        Log log = null;
        try {
            // get connection to database
            Connection connection = DBConnection.getConnectionToDatabase();

            // write select query to get the log
            String sql = "select * from logs where uuid=?";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setString(1, id);

            // execute query, get resultset and return Log info
            ResultSet set = statement.executeQuery();
            while (set.next()) {
                log = new TextLog();
                log.setId(UUID.fromString(set.getString("uuid")));
                log.setTitle(set.getString("title"));
                log.setContent(set.getString("content"));
            }

        } catch (SQLException exception) {
            exception.printStackTrace();
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return log;
    }

    public void createLog(Log log) {
        try {
            // get connection to database
            Connection connection = DBConnection.getConnectionToDatabase();

            // write select query to get the log
            String sql = "insert into logs (uuid, title, content) values (?, ?, ?);";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setString(1, log.getId().toString());
            statement.setString(2, log.getTitle());
            statement.setString(3, log.getContent());

            // execute query, update resultset
            statement.execute();

        } catch (SQLException exception) {
            exception.printStackTrace();
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    public void updateLog(Log log) {
        try {
            // get connection to database
            Connection connection = DBConnection.getConnectionToDatabase();

            // write select query to get the log
            String sql = "update logs set title=?, content=? where uuid=?;";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setString(1, log.getTitle());
            statement.setString(2, log.getContent());
            statement.setString(3, log.getId().toString());

            // execute query, update resultset
            statement.execute();

        } catch (SQLException exception) {
            exception.printStackTrace();
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    public void deleteLog(String id) {
        try {
            // get connection to database
            Connection connection = DBConnection.getConnectionToDatabase();

            // write select query to get the log
            String sql = "delete from logs where uuid=?;";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setString(1, UUID.fromString(id).toString());

            // execute query, delete resultset
            statement.execute();

        } catch (SQLException exception) {
            exception.printStackTrace();
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

  
    public void createOrUpdateLog(Log log) {
        Log locallog = readLogUUID(log.getId().toString());
        if (locallog == null) {
            createLog(log);
        } else {
            updateLog(log);
        }
    }

}

LOG

public abstract class Log {
    private UUID id;
    private String title;
    private String content;
    private Date createTimestamp;

    public Log() {
    }

    public Log(String title, String content) {
        this.id = UUID.randomUUID();
        this.title = title;
        this.content = content;
        this.createTimestamp = new Date();
    }

    /**
     * @return the id
     */
    public UUID getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(UUID id) {
        this.id = id;
    }

    /**
     * @return the title
     */
    public String getTitle() {
        return title;
    }

    /**
     * @param title the title to set
     */
    public void setTitle(String title) {
        this.title = title;
    }

    /**
     * @return the content
     */
    public String getContent() {
        return content;
    }

    /**
     * @param content the content to set
     */
    public void setContent(String content) {
        this.content = content;
    }

    /**
     * @return the createTimestamp
     */
    public Date getCreateTimestamp() {
        return createTimestamp;
    }

    /**
     * @param createTimestamp the createTimestamp to set
     */
    public void setCreateTimestamp(Date createTimestamp) {
        this.createTimestamp = createTimestamp;
    }

}