Context 代表一个WEB应用
public class SimpleContext implements Context, Pipeline {
public SimpleContext() {
pipeline.setBasic(new SimpleContextValve());
}
protected HashMap children = new HashMap();
protected Loader loader = null;
protected SimplePipeline pipeline = new SimplePipeline(this);
protected HashMap servletMappings = new HashMap();
protected Mapper mapper = null;
protected HashMap mappers = new HashMap();
private Container parent = null;
public void addServletMapping(String pattern, String name) {
synchronized (servletMappings) {
servletMappings.put(pattern, name);
}
}
public String findServletMapping(String pattern) {
synchronized (servletMappings) {
return ((String) servletMappings.get(pattern));
}
}
public void addChild(Container child) {
child.setParent((Container) this);
children.put(child.getName(), child);
}
public void addMapper(Mapper mapper) {
// this method is adopted from addMapper in ContainerBase
// the first mapper added becomes the default mapper
mapper.setContainer((Container) this); // May throw IAE
this.mapper = mapper;
synchronized(mappers) {
if (mappers.get(mapper.getProtocol()) != null)
throw new IllegalArgumentException("addMapper: Protocol '" +
mapper.getProtocol() + "' is not unique");
mapper.setContainer((Container) this); // May throw IAE
mappers.put(mapper.getProtocol(), mapper);
if (mappers.size() == 1)
this.mapper = mapper;
else
this.mapper = null;
}
}
public Container findChild(String name) {
if (name == null)
return (null);
synchronized (children) { // Required by post-start changes
return ((Container) children.get(name));
}
}
public Container[] findChildren() {
synchronized (children) {
Container results[] = new Container[children.size()];
return ((Container[]) children.values().toArray(results));
}
}
public Mapper findMapper(String protocol) {
// the default mapper will always be returned, if any,
// regardless the value of protocol
if (mapper != null)
return (mapper);
else
synchronized (mappers) {
return ((Mapper) mappers.get(protocol));
}
}
public void invoke(Request request, Response response)
throws IOException, ServletException {
pipeline.invoke(request, response);
}
public Container map(Request request, boolean update) {
//this method is taken from the map method in org.apache.cataline.core.ContainerBase
//the findMapper method always returns the default mapper, if any, regardless the
//request's protocol
Mapper mapper = findMapper(request.getRequest().getProtocol());
if (mapper == null)
return (null);
// Use this Mapper to perform this mapping
return (mapper.map(request, update));
}
}
Mapper用于定位到相应的Wrapper
public class SimpleContextMapper implements Mapper {
private SimpleContext context = null;
public Container getContainer() {
return (context)
}
public void setContainer(Container container) {
if (!(container instanceof SimpleContext))
throw new IllegalArgumentException
("Illegal type of container");
context = (SimpleContext) container;
}
public String getProtocol() {
return null;
}
public void setProtocol(String protocol) {
}
/**
* Return the child Container that should be used to process this Request,
* based upon its characteristics. If no such child Container can be
* identified, return <code>null</code> instead.
*
* @param request Request being processed
* @param update Update the Request to reflect the mapping selection?
*
* @exception IllegalArgumentException if the relative portion of the
* path cannot be URL decoded
*/
public Container map(Request request, boolean update) {
// Identify the context-relative URI to be mapped
String contextPath =
((HttpServletRequest) request.getRequest()).getContextPath();
String requestURI = ((HttpRequest) request).getDecodedRequestURI();
String relativeURI = requestURI.substring(contextPath.length());
// Apply the standard request URI mapping rules from the specification
Wrapper wrapper = null;
String servletPath = relativeURI;
String pathInfo = null;
String name = context.findServletMapping(relativeURI);
if (name != null)
wrapper = (Wrapper) context.findChild(name);
return (wrapper);
}
}
BasicValve 的任务是调用指定Wrapper的invoke
public class SimpleContextValve implements Valve, Contained {
protected Container container;
public void invoke(Request request, Response response, ValveContext valveContext)
throws IOException, ServletException {
// Validate the request and response object types
if (!(request.getRequest() instanceof HttpServletRequest) ||
!(response.getResponse() instanceof HttpServletResponse)) {
return; // NOTE - Not much else we can do generically
}
// Disallow any direct access to resources under WEB-INF or META-INF
HttpServletRequest hreq = (HttpServletRequest) request.getRequest();
String contextPath = hreq.getContextPath();
String requestURI = ((HttpRequest) request).getDecodedRequestURI();
String relativeURI =
requestURI.substring(contextPath.length()).toUpperCase();
Context context = (Context) getContainer();
// Select the Wrapper to be used for this Request
Wrapper wrapper = null;
try {
wrapper = (Wrapper) context.map(request, true);
}
catch (IllegalArgumentException e) {
badRequest(requestURI, (HttpServletResponse) response.getResponse());
return;
}
if (wrapper == null) {
notFound(requestURI, (HttpServletResponse) response.getResponse());
return;
}
// Ask this Wrapper to process this Request
response.setContext(context);
wrapper.invoke(request, response);
}
public Container getContainer() {
return container;
}
public void setContainer(Container container) {
this.container = container;
}
private void badRequest(String requestURI, HttpServletResponse response) {
try {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, requestURI);
}
catch (IllegalStateException e) {
;
}
catch (IOException e) {
;
}
}
private void notFound(String requestURI, HttpServletResponse response) {
try {
response.sendError(HttpServletResponse.SC_NOT_FOUND, requestURI);
}
catch (IllegalStateException e) {
;
}
catch (IOException e) {
;
}
}
}
启动类:
public final class Bootstrap2 {
public static void main(String[] args) {
HttpConnector connector = new HttpConnector();
Wrapper wrapper1 = new SimpleWrapper();
wrapper1.setName("Primitive");
wrapper1.setServletClass("PrimitiveServlet");
Wrapper wrapper2 = new SimpleWrapper();
wrapper2.setName("Modern");
wrapper2.setServletClass("ModernServlet");
Context context = new SimpleContext();
context.addChild(wrapper1);
context.addChild(wrapper2);
Valve valve1 = new HeaderLoggerValve();
Valve valve2 = new ClientIPLoggerValve();
((Pipeline) context).addValve(valve1);
((Pipeline) context).addValve(valve2);
Mapper mapper = new SimpleContextMapper();
mapper.setProtocol("http");
context.addMapper(mapper);
Loader loader = new SimpleLoader();
context.setLoader(loader);
// context.addServletMapping(pattern, name);
context.addServletMapping("/Primitive", "Primitive");
context.addServletMapping("/Modern", "Modern");
connector.setContainer(context);
try {
connector.initialize();
connector.start();
// make the application wait until we press a key.
System.in.read();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
分享到:
相关推荐
4. **部署Web应用**:在Tomcat 4.1.40中,可以将WAR(Web应用程序归档)文件或解压后的目录放入`webapps`目录,Tomcat会自动检测并部署应用。WAR文件是一种打包格式,包含了所有Web应用的资源,如HTML、CSS、...
Tomcat 配置文件数据库密码加密,增加factory属性和修改context....代码是jdk1.8版本,包含简单的加密类和http请求,如果使用简单的加密,不需要引用额外的lib包,只需要tomcat-dbcp.jar即可。使用http就需要多个har包
4. Web应用部署:在Tomcat中,Web应用通常以WAR文件形式部署,解压后放在webapps目录下。每个Web应用有自己的Context配置,定义了Servlet映射、欢迎页面、错误处理等信息。手写Tomcat时,我们需要实现解析WEB-INF/...
4. **容器结构**:Tomcat有多个级别的容器,包括Engine(引擎)、Host(主机)、Context(上下文)、Wrapper(Servlet容器),它们分别对应不同的Web应用范围。 5. **线程模型**:Tomcat使用基于Executor的线程池来...
以下是一个简单的`log4j2.xml`配置示例: ```xml [%t] %-5level %logger{36} - %msg%n"/> [%t] %-5level %logger{36} - %msg%n"/> ``` 此配置会将日志同时输出到控制台和名为`app....
Tomcat是轻量级的,相比其他如IBM WebSphere、Oracle WebLogic等商业应用服务器,Tomcat的安装和配置更为简单,因此在小型项目和开发环境中非常流行。 Tomcat的核心组件包括以下几个部分: 1. **Catalina**:这是...
【标题】"Tomcat源码学习:一个最简单的‘Tomcat’",这篇博客主要探讨的是如何通过学习Tomcat的源代码来理解这个流行的开源Java Servlet容器的工作原理。Tomcat是Apache软件基金会的一个项目,它是Java Web应用...
本篇文章将探讨如何在Tomcat中实现一个简单的定时器,以自动化执行特定任务。这个定时器的实现通常涉及使用Java的定时器类`java.util.Timer`和`java.util.TimerTask`。 首先,我们关注`MyTimerTask.java`这个文件,...
- `conf`:存放Tomcat的配置文件,如`server.xml`、`context.xml`和`web.xml`。 - `lib`:存放Tomcat运行所需的库文件。 - `webapps`:默认的Web应用部署目录,将WAR文件放在这里会自动解压并部署。 - `logs`:存放...
添加两个`context-param`标签,指定Mule的配置文件(例如`mule-config.xml`)和Log4J的日志配置文件(例如`log4j.properties`)的位置。 ```xml ... <context-param> <param-name>org.mule.config ...
- **易于配置**:配置文件如`server.xml`、`web.xml`和`context.xml`简单明了,便于管理和定制。 - **安全管理**:支持多种认证机制和角色基安全模型,确保应用的安全性。 - **跨平台**:可在多种操作系统上运行...
4. **管理工具**:Tomcat6提供了一个管理控制台,通过浏览器访问http://localhost:8080/manager/html,可以进行应用的部署、卸载、启动和停止操作。默认情况下,这些功能是关闭的,需要在conf/tomcat-users.xml中...
3. **配置过程**:Apache Tomcat 7.0.73的配置相对简单,解压后,通常只需要几个步骤即可开始使用。首先,设置环境变量CATALINA_HOME指向Tomcat的安装目录。其次,编辑`conf/server.xml`文件,根据需求配置端口号、...
【标题】:“Tomcat7免安装版tomcat” ...总之,Tomcat7免安装版为开发和测试提供了极大的便利,只需简单几步就能搭建起一个Java Web服务环境。理解其配置文件、部署方式以及安全管理,对于管理和维护Tomcat7至关重要。
- 对于简单Web应用,Tomcat足够使用,对于更复杂的Java EE应用,可能需要使用像JBoss、GlassFish这样的全功能应用服务器。 7. **版本更新**: - Tomcat 6.0.35虽已过时,但了解其工作原理有助于理解后续版本的...
尽管功能可能不如其他全功能的应用服务器如JBoss或WebLogic那样全面,但Tomcat的简单性和易用性使其成为开发者和小型企业的首选。 在“apache-tomcat-8.0.33”这个压缩包中,包含的是Tomcat 8.0.33的安装程序。这个...
Tomcat的启动过程始于`bin/catalina.sh`或`catalina.bat`,这些脚本会初始化Java环境,并加载`catalina.jar`中的`org.apache.catalina.startup.ClassLoader`,接着加载`Server`对象,初始化`Service`,`Engine`,`...
以下是一个创建嵌入式Tomcat的简单示例代码: ```java import java.io.File; import java.net.InetAddress; import java.net.UnknownHostException; import org.apache.catalina.Context; import org.apache....
对于高级用户和系统管理员,了解Tomcat的服务器配置文件如server.xml、context.xml和web.xml至关重要,这些文件控制着服务器的行为、连接器设置、虚拟主机和应用程序上下文。同时,熟悉Tomcat的安全设置,如用户角色...
2. **安装与配置**:Tomcat的安装相对简单,通常包括下载zip或tar.gz格式的压缩包,解压到指定目录,然后根据操作系统配置环境变量。在Windows上,可以通过修改系统环境变量`CATALINA_HOME`;在Linux或Unix系统上,...