Wednesday, February 28, 2007

Customize Tomcat's Static File Serving

Tomcat maps the static file request to DefaultServlet class (org.apache.catalina.servlets.DefaultServlet in Tomcat/server/lib/servlets-default.jar).

If you want to customize file serving the following steps need to be followed.
1. Mapping in web.xml for you application
<servlet>
<servlet-name>CustomFileServlet</servlet-name>
<servlet-class>com.example.servlet.CustomFileServlet</servlet-class>
<init-param>
<param-name>listing</param-name>
<param-value>true</param-value>
<!-- allow browsing directory inside web application -->
</servlet>
<servlet-mapping>
<servlet-name>CustomeFileServlet</servlet-name>
<url-pattern>/</url-pattern>
<!-- Maps all request except the ones which are mapped separately -->
</servlet-mapping>

2. Enable privilege for the application (since server library class is used).
Here is an example context file I created for such a application (Tomcat/conf/Catalina/localhost/customapp.xml)
<?xml version="1.0"?>
<context path="/customapp" docbase="/home/prasad/CustomApp/web" privileged="true" reloadable="true"></context>

3. Write a CustomFileServlet class.
package com.example.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.catalina.servlets.DefaultServlet;
public class CustomFileServlet extends DefaultServlet {
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
if (processRequest(request, response)) {
super.doPost(request, response);
}
}

public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
if (processRequest(request, response)) {
super.doGet(request, response);
}
}

public boolean processRequest(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
String requestURI = request.getRequestURI();
String contextPath = request.getContextPath();

String fileURI = "";
if (requestURI.indexOf(contextPath) != -1) {
// Request URI is CONTEXTPATH + RESOURCE URI
fileURI = requestURI.substring(
requestURI.indexOf(contextPath) +
contextPath.length());
}

boolean checkPassed = false;
// DO SOME CHECKS BEFORE SERVING FILE...

return checkPassed;
}


Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?