JSP helper class for printing content

前端 未结 1 1842
忘了有多久
忘了有多久 2020-11-30 14:25

I have a question on code reuse in JSP. I have a JSP page example.jsp that issues a call to a database and gets the results. I have a java class HelperCla

相关标签:
1条回答
  • 2020-11-30 14:56

    Just do not use a "HelperClass to print data". This makes no sense. There you have EL for.

    ${bean.property}
    

    That's all. Use a servlet to control, preprocess and postprocess requests. Use taglibs (e.g. JSTL) and EL to access and display backend data.

    Here's a basic kickoff example of a Servlet which preprocesses the request before display in JSP:

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Person> persons = personDAO.list(); // Get list of persons from DB.
        request.setAttribute("persons", persons); // So it's available as `${persons}` in EL.
        request.getRequestDispatcher("/WEB-INF/persons.jsp").forward(request, response); // Forward to JSP for display.
    }
    

    Here, the Person is just a Javabean class which represents a real world entity.

    public class Person {
        private Long id;
        private String name;
        private String email;
        private Integer age;
        // Add/generate getters and setters here.
    }
    

    The PersonDAO#list() method just returns a List of Person objects from the DB:

    public List<Person> list() throws SQLException {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        List<Person> persons = new ArrayList<Person>();
    
        try {
            connection = database.getConnection();
            statement = connection.createStatement("SELECT id, name, email, age FROM person");
            resultSet = statement.executeQuery();
            while (resultSet.next()) {
                Person person = new Person();
                person.setId(resultSet.getLong("id"));
                person.setName(resultSet.getString("name"));
                person.setEmail(resultSet.getString("email"));
                person.setAge(resultSet.getInteger("age"));
                persons.add(person);
            }
        } finally {
            if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}
            if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
            if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
        }
    
        return persons;
    }
    

    Map the servlet in web.xml on an url-pattern of /persons. The JSP is hidden in /WEB-INF so that nobody can access it directly without requesting the servlet first (else one would get an empty table).

    Now, here's how persons.jsp look like, it uses JSTL (just drop jstl-1.2.jar in /WEB-INF/lib) c:forEach to iterate over a List and it uses EL to access the backend data and bean properties. The servlet has put the List<Person> as request attribute with name persons so that it's available by ${persons} in EL. Each iteration in c:forEach gives a Person instance back, so that you can display their proeprties with EL.

    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    
    ...
    
    <table>
        <c:forEach items="${persons}" var="person">
            <tr>
                <td>${person.name}</td>
                <td>${person.email}</td>
                <td>${person.age}</td>
            </tr>
        </c:forEach>
    </table>
    

    Call it by http://example.com/contextname/persons. That's all. No need for a "HelperClass to print data" ;) To learn more about JSTL, check Java EE tutorial part II chapter 7 and to learn more about EL, check Java EE tutorial part II chapter 5. To learn more about stuff behind PersonDAO, check this article.

    0 讨论(0)
提交回复
热议问题