您的位置:首页 > 移动开发

知识库--The Simple Container Application

2016-12-06 09:50 169 查看
The Simple Container Application

The main purpose of the application in this chapter is show how to use the default connector. It consists of two classes:

The SimpleContainer class implements org.apache.catalina.container so that it can be associated with the connector. The Bootstrap class is used to start the application, we have removed the connector module and the ServletProcessor and StaticResourceProcessor classes in the application accompanying 3.0, so you cannot request a static page.

public class SimpleContainer implements Container {
public static final String WEB_ROOT = System.getProperty("user.dir") + File.separator + "webroot";
...// other method omit
@Override
public void invoke(Request request, Response response) throws IOException, ServletException {
String servletName = ((Httpservletrequest)request).getURI();
servletName = servletName.subString(servletName.lastIndexof("/")+1);
URLClassLoader loader = null;
try{
URL[] urls = new URL[1];
URLStreamHandler streamHandler = null;
File classpath = new File(WEB_ROOT);
String repository = (new URL("file",null,classpath.getCanonicalpath() + File.separator)).toString();
urls[0] = new URL(null,repository,streamHandler);
loader = new URLClassLoader(urls);
}catch(IOException e){
System.out.println(e.toString());
}
Class myClass = null;
try{
myClass = loader.loadclass(servletName);
}catch(classNotFoundException e){
System.out.ptintln(e.toString());
}

servlet servlet = null;
try{
servlet = (Servlet)myClass.newInstance();
servlet.service((HttpServletRequest)request,(HttpServletResponse)response);
}catch(Exception e){
...
}catch(Throwable e){
...
}

}
}


Bootstrap class:

public final class Bootstrap{
public static void main(String[] args){
HttpConnector connector = new HttpConnector();
SimpleContainer container = new SimpleContainer();
connector.setContainer(container);

try{
connector.initialize();
connector.start();
System.in.read();
}catch(Exception e){
...
}
}
}


The main method associates the connector with the container by calling the connector’s setContainer method, passing the container. Next, it calls the connector’s initialize and start methods. This will make the connector ready for processing any HTTP request on port 8080.

You can terminate the application by pressing a key on the console.

Running the Application

java -classpath ./lib/servlet.jar;./….Bootstrap
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  container