嵌入式的Tomcat不提供静态内容 [英] Embedded Tomcat not serving static content
问题描述
我用下面的(基于这个)来创建一个嵌入式Tomcat服务器
I'm using the following (based on this) to create an embedded Tomcat server:
File catalinaHome = new File(".");
File webAppDir = new File("web");
Embedded server = new Embedded();
server.setCatalinaHome(catalinaHome.getAbsolutePath());
Context rootContext = server.createContext("", webAppDir.getAbsolutePath());
rootContext.setParentClassLoader(Thread.currentThread().getContextClassLoader());
Host localHost = server.createHost("localhost", webAppDir.getAbsolutePath());
localHost.addChild(rootContext);
Engine engine = server.createEngine();
engine.setName("localEngine");
engine.addChild(localHost);
engine.setDefaultHost(localHost.getName());
server.addEngine(engine);
Connector http = server.createConnector((InetAddress) null, 8080, false);
server.addConnector(http);
server.setAwait(true);
server.start();
该网站的目录有静态内容(的index.html等)以及与servlet的描述,例如web.xml中WEB-INF目录下。这是开始,无一例外,在web.xml中的工作定义的servlet的,但像index.html的静态内容不工作。
The web directory has static content (index.html, etc.) as well as a WEB-INF directory with servlet descriptors like web.xml. This is starting without exception and the servlets defined in web.xml work, but static content like index.html aren't working.
我很困惑:我缺少什么,以获得静态内容进行处理。
I'm confused: what am I missing to get the static content handled?
推荐答案
您需要定义默认servlet 。这是一个负责提供静态内容。这可以通过在你的webapp的 /WEB-INF/web.xml
相同的方式,Tomcat的自己固定 / conf目录/网页要么明确声明它做的.xml
是干什么的,或者在嵌入式Tomcat的以下声明方式:
You need to define the default servlet. It's the one responsible for serving static content. This can be done by either explicitly declaring it in your webapp's /WEB-INF/web.xml
the same way as Tomcat's own regular /conf/web.xml
is doing, or in the following declarative manner for embedded Tomcat:
// Define DefaultServlet.
Wrapper defaultServlet = rootContext.createWrapper();
defaultServlet.setName("default");
defaultServlet.setServletClass("org.apache.catalina.servlets.DefaultServlet");
defaultServlet.addInitParameter("debug", "0");
defaultServlet.addInitParameter("listings", "false");
defaultServlet.setLoadOnStartup(1);
rootContext.addChild(defaultServlet);
rootContext.addServletMapping("/", "default");
你可能还喜欢为 JSP的servlet做同样如此你也可以使用的JSP:
You'd probably also like to do the same for the JSP servlet so that you can also use JSPs:
// Define JspServlet.
Wrapper jspServlet = rootContext.createWrapper();
jspServlet.setName("jsp");
jspServlet.setServletClass("org.apache.jasper.servlet.JspServlet");
jspServlet.addInitParameter("fork", "false");
jspServlet.addInitParameter("xpoweredBy", "false");
jspServlet.setLoadOnStartup(2);
rootContext.addChild(jspServlet);
rootContext.addServletMapping("*.jsp", "jsp");
这篇关于嵌入式的Tomcat不提供静态内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!