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

📄 servlethandler.cpp

📁 mini http server,可以集成嵌入到程序中,实现简单的web功能
💻 CPP
📖 第 1 页 / 共 2 页
字号:
/*____________________________________________________________________________*\
 *

 Copyright (c) 1997-2003 John Roy, Holger Zimmermann. All rights reserved.

 These sources, libraries and applications are
 FREE FOR COMMERCIAL AND NON-COMMERCIAL USE
 as long as the following conditions are adhered to.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:

 1. Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer. 

 2. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in
    the documentation and/or other materials provided with the
    distribution.

 3. The name of the author may not be used to endorse or promote products
    derived from this software without specific prior written permission. 

 THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 IN NO EVENT SHALL THE AUTHORS OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 OF THE POSSIBILITY OF SUCH DAMAGE.

 *____________________________________________________________________________*|
 *
 * $Source: /cvsroot/pi3web/Pi3Web_200/Source/Servlet/ServletHandler.cpp,v $
 * $Date: 2003/05/13 18:42:19 $
 *
 Description:
	Execute an servlet extension.

\*____________________________________________________________________________*/
//$SourceTop:$

#include <iostream.h>
#include <stdio.h>
#include <stdarg.h>
#include "ServletHandler.h"

/*____________________________________________________________________________*\
 *
 Description:
\*____________________________________________________________________________*/
#if 0
	/*
	** HTML documentation for this handler
	*/
/*___+++HTMLDOC_BEGIN+++___*/
Name:
	Servlet

Description:
	Load and execute a java servlet extension. You can find more
	informations about servlets here <A HREF="http://java.sun.com/">
    http://java.sun.com/</A>.

Options:

<TABLE BORDER=1>
<TH>Option
<TH>Default
<TH>Values
<TH>Short Description
<TH>Example(s)

<TR>
<TD>Context
<TD>+
<TD>Valid Pi3 object Reference
<TD>Reference to servlet container
<TD>ServletContainer

<TR>
<TD>ClassName
<TD>-
<TD>Quoted string
<TD>Valid Servlet class name
<TD>"org.pi3.servlet.samples.HelloServlet"

<TR>
<TD>ServletName
<TD>-
<TD>Quoted string
<TD>Any name for Servlet
<TD>"My 1st Servlet"

<TR>
<TD>Init
<TD>-
<TD>Quoted string
<TD>Servlet config option(s)
<TD>"color=red"


</TABLE>
<STRONG>-</STRONG> in the <IT>default</IT> indicates no default<BR>
<STRONG>+</STRONG> in the <IT>default</IT> indicates the field is mandatory<BR>

<H4>Description of Options</H4>
<H5>Context</H5>
The reference to the Servlet container must exist. In Pi3Web 2.0
it is only allowed to refer to one singleton servlet container.

<H5>ClassName</H5>
The class name of the Servlet to run. The class must exist within
<TT>CLASSPATH</TT> and must be a child class of <TT>Servlet</TT>.
The class could implement the interface <TT>SingleThreadModel</TT>.

<H5>ServletName</H5>
Optional name of the Servlet for human reading. This feature is for
use with future versions and is ignored in Servlet API 2.1.

<H5>Init</H5>
The value has to be a quoted string of format "key=value".
The key and the value are forwarded as ServletConfig parameters
to the Servlet on initialization. The possible values are Servlet
specific.

Phase:
	HANDLE

Returns:
	PIAPI_COMPLETED, PIAPI_ERROR or INT_REDIRECT according to the result of
	JNI calls and the status returned by the servlet.

Note:
Example:
	<PRE>
	&lt;Object&gt;
		Name Servlet
		Class ServletClass
		Context ServletContainer
	&lt;/Object&gt;

	&lt;Object&gt;
		...
		Handle Condition="&cmp(&dblookup(response,string,ObjectMap,SERVLET),Servlet)" \
			Servlet ClassName="MyServlet"
		...
	&lt;/Object&gt;
	</PRE>

/*___+++HTMLDOC_END+++___*/
#endif


