从视图中的类中检索带注释的字段

时间:2014-08-17 22:05:48

标签: java annotations jstl taglib custom-tags

在我当前的spring项目中,来自我的实体类的atributes有注释来指示应该使用哪种类型的表单控件进行数据输入,如下所示:

@Column(name = "login", unique=true)
@Order(value=1)
@Input(name="login")
private String login;

@Column(name = "senha")
@Order(value=2)
@Input(type="password", name="senha")
private String senha;

@Column(name="nome")
@Order(value=3)
@Input(name="nome")
private String nome;

@Column(name="sobrenome")
@Order(value=4)
@Input(name="sobrenome")
private String sobrenome;

@Column(name="email")
@Order(value=5)
@Input(name="email")
private String email;

我有自定义标签,应该读取注释的属性并向页面添加正确的标签,如:

public class InputTag extends TagSupport {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public void doTag() throws IOException, NoSuchFieldException, SecurityException {
        JspWriter out = pageContext.getOut();
        String name = this.getName();
        String type = this.getType();
        String pattern = this.getPattern();

        if(type == null) {
            if(pattern == "") {
                out.println("<form:input path=\""+name+"\" class=\"form-control\"/>");
            } else {
                out.println("<form:input path=\""+name+"\" class=\"form-control valida\" pattern=\""+pattern+"\"/>");
            }
        } else {
            if(pattern == "") {
                out.println("<form:input path=\""+name+"\" type=\""+type+"\" class=\"form-control\"/>");
            } else {
                out.println("<form:input path=\""+name+"\" type=\""+type+"\" class=\"form-control valida\" pattern=\""+pattern+"\"/>");
            }
        }
    }
    ...
}

标记类中的getter方法具有以下格式:

private String getName() throws NoSuchFieldException, SecurityException {
    Field field = null;
    Annotation annotation = field.getAnnotation(Input.class);
    Input inputAnnotation = (Input) annotation;
    String name = inputAnnotation.name();
    return name;
}

我现在需要的是在我想要添加到页面的变量field中存储的方式。如果我在实体类(类似getClass().getField("<nome>"))中,我知道这样做的方法,但我如何从我的标记类中访问这些信息?

视图以这种方式映射到我的控制器中:

@RequestMapping(value="cadastra")
@PreAuthorize("hasPermission(#user, 'cadastra_'+#this.this.name)")
public String cadastra(Model model) throws InstantiationException, IllegalAccessException {
    model.addAttribute("command", this.entity.newInstance());
    return "private/cadastrar";
}

和jsp代码在这一刻它(只是基本结构):

<c:url value="/${entity}/cadastra" var="cadastra"/>
<form:form method="POST" action="${cadastra}" class="form" enctype="multipart/form-data">

    <button type="submit" class="btn btn-lg btn-primary">cadastrar</button>

</form:form>

任何人都知道如何实现这一目标?

0 个答案:

没有答案