我正在尝试使用一个提供动态数据的自定义servlet和一个将为某些图像提供服务的默认servlet来创建一个嵌入式jetty服务器。我有自定义servlet工作,但我无法弄清楚如何添加默认servlet来提供图像文件。
这就是我的......
private void setUpServer(ServerOptions options){
s = new Server(options.getPort());
this.options = options;
context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
s.setHandler(context);
context.addServlet(new ServletHolder(new DataServlet()), "/data/*");
context.addServlet(new ServletHolder(new DefaultServlet()), "/pictures/*");
}
我无法弄清楚如何将DefaultServlet配置为作为文件服务器工作,并且仍然可以使用自定义DataServelet。
有没有人有任何想法?
答案 0 :(得分:32)
你需要什么:
ServletHolder.setInitParameter(name,value)
完成此操作pathInfoOnly
参数设置为true
(以解决“默认”命名调度程序的特殊情况)<强> AltDefaultServlet.java 强>
package jetty.demo;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
public class AltDefaultServlet
{
public static void main(String[] args)
{
System.setProperty("org.eclipse.jetty.LEVEL","INFO");
Server server = new Server();
ServerConnector connector = new ServerConnector(server);
connector.setPort(8080);
server.addConnector(connector);
// The filesystem paths we will map
String homePath = System.getProperty("user.home");
String pwdPath = System.getProperty("user.dir");
// Setup the basic application "context" for this application at "/"
// This is also known as the handler tree (in jetty speak)
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setBaseResource(Resource.newResource(pwdPath));
context.setContextPath("/");
server.setHandler(context);
// add a simple Servlet at "/dynamic/*"
ServletHolder holderDynamic = new ServletHolder("dynamic", DynamicServlet.class);
context.addServlet(holderDynamic, "/dynamic/*");
// add special pathspec of "/home/" content mapped to the homePath
ServletHolder holderHome = new ServletHolder("static-home", DefaultServlet.class);
holderHome.setInitParameter("resourceBase",homePath);
holderHome.setInitParameter("dirAllowed","true");
holderHome.setInitParameter("pathInfoOnly","true");
context.addServlet(holderHome,"/home/*");
// Lastly, the default servlet for root content (always needed, to satisfy servlet spec)
// It is important that this is last.
ServletHolder holderPwd = new ServletHolder("default", DefaultServlet.class);
holderPwd.setInitParameter("dirAllowed","true");
context.addServlet(holderPwd,"/");
try
{
server.start();
server.dump(System.err);
server.join();
}
catch (Throwable t)
{
t.printStackTrace(System.err);
}
}
}