在JSF表单提交上保留GET请求查询字符串参数

在JSF表单提交上保留GET请求查询字符串参数,jsf,jsf-2,navigation,http-request-parameters,Jsf,Jsf 2,Navigation,Http Request Parameters,我有3页: main.xhtml agreement.xhtml generated.xhtml agreement.xhtml需要两个参数才能正确加载:serviceId和site。所以,一个普通的url看起来是这样的:/app/agreement.xhtml?site=US&serviceId=AABBCC 我在agreement.xhtml <h:form> <h:commandButton value="Generate License File" actio

我有3页:

  • main.xhtml
  • agreement.xhtml
  • generated.xhtml
agreement.xhtml
需要两个参数才能正确加载:
serviceId
site
。所以,一个普通的url看起来是这样的:
/app/agreement.xhtml?site=US&serviceId=AABBCC

我在
agreement.xhtml

<h:form>
   <h:commandButton value="Generate License File" action="#{agreement.generateMethod}" />   
</h:form>
我需要在单击时执行
generateMethod()
方法,完成后,用户被重定向到
generated.xhtml
页面。所发生的情况是,点击后,页面浏览器会将用户发送到
/app/agreement.xhtml
,由于它没有发送参数
site
serviceId
,因此会崩溃


我试着让
generateMethod()
返回一个
“generated?faces redirect=true”
,但仍然没有结果。有什么想法吗?

您的
生成方法必须返回

return "generated?site=US&amp;serviceId=AABBCC&amp;faces-redirect=true";
您甚至可以替换
&&
编码>但在xhtml中转义它

generated.xhtml
中,您可以像下面这样捕获通过
传递的参数

<f:metadata>
    <f:viewParam name="site" value="#{yourBean.site}"/><!--Make sure you have a setter-->
    <f:viewParam name="serviceId" value="#{yourBean.serviceId}"/><!--Make sure you have a setter-
</f:metadata>
<h:head>


您的具体问题是由于JSF
默认情况下提交到当前请求URL而没有任何查询字符串。仔细查看生成的HTML输出,您将看到


因此,您需要自己明确地包含这些请求参数。有几种方法可以解决这个问题。如果没有发送重定向,那么可以将它们作为隐藏输入添加到JSF表单中

<h:form>
    <input type="hidden" name="site" value="#{param.site}" />
    <input type="hidden" name="site" value="#{param.serviceId}" />
    ...
</h:form>
生成的目标页面
。xhtml


现在,您可以发送包含视图参数的重定向,如下所示:

public String generateMethod() {
    // ...

    return "generated?faces-redirect=true&includeViewParams=true";
}
请注意,bean应该是
@viewscope
,以便在打开表单页面和提交表单之间以及在验证错误时保持这些参数的活动状态。否则,当坚持使用
@RequestScoped
bean时,您应该将它们作为
保留在命令组件中:

<h:commandButton ...>
    <f:param name="site" value="#{generated.site}" />
    <f:param name="serviceId" value="#{generated.serviceId}" />
</h:commandButton>
基本上就这些。这将生成包含当前查询字符串的


然后,这些请求参数仅在表单submit的请求参数映射中可用。您不需要额外的元数据/视图参数,也不需要发送重定向,如果需要,您的bean可以保持
@requestscope

public String generateMethod() {
    // ...

    return "generated";
}
或者,如果您正在使用一个“漂亮的URL”库,例如PrettyFaces或FacesView,或者是一些自制的东西,并且打算提交到与浏览器地址栏中显示的URL完全相同的URL,那么您可以使用
useRequestURI


另见:

使用面重定向=真。参见此[问题][1][1]:将原始
h:form
切换到
o:form
后,
h:input
s、
h:message
和其他元素在原始
h:form
中是否仍然有效?或者是否需要做任何额外的工作?原始commandButton(键入
submit
,使用POST)也可以返回
void/null
public String generateMethod() {
    // ...

    return "generated";
}