自定义FacesServlet <url-pattern>以摆脱.xhtml扩展名</url-pattern>

时间:2013-08-29 10:21:50

标签: jsf jsf-2 friendly-url

我有Login.xhtmlHome.xhtml。我在web.xml中配置了url模式,如下所示

<servlet-mapping>
   <servlet-name>Faces Servlet</servlet-name>
   <url-pattern>/faces/*</url-pattern>
</servlet-mapping>

<welcome-file-list>
  <welcome-file>Login.xhtml</welcome-file>
</welcome-file-list>

当我运行整个项目时,登录页面URL就像这个http://localhost:8080/fran/Login.xhtml,这里fran是我的项目名称..

但是,我希望它是http://localhost:8080/fran/Login/而不是http://localhost:8080/fran/Login.xhtml

我怎样才能做到这一点?是否可以为每个页面自定义<url-pattern>以摆脱.xhtml扩展名?

2 个答案:

答案 0 :(得分:14)

如果您的唯一理由是摆脱.xhtml扩展名,那么根据您使用的JSF版本,有多种方式。

JSF 2.3 +

JSF 2.3提供了一个新的API来收集所有视图:ViewHandler#getViews()。将其与ServletContextListener中的ServletRegistration#addMapping()结合使用,如下所示。

@FacesConfig
@WebListener
public class ApplicationConfig implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent event) {
        addExtensionLessMappings(event.getServletContext(), FacesContext.getCurrentInstance());
    }

    private void addExtensionLessMappings(ServletContext servletContext, FacesContext facesContext) {
        servletContext
            .getServletRegistrations().values().stream()
            .filter(servlet -> servlet.getClassName().equals(FacesServlet.class.getName()))
            .findAny()
            .ifPresent(facesServlet -> facesContext
                .getApplication()
                .getViewHandler()
                .getViews(facesContext, "/", ViewVisitOption.RETURN_AS_MINIMAL_IMPLICIT_OUTCOME)
                .forEach(view -> facesServlet.addMapping(view))
        );
    }
}

实际上,这是一个oneliner。来源:The Definitive Guide to JSF

JSF 2.2 -

使用OmniFaces FacesViews。它提供了一种零配置方式,通过将视图文件放在/WEB-INF/faces-views/文件夹中来实现。否则,如果您打算不修改项目结构并希望将视图文件保留在通常位置并仍然可以使用无扩展名URL,则需要添加以下上下文参数:

<context-param>
    <param-name>org.omnifaces.FACES_VIEWS_SCAN_PATHS</param-name>
    <param-value>/*.xhtml</param-value>
</context-param>

如果你不想使用OmniFaces,而是想要自己开发,只需看看OmniFaces的source code。它是Apache 2.0许可下的开源软件。它不仅仅是一个oneliner。

答案 1 :(得分:3)

看看prettyfaces: Pretty URLs for JavaServer Faces

看看 2。在主页

中创建pretty-config.xml示例

并查看Chapter 2. Get Started