【问题标题】:How do I map URLs to resources instead of JSF pages?如何将 URL 映射到资源而不是 JSF 页面?
【发布时间】:2017-05-27 20:08:01
【问题描述】:

我非常习惯 Jax-RS 以及通过自定义 URL 向调用者提供数据的能力,例如:

/bicycles/by_color/blue

通过做:

@Path("{searchCategory}/{searchParam}")
List<Item> get(@PathParam....

JSF 中的等价物是什么?我有一个带有 ReST API 的应用程序,想显示一个模板页面,根据 xhtml 页面的部分 URL 从数据库中获取特定实体,以从中获取数据。

我见过带有“?id=5&pages=true”之类的查询参数的示例,但没有看到带有“/5/true”之类的 URL 映射的示例。我该如何做到这一点?

【问题讨论】:

标签: jsf url-routing


【解决方案1】:

对于那些在谷歌上搜索问题的实际答案的人,PrettyFaces 是一种方法。它对 URL 进行“美化”,包括将 URL 路径的元素变成可接收的参数。

我将给出一个使用 JAX-RS 的示例,然后是 PrettyFaces 的等价物:

Jax-RS

@Path("user")
public class UserEndpoint{
    @PersistenceContext
    EntityManager em;

    @GET
    @Path("{userid}")
    public UserEntity getUser(@PathParam("userid")long userId){
        return em.find(UserEntity.class, userId);
    }
}

JSF 与 PrettyFaces

这里有很好的帮助:http://www.ocpsoft.org/prettyfaces/

支持 Bean

@Named
public class UserViewController{
    @PersistenceContext
    EntityManager em;

    public UserEntity getUser(){
        ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
        Map<String, String> params = ec.getRequestParameterMap();
        long userId = Long.valueOf(params.get("userid"));
        return em.find(UserEntity.class, userId);
    }
}

pretty-config.xml(必须在 WEB-INF 文件夹中创建的特殊文件)

<pretty-config xmlns="http://ocpsoft.org/schema/rewrite-config-prettyfaces" 
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
            xsi:schemaLocation="http://ocpsoft.org/schema/rewrite-config-prettyfaces
                                http://ocpsoft.org/xml/ns/prettyfaces/rewrite-config-prettyfaces.xsd">

<url-mapping id="view-user">
        <pattern value="/user/#{userid}" />
        <view-id value="/user/view.xhtml" />
    </url-mapping>
</pretty-config>

【讨论】:

    猜你喜欢
    • 2023-03-27
    • 1970-01-01
    • 2022-01-24
    • 2017-12-14
    相关资源
    最近更新 更多