Redirect if a f:viewParam is empty

北战南征 提交于 2019-12-05 12:29:10
BalusC

When I add required="true", nothing happens

You need <h:message(s)> to show faces messages associated with a given (input) component. You probably already know how to do that for <h:inputText>. You can do exactly the same for <f:viewParam>.

<f:metadata>
    <f:viewParam id="foo" ... required="true" />
</f:metadata>
...
<h:message for="foo" />

Сan I do a redirect (or error) if a f:viewParam is empty?

Not directly with standard JSF validation facilities. You'd need to do the job manually in <f:viewAction> (you need to make sure that you don't have any validators/converters on it, otherwise it wouldn't be invoked due to a validation/conversion error; you could alternatively use <f:event type="preRenderView">).

<f:metadata>
    <f:viewParam value="#{bean.foo}" />
    <f:viewAction action="#{bean.checkFoo}" />
</f:metadata>

public String checkFoo() {
    if (foo == null || foo.isEmpty()) {
        return "some.xhtml"; // Redirect to that page.
    } else {
        return null; // Stay on current page.
    }
}

Sending a HTTP error can be done as below (this example sends a HTTP 400 error):

public void checkFoo() {
    if (foo == null || foo.isEmpty()) {
        FacesContext context = Facescontext.getCurrentInstance();
        context.getExternalContext().responseSendError(400, "Foo parameter is required");
        context.responseComplete();
    }
}

If you happen to use the JSF utility library OmniFaces, then you can use the <o:viewParamValidationFailed> tag for the very purpose without needing additional backing bean logic.

Sending a redirect on view param validation fail:

<f:metadata>
    <f:viewParam ... required="true">
        <o:viewParamValidationFailed sendRedirect="some.xhtml" />
    </f:viewParam>
</f:metadata>

Sending a HTTP 400 error on view param validation fail:

<f:metadata>
    <f:viewParam ... required="true">
        <o:viewParamValidationFailed sendError="400" />
    </f:viewParam>
</f:metadata>

See also:

You can add a filter to your page (Filtering requests):

@WebFilter(filterName = "MyFilter")
public class MyFilter implements Filter {

@Override
public void doFilter(ServletRequest request, ServletResponse response,  FilterChain chain)
  throws IOException, ServletException {

  if (request.getParameterMap().get("accountId") == null){
     // do redirect
     return;
    }
   chain.doFilter(request, response); 
  }

}

And rememeber to declare your filter in web.xml file:

<filter>
  <filter-name>MyFilter</filter-name>
  <filter-class>my.filter.classpath.MyFilterclass</filter-class>
</filter>
<filter-mapping>
  <filter-name>MyFilter</filter-name>
  <url-pattern>/url/to/my/page.xhtml</url-pattern>
</filter-mapping>

Also, when working with filters, I suggest to use forward than redirect.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!