如何将调用对象方法的JSP servlet转换为JSTL? [英] How to translate JSP servlet which calls an object method into JSTL?
问题描述
我刚刚开始在项目中使用JSTL,但是很抱歉,这确实让我感到困惑.
I just started to use JSTL for my project, but sorry to say it's really confusing to me.
我最初使用Number.java
package com.mycompany
public class Number {
private int total;
public static int add (int x, int y) {
return total;
}
在showNumber.jsp
中,我可以使用
<%@page import= "com.mycompany.Number" %>
和内联使用<%= Number.add(5,6) %>
如何在JSTL
中重写此部分?
也可以导入类Number.java
吗?
我尝试了很多不同的事情,例如<c:out value="${Number}.add(5,6)" />
,但仍然找不到解决方案.谢谢.
How can I rewrite this part in JSTL
?
Is that also possible to import the class Number.java
?
I tried so many different things, e.g. <c:out value="${Number}.add(5,6)" />
, but still cannot find a solution. Thanks.
我使用@Victor的方法,它确实起作用.就我而言,我需要重用spring框架中的other变量,例如NumberTwo.java
和totalTwo
作为内部的私有变量.并在此totalTwo
上添加"100".
Edited:
I use @Victor's approach, and it does work. In my case, I need to reuse other's variable from spring framework, say NumberTwo.java
and totalTwo
as private variable inside. And added "100" to this totalTwo
.
对于我需要使用它的src是<spring:param name="secondNumber" value ="${NumberTwo.totalTwo}" />
.
For the src where i need to use it is <spring:param name="secondNumber" value ="${NumberTwo.totalTwo}" />
.
但是,凭直觉我使用了(int) pageContext.getAttribute("NumberTwo.totalTwo")
,它总是让我返回null
.
However, intutively i used (int) pageContext.getAttribute("NumberTwo.totalTwo")
, it always returned me null
.
另一个解决方法是
第一个<c:set var="result" value="${NumberTwo.totalTwo}" />
然后<% String result = (String) pageContext.getAttribute("result"); %>
然后<%= Number.add(result, 100) %>
The other workaround is
first <c:set var="result" value="${NumberTwo.totalTwo}" />
then <% String result = (String) pageContext.getAttribute("result"); %>
and then <%= Number.add(result, 100) %>
推荐答案
不幸的是,无法使用JSTL任意调用方法,JSTL的功能非常有限:
Unfortunately it's not possible to arbitrarily call methods with JSTL, the function capabilities of JSTL are very limited: http://docs.oracle.com/javaee/5/tutorial/doc/bnalg.html . But it's still possible to use your Number class. Here the workaround:
<%@page import= "com.mycompany.Number" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
pageContext.setAttribute("addResult", Number.add(7, 8));
%>
<html>
<body>
JSP 1.x: Result is: <c:out value="${addResult}" /><br/>
JSP 2.x: Result is: ${addResult}
</body>
</html>
使用 pageContext.setAttribute(),方法结果存储在页面上下文中,并且JSTL标记可以访问存储在该上下文中的值(属性).
With pageContext.setAttribute() the method result is stored in the page context, and the JSTL tags can access values (attributes) stored in that context.
注意:第二个输出行"结果是:$ {result} "仅适用于JSP 2 afaik.
Note: the second output line "Result is: ${result}" works only with JSP 2 afaik.
这篇关于如何将调用对象方法的JSP servlet转换为JSTL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!