0

I have a table where I display items from database. In first ResultSet I have created an dropdown menu that let you choose if you want item to be available or not. But, because I have created it in first ResultSet rs, I cannon use it in second ResultSet rs1. Problem is in this line:

if (request.getParameter(rs1.getString("naziv") + "polje").equals("Nedostupno"))

And here is the whole code:

<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<html>
<head>
    <link rel="stylesheet" type="text/css" href="Stil/cssstil.css">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Prikaz oružja</title>
</head>
<body>
    <h1>Prikaz oruzja</h1>
    <%
        out.print("<p align = \"center\">Administrator <a style=\"color:red;\">" +     session.getAttribute("user") + "</a></p>");
    %>
    <table align = "center" bgcolor = "darkgrey" border = "1" cellpadding="3" cellspacing="1">
        <tr>
            <td>
                <p style = "color: black;">Naziv</p>
            </td>
            <td>
                <p style = "color: black;">Opis</p>
            </td>
            <td>
                <p style = "color: black;">Cena</p>
            </td>
            <td>
                <p style = "color: black;">Dostupnost</p>
            </td>
            <td>

            </td>
        </tr>
        <%
            try {
                Class.forName("com.mysql.jdbc.Driver");
                Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/CS230-Projekat", "root", "123");
                Statement statement = connection.createStatement();
                String sql = "SELECT * FROM oruzje";
                ResultSet rs = statement.executeQuery(sql);
                while (rs.next()) {
        %>
        <tr bgcolor="grey">

            <td><%=rs.getString("naziv")%></td>
            <td><%=rs.getString("opis")%></td>
            <td><%=rs.getString("cena")%></td>
            <%
                if (rs.getString("dostupnost").equals("1")) {
                    out.print("<td><p style = \"color: green; font-size: 20px\">Dostupno</p></td>");

                } else {
                    out.print("<td><p style = \"color: red; font-size: 20px\">Nedostupno</p></td>");
                }
            %>
            <%
                    int a = rs.getInt("dostupnost");
                    if (a == 1) {
                        out.print("<td><select name=\"" + rs.getString("naziv") + "polje\"><option value = \"Dostupno\">Dostupno</option><option value = \"Nedostupno\">Nedostupno</option></select></td>");
                    } else {
                        out.print("<td><select name=\"" + rs.getString("naziv") + "polje\"><option value = \"Dostupno\">Dostupno</option><option value = \"Nedostupno\">Nedostupno</option></select></td>");
                    }
                }


            %>
        </tr>
        <tr><td></td><td></td><td></td><td></td>
            <td align=center>
                <form method="post">
                    <%      Statement statement1 = connection.createStatement();
                            int bre;
                            ResultSet rs1 = statement.executeQuery(sql);
                            while (rs1.next()) {
                                if (request.getParameter(rs1.getString("naziv") + "polje").equals("Nedostupno")) {
                                    bre = statement1.executeUpdate("UPDATE oruzje SET dostupnost = 0 WHERE  naziv='" + rs1.getString("naziv") + "'");
                                } else {
                                    bre = statement1.executeUpdate("UPDATE oruzje SET dostupnost = 0 WHERE  naziv='" + rs1.getString("naziv") + "'");
                                }

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    %>
                    <input type="submit" value="Apply" name="Apply" />
                </form>
            </td>
        </tr>
    </table>

    <p style=" position: absolute; bottom: 0; left: 0; width: 100%; text-align: center;"><a href ="index.jsp"><img src = "Slike/home.png" alt = "home"/></a></p>
</body>

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • 1
    I would recommend not using *dynamic* names for your HTML components. Also, avoid using scriptlets in your code. – Luiggi Mendoza Sep 05 '14 at 00:50
  • I know my code is bad, but this is school assignment and I have to finish it as soon as possible, so I didn't have much time to do research, as you can see. Is it possible to solve this problem without completely changing the code? – Svrkota Stefan Sep 05 '14 at 00:52
  • Again: **I would recommend not using dynamic names for your HTML components**. There's no need to do that. Use a fixed name for your ` – Luiggi Mendoza Sep 05 '14 at 00:53
  • I understand, but, what if I add aditional entries to database? Then number of – Svrkota Stefan Sep 05 '14 at 00:54
  • The content of the ` – Luiggi Mendoza Sep 05 '14 at 00:55
  • It has to be dynamic because every entry from database needs to have unique – Svrkota Stefan Sep 05 '14 at 00:59
  • Again: **no, that's not the right approach**. The problem is the design you're using to solve this problem. Also, you just threw your code here without a proper explanation of the use case where it states that you have an irregular number of ` – Luiggi Mendoza Sep 05 '14 at 01:03
  • OK, you are right, I am sorry. I will try to be more precise. This is my usecase: For every entry in database, I have – Svrkota Stefan Sep 05 '14 at 01:08
  • Ok, I got it better. – Luiggi Mendoza Sep 05 '14 at 01:14
  • Great, I hope you can help me now because I'm becoming hopeless, I spent a few hours trying to solve this. – Svrkota Stefan Sep 05 '14 at 01:20
  • Well, do you have a field with name `id` or something similar? – Luiggi Mendoza Sep 05 '14 at 01:21
  • If you mean in database, yeah, I have, but every Naziv (Username) is also unique, so I can use that. – Svrkota Stefan Sep 05 '14 at 01:22

1 Answers1

0

First, I'll split your code in Servlets and JSP and show you why this is a better way to go.

Your view (assuming is called "foo.jsp"):

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

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="Stil/cssstil.css">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Prikaz oružja</title>
</head>
<body>
    <h1>Prikaz oruzja</h1>
    <p align="center">
        Administrator <span style="color:red"><c:out value="${user}" /></span>
    </p>
    <!--
        In this case, the form should wrap all your table
        since you want to process all the input elements
        inside it. Otherwise, you will update the entire data
        rather than update per entity.
    -->
    <form method="post">
        <table align="center" bgcolor="darkgrey" border="1" cellpadding="3" cellspacing="1">
            <th>
                <td>
                    <p style = "color: black;">Naziv</p>
                </td>
                <td>
                    <p style = "color: black;">Opis</p>
                </td>
                <td>
                    <p style = "color: black;">Cena</p>
                </td>
                <td>
                    <p style = "color: black;">Dostupnost</p>
                </td>
                <td>

                </td>
            </th>
            <c:forEach items="${oruzjeList}" var="oruzje">
            <tr bgcolor="grey">
                <td>${oruzje.naziv}</td>
                <td>${oruzje.opis}</td>
                <td>${oruzje.cena}</td>
                <td>
                    <p style="color: green; font-size: 20px">
                        <!-- printing the value dynamically in view -->
                        <c:out value="${oruzje.dostupnost == '1' ? 'Dostupno' : 'Nedostupno'}" />
                    </p>
                </td>
                <td>
                    <!--
                        oruzje.naziv should be an ID, not the "unique name"
                        because a name could contain empty spaces which
                        will break the name of the component
                        here I use id but you will replace it with your ID
                    -->
                    <select name="polje_${oruzje.id}">
                        <option value="1" ${oruzje.dostupnost == '1' ? 'selected' : ''}>Dostupno</option>
                        <option value="0" ${oruzje.dostupnost == '0' ? 'selected' : ''}>Nedostupno</option>
                    </select>
                    <!--
                        Additionally, we need to obtain the respective id for
                        the row to be updated.
                        We will use a hidden input field which uses the ID
                    -->
                    <input type="hidden" name="hidId_${oruzje.id}" value="${oruzje.id}" />
                </td>
            </tr>
            </c:forEach>
            <tr>
                <td></td><td></td><td></td><td></td>
                <td>
                    <input type="submit" value="Apply" />
                </td>
            </tr>
        </table>
    </form>
        <p style="position: absolute; bottom: 0; left: 0; width: 100%; text-align: center;">
            <a href="index.jsp"><img src="Slike/home.png" alt="home"/></a>
        </p>
</body>
</html>

This assumes you have an entity that supports that maps to your database table:

public class Oruzje {
    private int id;
    private String naziv;
    private String opis;
    private String cena;
    private String dostupnost;
    //propers getters and setters for your fields
}

Now, your Servlet:

//yes, a Servlet can map directly to your JSP
//there's no problem using this approach
@WebServlet("/foo.jsp")
public class OruzjeServlet extends HttpServlet {
    //I won't go far with more classes
    //nor with other improvements to the code
    //I'll write the basic stuff here in Servlet

    //this method should be in an utility class
    //to provide reusability
    private void closeResource(Closeable resource) {
        try {
            if (resource != null) {
                resource.close();
            }
        } catch (IOException e) {
            //silent exception
        }
    }

    //this method should also be in an utility class
    //and should recover the connection from a DataSource
    //instead of creating the physical connection everytime
    private Connection getConnection() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection connection = DriverManager
                .getConnection("jdbc:mysql://localhost:3306/CS230-Projekat", "root", "123");
        } catch (Exception e) {
            //this should be splitted for better handling
            //but I leave this up to you
            //handle the exception
            //very basic handling
            e.printStacktrace();
        }
    }

    //this method should be in a proper DAO class
    //reusing a connection for execution of multiple statements
    private List<Oruzje> getOruzjeList(Connection con) {
        List<Oruzje> oruzjeList = new ArrayList<Oruzje>();
        Statement statement = null;
        ResultSet rs = null;
        try {
            statement = connection.createStatement();
            String sql = "SELECT * FROM oruzje";
            ResultSet rs = statement.executeQuery(sql);
            while (rs.next()) {
                Oruzje oruzje = new Oruzje();
                oruzje.setId(rs.getInt("id")); //use the real column
                oruzje.setNaziv(rs.getString("naziv"));
                oruzje.setOpis(rs.getString("opis"));
                oruzje.setCena(rs.getString("cena"));
                oruzje.setDostupnost(rs.getString("dostupnost"));
                oruzjeList.add(oruzje);
            }
        } catch (SQLException e) {
            //again, handle the exception
            e.printStacktrace();
        } finally {
            closeResource(rs);
            closeResource(statement);
        }
        return oruzjeList;
    }

    //this method will be executed when a client (browser)
    //tries to enter to your foo.jsp page
    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        Connection con = getConnection();
        List<Oruzje> oruzjeList = getOruzjeList(con);
        closeResource(con);
        //setting the oruzjeList variable as attribute
        //this will feed the ${oruzjeList} used in the
        //<c:forEach>
        request.setAttribute("oruzjeList", oruzjeList);
        //now, forward the view to the right view (JSP)
        //it is not a redirect
        request.getRequestDispatcher("/foo.jsp").forward(request, response);
    }

    //this method will be executed when user selects "Apply"
    //option in the view (the JSP)
    //because you stated that the method to submit the <form>
    //is POST
    public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        //now, we just retrieve the necessary parameters and process the data
        //sent from the form
        Connection con = getConnection();
        List<Oruzje> oruzjeList = getOruzjeList(con);

        //each ? is a parameter in the query
        //starting at index 1
        String updateSql = "UPDATE oruzje SET dostupnost = ? WHERE id = ?";
        PreparedStatement pstmt = con.prepareStatement();
        for(Oruzje oruzje : oruzjeList) {
            //this is where the static part of the name becomes handy
            String theId = request.getParameter("hidId_" + oruzje.getId());
            String theDostupnost = request.getParameter("polje_" + oruzje.getId());
            //I'll avoid basic validation like
            //if (theId == null || "".equals(theId))
            //right to the update!

            //setting the first parameter: dostupnost = ?
            pstmt.setString(1, theDostupnost);
            //setting the second parameter: ID = ?
            //since it's an int, parsing the String to int
            pstmt.setInt(2, Integer.parseInt(theId));
            //perform the update for the current ID and Dostupnost
            pstmt.execute();
        }
        //at the end, closing the resources
        closeResource(pstmt);

        //this is cumbersome but just to make sure
        //the data was updated successfully
        oruzjeList = getOruzjeList(con);
        closeResource(con);
        //similar to the doGet, we will forward to the view
        request.getRequestDispatcher("/foo.jsp").forward(request, response);
    }
}

More info:

Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332