int Servlet::Parameter( const char *pVariable, const char *pValue,
	const char *pWhere )
	{
	assert( pVariable && pValue );
	PIOStrStream os;
	os << pWhere << GetLogName() << ": ";

	if ( !PIUtil_stricmp( KEY_CONF_CLASSNAME, pVariable ) )
		{
		sClassName = (const char *)DeQuote( pValue );
		}
	else if ( !PIUtil_stricmp( KEY_CONF_SERVLETNAME, pVariable ) )
		{
		sServletName = (const char *)DeQuote( pValue );
		}
	else if ( !PIUtil_stricmp( KEY_CONF_INITPARAM, pVariable ) )
		{
		const char *pKey = DeQuote(pValue);
		char *pVal = pKey ? strchr(pKey,'=') : 0;
		if (!pKey || !pVal)
			{
			os << "Bad Init parameter '" << pValue << "'" << ends;
			CONFIG_ERR( Object(), os.str() );
			return 0;
			}
		else
			{
			pVal[0] = 0;
			// Memory usage due to DuplicateString?
			PIDB_replace( pInitParams, PIDBTYPE_OPAQUE, pKey,
				(void *)DuplicateString(++pVal), 0 );
			};
		}
	else if ( !PIUtil_stricmp( KEY_CONF_SERVLETCONTEXT, pVariable ) )
		{
		// The error is already logged by PIObject_loadFromLine()
		if ( !Context() ) return 0;
		}
	else if ( !PIUtil_stricmp( KEY_CONF_EXTENDS, pVariable ) )
		{
		}
	else if ( !PIUtil_stricmp( KEY_CONF_CLASSPATH, pVariable ) )
		{
		}
	else if ( !PIUtil_stricmp( KEY_CONF_SOURCEPATH, pVariable ) )
		{
		}
	else if ( !PIUtil_stricmp( KEY_CONF_OUTPUTPATH, pVariable ) )
		{
		}
	else if ( !PIUtil_stricmp( KEY_CONF_ENCODING, pVariable ) )
		{
		}
	else if ( !PIUtil_stricmp( KEY_CONF_COMPILER, pVariable ) )
		{
		}
	else
		{
		os << "Unknown directive '" << pVariable <<	"'" << ends;
		CONFIG_ERR( Object(), os.str() );
		return 0;
		};

	if ( !Context() ) return 0;

	return 1;
	};

Servlet::Servlet( PIObject *pObject, int iArgc, const char *ppArgv[], const char *pLogName )
	:	HandlerBaseServlet( pObject, pLogName ),
		pRequestTypes( PIDB_new( 0, "RequestTypes" )),
		pResponseTypes( PIDB_new( 0, "ResponseTypes" )),
		pInitParams( PIDB_new( 0, "InitParams" )),
		sClassName( 0 ),
		sServletName( 0 ),
		jServlet( 0 ),
		jServletConfig( 0 ),
		pMutex ( PIPlatform_allocLocalMutex()) 
{
	ReadParameters( iArgc, ppArgv );
	if (IsOK()) { SetOK( pMutex != 0 ); }
	if (Context()) initServlet( ENV() );

#define AT( name, function ) \
PIDB_add( pRequestTypes, PIDBTYPE_OPAQUE, (name), (void *)function, 0 );
	AT( KEY_HTTP_PROTOCOL,		fnServerProtocol );
	AT( KEY_HTTP_METHOD,		fnRequestMethod );
	AT( KEY_HTTP_QUERYSTRING,	fnQueryString );
	AT( KEY_HTTP_CONTENTLENGTH,	fnContentLengthReq );
	AT( KEY_HTTP_CONTENTTYPE,	fnContentTypeReq );
	AT( KEY_HTTP_IFMODIFIEDSINCE, fnIfModifiedSince );
	AT( KEY_HTTP_URI,			fnHttpUri );
	//	AT( "ALL_HTTP",			fnAllHttp );
	AT( "GATEWAY_INTERFACE",	fnGatewayInterface );
	AT( KEY_INT_REMOTEADDR,		fnRemoteAddr );
	AT( KEY_INT_REMOTEHOST,		fnRemoteHost );
	AT( KEY_INT_HOSTNAME,		fnServerName );
	AT( KEY_INT_SERVERPORT,		fnServerPort );
	AT( KEY_HTTP_SERVER,		fnServerSoftware );
	AT( KEY_HTTPS_KEYSIZE,		fnHttpsKeysize);
	AT( KEY_HTTPS_SECRETKEYSIZE, fnHttpPrivKeysize);
#undef AT

#define AT( name, function ) \
PIDB_add( pResponseTypes, PIDBTYPE_OPAQUE, (name), (void *)function, 0 );
	AT( "AUTH_TYPE",				fnAuthType );
	AT( "AUTH_PASS",				fnAuthPass );
	AT( KEY_HTTP_CONTENTLENGTH,	fnContentLengthRes );
	AT( KEY_HTTP_CONTENTTYPE,	fnContentTypeRes );
	AT( KEY_HTTP_LASTMODIFIED,	fnLastModified );
	AT( KEY_INT_PATHINFO,		fnPathInfo );
	AT( KEY_INT_PATHTRANSLATED,	fnPathTranslated );
	AT( KEY_INT_REMOTEUSER,		fnRemoteUser );
	AT( KEY_INT_SCRIPTNAME,		fnScriptName );
	AT( "GATEWAY_INTERFACE",		fnGatewayInterface );
	AT( KEY_INT_REMOTEADDR,		fnRemoteAddr );
	AT( KEY_INT_REMOTEHOST,		fnRemoteHost );
	AT( KEY_INT_HOSTNAME,		fnServerName );
	AT( KEY_INT_SERVERPORT,		fnServerPort );
	AT( KEY_HTTP_SERVER,		fnServerSoftware );
#undef AT

};

