Retrieve values from JDBC and use JSTL tags to call the methods

怎甘沉沦 提交于 2019-12-18 02:58:17

问题


Below is the code which i have written to retrieve values from the database (I have added the whole code so it will be easier for you to understand what i am trying to say here):

package ipscheme;

import java.sql.*;

public class AddRecords {

Connection con = new DBConnection().getConnection();
ResultSet  resultSet = null;  

public String [] populateSelect() throws SQLException {

    Statement statement = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);

    resultSet = statement.executeQuery("SELECT * FROM ipsections");

    resultSet.last();
    int size = resultSet.getRow();
    resultSet.beforeFirst();

    String [] sectionName = new String[size];

    int j = 0;
    while (resultSet.next()){
        sectionName[j] = resultSet.getString("section_name");
        j = j + 1;
    }

    resultSet.close();
    statement.close();
    con.close();

    return sectionName;

}

}

And down here is the JSP Code which i have used to populate values from the database into a selectbox.

<select name="sltSection">
 <% 
    AddRecords added = new AddRecords();
    String sectionNm  [] = added.populateSelect();
        for(int i=0; i<sectionNm.length; i++){ %>   
    <option>
        <% out.print(sectionNm[i]); %>
    </option>
 <% } %>
</select>

The above code works fine without any compilation errors. As you can see i have used Java code in my .jsp page to fulfill the task, which is a wrong thing to do.

I need to implement this code according to the MVC and therefore i should use JSTL tags to implement the code to .jsp? if so how do i do that? How do i instantiate Object from the class AddRecords and call its methods? Can someone please help me. Thanks in advance!


回答1:


Since it looks you're new to Java Web Programming, you can implement a full MVC scenario using JSP (View), Servlet (Controller) and Entities, DAOs and Service layer (Model). This is what you have:

Model:

  • DBConnection as a database access class (Data access layer)
  • AddRecords as your DAO class (Data access layer)
  • No class as Service class (Business logic layer). For this example, let's have a RecordService class for this:

    public class RecordService {
        public RecordService() {
        }
        //since it has no real business logic, it will serve as facade
        public String[] getRecords() {
            AddRecords addRecords = new AddRecords();
            return addRecords.populateSelect();
        }
    }
    

Controller:

  • No class for Controller yet. Since I assume you're using plain Java EE, you would use a Servlet (implementation based on Servlets StackOverflow wiki):

    @WebServlet("/RecordServlet")
    public class RecordsServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            //it will fire on a GET request (like accessing directly to the URL
            //from the browser)
            //here you should load the data for the View (JSP)
            loadData(request);
            //forward to show the view
            request.getRequestDispatcher("hello.jsp").forward(request, response);
        }
    
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            //it will fire on a POST request (like submitting the form using POST method)
            String selectedRecord = request.getParameter("selectedRecord");
            System.out.println(selectedRecord);
            request.setAttribute("selectedRecord", selectedRecord);
            loadData(request);
            //forward to show the view
            request.getRequestDispatcher("hello.jsp").forward(request, response);
        }
    
        //method to load the data available to select
        private void loadData(HttpServletRequest request) {
            RecordService recordService = new RecordService();
            String[] records = recordService.getRecords();
            //set the data as attribute on the request to be available on the View
            request.setAttribute("records", records);
        }
    }
    

View:

  • You already have a JSP file. Since you haven't posted the name, let's call it hello.jsp. I will just adap your actual JSP code using JSTL:

    <!-- at the beginning of the JSP, call the JSTL library -->
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    
    <form action="RecordServlet" method="POST">
        Please select an element:
        <select id="selectedRecord" name="selectedRecord">
            <c:forEach items="${records}" var="record">
            <option value="${record}">${record}</option>
            </c:forEach>
        </select>
        <br />
        <input type="submit" value="Show selected record" />
        <c:if test="${not empty selectedRecord}">
            <br />
            You've selected ${selectedRecord}!
        </c:if>
    </form>
    

Now, to run the example, build the project and access to it using http://localhost:8080/YourWebProjectName/RecordServlet. Also, you can set in the web.xml file:

<welcome-file-list>
    <welcome-file>RecordServlet</welcome-file>
</welcome-file-list>

And just run the web project.

Some notes:

  • Use relevant names for the class/methods, I used RecordXXX since you had this AddRecord class (it should be RecordDAO or something more useful to code readers like UserDAO or YourEntityDAO).
  • Distribute your classes through different packages. Every package should contain only relevant classes to its scope i.e. edu.home.dao for DAO classes, edu.home.service for service/business logic classes, and on...



回答2:


Use list in class as return value,

 List<String> sectionName = new ArrayList<String>();

while (resultSet.next())
   sectionName.add(resultSet.getString("section_name"));

then do

 <select name='name'>
 <c:forEach var="parameter" items="${sectionName }"> 
  <option value="${parameter}">${parameter}</option> 
  </c:forEach> 
</select>

Here parameter is meadiator variable to access list variable value You can use String array also




回答3:


First of all, If you are trying to do something with MVC you should decouple your code. JSP file only access to the request with no java code at all.

So your Controller needs to do something like this.

 request.setAttribute("ipsections",added.populateSelect());

and then, in your jsp file

<select name='anything'>
     <c:forEach items="${ipsections}" var="ipsection">
          <option value="${ipsection}">${ipsection}</option>
    </c:forEach>
</select>


来源:https://stackoverflow.com/questions/15149497/retrieve-values-from-jdbc-and-use-jstl-tags-to-call-the-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!