今天看老方的web视频,知道了一个一直迷惑我的东西:
对tomcat下web容器的访问都是Servlet。
相信不知道的同学和我有同样的疑惑:html那些静态资源也是通过Servlet来访问的?
是的,比如客户端访问1.html,tomcat首先会查找1.html这个Servlet,如果找不到,就会去找默认的Servlet,
默认的Servlet又在哪里配置的呢?在$CATALINA_BASE/conf/web.xml里,这个web.xml是所有web共享的
我们可以在这个web.xml里找到那个默认的Servlet
- <servlet>
- <servlet-name>default</servlet-name>
- <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
- <init-param>
- <param-name>debug</param-name>
- <param-value>0</param-value>
- </init-param>
- <init-param>
- <param-name>listings</param-name>
- <param-value>false</param-value>
- </init-param>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>default</servlet-name>
- <url-pattern>/</url-pattern>
- </servlet-mapping>
复制代码
并且发现这个默认的Servlet是随tomcat启动就创建了实例。
这个Servlet就会去加载1.html资源并返回给客户端,找不到1.html就返回一个错误。
源码如下:
- protected void serveResource(HttpServletRequest request,
- HttpServletResponse response,
- boolean content)
- throws IOException, ServletException {
- // Identify the requested resource path
- String path = getRelativePath(request);
- if (debug > 0) {
- if (content)
- log("DefaultServlet.serveResource: Serving resource '" +
- path + "' headers and data");
- else
- log("DefaultServlet.serveResource: Serving resource '" +
- path + "' headers only");
- }
- CacheEntry cacheEntry = resources.lookupCache(path);
- if (!cacheEntry.exists) {
- // Check if we're included so we can return the appropriate
- // missing resource name in the error
- String requestUri = (String) request.getAttribute(
- Globals.INCLUDE_REQUEST_URI_ATTR);
- if (requestUri == null) {
- requestUri = request.getRequestURI();
- } else {
- // We're included, and the response.sendError() below is going
- // to be ignored by the resource that is including us.
- // Therefore, the only way we can let the including resource
- // know is by including warning message in response
- response.getWriter().write(RequestUtil.filter(
- sm.getString("defaultServlet.missingResource",
- requestUri)));
- }
- response.sendError(HttpServletResponse.SC_NOT_FOUND,
- requestUri);
- return;
- }
复制代码
大家可以自己写一个Servlet然后在自己的web项目的web.xml里配置这个Servlet为默认的Servlet,那就访问不了静态页面了,而是去找你配置的那个Servlet
但jsp是个例外,因为jsp本身就是Servlet |
|