开发者

JSP helper class for printing content

I have a question on code开发者_如何学JAVA 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 HelperClass.java that accepts a record and prints out the different fields

response.getWriter().println

Now my JSP page has HTML as well and the problem is the content printed out by the HelperClass appears before the content in the JSP page. E.g.

<body>
    This is the first line <br/>
    HelperClass.printdata("second line"); 
</body>

output is

secondline This is the first line

Is this a known issue. What is the best way to design an HelperClass for a JSP page that prints content out to the page. Any pointers would be greatly appreciated.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