⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 staticinterceptor.java

📁 低版本的tomcat 对于有些老版本的应用还真的需要老版的中间件
💻 JAVA
📖 第 1 页 / 共 2 页
字号:

/** Serve the content of a file ( and nothing more !).
 *
 */
class FileHandler extends ServletWrapper  {
    int realFileNote;
    
    FileHandler() {
	initialized=true;
	internal=true;
	name="tomcat.fileHandler";
    }

    public void setNoteId( int n ) {
	realFileNote=n;
    }

    public void doService(Request req, Response res)
	throws Exception
    {
	// if we are in include, with req==original request
	// - just use the current sub-request
	Request subReq=req;
	if(req.getChild()!=null) 
	    subReq=req.getChild();

	Context ctx=subReq.getContext();
    // If this file is being included, use javax.servlet.include.servlet_path.
    String pathInfo = (String)subReq.getAttribute("javax.servlet.include.servlet_path");
    if(pathInfo == null)
        pathInfo=subReq.getServletPath();
	String absPath = (String)subReq.getNote( realFileNote );
	if( absPath==null ) 
	    absPath=ctx.getRealPath( pathInfo );

	if( debug>0) log( "Requested file = " + absPath);
	String base = ctx.getAbsolutePath();
	absPath = extraCheck( base, absPath );
	if( absPath==null ) {
	    context.getContextManager().handleStatus( req, res, 404);
	    return;
	}

	File file = new File( absPath );
	if( debug>0) log( "After paranoic checks = " + absPath);
	
	String mimeType=ctx.getMimeMap().getContentTypeFor(absPath);

	if (mimeType == null) {
	    mimeType = "text/plain";
	}
	if( debug>0) log( "Serving  " + absPath);
	
	res.setContentType(mimeType);
	res.setContentLength((int)file.length());

	setDateHeader(res, "Last-Modified", file.lastModified());

	FileInputStream in=null;
	try {
	    in = new FileInputStream(file);

	    if( res.isUsingWriter() ) {
		InputStreamReader r = new InputStreamReader(in);
		PrintWriter out=res.getWriter();
		char[] buf = new char[1024];
		int read = 0;
		
		while ((read = r.read(buf)) != -1) {
		    out.write(buf, 0, read);
		}
	    } else {
		OutputStream out=res.getOutputStream();
		byte[] buf = new byte[1024];
		int read = 0;
		
		while ((read = in.read(buf)) != -1) {
		    out.write(buf, 0, read);
		}
	    } 
	} catch (FileNotFoundException e) {
	    // Figure out what we're serving
	    context.getContextManager().handleStatus( req, res, 404);
	} finally {
	    if (in != null) {
		in.close();
	    }
	}
    }

    static void setDateHeader( Response res, String name, long value ) {
	MimeHeaders headers=res.getMimeHeaders();
	MimeHeaderField headerF=headers.find( name );
	if( headerF == null )
	    headerF=headers.putHeader();
	headerF.setName( name );
	headerF.setDateValue( value );
    }

    /** All path checks that were part of DefaultServlet
     */
    String extraCheck( String base, String absPath ) {
	// Extra safe 
	if (absPath.endsWith("/") ||
	    absPath.endsWith("\\") ||
	    absPath.endsWith(".")) {
	    log("Ends with \\/. " + absPath);
	    return null;
	}
    if (absPath.length() > base.length())
	{
		String relPath=absPath.substring( base.length() + 1);
		if( debug>0) log( "RelPath = " + relPath );

		String relPathU=relPath.toUpperCase();
		if ( relPathU.startsWith("WEB-INF") ||
                     relPathU.startsWith("META-INF") ||
                    (relPathU.indexOf("/WEB-INF/") >= 0) ||
                    (relPathU.indexOf("/META-INF/") >= 0) ) {
			return null;
		}
	}
	return absPath;
    }


}

// -------------------- Directory --------------------

/** HTML-display for directories ( and nothing more !).
 *  This is the handler for static resources of type "dir".
 */
class DirHandler extends ServletWrapper  {
    private static final String datePattern = "EEE, dd MMM yyyyy HH:mm z";
    int realFileNote;
    
    DirHandler() {
	initialized=true;
	internal=true;
	name="tomcat.dirHandler";
    }

    public void setNoteId( int n ) {
	realFileNote=n;
    }

