Merge pull request #136 from TopCoderMyDream/dev

add:允许自定义ErrorHandler
This commit is contained in:
Wendal Chen 2018-05-08 05:13:02 -07:00 committed by GitHub
commit fd44485fce
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 32 additions and 2 deletions

View File

@ -0,0 +1,25 @@
package io.nutz.demo.simple.handler;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.ErrorHandler;
import org.eclipse.jetty.servlet.ErrorPageErrorHandler;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.lang.util.NutMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@IocBean
public class MyHandler extends ErrorPageErrorHandler {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException {
if(response.getStatus() == 404){
response.getWriter().write(Json.toJson(new NutMap("code","-1").setv("msg","404 error")));
return;
}
super.handle(target, baseRequest, request, response);
}
}

View File

@ -18,6 +18,7 @@ import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.ErrorHandler;
import org.eclipse.jetty.servlet.ErrorPageErrorHandler;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.util.resource.ResourceCollection;
@ -194,8 +195,12 @@ public class JettyStarter extends AbstractServletContainerStarter implements Ser
wac.getServletContext().setExtendedListenerTypes(true);
wac.getSessionHandler().setMaxInactiveInterval(getSessionTimeout());
ErrorPageErrorHandler ep = new ErrorPageErrorHandler();
ep.setErrorPages(getErrorPages());
ErrorHandler ep = Lang.first(appContext.getBeans(ErrorHandler.class));
if(ep == null){
ErrorPageErrorHandler handler = new ErrorPageErrorHandler();
handler.setErrorPages(getErrorPages());
ep = handler;
}
wac.setErrorHandler(ep);
// 设置一下额外的东西