我是JSP的新手。我尝试连接MySQL和我的JSP页面,它工作正常。但这是我需要做的。 我有一个名为“balance”的表属性。检索它并使用它来计算一个名为“amount”的新值。 (我不打印“余额”)。
<c:forEach var="row" items="${rs.rows}">
ID: ${row.id}<br/>
Passwd: ${row.passwd}<br/>
Amount: <%=Calculate.getAmount(${row.balance})%>
</c:forEach>
似乎无法在JSTL标记中插入scriptlet。
答案 0 :(得分:124)
您无法直接在EL中调用静态方法。 EL只会调用实例方法。
对于失败的 scriptlet 尝试,您不能混合使用 scriptlet 和EL。使用其中一个。由于 scriptlet 是discouraged十年以来,你应该坚持使用仅限EL的解决方案。
您基本上有2个选项(假设balance
和Calculate#getAmount()
都是double
)。
只需将其包装在实例方法中即可。
public double getAmount() {
return Calculate.getAmount(balance);
}
然后使用它:
Amount: ${row.amount}
或者,将Calculate#getAmount()
声明为EL函数。首先创建一个/WEB-INF/functions.tld
文件:
<?xml version="1.0" encoding="UTF-8" ?>
<taglib
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
version="2.1">
<display-name>Custom Functions</display-name>
<tlib-version>1.0</tlib-version>
<uri>http://example.com/functions</uri>
<function>
<name>calculateAmount</name>
<function-class>com.example.Calculate</function-class>
<function-signature>double getAmount(double)</function-signature>
</function>
</taglib>
使用如下:
<%@taglib uri="http://example.com/functions" prefix="f" %>
...
Amount: ${f:calculateAmount(row.balance)}">
答案 1 :(得分:56)
另一种方法是使用Spring SpEL:
<%@taglib prefix="s" uri="http://www.springframework.org/tags" %>
<s:eval expression="T(org.company.Calculate).getAmount(row.balance)" var="rowBalance" />
Amount: ${rowBalance}
如果您跳过可选var="rowBalance"
,则<s:eval>
将打印表达式的结果以输出。
答案 2 :(得分:4)
也可以使用像StaticInterface这样的Bean
<h:commandButton value="reset settings" action="#{staticinterface.resetSettings}"/>
和bean
package com.example.common;
import com.example.common.Settings;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
@ManagedBean(name = "staticinterface")
@ViewScoped
public class StaticInterface {
public StaticInterface() {
}
public void resetSettings() {
Settings.reset();
}
}
答案 3 :(得分:3)
EL 2.2具有调用方法的内置机制。更多信息:oracle site。 但它无法访问静态方法。虽然你可以通过对象引用来调用它。但我使用另一种解决方案,如本文所述:Calling a Static Method From EL
答案 4 :(得分:3)
如果您的Java类是:
package com.test.ejb.util;
public class CommonUtilFunc {
public static String getStatusDesc(String status){
if(status.equals("A")){
return "Active";
}else if(status.equals("I")){
return "Inactive";
}else{
return "Unknown";
}
}
}
然后你可以在JSP页面中调用静态方法'getStatusDesc',如下所示。
使用JSTL useBean在JSP页面顶部获取类:
<jsp:useBean id="cmnUtilFunc" class="com.test.ejb.util.CommonUtilFunc"/>
然后使用表达式语言调用函数:
<table>
<td>${cmnUtilFunc.getStatusDesc('A')}</td>
</table>
答案 5 :(得分:2)
如果你正在使用struts2,你可以使用
<s:var name='myVar' value="%{@package.prefix.MyClass#myMethod('param')}"/>
然后将html或html标记属性中的'myVar'引用为${myVar}
答案 6 :(得分:2)
根据@Lukas的回答,您可以使用该bean并通过反射调用方法:
@ManagedBean (name = "staticCaller")
@ApplicationScoped
public class StaticCaller {
private static final Logger LOGGER = Logger.getLogger(StaticCaller.class);
/**
* @param clazz
* @param method
* @return
*/
@SuppressWarnings("unchecked")
public <E> E call(String clazz, String method, Object... objs){
final ClassLoader loader = Thread.currentThread().getContextClassLoader();
final List<Class<?>> clasesparamList = new ArrayList<Class<?>>();
final List<Object> objectParamList = new ArrayList<Object>();
if (objs != null && objs.length > 0){
for (final Object obj : objs){
clasesparamList.add(obj.getClass());
objectParamList.add(obj);
}
}
try {
final Class<?> clase = loader.loadClass(clazz);
final Method met = clase.getMethod(method, clasesparamList.toArray(new Class<?>[clasesparamList.size()]));
return (E) met.invoke(null, objectParamList.toArray());
} catch (ClassNotFoundException e) {
LOGGER.error(e.getMessage(), e);
} catch (InvocationTargetException e) {
LOGGER.error(e.getMessage(), e);
} catch (IllegalAccessException e) {
LOGGER.error(e.getMessage(), e);
} catch (IllegalArgumentException e) {
LOGGER.error(e.getMessage(), e);
} catch (NoSuchMethodException e) {
LOGGER.error(e.getMessage(), e);
} catch (SecurityException e) {
LOGGER.error(e.getMessage(), e);
}
return null;
}
}
xhtml,进入命令按钮,例如:
<p:commandButton action="#{staticCaller.call('org.company.Calculate', 'getAmount', row.balance)}" process="@this"/>
答案 7 :(得分:0)
在Struts2或Webwork2中,您可以使用:
<s:set name="tourLanguage" value="@foo.bar.TourLanguage@getTour(#name)"/>
然后在你的jsp中引用#tourLanguage
答案 8 :(得分:0)
<c:forEach var="row" items="${rs.rows}">
ID: ${row.id}<br/>
Passwd: ${row.passwd}<br/>
<c:set var="balance" value="${row.balance}"/>
Amount: <%=Calculate.getAmount(pageContext.getAttribute("balance").toString())%>
</c:forEach>
在此解决方案中,我们将value(通过核心标签)分配给变量,然后在scriplet中获取该变量的值。