    public void doService(Request req, Response res)
	throws Exception
    {
	// this is how get locale is implemented. Ugly, but it's in
	// the next round of optimizations
	Locale locale=RequestUtil.getLocale(req);
	StringManager sm=StringManager.
	    getManager("org.apache.tomcat.resources",locale);
	DateFormat dateFormat =
	    new SimpleDateFormat(datePattern,locale );

	boolean inInclude=req.getChild()!=null;
	Request subReq=req;
	if( inInclude ) subReq = req.getChild();
	Context ctx=req.getContext();
	String pathInfo=subReq.getServletPath();
	if( pathInfo == null ) pathInfo="";
	String absPath=ctx.getRealPath( pathInfo );
	File file = new File( absPath );
	String requestURI=subReq.getRequestURI();
	String base = ctx.getAbsolutePath();
	if (absPath.length() > base.length())
	{
		String relPath=absPath.substring( base.length() + 1);
		String relPathU=relPath.toUpperCase();
		if ( relPathU.startsWith("WEB-INF") ||
				relPathU.startsWith("META-INF")) {
			context.getContextManager().handleStatus( req, res, 404);
			return;
		}
	}

	StringBuffer buf = new StringBuffer();
	
	if (! inInclude) {
	    res.setContentType("text/html");
	    buf.append("<html>\r\n");
	    buf.append("<head>\r\n");
	    buf.append("<title>")
		.append(sm.getString("defaultservlet.directorylistingfor"))
		.append(requestURI);
	    buf.append("</title>\r\n</head><body bgcolor=white>\r\n");
	}

	buf.append("<table width=90% cellspacing=0 ");
	buf.append("cellpadding=5 align=center>");
	buf.append("<tr><td colspan=3><font size=+2><strong>");
	buf.append(sm.getString("defaultservlet.directorylistingfor"))
	    .append(requestURI);
	buf.append("</strong></td></tr>\r\n");

	if (! pathInfo.equals("/")) {
	    buf.append("<tr><td colspan=3 bgcolor=#ffffff>");
	    //buf.append("<a href=\"../\">Up one directory");
	    
	    String toPath = requestURI;

	    if (toPath.endsWith("/")) {
		toPath = toPath.substring(0, toPath.length() - 1);
	    }
	    
	    toPath = toPath.substring(0, toPath.lastIndexOf("/"));
	    
	    if (toPath.length() == 0) {
		toPath = "/";
	    }
	    
	    buf.append("<a href=\"" + toPath + "\"><tt>"+
		       sm.getString("defaultservlet.upto")+ toPath);
	    buf.append("</tt></a></td></tr>\r\n");
	}

	// Pre-calculate the request URI for efficiency

	// Make another URI that definitely ends with a /
	String slashedRequestURI = null;

	if (requestURI.endsWith("/")) {
	    slashedRequestURI = requestURI;
	} else {
	    slashedRequestURI = requestURI + "/";
	}

	String[] fileNames = file.list();
	boolean dirsHead=true;
	boolean shaderow = false;

	for (int i = 0; i < fileNames.length; i++) {
	    String fileName = fileNames[i];

	    // Don't display special dirs at top level
	    if( (pathInfo.length() == 0 || "/".equals(pathInfo)) &&
     		"WEB-INF".equalsIgnoreCase(fileName) ||
 	    	"META-INF".equalsIgnoreCase(fileName) )
    		continue;

	    File f = new File(file, fileName);

	    if (f.isDirectory()) {
		if( dirsHead ) {
		    dirsHead=false;
		    buf.append("<tr><td colspan=3 bgcolor=#cccccc>");
		    buf.append("<font size=+2><strong>").
			append( sm.getString("defaultservlet.subdirectories")).
			append( "</strong>\r\n");
		    buf.append("</font></td></tr>\r\n");
		}

	        String fileN = f.getName();

	        buf.append("<tr");

	        if (shaderow) buf.append(" bgcolor=#eeeeee");
		shaderow=!shaderow;
		
	        buf.append("><td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
	        buf.append("<tt><a href=\"")
		    .append(slashedRequestURI)
	            .append(fileN)
		    .append("\">")
		    .append(fileN)
	            .append("/</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;")
	            .append("</tt>\r\n");
	        buf.append("</td><td><tt>&nbsp;&nbsp;</tt></td>");
	        buf.append("<td align=right><tt>");
		buf.append(dateFormat.format(new Date(f.lastModified())));
	        buf.append("</tt></td></tr>\r\n");
	    }
	}

	shaderow = false;
	buf.append("<tr><td colspan=3 bgcolor=#ffffff>&nbsp;</td></tr>");
	boolean fileHead=true;
	
	for (int i = 0; i < fileNames.length; i++) {
	    File f = new File(file, fileNames[i]);

	    if (f.isFile()) {
		String fileN = f.getName();
		
		if( fileHead ) {
		    fileHead=false;
		    buf.append("<tr><td colspan=4 bgcolor=#cccccc>");
		    buf.append("<font size=+2><strong>")
			.append(sm.getString("defaultservlet.files"))
			.append("</strong></font></td></tr>");
		}

		buf.append("<tr");

		if (shaderow) buf.append(" bgcolor=#eeeeee");
		shaderow = ! shaderow;
		
		buf.append("><td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\r\n");

		buf.append("<tt><a href=\"")
		    .append(slashedRequestURI)
		    .append(fileN).append("\">")
		    .append( fileN )
		    .append( "</a>");
		buf.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt>");
		buf.append("</td>\r\n");

		buf.append("<td align=right><tt>");
		displaySize( buf, (int)f.length());
		buf.append("</tt></td>");

		buf.append("<td align=right><tt>");
		buf.append(dateFormat.format(new Date(f.lastModified())));
		buf.append("</tt></td></tr>\r\n");
	    }
	    
	    buf.append("\r\n");
	}
	
	buf.append("<tr><td colspan=3 bgcolor=#ffffff>&nbsp;</td></tr>");
	buf.append("<tr><td colspan=3 bgcolor=#cccccc>");
	buf.append("<font size=-1>");
	buf.append(Constants.TOMCAT_NAME);
	buf.append(" v");
	buf.append(Constants.TOMCAT_VERSION);
	buf.append("</font></td></tr></table>");
	
	if (! inInclude)  buf.append("</body></html>\r\n");

	if( res.isUsingWriter() ) {
	    PrintWriter out=res.getWriter();
	    out.print(buf);
	} else {
	    ServletOutputStream out=res.getOutputStream();
	    out.print(buf.toString());
	}
    }

    void displaySize( StringBuffer buf, int filesize ) {
	int leftside = filesize / 1024;
	int rightside = (filesize % 1024) / 103;  // makes 1 digit
	// To avoid 0.0 for non-zero file, we bump to 0.1
	if (leftside == 0 && rightside == 0 && filesize != 0) 
	    rightside = 1;
	buf.append(leftside).append(".").append(rightside);
	buf.append(" KB");
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -