javax.el.PropretyNotWritableException:类Article没有可写属性'id'

rom*_*ome 9 jsf el primefaces jsf-2

我有文章DTO(Article.java;代码摘录)

public class Article {

private int id;

public Article() {
    this.id = 0;
}

public Integer getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}
Run Code Online (Sandbox Code Playgroud)

我有一个用于编辑文章的视图模板(edit_article.xhtml;代码摘录):

            <h:form id="article_form">
                <p:messages id="messages"/>
                <h:panelGrid columns="2">
                    <h:outputText value="" />
                    <h:inputHidden id="articleId" value="#{hqArticleView.article.id}" converter="javax.faces.Integer" />

                </h:panelGrid>
            </h:form>
Run Code Online (Sandbox Code Playgroud)

我有一个视图支持bean(HqArticleView.java;代码摘录):

@Named("hqArticleView")
@RequestScoped
public class HqArticleView implements Serializable {

/**
 * 
 */
private static final long serialVersionUID = 1L;
private Logger log;

@Inject
private IArticleService articleService;

private Article article;
private List<Article> articles;
private Map<String, String> requestParams;

@PostConstruct
private void init() {
    log = LoggerFactory.getLogger(getClass());

    requestParams = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();

    article = new Article();
    article.setPublish(true);

    if (requestParams.containsKey("id")) {
        article.setId(Integer.parseInt(requestParams.get("id")));
        article = articleService.getArticle(article);
    }
}

public Article getArticle() {
    return article;
}

public void setArticle(Article article) {
    this.article = article;
}

public List<Article> getArticles() {
    articles = articleService.getAll();
    Collections.reverse(articles);
    return articles;
}

public void save() {
    log.debug("save pressed");
}

public void edit(Article article) {
    log.debug("edit pressed | id=" + article.getId());
}

public void delete(Article article) {
    log.debug("delete pressed | id=" + article.getId());
}
}
Run Code Online (Sandbox Code Playgroud)

问题是:我尝试访问视图我收到错误:类文章没有可写属性'id'.文章中的所有其他字段都正确处理,只有id是一个问题.奇怪的是,当我在bean中包装了对象的get getter和setter时:

public void setId(int id){
    this.article.setId(id);
}

public int getId(){
    return this.article.getId();
}
Run Code Online (Sandbox Code Playgroud)

然后它完美地运作.我错过了什么?

Bal*_*usC 21

在检查属性类型以进行读取时,EL会查看getter的返回类型:

public Integer getId() {
    return id;
}
Run Code Online (Sandbox Code Playgroud)

它就是这种类型Integer.当EL需要写入更改后的值时,EL期望一个setter采用相同的类型:

public void setId(Integer id) {
    this.id = id;
}
Run Code Online (Sandbox Code Playgroud)

但是,你Article班上没有这样的二传手.相反,你是一个制定者int.这就是为什么EL扔了一个PropertyNotWritableException.这意味着它无法找到完全相同类型的匹配setter.通过使用Integer而不是int在setter中(或者,在这种特殊情况下更好地,通过使用int而不是Integer在getter中)来相应地修复它.

当你在控制器中爆炸模型时(顺便说一下,糟糕的做法)它是有效的,因为getter和setter相互匹配.