Quantcast
Channel: Active questions tagged servlets - Stack Overflow
Viewing all articles
Browse latest Browse all 675

How to make a data to be displayed whenever the JSP page is opened and not show empty data when data is actually present in the database? [duplicate]

$
0
0

I am trying to send partyList from AddPartyServlet.java to addParty.jsp. Whenever addParty.jsp is opened, the partyList isn't displayed readily and no records are seen. It just shows You have not added any party yet.. However, all the records magically appear only after a party is added through the Add Party button. The parties are being added fine as it reflects in the database. I want all the parties to be displayed whenever the jsp page is opened and not show empty data when data is actually present.

PartyDaoImp.java:

package com.company.dao;import java.io.InputStream;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import com.company.dao.PartyDaoImp;import com.company.util.DBUtil;import jakarta.servlet.http.Part;public class PartyDaoImp implements PartyDao {    @Override    public List<Party> getAllParties() {        List<Party> partyList = new ArrayList<>();        String query = "SELECT * FROM party ORDER BY vote_count DESC";         try (                Connection connection = DBUtil.getConnection(); // works fine                PreparedStatement preparedStatement = connection.prepareStatement(query)) { //works fine                ResultSet resultSet = preparedStatement.executeQuery(); //works fine                while (resultSet.next()) {                    int party_id = resultSet.getInt("party_id");                    String party_name = resultSet.getString("party_name");                    byte[] party_symbol = resultSet.getBytes("party_symbol");                    int vote_count = resultSet.getInt("vote_count");                    partyList.add(new Party(party_id, party_name, party_symbol, vote_count));                    System.out.println("Fetched Party: id=" + party_id +", name=" + party_name +", vote_count=" + vote_count +", party_symbol_length=" + (party_symbol != null ? party_symbol.length : 0));                }                System.out.println("Reached partyList logging section.");        } catch (Exception e) {            e.printStackTrace();        }        return partyList;    }}   

AddPartyServlet.java:

package com.company.servlet;import jakarta.servlet.ServletException;import jakarta.servlet.annotation.MultipartConfig;import jakarta.servlet.annotation.WebServlet;import jakarta.servlet.http.HttpServlet;import jakarta.servlet.http.HttpServletRequest;import jakarta.servlet.http.HttpServletResponse;import jakarta.servlet.http.Part;import java.io.IOException;import java.util.List;import com.company.dao.Party;import com.company.dao.PartyDao;import com.company.dao.PartyDaoImp;@WebServlet("/AddPartyServlet")@MultipartConfigpublic class AddPartyServlet extends HttpServlet {    private static final long serialVersionUID = 1L;    private static PartyDao pDao = new PartyDaoImp();    public AddPartyServlet() {        super();    }    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {           // ADD PARTY        int party_id = Integer.parseInt(request.getParameter("party_id"));        String party_name = request.getParameter("party_name");        Part partySymbolPart = request.getPart("party_symbol");        int rowsInserted = pDao.addPartyToDatabase(party_id, party_name, partySymbolPart);        if (rowsInserted > 0) {            List<Party> partyList = pDao.getAllParties(); // On success, fetch the updated party list and forward            request.setAttribute("partyList", partyList);            request.setAttribute("error", "0");            request.getRequestDispatcher("addParty.jsp").forward(request, response);         } else {            request.setAttribute("error", "1");            response.sendRedirect("addParty.jsp"); // On failure, redirect with error message        }    }    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        List<Party> partyList = pDao.getAllParties();        request.setAttribute("partyList", partyList);        request.getRequestDispatcher("addParty.jsp").forward(request, response);    }}

addParty.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ page import="java.util.List" %><%@ page import="com.company.dao.Party" %><%@ page import="com.company.dao.PartyDao" %><%@ page import="com.company.dao.PartyDaoImp" %><!DOCTYPE html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Add Party</title><link rel="stylesheet" href="css/jspStyles.css"></head><body><%        // Retrieve the existing session (do not create a new session)        HttpSession session1 = request.getSession(false);         if (session1 != null && session1.getAttribute("admin_username") != null) {            String admin_username = (String) session1.getAttribute("admin_username");    %><h1 class="admin-heading">Hi <%= admin_username %>!</h1><div class="addParty-container"><h2>Manage Political Parties</h2><!-- Party Table --><table class="party-table"><thead><tr><th>Party ID</th><th>Party Name</th><th>Party Symbol</th><th>Vote Count</th><th>Action</th></tr></thead><tbody><%                                      List<Party> partyList = (List<Party>) request.getAttribute("partyList");                    if (partyList != null && !partyList.isEmpty()) {                        for (Party party : partyList) {                %><tr><td><%= party.getParty_id() %></td><td><%= party.getParty_name() %></td><td><img src="data:image/png;base64,<%= java.util.Base64.getEncoder().encodeToString(party.getParty_symbol()) %>"                              alt="Party Symbol" width="50" height="50"></td><td><%= party.getVote_count() %></td><td><form action="DeletePartyServlet" method="post"><input type="hidden" name="party_id" value="<%= party.getParty_id() %>"><button type="submit" class="delete-button">Delete Party</button></form></td></tr><%                        }                    } else {                %><tr><td colspan="5" class="no-parties">You have not added any party yet.</td></tr><% } %></tbody></table><!-- Form to Add a New Party --><form action="AddPartyServlet" method="post" enctype="multipart/form-data" class="add-party-form"><table class="form-table"><tr><td><input type="number" name="party_id" placeholder="Party ID" required                                pattern="\d+" title="Only numeric values are allowed"></td><td><input type="text" name="party_name" placeholder="Party Name" required                                pattern="[A-Za-z\s]+" title="Only letters and spaces are allowed"></td><td><input type="file" name="party_symbol" accept="image/*" required                                title="Please upload a file in PNG, JPEG, or JPG format."></td><td><button type="submit">Add Party</button></td></tr></table></form></div><%        // Display error or success messages        String error = (String) request.getAttribute("error");        if (error != null) {            if ("1".equals(error)) {    %><p style="color: red; font-weight: bold; margin-bottom: 15px;">Failed to add party. Try again.</p><%            } else if ("2".equals(error)) {    %><p style="color: red; font-weight: bold; margin-bottom: 15px;">Failed to delete the party. Please try again.</p><%            } else if ("3".equals(error)) {    %><p style="color: green; font-weight: bold; margin-bottom: 15px;">Party deleted successfully!</p><%            } else if ("4".equals(error)) {    %><p style="color: green; font-weight: bold; margin-bottom: 15px;">Party added successfully!</p><%            }        }    %><p class="back-to-home"><a href="index.jsp">Back to Home</a></p><p class="addPartyLogout">        If you are finished, don't forget to <b>LOGOUT</b> using the button below to ensure the security of your session.</p><a href="AdminLogoutServlet"><button type="button" class="admin-logout-btn">Logout</button></a><%        } else {            response.sendRedirect("adminLogin.jsp"); // Redirect to login if session is invalid        }    %></body></html>

Viewing all articles
Browse latest Browse all 675

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>