JSP / JSTL无法正常工作

时间:2013-11-11 19:35:33

标签: jsp jstl

我正在尝试实现JSP应用程序,我需要帮助。有两个问题:

1)JSTL标签不会转换为HTML。

2)如果我在JSP页面中使用普通java而不是JSTL,它仍然无效。

我正在使用netbeans 7.3和tomcat 7以及Java EE 6.我在项目中添加了netbeans 7.3附带的JSTL库(即JSTL 1.1)。

我的web.xml以:

开头
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
     version="3.0">
...
</web-app>

以下是一个示例代码:

public class Item {
    private int id;
    private String name;
// setters and getters follow
}


public class Controller {
    public List<Item> getAllItems() {
        // returns a list of items (size of list = 2)
    }
}

的index.jsp:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <% 
           Controller controller = new Controller(); 
           List<Item> items = controller.getAllItems();
        %>
        <table>
        <c:forEach items="${items}" var="item">
            <tr>
                <td>${item.id}</td>
                <td>${item.name}</td>
            </tr>
        </c:forEach>
</table>
    </body>
</html>

1)jstl代码未转换为html。页面的来源如下:

...
<table>
<c:forEach items="" var="item">
            <tr>
                <td></td>
                <td></td>
            </tr>
  </c:forEach> 
</table>
...

我也试过使用$ {item.getId()}和$ {item.getName()}但结果相同

2)如果我用c替换c:forEach,如下所示:

    <% for (Item item : items) {%>
        <tr>
            <td><%item.getId();%></td>
            <td><%item.getName();%></td>
        </tr>
    <% } %>

我得到以下来源(回想一下List的大小是2):

    ...
        <tr>
            <td></td> 
            <td></td>  
        </tr>           
        <tr>
            <td></td>
            <td></td>    
        </tr>

我做错了什么?我是否正确设置了jstl?请注意,Controller是一个普通的java类,而不是bean。我需要把它做成豆吗?如果有,怎么样? 提前谢谢!

1 个答案:

答案 0 :(得分:-1)

检查web.xml中使用的xsd的版本。在我的情况下,版本需要为2.5,而较旧的版本不显示jsp中的值。并没有抛出任何错误。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
相关问题