5

如果这是一个超级简单的问题,我对 Java 和 JSTL 真的很陌生,很抱歉。我试图举一个我在网上找到的例子并让它工作,但我似乎遇到了问题。假设发生的所有事情都是您创建一个 java bean 并从 java bean 访问属性。但相反,我在 JSTL jsp:useBean id="students" class="com.beans.Students"中调用类的行上出现空指针异常。这是java类:

package com.beans;

public class Students implements java.io.Serializable
{
    private String firstName = null;
    private int age = 0;

    public Students() {
    }
    public String getFirstName(){
        return firstName;
    }
    public int getAge(){
        return age;
    }
    public void setFirstName(String firstName){
        this.firstName = firstName;
    }
    public void setAge(Integer age){
        this.age = age;
    }
}

我试图在其中访问 Java bean 的 JSTL:

<jsp:useBean id="students" 
                class="com.beans.Students"> 
<jsp:setProperty name="students" property="firstName"
                 value="Zara"/>
<jsp:setProperty name="students" property="age" 
                value="10"/>
</jsp:useBean>

<p>Student First Name: 
<jsp:getProperty name="students" property="firstName"/>
</p>

<p>Student Age: 
<jsp:getProperty name="students" property="age"/>
</p>

堆栈跟踪:

Caused by: org.apache.sling.api.SlingException: An exception occurred processing JSP page /students.jsp at line 18
at org.apache.sling.scripting.jsp.jasper.servlet.JspServletWrapper.handleJspExceptionInternal(JspServletWrapper.java:574)
at org.apache.sling.scripting.jsp.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:499)
at org.apache.sling.scripting.jsp.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:443)
at org.apache.sling.scripting.jsp.JspServletWrapperAdapter.service(JspServletWrapperAdapter.java:59)
at org.apache.sling.scripting.jsp.JspScriptEngineFactory$JspScriptEngine.eval(JspScriptEngineFactory.java:453)
at org.apache.sling.scripting.core.impl.DefaultSlingScript.call(DefaultSlingScript.java:358)
... 174 more
Caused by: java.lang.NullPointerException
at    org.apache.sling.scripting.jsp.jasper.runtime.JspRuntimeLibrary.internalIntrospecthelper(JspRuntimeLibrary.java:322)
at    org.apache.sling.scripting.jsp.jasper.runtime.JspRuntimeLibrary.introspecthelper(JspRuntimeLibrary.java:308)
at org.apache.jsp.students_002d_jsp._jspServ

任何帮助是极大的赞赏!

4

1 回答 1

11

如果您Students在您的 servlet 中的请求上放置了一个对象,执行类似request.setAttribute("students", myStudentObject);的操作,那么您页面上的 JSTL 等价物将是:

<p>Student First Name: <c:out value="${students.firstName}"/></p>

<p>Student Age: <c:out value="${students.age}"/></p>

确保在页面顶部包含 JSTL 核心标签,如下所示:

<%@ taglib prefix="c" 
       uri="http://java.sun.com/jsp/jstl/core" %>

c:out如果您需要担心 XSS 攻击,则使用该标签很好,但如果这不是问题,您可以跳过该c:out标签并使用这样的 EL 表达式:

<p>Student First Name: ${students.firstName}</p>

<p>Student Age: ${students.age}</p>
于 2013-04-21T23:21:42.710 回答