jsp:param with Java class

感情迁移 提交于 2019-12-22 01:54:03

问题


I have a JSP file that includes another JSP file. The first JSP should pass an instance of a Java class (widget) to the second JSP file.

This is what I have:

The first JSP:

<jsp:include page="/container/SpecialWidget.jsp">
     <jsp:param name="widget" value="${widget}"/> // widget is a .Java POJO
</jsp:include>

The second JSP:

${param.widget.id}

The problem is that this code gives an error (it says it doesn't know ID). If I omit the ".id" part, the page prints the Java code for the Java class, which means the class has been transferred correctly. If I change the ${widget} rule of the first page in, for example, ${widget.id} and I try to print ${param.widget}, everything works fine.

My question: Why can't I pass a Java class and directly call upon its attributes? What am I doing wrong?

Edit: error message: Caused by: javax.el.PropertyNotFoundException: Property 'id' not found on type java.lang.String


回答1:


When you pass the variable ${widget} it is translated at request time to a string (widget.toString()). This value is then passed to the second JSP as a String, not as the original java object.

One approach to access the object's values is setting the parameter's value with the attribute's value:

<jsp:param name="widgetId" value="${widget.id}"/>

Then use the code bellow on the second JSP:

${param.widgetId}

You can also set widget as an request attribute and use it on the second page as ${widget.id} or ${request.widget.id}. I suggest you use the second approach.




回答2:


I managed to fix my problem with the following code:

<c:set var="widget" value="${widget}" scope="request" />
<jsp:include page="/SOMEWHERE/SpecialWidget.jsp"/>

Thank you both for your help:) It saved my day




回答3:


<jsp:param> passes the parameter as an HTTP request parameter, which can only be a String. So toString() is called on your widget, and the result of this method is passed as parameter.

You should use a JSP tag, implemented as a tag file, instead of using a JSP include. See http://docs.oracle.com/javaee/1.4/tutorial/doc/JSPTags5.html for how to define an use them.

For example:

Tag definintion, in /WEB-INF/tags/specialWidget.tag:

<%@ tag %>
<%@ attribute name="widget" required="true" type="the.fully.qualified.name.of.WidgetClass" %>
TODO: add the HTML markup that must be displayed, using ${widget} to access the passed in widget attribute

Tag usage, in any JSP:

<%@ taglib prefix="myTags" tagdir="/WEB-INF/tags" %>
...
Tada! I will use the specialWidget tag here, with widget as an attribute:
<myTags:specialWidget widget="${widget}"/>


来源:https://stackoverflow.com/questions/13496889/jspparam-with-java-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!