Servlet::~Servlet()
{
	destroyServlet();
	PIDB_delete( pRequestTypes );
	PIDB_delete( pResponseTypes );
	if (pMutex) PISync_delete( pMutex );
};


int Servlet::initServlet( JNIEnv *env ) {

	jclass ServletClass = 0;
	static jclass ServletConfigClass = 0;
	static jmethodID ServletConfigConstructorMID = 0;
	static jmethodID putMID = 0;

    /* get the ServletConfig class */
	if (!ServletConfigClass) {
		ServletConfigClass = env->FindClass("org/pi3/servlet/core/Pi3ServletConfig");
		if (!ServletConfigClass) { goto init_error; };
	};

	/* get the ServletConfig constructor */
	if (!ServletConfigConstructorMID) {
		ServletConfigConstructorMID = env->GetMethodID( ServletConfigClass, "<init>",
			"(Lorg/pi3/servlet/core/Pi3ServletContext;)V");
		if (!ServletConfigConstructorMID) { goto init_error; };
	};

	/* Put the init params into the servlet config */
	if (!putMID) {
		putMID = env->GetMethodID( ServletConfigClass, "setInitParameter",
			"(Ljava/lang/String;Ljava/lang/Object;)V");
		if (!putMID) { goto init_error; };
	};

    /* get the ServletConfig object */
	jServletConfig = env->NewObject( ServletConfigClass, ServletConfigConstructorMID,
		ServletContext());
    if (!jServletConfig) {
		goto init_error;
	} else {
		Log( "%s: %s", GetLogName(), "ServletConfig created.");
	};

	jServletConfig = env->NewGlobalRef(jServletConfig);

	/* ---
	iterate through the InitParams DB	
	--- */
	const char *pKey;
	const char *pValue;
	PIDBIterator *pIter;
	pIter = PIDB_getIterator( pInitParams, PIDBTYPE_OPAQUE, 0, 0 );
	if ( pIter ) {
		for( ; PIDBIterator_atValidElement( pIter ); PIDBIterator_next( pIter )) {

			pValue = (const char *)PIDBIterator_current( pIter, &pKey );
			
			env->CallVoidMethod(jServletConfig, putMID, env->NewStringUTF( pKey ),
				env->NewStringUTF( pValue ));
			if ( env->ExceptionOccurred() )
				{
				env->ExceptionDescribe();
				env->ExceptionClear();
				PIDBIterator_delete( pIter );
				goto init_error;
				};
		};
		PIDBIterator_delete( pIter );
	};

	/* the servlet is loaded later by request */
	if (!sClassName.Len()) return PIAPI_COMPLETED;
	
	/* get the Servlet class */
	while (strchr(sClassName, '.')) strchr(sClassName, '.')[0] = '/';
	ServletClass = env->FindClass(sClassName);
    if (!ServletClass) { goto init_error; };

    /* get the Servlet constructor */
	jmethodID ServletMID;
	ServletMID = env->GetMethodID( ServletClass, "<init>", "()V");
    if (!ServletMID) { goto init_error; };

    /* get the Servlet object */
	jServlet = env->NewObject( ServletClass, ServletMID);
    if (!jServlet) { 
		goto init_error;
	} else {
		Log( "%s: Servlet '%s' created.", GetLogName(), (const char *)sClassName );
	};

	jServlet = env->NewGlobalRef(jServlet);
	Context()->registerServlet( (const char *)sClassName, jServlet );

    /* invoke the Servlet.init method */
	jmethodID ServletInitMID;
	ServletInitMID = env->GetMethodID( ServletClass, "init",
		"(Ljavax/servlet/ServletConfig;)V");
    if (!ServletInitMID) { goto init_error; };

	env->CallVoidMethod(jServlet, ServletInitMID, jServletConfig);
	if ( env->ExceptionOccurred() )	{ goto init_error; };

	PIDB_delete( pInitParams );	
	return PIAPI_COMPLETED;

init_error:
	if ( env->ExceptionOccurred() )
		{
		env->ExceptionDescribe();
		env->ExceptionClear();
		};

	PIDB_delete( pInitParams );
	return PIAPI_ERROR;
	// introduce logging later!
};

