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

查看:90
本文介绍了用于打印内容的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 for。

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

${bean.property}

这就是全部。使用servlet来控制,预处理和后处理请求。使用taglibs(例如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.
}

这里,只是一个表示真实世界实体的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()方法只返回数据库中 List 的 c> c>对象

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

将servlet映射到 web.xml /人 url-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 (只需删除 / WEB-INF / lib 中的-1.2.jarrel =noreferrer> jstl-1.2.jar c:forEach 迭代 List ,它使用EL来访问后端数据和bean属性。 servlet将 List< Person> 作为请求属性,名称为 persons ,以便<$ c $ EL中的c> $ {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天全站免登陆