在 JSF 托管 bean 构造函数中,我使用请求参数从数据库加载实体。有时,实体不在数据库中,我想显示带有 404 消息的其他 JSF (.xhtml) 页面。
这是托管 bean 的示例:
@ManagedBean(name = "someBean")
@RequestScoped
public class SomeBean implements Serializable {
private static final long serialVersionUID = 1L;
private SomeData someData;
public SomeBean() throws IOException {
someData = ... loads from database using JPA features
if(someData == null){
HttpServletResponse response = (HttpServletResponse) FacesContext
.getCurrentInstance().getExternalContext().getResponse();
response.sendError(404);
}
}
public SomeData getSomeData(){
return someData;
}
}
Run Code Online (Sandbox Code Playgroud)
我配置了类似这样的 web.xml 文件:
<error-page>
<error-code>404</error-code>
<location>/404.xhtml</location>
</error-page>
Run Code Online (Sandbox Code Playgroud)
我有一个 JSF 页面来处理托管 bean 加载的实体。当实体存在时,我将在页面中使用它。像那样:
<h1>#{someBean.someEntity.name}</h1>
<h2>#{someBean.someEntity.description}</h2> …Run Code Online (Sandbox Code Playgroud)