我试图从由servlet设置和调度的jsp页面访问会话属性,但是却收到错误消息“ jsp:attribute必须是标准或自定义操作的子元素”。可能是什么问题,我访问不正确吗?以下是代码段。
Servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
session.setAttribute("Questions", getQuestion());
System.out.println(session.getAttribute("Questions"));
RequestDispatcher req = request.getRequestDispatcher("DisplayQuestions.jsp");
req.forward(request, response);
}
private QuestionBookDAO getQuestion(){
QuestionBookDAO q = new QuestionBookDAO();
q.setQuestion("First Question");
q.setQuestionPaperID(100210);
q.setSubTopic("Java");
q.setTopic("Threads");
return q;
}
我能够成功设置会话属性。但是,当我尝试在我的jsp文件(如下)中访问相同文件时,出现运行时错误
<jsp:useBean id="Questions" type="com.cet.evaluation.QuestionBook" scope="session">
<jsp:getProperty property="Questions" name="questionPaperID"/>
<jsp:getProperty property="Questions" name="question"/>
</jsp:useBean>
Bean QuestionBook包含两个私有变量questionPaperID和question
我在Tomcat上运行该应用程序,以下是引发的错误。
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: /DisplayQuestions.jsp(15,11) jsp:attribute must be the subelement of a standard or custom action
org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:40)
org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:407)
org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:88)
org.apache.jasper.compiler.Parser.parseStandardAction(Parser.java:1160)
org.apache.jasper.compiler.Parser.parseElements(Parser.java:1461)
org.apache.jasper.compiler.Parser.parseBody(Parser.java:1670)
org.apache.jasper.compiler.Parser.parseOptionalBody(Parser.java:1020)
....
最佳答案
您绝对应该避免使用<jsp:...>
标记。它们是过去的遗物,现在应始终避免使用。
使用JSTL。
现在,无论您使用JSTL还是任何其他标签库,访问bean属性都需要您的bean具有此属性。属性不是私有实例变量。这是一个可通过公共获取器(如果属性可写,则是setter)可访问的信息。要访问questionPaperID属性,您需要具有一个
public SomeType getQuestionPaperID() {
//...
}
bean中的方法。
一旦有了,就可以使用以下代码显示此属性的值:
<c:out value="${Questions.questionPaperID}" />
或者,专门针对会话范围的属性(如果范围之间发生冲突):
<c:out value="${sessionScope.Questions.questionPaperID}" />
最后,我建议您将范围属性命名为Java变量:以小写字母开头。
关于jsp - jSTL上的访问 session 属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4889431/