用于打印内容的 JSP 助手类 [英] JSP helper class for printing content

查看:24
本文介绍了用于打印内容的 JSP 助手类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于 JSP 中代码重用的问题.我有一个 JSP 页面 example.jsp,它发出对数据库的调用并获取结果.我有一个 java 类 HelperClass.java 接受记录并打印出不同的字段

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 HelperClass.java that accepts a record and prints out the different fields

response.getWriter().println

现在我的 JSP 页面也有 HTML,问题是 HelperClass 打印的内容出现在 JSP 页面中的内容之前.例如

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>

输出是

secondline This is the first line

这是一个已知问题.为将内容打印到页面的 JSP 页面设计 HelperClass 的最佳方法是什么?任何指针将不胜感激.

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.

推荐答案

只是不要使用HelperClass 打印数据".这没有任何意义.你有 EL.

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

${bean.property}

仅此而已.使用 servlet 来控制、预处理和后处理请求.使用标签库(例如 JSTL)和 EL 访问和显示后端数据.

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.

这是一个 Servlet 的基本启动示例,它在 JSP 中显示之前对请求进行预处理:

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.
}

这里,Person 只是一个 Javabean 类,它代表了一个现实世界的实体.

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.
}

PersonDAO#list() 方法只是从数据库返回一个 Person 对象的 List:

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;
}

web.xml 中的 servlet 映射到 /personsurl-pattern.JSP 隐藏在 /WEB-INF 中,因此没有人可以直接访问它,而无需先请求 servlet(否则会得到一个空表).

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).

现在,这是 persons.jsp 的样子,它使用 JSTL(只需删除 jstl-1.2.jar/WEB-INF/lib) c:forEach 迭代 List 并使用 EL 访问后端数据和 bean 属性.servlet 已将 List 作为名称为 persons 的请求属性,以便它可以在 EL 中通过 ${persons} 使用.c:forEach 中的每次迭代都会返回一个 Person 实例,以便您可以使用 EL 显示它们的属性.

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>

通过 http://example.com/contextname/persons 调用.就这样.不需要HelperClass 来打印数据";) 要了解有关 JSTL 的更多信息,请查看 Java EE 教程第二部分第 7 章,要了解有关 EL 的更多信息,请查看 Java EE 教程第二部分第 5 章.要了解有关 PersonDAO 背后的更多信息,请查看这篇文章.

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.

这篇关于用于打印内容的 JSP 助手类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