当我从javax.faces.resource键入一个不存在的资源的URL时,例如
http://myapp/javax.faces.resource/noexisting.xhtml
我正在获取默认的HTTP 404页面而我的404错误页面没有呈现。我知道FacesServlet正在将状态代码设置为404而不是发送en错误,这就是我从未调用过错误页面的原因。有没有办法覆盖此实现以发送错误而不是设置状态代码?
我正在使用primefaces 3.5和morajara 2.1.14。
感谢您的帮助。
答案 0 :(得分:5)
我自己找到了解决方案。我实现了自己的ResourceHandlder并检查资源是否存在。如果资源不存在,我发送404错误。 如果其他人有同样的问题,这里是代码:
package com.mypackage;
import java.io.IOException;
import javax.faces.application.Resource;
import javax.faces.application.ResourceHandler;
import javax.faces.application.ResourceHandlerWrapper;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import com.sun.faces.util.Util;
public class MyResourceHandler extends ResourceHandlerWrapper {
// Properties
// -----------------------------------------------------------------------------------------------------
private final ResourceHandler wrapped;
public MyResourceHandler (final ResourceHandler wrapped) {
this.wrapped = wrapped;
}
@Override
public ResourceHandler getWrapped() {
return wrapped;
}
/**
* @see javax.faces.application.ResourceHandlerWrapper#isResourceRequest(javax.faces.context.FacesContext)
*/
@Override
public boolean isResourceRequest(final FacesContext context) {
return super.isResourceRequest(context);
}
@Override
public void handleResourceRequest(FacesContext context) throws IOException {
String resourceId = normalizeResourceRequest(context);
if (null != resourceId && resourceId.startsWith(RESOURCE_IDENTIFIER)) {
Resource resource = null;
String resourceName = null;
if (ResourceHandler.RESOURCE_IDENTIFIER.length() < resourceId.length()) {
resourceName = resourceId.substring(RESOURCE_IDENTIFIER.length() + 1);
if (!StringUtils.isEmpty(resourceName)) {
resource =
context
.getApplication()
.getResourceHandler()
.createResource(resourceName,
context.getExternalContext().getRequestParameterMap().get("ln"));
}
}
if (resource == null) {
HttpServletResponse response =
(HttpServletResponse) context.getExternalContext().getResponse();
response.sendError(404);
return;
}
}
super.handleResourceRequest(context);
}
private String normalizeResourceRequest(FacesContext context) {
String path;
String facesServletMapping = Util.getFacesMapping(context);
// If it is extension mapped
if (!Util.isPrefixMapped(facesServletMapping)) {
path = context.getExternalContext().getRequestServletPath();
// strip off the extension
int i = path.lastIndexOf(".");
if (0 < i) {
path = path.substring(0, i);
}
} else {
path = context.getExternalContext().getRequestPathInfo();
}
return path;
}
}