int Servlet::destroyServlet() {

	if (!JVM()) return PIAPI_ERROR;

	JNIEnv *env;
	if (JVM()->AttachCurrentThread((void **)&env, NULL)) goto init_error;

	if (jServlet) {

		jclass ServletClass = env->GetObjectClass(jServlet);
		if (!ServletClass) { goto init_error; };

		Context()->unregServlet( (const char *)sClassName );

	    /* invoke the Servlet.destroy method */
		jmethodID ServletDestroyMID;
		ServletDestroyMID = env->GetMethodID( ServletClass, "destroy", "()V" );
		if (!ServletDestroyMID) { goto init_error; };

		env->CallVoidMethod(jServlet, ServletDestroyMID);
		if ( env->ExceptionOccurred() )	{ goto init_error; };

		env->DeleteGlobalRef(jServlet);
		if ( env->ExceptionOccurred() )	{
			goto init_error;
		} else {
			Log( "%s: Servlet '%s' destroyed.", GetLogName(), (const char *)sClassName);
		};
	};

	if (jServletConfig) {
		env->DeleteGlobalRef(jServletConfig);
		if ( env->ExceptionOccurred() )	{
			goto init_error;
		} else {
			Log( "%s: ServletConfig destroyed.", GetLogName());
		};
	};

	JVM()->DetachCurrentThread();
	return PIAPI_COMPLETED;

init_error:
	if ( env->ExceptionOccurred() )
		{
		env->ExceptionDescribe();
		env->ExceptionClear();
		};
	JVM()->DetachCurrentThread();
	return PIAPI_ERROR;
	// introduce logging later!
}


const char *Servlet::GetPathTranslated( PIHTTP *pPIHTTP, const char *pPath )
{
	/* --- make sub request context --- */
	PIHTTP *pChildHTTP = PIHTTP_newChild( pPIHTTP );

	/* --- set path --- */
	PIDB_replace( pChildHTTP->pResponseDB, PIDBTYPE_STRING,
		KEY_INT_PATH, (void *)pPath, 0 );

	const char *pPathTranslated = NULL;

	/* --- dispatch the sub request across the mapping phase --- */
	int iRet = HTTPCore_dispatch( pChildHTTP, PH_MAPPING, PH_MAPPING );
			
	/* --- copy the childs path to this path translated --- */
	if ( iRet == PIAPI_COMPLETED && (( pChildHTTP->iStatus == 0 )
		|| ( pChildHTTP->iStatus == ST_OK )))
		{
		pPathTranslated = (const char *)PIDB_lookup( pChildHTTP->pResponseDB, PIDBTYPE_STRING,
			KEY_INT_PATH, 0 );
		}
	else
		{
		PIHTTP_delete( pChildHTTP );
		return pPathTranslated;
		};

	PIHTTP_delete( pChildHTTP );
	return pPathTranslated;
};


const char *Servlet::GetRequestVariable( PIHTTP *pPIHTTP, const char *pVariableName )

⌨️ 快捷键说明

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