如何将调用对象方法的JSP servlet转换为JSTL? [英] How to translate JSP servlet which calls an object method into JSTL?

查看:83
本文介绍了如何将调用对象方法的JSP servlet转换为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.javatotalTwo作为内部的私有变量.并在此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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