首页 \ 问答 \ ViewScoped bean在每个请求上构建...第99部分[重复](ViewScoped bean getting constructed on every request… part 99 [duplicate])

ViewScoped bean在每个请求上构建...第99部分[重复](ViewScoped bean getting constructed on every request… part 99 [duplicate])

这个问题在这里已有答案:

ARGH ...这似乎有一百个答案,我还没有找到一个适合我的答案,所以我想我会再次问它。 这是我的情景:

我的网站在技术上有一个页面,其内容被换出,而不是导航到多个页面。 起点是这个块:

<?xml version="1.0" encoding="UTF-8"?>
<f:view xmlns:f="http://java.sun.com/jsf/core"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:ui="http://java.sun.com/jsf/facelets">
  <h:head />
  <h:body>
    <ui:include src="resourceInclude.xhtml" />
    <ui:include src="main.xhtml" />
  </h:body>
</f:view>

resourceInclude.xhtml包含我的css文件:

<?xml version="1.0" encoding="UTF-8"?>
<ui:composition xmlns:h="http://java.sun.com/jsf/html"
  xmlns:ui="http://java.sun.com/jsf/facelets">
  <h:outputStylesheet library="css" name="test.css" target="head" />
</ui:composition>

而main.xhtml是视图:

<?xml version="1.0" encoding="UTF-8"?>
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
  xmlns:ui="http://java.sun.com/jsf/facelets"
  xmlns:h="http://java.sun.com/jsf/html">
  <h:panelGroup styleClass="test-container" layout="block">
    <h:form id="main-form">
      <h:panelGroup styleClass="test-header" layout="block">
        <h:panelGroup styleClass="navigation" layout="block">
          <ul>
            <li><h:commandLink action="#{viewSelector.setModeHome}">
                <h:outputText value="Home" />
              </h:commandLink></li>
            <li><h:commandLink action="#{viewSelector.setModeReports}">
                <h:outputText value="ASAP Reports" />
              </h:commandLink></li>
            <li><h:commandLink action="#{viewSelector.setModeSupport}">
                <h:outputText value="Technical Support" />
              </h:commandLink></li>
            <li><h:commandLink action="#{viewSelector.setModeHelp}">
                <h:outputText value="Help" />
              </h:commandLink></li>
          </ul>
        </h:panelGroup>
      </h:panelGroup>
      <h:panelGroup styleClass="test-content" layout="block">
        <ui:include src="#{viewSelector.modeName}-view.xhtml" />
      </h:panelGroup>
      <h:panelGroup styleClass="test-footer" layout="block">
        <h:messages />
      </h:panelGroup>
    </h:form>
  </h:panelGroup>
</ui:composition>

它由三个h:panelGroup组成。 第一个是一组四个通用导航链接,每个链接更改viewSelector.modeName值,该值用于包含第二个h:panelGroup的内容,因此<ui:include src="#{viewSelector.modeName}-view.xhtml" /> 。 我已经删除了这个例子所以每个视图基本上是这样的:

<?xml version="1.0" encoding="UTF-8"?>
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
  xmlns:ui="http://java.sun.com/jsf/facelets"
  xmlns:h="http://java.sun.com/jsf/html">
  <h:panelGroup styleClass="test-home-view">
    <p>home</p>
  </h:panelGroup>
</ui:composition>

第三个h:panelGroup是调试出错的所有消息的页脚。

无论如何,每次单击其中一个导航链接时,都会调用viewSelector bean的构造函数。 这就是我的viewSelector bean的样子:

package org.mitre.asias.aires.controller;


import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;


import org.apache.log4j.Logger;


@ManagedBean( name="viewSelector" )
@ViewScoped
public class ViewSelector {
    protected static Logger log = Logger.getLogger( ViewSelector.class );
    private Mode mode = Mode.HOME;
    public static final String PORTLET_NAME = "Test";

    public static enum Mode {
        HOME(1, "home"),
        REPORTS(2, "reports"),
        SUPPORT(3, "support"),
        HELP(4, "help");

