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

📄 httpserver.java

📁 java写的一个很小但是实用的http server
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
				{
					// TODO: warn on duplicate patterns?
					prefixServletMappings.put(
						propValue.substring( 0, propValue.length() - 2 ),
						servletName);
				}
				// else, if extension mapping
				else if( propValue.startsWith( "*." ))
				{
					// TODO: warn on duplicate patterns?
					extensionServletMappings.put(
						propValue.substring( 2 ), servletName);
				}
				// else, if exact or default mapping
				else if( propValue.startsWith( "/" ))
				{
					if( propValue.length() == 1 )
					{
						defaultServletName = servletName;
					}
					// TODO: warn on duplicate patterns?
					exactServletMappings.put( propValue, servletName);
				}
				else
				{
					log( "Invalid servlet mapping: " +
						propName + "=" + propValue );
				}
			}
		}

		if( defaultServletName == null )
		{
			defaultServletName = DEFAULT_SERVLET_NAME;
		}
	}

	/**
	 * Determines servlet path and name based on request path.
	 * Follows procedure described in section 10.1 of the
	 * Java Servlet Specification 2.2.
	 *
	 * @param path The request path (minus any fragment or query string).
	 * @param servletpathAndName is a String[] with a minimum lenth of 2.
	 */
	protected void getServletPathAndName(
		String path, String[] servletPathAndName )
	{
		String servletPath = "/";
		String servletAlias = defaultServletName;

		// Exact match?
		if( exactServletMappings.containsKey( path ))
		{
			servletPath = path;
			servletAlias = (String)exactServletMappings.get( path );
		}
		// Exact prefix match?
		else if( prefixServletMappings.containsKey( path ))
		{
			servletPath = path;
			servletAlias = (String)prefixServletMappings.get( path );
		}
		else
		{
			// Look for longest prefix match
			int matchLength = 0;
			Enumeration prefixEnum = prefixServletMappings.keys();
			while( prefixEnum.hasMoreElements() )
			{
				String prefix = (String)prefixEnum.nextElement();
				if( path.startsWith( prefix )
				&&  path.charAt( prefix.length() ) == '/'
				&&  prefix.length() > matchLength )
				{
					servletPath = prefix;
					servletAlias = (String)prefixServletMappings.get( prefix );
					matchLength = prefix.length();
				}
			}

			// If no prefix match found
			if( matchLength == 0 )
			{
				// Get extension
				int lastDot = path.lastIndexOf( '.' );
				if( lastDot > -1 )
				{
					String ext = path.substring( lastDot + 1 );
					if( extensionServletMappings.containsKey( ext ))
					{
						servletPath = path;
						servletAlias =
							(String)extensionServletMappings.get( ext );
					}
				}
			}
		}

		servletPathAndName[0] = servletPath;
		servletPathAndName[1] =
			servletProperties.getProperty(
				servletAlias + ".name", servletAlias );
	}

	// TODO: Move to utility class?
	protected static boolean matchURL( String pattern, String path)
	{
		if( pattern.length() == 0)
		{
			return path.length() == 0;
		}
		else if( pattern.indexOf('*') < 0)
		{
			return path.equals(pattern);
		}

		StringTokenizer tokenizer = new StringTokenizer(pattern, "*");
		String fragment = "";
		int pos = 0;

		// the path must start with the first fragment if the
		// pattern doesn't start with a wildcard
		if( !pattern.startsWith("*"))
		{
			fragment = tokenizer.nextToken();
			if( !path.startsWith(fragment))
			{
				return false;
			}
			// return now if no more tokens are present
			if( !tokenizer.hasMoreTokens()) {
				return true;
			}
			// update the current position for the
			// following loop
			pos = fragment.length();
		}

		// loop through the fragments and make sure, that each
		// fragment occurs somewhere _after_ the previous one
		while ( tokenizer.hasMoreTokens() )
		{
			fragment = tokenizer.nextToken();
			if( pos >= path.length())
			{
				return false;
			}
			pos = path.indexOf( fragment, pos);
			if( pos < 0)
			{
				return false;
			}
			pos += fragment.length();
		}

		// the path must end with the last fragment if the
		// pattern doesn't end with a wildcard
		if( !pattern.endsWith("*") && !path.endsWith(fragment))
		{
			return false;
		}

		// all tests passed -> the path matches the pattern
		return true;
	}


	protected Servlet getServletFromName( String servletName)
	{
		String servletClassName = getServletProperty(
			servletName + CODE, servletName);

		Class servletClass;
		try { servletClass = Class.forName( servletClassName); }
		catch( ClassNotFoundException cnfe)
		{
			log( "Class '" + servletClassName + "' not found.");
			return null;
		}

		// If not a servlet
		if( !Servlet.class.isAssignableFrom( servletClass))
		{
			log( servletClassName + " is not a Servlet.");
			return null;
		}

		Servlet servlet = null;
		try { servlet = (Servlet)servletClass.newInstance(); }
		catch( Exception e)
		{
			log( "Could not instantiate Servlet " + servletClassName);
			return null;
		}

		ServletConfig servletConfig =
			new com.smartsc.http.ServletConfig( this,
				getServletProperty( servletName + INIT_ARGS ),
				servletName );

		try { servlet.init( servletConfig); }
		catch( Exception e)
		{
			log( "Error initializing Servlet " + servletClassName);
			log( e);
			return null;
		}

		return servlet;
	}

	public static
	String
	getContentTypeFor( String fileName)
	{
		String type = "text/plain";

		int lastDot = fileName.lastIndexOf( '.');
		if( lastDot != -1)
		{
			String ext = fileName.substring( lastDot);
			String t = (String)extToMimeType.get( ext);
			if( t != null) type = t;
		}

		return type;
	}

	protected
	boolean
	isLogOversized( File log)
	{
		boolean oversized = false;

		if( log != null && log.length() >
			props.getIntProperty( PROP_MAX_LOG_SIZE, DEFAULT_MAX_LOG_SIZE) )
		{
			oversized = true;
		}

		return oversized;
	}

	protected
	void
	mailLog( File log)
	throws IOException
	{
		if( mailHeaders == null)
		{
			mailHeaders = new Hashtable();
			mailHeaders.put(
				Mailer.HEADER_TO, props.get( PROP_MAIL_TO));
			mailHeaders.put(
				Mailer.HEADER_FROM, props.get( PROP_MAIL_FROM));
		}
		mailHeaders.put(
			Mailer.HEADER_SUBJECT, serverName + " " + log.getName());
		try
		{
			// Mail log
			Mailer.send( mailHeaders, log);
		}
		// If bad address
		catch( MalformedURLException mfue)
		{
			// Don't send log anymore
			props.remove( PROP_MAIL_TO);
			throw mfue;
		}
	}

	public
	void
	banner( boolean verbose)
	{
		synchronized( logWriter)
		{
			log( SERVER_INFO);
			log( COPYRIGHT);
			logWriter.println();
			if( verbose)
				props.list( logWriter);
		}
	}

	public static
	void
	help()
	{
		System.out.println( SERVER_INFO);
		System.out.println( COPYRIGHT);
		System.out.println();
		System.out.println( "HttpServer [-(h|v)] [properties_file]");
	}

	public static
	Properties
	getProperties( String[] args)
	{
		boolean help = false;
		boolean verbose = false;

		String propertyFile = null;

		Properties props = new Properties( defaultProps);

		if( args.length > 2)
		{
			help = true;
		}
		else if( args.length == 1)
		{
			if( "-h".equals( args[0])) help = true;
			else if( "-v".equals( args[0])) verbose = true;
			else propertyFile = args[0];
		}
		else if( args.length == 2)
		{
			propertyFile = args[1];
			if( "-v".equals( args[0])) verbose = true;
			else help = true;
		}

		if( help)
		{
			help();
			return null;
		}

		if( propertyFile != null)
		{
			try
			{
				File f = AbsoluteFile.create( propertyFile);
				props.load( new FileInputStream( f));
			}
			catch( IOException ioe)
			{
				System.err.print( "Error reading property file '");
				System.err.print( propertyFile);
				System.err.println( "'.  Using defaults.");
			}
		}

		if( verbose)
		{
			// put() works with both JDK 1.1 and 1.2.
			// setProperty() works with JDK 1.2 only.
			props.put( PROP_VERBOSE, "true");
		}

		// Reconcile path-like properties
		reconcilePathProperty( props, PROP_MIME_TYPES_FILE);
		reconcilePathProperty( props, PROP_DOC_ROOT);
		reconcilePathProperty( props, PROP_SERVLET_PROPS);

		// Load MIME types
		String mimeTypesFilename = props.getProperty( PROP_MIME_TYPES_FILE);
		if( mimeTypesFilename != null)
		{
			try
			{
				extToMimeType.load( new FileInputStream( mimeTypesFilename));
			}
			catch( IOException ioe)
			{
				System.err.print( "Error reading MIME types file '");
				System.err.print( mimeTypesFilename);
				System.err.println( "'.  Using defaults.");
			}
		}

		return props;
	}

	public static
	void
	reconcilePathProperty( Properties props, String pathPropName)
	{
		String pathPropValue = props.getProperty( pathPropName);
		if( pathPropValue == null) return;
		File f = AbsoluteFile.create( pathPropValue);
		pathPropValue = f.getAbsolutePath();
		props.put( pathPropName, pathPropValue);
	}

	public static
	void
	main( String[] args)
	{
		Properties props = getProperties( args);

		if( props != null)
		{
			try
			{
				HttpServer server = new HttpServer( props);
				new Thread( server).start();
			}
			catch( IOException ioe)
			{
				System.err.println( "Could not start server.  (" +
					ioe.getMessage() + ")" );
			}
		}
	}

	private long lastGCTime = System.currentTimeMillis();

	// Server non-properties related constants
	public static final String SERVER_INFO             = "SSC Web Server/1.0";
	public static final String COPYRIGHT =
		"Copyright (C) 1999-2002  Smart Software Consulting.";
	public static final String HTTP_VERSION            = "HTTP/1.1";
	public static final int JSDK_MAJOR_VERSION         = 2;
	public static final int JSDK_MINOR_VERSION         = 2;
	public static final long MIN_GC_TIME               = 30 * 1000;

⌨️ 快捷键说明

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