Embedded jetty ServletTester serving single static file
I'm unit testing with jetty and I want to serve not only my servlet under test but a static page as well. The static page is needed by my application. I'm initializing jetty like this
tester = new ServletTester();
tester.setContextPath("/context");
tester.addServlet(MyServlet.class, "/servlet/*");
tester.start();
What I need now, is something like
开发者_开发百科tester.addStaticPage("local/path/in/my/workspace", "/as/remote/file");
Is this possible with jetty?
I don't think you can do this with ServletTester. ServletTester creates a single Context for the servlet. You need to set up embedded jetty with at least two contexts: one for the servlet, and one for the static content.
If there was a full WebAppContext, you'd be set, but there isn't.
You could make a copy of ServletTester and add hair, or you can just read up on the API and configure the necessary contexts. Here's a code fragment to show you the basic idea, you will not be able to compile this as-is. You will need to create a suitable context for the static content.
server = new Server();
int port = Integer.parseInt(portNumber);
if (connector == null) {
connector = createConnector(port);
}
server.addConnector(connector);
for (Webapp webapp : webapps) {
File sourceDirFile = new File(webapp.getWebappSourceDirectory());
WebAppContext wac = new WebAppContext(sourceDirFile.getCanonicalPath(), webapp.getContextPath());
WebAppClassLoader loader = new WebAppClassLoader(wac);
if (webapp.getLibDirectory() != null) {
Resource r = Resource.newResource(webapp.getLibDirectory());
loader.addJars(r);
}
if (webapp.getClasspathEntries() != null) {
for (String dir : webapp.getClasspathEntries()) {
loader.addClassPath(dir);
}
}
wac.setClassLoader(loader);
server.addHandler(wac);
}
server.start();
Set the resource base to the directory containing your static content, and add the jetty "default servlet" to serve that content. I have added the appropriate code to your example below.
tester = new ServletTester();
tester.setContextPath("/context");
tester.setResourceBase("/path/to/your/content");
tester.addServlet(MyServlet.class, "/servlet/*");
tester.addServlet(org.eclipse.jetty.servlet.DefaultServlet.class, "/*");
tester.start();
精彩评论