        private int value;
        private String name;

        private Mode( int value, String name ) {
            this.value = value;
            this.name = name;
        }

        public int getValue() {
            return value;
        }

        public String getName() {
            return name;
        }
    }

    public ViewSelector() {
        log.trace( "constructing new ViewSelector" );
    }

    public Mode getMode() {
        log.trace( "getting mode" );

        return mode;
    }

    public String getModeName() {
        log.debug( "in getmodename" );
        return getMode().getName();
    }

    public String getPortletName() {
        return PORTLET_NAME;
    }

    public boolean isModeReports() {
        return getMode() == Mode.REPORTS;
    }

    public void setMode( Mode mode ) {
        this.mode = mode;
    }

    public void setModeHelp() {
        setMode( Mode.HELP );
    }

    public void setModeHome() {
        setMode( mode = Mode.HOME );
    }

    public void setModeReports() {
        setMode( mode = Mode.REPORTS );
    }

    public void setModeSupport() {
        setMode( mode = Mode.SUPPORT );
    }
}

我知道我必须以错误的方式做某事,否则我会遗漏一些关于JSF如何工作的核心内容。 任何输入?


This question already has an answer here:

ARGH... This seems to have a hundred answers and I haven't found one that works for me, so I guess I will actually ask it again. Here is my scenario:

My site technically has a single page whose contents get swapped out rather than having multiple pages that you navigate to. The starting point is this chunk:

<?xml version="1.0" encoding="UTF-8"?>
<f:view xmlns:f="http://java.sun.com/jsf/core"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:ui="http://java.sun.com/jsf/facelets">
  <h:head />
  <h:body>
    <ui:include src="resourceInclude.xhtml" />
    <ui:include src="main.xhtml" />
  </h:body>
</f:view>

The resourceInclude.xhtml includes my css file:

<?xml version="1.0" encoding="UTF-8"?>
<ui:composition xmlns:h="http://java.sun.com/jsf/html"
  xmlns:ui="http://java.sun.com/jsf/facelets">
  <h:outputStylesheet library="css" name="test.css" target="head" />
</ui:composition>

And main.xhtml is the view:

<?xml version="1.0" encoding="UTF-8"?>
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
  xmlns:ui="http://java.sun.com/jsf/facelets"
  xmlns:h="http://java.sun.com/jsf/html">
  <h:panelGroup styleClass="test-container" layout="block">
    <h:form id="main-form">
      <h:panelGroup styleClass="test-header" layout="block">
        <h:panelGroup styleClass="navigation" layout="block">
          <ul>
            <li><h:commandLink action="#{viewSelector.setModeHome}">
                <h:outputText value="Home" />
              </h:commandLink></li>
            <li><h:commandLink action="#{viewSelector.setModeReports}">
                <h:outputText value="ASAP Reports" />
              </h:commandLink></li>
            <li><h:commandLink action="#{viewSelector.setModeSupport}">
                <h:outputText value="Technical Support" />
              </h:commandLink></li>
            <li><h:commandLink action="#{viewSelector.setModeHelp}">
                <h:outputText value="Help" />
              </h:commandLink></li>
          </ul>
        </h:panelGroup>
      </h:panelGroup>
      <h:panelGroup styleClass="test-content" layout="block">
        <ui:include src="#{viewSelector.modeName}-view.xhtml" />
      </h:panelGroup>
      <h:panelGroup styleClass="test-footer" layout="block">
        <h:messages />
      </h:panelGroup>
    </h:form>
  </h:panelGroup>
</ui:composition>

It consists of three h:panelGroups. The first is a set of four general navigation links, each link changes the viewSelector.modeName value which is used to include the contents in the second h:panelGroup thusly <ui:include src="#{viewSelector.modeName}-view.xhtml" />. I have stripped this down for this example so each view is basically this:

<?xml version="1.0" encoding="UTF-8"?>
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
  xmlns:ui="http://java.sun.com/jsf/facelets"
  xmlns:h="http://java.sun.com/jsf/html">
  <h:panelGroup styleClass="test-home-view">
    <p>home</p>
  </h:panelGroup>
</ui:composition>

The third h:panelGroup is a footer for all the messages to debug what is going wrong.

Anyway, every time I click one of the navigation links, the constructor of the viewSelector bean gets called. This is what my viewSelector bean looks like:

package org.mitre.asias.aires.controller;


import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;


import org.apache.log4j.Logger;


@ManagedBean( name="viewSelector" )
@ViewScoped
public class ViewSelector {
    protected static Logger log = Logger.getLogger( ViewSelector.class );
    private Mode mode = Mode.HOME;
    public static final String PORTLET_NAME = "Test";

    public static enum Mode {
        HOME(1, "home"),
        REPORTS(2, "reports"),
        SUPPORT(3, "support"),
        HELP(4, "help");

        private int value;
        private String name;

        private Mode( int value, String name ) {
            this.value = value;
            this.name = name;
        }

        public int getValue() {
            return value;
        }

        public String getName() {
            return name;
        }
    }

    public ViewSelector() {
        log.trace( "constructing new ViewSelector" );
    }

    public Mode getMode() {
        log.trace( "getting mode" );

        return mode;
    }

    public String getModeName() {
        log.debug( "in getmodename" );
        return getMode().getName();
    }

    public String getPortletName() {
        return PORTLET_NAME;
    }

    public boolean isModeReports() {
        return getMode() == Mode.REPORTS;
    }

    public void setMode( Mode mode ) {
        this.mode = mode;
    }

    public void setModeHelp() {
        setMode( Mode.HELP );
    }

    public void setModeHome() {
        setMode( mode = Mode.HOME );
    }

    public void setModeReports() {
        setMode( mode = Mode.REPORTS );
    }

    public void setModeSupport() {
        setMode( mode = Mode.SUPPORT );
    }
}

I know I must be doing something the wrong way, or else I missing something central as to how JSF works. Any Input?


原文:https://stackoverflow.com/questions/7449873
更新时间:2024-03-09 20:03

最满意答案

这个怎么样:

def toSentiment(sentiment: Int): Sentiment = sentiment match {
    case 0 | 1 ⇒ Sentiment.NEGATIVE
    case 2     ⇒ Sentiment.NEUTRAL
    case 3 | 4 ⇒ Sentiment.POSITIVE
}

请注意,此匹配并非详尽无遗。 如果运行,可能会出现运行时错误,例如: toSentiment(5) 。 有些短裤会警告你这件事。 一个更安全的版本(假设任何其他数字是中立的)可能是:

def toSentiment(sentiment: Int): Sentiment = sentiment match {
    case 0 | 1 ⇒ Sentiment.NEGATIVE
    case 3 | 4 ⇒ Sentiment.POSITIVE
    case _     ⇒ Sentiment.NEUTRAL   
}

How about this:

def toSentiment(sentiment: Int): Sentiment = sentiment match {
    case 0 | 1 ⇒ Sentiment.NEGATIVE
    case 2     ⇒ Sentiment.NEUTRAL
    case 3 | 4 ⇒ Sentiment.POSITIVE
}

Note that this match is not exhaustive. You could get a runtime error if you run, for example: toSentiment(5). Some linters would warn you about this. A safer version (assumming any other number would be neutral) could be:

def toSentiment(sentiment: Int): Sentiment = sentiment match {
    case 0 | 1 ⇒ Sentiment.NEGATIVE
    case 3 | 4 ⇒ Sentiment.POSITIVE
    case _     ⇒ Sentiment.NEUTRAL   
}

相关问答

