将java bean属性传递给JSTL

时间:2013-04-21 17:17:25

标签: java jstl

我是Java和JSTL的新手,很抱歉,如果这是一个非常简单的问题。我试图举一个例子,我在网上找到并开始工作,但我似乎遇到了问题。所有这一切都是你想要创建一个java bean并从java bean访问属性。但是我在JSTL jsp:useBean id =“students”中调用类的行上得到空指针异常                 类= “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

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:9)

如果您在servlet中的请求中放置Students对象执行类似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" %>

如果您需要担心XSS攻击,使用c:out标记很有用,但如果不关心这一点,您可以跳过c:out标记并使用这样的EL表达式:

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

<p>Student Age: ${students.age}</p>