Home > Software design >  Trying to fetch results from mySQL database and display it in a jsp file
Trying to fetch results from mySQL database and display it in a jsp file

Time:10-10

using a MVC model to try and fetch from a mySQL db. The code tries to query db and put the results into and array to pass it to the controller. The jsp page can then call it. At the moment, I am not getting results to display even though it can compile

View

public class ViewQA {
    public static void main(String category, String questions, String answers) {
        // TODO Auto-generated constructor stub
    }

    public static List<ViewQA> listData() throws SQLException, ClassNotFoundException {
        List<ViewQA> listData = new ArrayList<>();

        try (java.sql.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/examgenappschema",
                "EXadmin", "abc123");) {
            
        PreparedStatement select = null;
        String queryString = ("SELECT category, questions, answers FROM examgen");
        
        select = conn.prepareStatement(queryString);
        
        
            ResultSet rs = select.getResultSet();
            while (rs.next()) {
                rs.getString("category");
                rs.getString("questions");
                rs.getString("answers");
                ViewQA results = new ViewQA();
                listData.add(results);
            }
        }
        return listData;
    }
}

Controller

    @Controller
public class ExamGenController {
    @RequestMapping(value = "/examgen", method = RequestMethod.GET)
    public String DataArray(@ModelAttribute("listData") ViewQA listData, ModelMap model)
            throws ClassNotFoundException, SQLException {
        return "examgen";
    }}

jsp page

    <!DOCTYPE html>
<html>
    <body>
    <center>
        <h1>List of Questions and Answers</h1>
    </center>
    <div align="center">
        <table border="1" cellpadding="3">
            <tr>
                <th>category</th>
                <th>questions</th>
                <th>answers</th>
            </tr><c:forEach var="listData" items="${DataArray}"> 
        <div > ${DataArray.category} </div>
        <div > ${DataArray.questions} </div>
        <div > ${DataArray.answers} </div>
</c:forEach>        
        </table>
    </div>   
</body>
</html>

CodePudding user response:

You forgot to add your query result to ViewQA. You adding a blank ViewQA object into the list.

CodePudding user response:

You are taking var but not using it in the code try this way.

<c:forEach var="listData" items="${DataArray}"> 
        <div > ${listData.category} </div>
        <div > ${listData.questions} </div>
        <div > ${listData.answers} </div>
  • Related