JSF单控制器和不同的视图,编辑,更新页面

时间:2012-08-08 13:52:45

标签: jsf-2 crud

我在JSF 2.0中这样做。我已经使用相同的控制器实现了添加和查看页面。我不知道使用同一个控制器是否是最佳做法,是吗?与在this示例中一样,它使用单页进行所有添加,编辑,查看,但我有不同的页面。因此,当从视图页面迁移到编辑页面时,我想保留价值,但我不能。如何保持同一控制器中不同页面之间的值?输出控制台显示编辑 true 更改为 false 的值,我在 editLegendType 函数中将其更改为true。

@ManagedBean
@ViewScoped
public class LegendController implements Serializable {

    LegendDTO legendDTO = new LegendDTO();
    String selectedLegend;
boolean edit;

public LegendController() {
      Logger.getLogger(LegendController.class.getName()).warning("The size of list" + edit);
    if (!edit) {
        legendDTO.getList().add(new Legend());
        Logger.getLogger(LegendController.class.getName()).warning("The size of list" + legendDTO.getList().size());
    }
}


//All function from here is to legend edit
public String editLegendType(LegendDTO dto) {
    edit = true;
    legendDTO = dto;
        Logger.getLogger(LegendController.class.getName()).warning("The size of list" + edit);
        return "addLegend";//from view page to addPage for edit.
    }
}

1 个答案:

答案 0 :(得分:1)

对于多个视图使用相同的控制器是可以的,如果它可以防止代码重复,并且通过使用单独的视图来提高可用性。

很遗憾,您无法继续使用View范围。但有几种选择。您可以使用新的自定义Conversation scope,也可以回退到会话范围。两者都有利弊 - 在谈话范围内,您必须自己进行范围处理。使用会话范围,您可能会在会话中不必要地放入太多数据。

因此,如果我必须选择,我宁愿将会话范围用作会话范围,因为它是更繁琐但更清晰的解决方案。

编辑:请注意,会话范围不是JSF功能,它来自CDI,这意味着您必须将bean上的注释从@ManagedBean更改为@命名

EDIT2:要在tomcat上使用CDI,您需要在类路径中使用它。如果你正在使用maven,请将其添加到.pom,在其他地方,下载并“手动”使用jar。

<dependency>
  <groupId>org.jboss.weld.servlet</groupId>
   <artifactId>weld-servlet</artifactId>
   <version>1.1.9-Final</version>
</dependency>

此外,您必须将此添加到web.xml

<listener>
   <listener-class>
      org.jboss.weld.environment.servlet.Listener
   </listener-class>
</listener>

您可能还需要empty beans.xml。我不确定。