我想使用自定义注释“T9n”来用字符串标签注释类属性。我宁愿这样做,也不愿引用对属性(刚刚在 JSP 页面中定义)具有弱引用的 messages.properties 文件。我想做这样的事情:
注释:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface T9n {
String value();
}
类(class):
public class MyClass {
@T9n("My Variable")
private String variableName;
}
JSP(Spring 表单 JSTL 标签):
<form:label path="variableName"><!-- Access T9n annotation here --></form:label>
<form:input path="variableName" />
这可能吗?我目前的想法是使用自定义 JSP 标签做一些事情,但我无法通过搜索找到任何内容。
最佳答案
我最终实现了一个自定义标签。我发现一篇很好的文章定义了这里的步骤:
http://www.codeproject.com/Articles/31614/JSP-JSTL-Custom-Tag-Library
我获取T9n值的Java代码是:
public class T9nDictionaryTag extends TagSupport {
private String fieldName;
private String objectName;
public int doStartTag() throws JspException {
try {
Object object = pageContext.getRequest().getAttribute(objectName);
Class clazz = object.getClass();
Field field = clazz.getDeclaredField(fieldName);
if (field.isAnnotationPresent(T9n.class)) {
T9n labelLookup = field.getAnnotation(T9n.class);
JspWriter out = pageContext.getOut();
out.print(labelLookup.value());
}
} catch(IOException e) {
throw new JspException("Error: " + e.getMessage());
} catch (SecurityException e) {
throw new JspException("Error: " + e.getMessage());
} catch (NoSuchFieldException e) {
throw new JspException("Error: " + e.getMessage());
}
return EVAL_PAGE;
}
public int doEndTag() throws JspException {
return EVAL_PAGE;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
public void setObjectName(String objectName) {
this.objectName = objectName;
}
}
现在我的 JSP 中看起来像这样:
<form:label path="variableName"><ct:t9n objectName="myObject" fieldName="variableName" /></form:label>
<form:input path="variableName" />
希望这能在某个时候对其他人有所帮助
@Holger - 我可以使用嵌入式 Java 代码,但这看起来很困惑,而且不利于表示层分离。
关于java - 是否可以在JSP中访问方法注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19513200/