更多
  • 我们来改进堆垛机的例子,并使用Scala的案例类 : case class Person(firstName: String, lastName: String) 上述Scala类包含以下Java类的所有功能, 还有一些更多 - 例如它支持模式匹配 (Java没有)。 Scala 2.8添加了命名和默认参数,用于为case类生成一个复制方法 ,它赋予与以下Java类的with *方法相同的功能。 public class Person implements Serializable { priva ...
  • _invoke_和_invoke_行为与Ruby的missing_method类似。 在没有实现该方法的动态实例上调用任何方法时,将调用_invoke_或_invoke_ 。 这两种方法可以按照你的意愿实现。 在你的例子中,他们使用反射来调用x成员的实际实现。 例如: scala> val s: Dynamic = "Hello, world!" s: Dynamic = Dynamic(Hello, world!) scala> s.toLowerCase dynatype: line8$object. ...
  • 零填料 String.format("%08d", value) 心灵应该长,超过8位数你会溢出。 With a zero filler String.format("%08d", value) Mind should the long have more than 8 digits you get an overflow.
  • 这个怎么样: def toSentiment(sentiment: Int): Sentiment = sentiment match { case 0 | 1 ⇒ Sentiment.NEGATIVE case 2 ⇒ Sentiment.NEUTRAL case 3 | 4 ⇒ Sentiment.POSITIVE } 请注意,此匹配并非详尽无遗。 如果运行,可能会出现运行时错误,例如: toSentiment(5) 。 有些短裤会警告你这件事。 一个更安全的版本(假设 ...
  • 在我的头顶上,可能有更好的方法: List(a, b, c, d).exists(_.isDefined) and (来自Rob Starling评论): List(a, b, c, d).forall(_.isDefined) 你也可以有更复杂的条件组合: // (a || b) && (c || d) List( List(a, b).exists(_.isDefined), List(c, d).exists(_.isDefined) ).forall(identity) // (a ...
  • 考虑 util.Try(s.toInt).getOrElse(0) 这将在捕捉可能的异常时提供整数值。 从而, def toInt(s: String): Int = util.Try(s.toInt).getOrElse(0) 或者如果Option是优选的, def toInt(s: String): Option[Int] = util.Try(s.toInt).toOption 如果转换失败,则交付None 。 Consider util.Try(s.toInt).getOrElse(0) T ...
  • 您的代码(和Martin的)定义了一个新的Boolean即使它是在Scala中预定义/内置的。 您遇到的问题是您没有定义新的false来取代内置的false ,而内置的false与您重新定义的Boolean不兼容。 Your code (and Martin's) defines a new Boolean even though it's pre-defined / built-in in Scala. The problem you're encountering is that you have no ...
  • Case类不仅定义了equals , hashCode和toString方法,而且还定义了copy 。 幸运的是, copy方法的定义方式是, this对象的当前值是默认参数,但您可以使用命名参数更改它们中的任何一个。 你的例子看起来像这样: case class Type( x : int, y : int, z : int, ) val v = Type(x = 1, y = 2, z = 3) v.copy(z=42) 但是你也可以使用其中一个镜头库。 (我认为scalaz和shape ...
  • 你的解释是正确的。 但你并不需要所有的大括号。 def mul(a: Int)(b: Int) = a*b val mulAB = (a: Int) => { (b: Int) => a*b } // Same as mul _ val mul5B = (b: Int) => 5*b // Same as mulAb(5) or mul(5) _ 一般来说,你可以用多个参数重写任何函数作为咖喱链,而每个参数产生的函数只需要少一个参数,直到最后一个实际产生该值为止: ...
  • 第一行定义了一个类型为Either[String, Int]的变量l 。 Either (抽象)类用于表示何时某些东西可以包含两个可能值中的一个。 Left和Right类是子类,因此是有效赋值。 惯例是使用Left来表示某种失败(例如,描述出错的String ),以及表示某种成功计算/值的权利。 有了这些信息,第二行也是相当自我解释的。 第3行和第4行使用l和r变量上的投影并执行map 。 right方法返回投影..如果left投影Left变量,则可以map内部值。 如果您在Left变量上投影,即使在map ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)