POST /examples/default.jsp HTTP/1.1
Accept: text/plain; text/html
Accept-Language: en-gb
Connection: Keep-Alive
Host: localhost
User-Agent: Mozilla/4.0 (compatible; MSIE 4.01; Windows 98)
Content-Length: 33
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
lastName=Franks&firstName=Michael
POST /examples/default.jsp HTTP/1.1
lastName=Franks&firstName=Michael实体内容在一个典型的HTTP请求中能够很容易的变得更长。
HTTP/1.1 200 OK响应头部的第一行相似于请求头部的第一行。第一行告诉你该协议使用HTTP 1.1,请求成功(200=成功),表示一切都运行良好。
Server: Microsoft-IIS/4.0
Date: Mon, 5 Jan 2004 13:13:33 GMT
Content-Type: text/html
Last-Modified: Mon, 5 Jan 2004 13:13:12 GMT
Content-Length: 112
<html>
<head>
<title>HTTP Response Example</title>
</head>
<body>
Welcome to Brainy Software
</body>
</html>
public Socket (java.lang.String host, int port)在这里主机是指远程机器名称或者IP地址,端口是指远程应用的端口号。例如,要链接yahoo.com的80端口,你须要构造如下的Socket对象:
new Socket ("yahoo.com", 80);一旦你成功建立了一个Socket类的实例,你可使用它来发送和接受字节流。要发送字节流,你首先必须调用Socket类的getOutputStream方法来获取一个java.io.OutputStream对象。要发送文本到一个远程应用,你常常要从返回的OutputStream对象中构造一个java.io.PrintWriter对象。要从链接的另外一端接受字节流,你能够调用Socket类的getInputStream方法用来返回一个java.io.InputStream对象。
Socket socket = new Socket("127.0.0.1", "8080");请注意,为了从web服务器获取适当的响应,你须要发送一个遵照HTTP协议的HTTP请求。假如你已经阅读了前面一节超文本传输协议(HTTP),你应该可以理解上面代码提到的HTTP请求。
OutputStream os = socket.getOutputStream();
boolean autoflush = true;
PrintWriter out = new PrintWriter(
socket.getOutputStream(), autoflush);
BufferedReader in = new BufferedReader(
new InputStreamReader( socket.getInputstream() ));
// send an HTTP request to the web server
out.println("GET /index.jsp HTTP/1.1");
out.println("Host: localhost:8080");
out.println("Connection: Close");
out.println();
// read the response
boolean loop = true;
StringBuffer sb = new StringBuffer(8096);
while (loop) {
if ( in.ready() ) {
int i=0;
while (i!=-1) {
i = in.read();
sb.append((char) i);
}
loop = false;
}
Thread.currentThread().sleep(50);
}
// display the response to the out console
System.out.println(sb.toString());
socket.close();
public ServerSocket(int port, int backLog, InetAddress bindingAddress);对于这个构造方法,绑定地址必须是java.net.InetAddress的一个实例。一种构造InetAddress对象的简单的方法是调用它的静态方法getByName,传入一个包含主机名称的字符串,就像下面的代码同样。
InetAddress.getByName("127.0.0.1");下面一行代码构造了一个监听的本地机器8080端口的ServerSocket,它的backlog为1。
new ServerSocket(8080, 1, InetAddress.getByName("127.0.0.1"));一旦你有一个ServerSocket实例,你可让它在绑定地址和服务器套接字正在监听的端口上等待传入的链接请求。你能够经过调用ServerSocket类的accept方法作到这点。这个方法只会在有链接请求时才会返回,而且返回值是一个Socket类的实例。Socket对象接下去能够发送字节流并从客户端应用中接受字节流,就像前一节"Socket类"解释的那样。实际上,这章附带的程序中,accept方法是惟一用到的方法。
package ex01.pyrmont;Listing 1.2: HttpServer类的await方法
import java.net.Socket;
import java.net.ServerSocket;
import java.net.InetAddress;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.File;
public class HttpServer {
/** WEB_ROOT is the directory where our HTML and other files reside.
* For this package, WEB_ROOT is the "webroot" directory under the
* working directory.
* The working directory is the location in the file system
* from where the java command was invoked.
*/
public static final String WEB_ROOT =
System.getProperty("user.dir") + File.separator + "webroot";
// shutdown command
private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";
// the shutdown command received
private boolean shutdown = false;
public static void main(String[] args) {
HttpServer server = new HttpServer();
server.await();
}
public void await() {
...
}
}
public void await() {web服务器能提供公共静态final变量WEB_ROOT所在的目录和它下面全部的子目录下的静态资源。以下所示,WEB_ROOT被初始化:
ServerSocket serverSocket = null;
int port = 8080;
try {
serverSocket = new ServerSocket(port, 1,
InetAddress.getByName("127.0.0.1"));
}
catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
// Loop waiting for a request
while (!shutdown) {
Socket socket = null;
InputStream input = null;
OutputStream output = null;
try {
socket = serverSocket.accept();
input = socket.getInputStream();
output = socket.getOutputStream();
// create Request object and parse
Request request = new Request(input);
request.parse();
// create Response object
Response response = new Response(output);
response.setRequest(request);
response.sendStaticResource();
// Close the socket
socket.close();
//check if the previous URI is a shutdown command
shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
}
catch (Exception e) {
e.printStackTrace ();
continue;
}
}
}
public static final String WEB_ROOT =代码列表包括一个叫webroot的目录,包含了一些你能够用来测试这个应用程序的静态资源。你一样能够在相同的目录下找到几个servlet用于测试下一章的应用程序。为了请求一个静态资源,在你的浏览器的地址栏或者网址框里边敲入如下的URL:
System.getProperty("user.dir") + File.separator + "webroot";
http://machineName:port/staticResource若是你要从一个不一样的机器上发送请求到你的应用程序正在运行的机器上,machineName应该是正在运行应用程序的机器的名称或者IP地址。假如你的浏览器在同一台机器上,你可使用localhost做为machineName。端口是8080,staticResource是你须要请求的文件的名称,且必须位于WEB_ROOT里边。
http://localhost:8080/index.html要中止服务器,你能够在web浏览器的地址栏或者网址框里边敲入预约义字符串,就在URL的host:port的后面,发送一个shutdown命令。shutdown命令是在HttpServer类的静态final变量SHUTDOWN里边定义的:
private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";所以,要中止服务器,使用下面的URL:
http://localhost:8080/SHUTDOWN如今咱们来看看Listing 1.2印出来的await方法。
serverSocket = new ServerSocket(port, 1,while循环里边的代码运行到ServletSocket的accept方法停了下来,只会在8080端口接收到一个HTTP请求的时候才返回:
InetAddress.getByName("127.0.0.1"));
...
// Loop waiting for a request
while (!shutdown) {
...
}
socket = serverSocket.accept();接收到请求以后,await方法从accept方法返回的Socket实例中取得java.io.InputStream和java.io.OutputStream对象。
input = socket.getInputStream();await方法接下去建立一个ex01.pyrmont.Request对象而且调用它的parse方法去解析HTTP请求的原始数据。
output = socket.getOutputStream();
// create Request object and parse在这以后,await方法建立一个Response对象,把Request对象设置给它,并调用它的sendStaticResource方法。
Request request = new Request(input);
request.parse ();
// create Response object最后,await关闭套接字并调用Request的getUri来检测HTTP请求的URI是否是一个shutdown命令。假如是的话,shutdown变量将被设置为true且程序会退出while循环。
Response response = new Response(output);
response.setRequest(request);
response.sendStaticResource();
// Close the socket
socket.close ();
//check if the previous URI is a shutdown command
shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
package ex01.pyrmont;Listing 1.4: Request类的parse方法
import java.io.InputStream;
import java.io.IOException;
public class Request {
private InputStream input;
private String uri;
public Request(InputStream input) {
this.input = input;
}
public void parse() {
...
}
private String parseUri(String requestString) {
...
}
public String getUri() {
return uri;
}
}
public void parse() {Listing 1.5: Request类的parseUri方法
// Read a set of characters from the socket
StringBuffer request = new StringBuffer(2048);
int i;
byte[] buffer = new byte[2048];
try {
i = input.read(buffer);
}
catch (IOException e) {
e.printStackTrace();
i = -1;
}
for (int j=0; j<i; j++) {
request.append((char) buffer[j]);
}
System.out.print(request.toString());
uri = parseUri(request.toString());
}
private String parseUri(String requestString) {parse方法解析HTTP请求里边的原始数据。这个方法没有作不少事情。它惟一可用的信息是经过调用HTTP请求的私有方法parseUri得到的URI。parseUri方法在uri变量里边存储URI。公共方法getUri被调用并返回HTTP请求的URI。
int index1, index2;
index1 = requestString.indexOf(' ');
if (index1 != -1) {
index2 = requestString.indexOf(' ', index1 + 1);
if (index2 > index1)
return requestString.substring(index1 + 1, index2);
}
return null;
}
GET /index.html HTTP/1.1parse方法从传递给Requst对象的套接字的InputStream中读取整个字节流并在一个缓冲区中存储字节数组。而后它使用缓冲区字节数据的字节来填入一个StringBuffer对象,而且把表明StringBuffer的字符串传递给parseUri方法。
package ex01.pyrmont;首先注意到它的构造方法接收一个java.io.OutputStream对象,就像以下所示。
import java.io.OutputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.File;
/*
HTTP Response = Status-Line
*(( general-header | response-header | entity-header ) CRLF)
CRLF
[ message-body ]
Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
*/
public class Response {
private static final int BUFFER_SIZE = 1024;
Request request;
OutputStream output;
public Response(OutputStream output) {
this.output = output;
}
public void setRequest(Request request) {
this.request = request;
}
public void sendStaticResource() throws IOException {
byte[] bytes = new byte[BUFFER_SIZE];
FileInputStream fis = null;
try {
File file = new File(HttpServer.WEB_ROOT, request.getUri());
if (file.exists()) {
fis = new FileInputStream(file);
int ch = fis.read(bytes, 0, BUFFER_SIZE);
while (ch!=-1) {
output.write(bytes, 0, ch);
ch = fis.read(bytes, 0, BUFFER_SIZE);
}
}
else {
// file not found
String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length: 23\r\n" +
"\r\n" +
"<h1>File Not Found</h1>";
output.write(errorMessage.getBytes());
}
}
catch (Exception e) {
// thrown if cannot instantiate a File object
System.out.println(e.toString() );
}
finally {
if (fis!=null)
fis.close();
}
}
}
public Response(OutputStream output) {响应对象是经过传递由套接字得到的OutputStream对象给HttpServer类的await方法来构造的。Response类有两个公共方法:setRequest和sendStaticResource。setRequest方法用来传递一个Request对象给Response对象。
this.output = output;
}
File file = new File(HttpServer.WEB_ROOT, request.getUri());而后它检查该文件是否存在。假如存在的话,经过传递File对象让sendStaticResource构造一个java.io.FileInputStream对象。而后,它调用FileInputStream的read方法并把字节数组写入OutputStream对象。请注意,这种状况下,静态资源是做为原始数据发送给浏览器的。
if (file.exists()) {假如文件并不存在,sendStaticResource方法发送一个错误信息到浏览器。
fis = new FileInputstream(file);
int ch = fis.read(bytes, 0, BUFFER_SIZE);
while (ch!=-1) {
output.write(bytes, 0, ch);
ch = fis.read(bytes, 0, BUFFER_SIZE);
}
}
String errorMessage =
"Content-Type: text/html\r\n" +
"Content-Length: 23\r\n" +
"\r\n" +
"<h1>File Not Found</h1>";
output.write(errorMessage.getBytes());
java ex01.pyrmont.HttpServer为了测试应用程序,能够打开你的浏览器并在地址栏或网址框中敲入下面的命令:
http://localhost:8080/index.html正如Figure 1.1所示,你将会在你的浏览器里边看到index.html页面。
GET /index.html HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg,
application/vnd.ms-excel, application/msword, application/vnd.ms-
powerpoint, application/x-shockwave-flash, application/pdf, */*
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR
1.1.4322)
Host: localhost:8080
Connection: Keep-Alive
GET /images/logo.gif HTTP/1.1
Accept: */*
Referer: http://localhost:8080/index.html
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR
1.1.4322)
Host: localhost:8080
Connection: Keep-Alive
import javax.servlet.*;两个应用程序的类都放在ex02.pyrmont包里边。为了理解应用程序是如何工做的,你须要熟悉javax.servlet.Servlet接口。为了给你复习一下,将会在本章的首节讨论这个接口。在这以后,你将会学习一个servlet容器作了什么工做来为一个servlet提供HTTP请求。
import java.io.IOException;
import java.io.PrintWriter;
public class PrimitiveServlet implements Servlet {
public void init(ServletConfig config) throws ServletException {
System.out.println("init");
}
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
System.out.println("from service");
PrintWriter out = response.getWriter();
out.println("Hello. Roses are red.");
out.print("Violets are blue.");
}
public void destroy() {
System.out.println("destroy");
}
public String getServletInfo() {
return null;
}
public ServletConfig getServletConfig() {
return null;
}
}
public void init(ServletConfig config) throws ServletException在Servlet的五个方法中,init,service和destroy是servlet的生命周期方法。在servlet类已经初始化以后,init方法将会被servlet容器所调用。servlet容器只调用一次,以此代表servlet已经被加载进服务中。init方法必须在servlet能够接受任何请求以前成功运行完毕。一个servlet程序员能够经过覆盖这个方法来写那些仅仅只要运行一次的初始化代码,例如加载数据库驱动,值初始化等等。在其余状况下,这个方法一般是留空的。
public void service(ServletRequest request, ServletResponse response)
throws ServletException, java.io.IOException
public void destroy()
public ServletConfig getServletConfig()
public java.lang.String getServletInfo()
http://machineName:port/staticResource就像是在第1章提到的,你能够请求一个静态资源。
http://machineName:port/servlet/servletClass所以,假如你在本地请求一个名为PrimitiveServlet的servlet,你在浏览器的地址栏或者网址框中敲入:
http://localhost:8080/servlet/PrimitiveServletservlet容器能够就提供PrimitiveServlet了。不过,假如你调用其余servlet,如ModernServlet,servlet容器将会抛出一个异常。在如下各章中,你将会创建能够处理这两个状况的程序。
package ex02.pyrmont;类的await方法等待HTTP请求直到一个shutdown命令给发出,让你想起第1章的await方法。Listing 2.2的await方法和第1章的区别是,在Listing 2.2里边,请求能够分发给一个StaticResourceProcessor或者一个ServletProcessor。假如URI包括字符串/servlet/的话,请求将会转发到后面去。
import java.net.Socket;
import java.net.ServerSocket;
import java.net.InetAddress;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
public class HttpServer1 {
/** WEB_ROOT is the directory where our HTML and other files reside.
* For this package, WEB_ROOT is the "webroot" directory under the
* working directory.
* The working directory is the location in the file system
* from where the java command was invoked.
*/
// shutdown command
private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";
// the shutdown command received
private boolean shutdown = false;
public static void main(String[] args) {
HttpServer1 server = new HttpServer1();
server.await();
}
public void await() {
ServerSocket serverSocket = null;
int port = 8080;
try {
serverSocket = new ServerSocket(port, 1,
InetAddress.getByName("127.0.0.1"));
}
catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
// Loop waiting for a request
while (!shutdown) {
Socket socket = null;
InputStream input = null;
OutputStream output = null;
try {
socket = serverSocket.accept();
input = socket.getInputstream();
output = socket.getOutputStream();
// create Request object and parse
Request request = new Request(input);
request.parse();
// create Response object
Response response = new Response(output);
response.setRequest(request);
// check if this is a request for a servlet or
// a static resource
// a request for a servlet begins with "/servlet/"
if (request.getUri().startsWith("/servlet/")) {
ServletProcessor1 processor = new ServletProcessor1();
processor.process(request, response);
}
else {
StaticResoureProcessor processor =
new StaticResourceProcessor();
processor.process(request, response);
}
// Close the socket
socket.close();
//check if the previous URI is a shutdown command
shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
}
catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
}
package ex02.pyrmont;另外,Request类仍然有在第1章中讨论的parse和getUri方法。
import java.io.InputStream;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
public class Request implements ServletRequest {
private InputStream input;
private String uri;
public Request(InputStream input){
this.input = input;
}
public String getUri() {
return uri;
}
private String parseUri(String requestString) {
int index1, index2;
index1 = requestString.indexOf(' ');
if (index1 != -1) {
index2 = requestString.indexOf(' ', index1 + 1);
if (index2 > index1)
return requestString.substring(index1 + 1, index2);
}
return null;
}
public void parse() {
// Read a set of characters from the socket
StringBuffer request = new StringBuffer(2048);
int i;
byte[] buffer = new byte[2048];
try {
i = input.read(buffer);
}
catch (IOException e) {
e.printStackTrace();
i = -1;
}
for (int j=0; j<i; j++) {
request.append((char) buffer(j));
}
System.out.print(request.toString());
uri = parseUri(request.toString());
}
/* implementation of ServletRequest */
public Object getAttribute(String attribute) {
return null;
}
public Enumeration getAttributeNames() {
return null;
}
public String getRealPath(String path) {
return null;
}
public RequestDispatcher getRequestDispatcher(String path) {
return null;
}
public boolean isSecure() {
return false;
}
public String getCharacterEncoding() {
return null;
}
public int getContentLength() {
return 0;
}
public String getContentType() {
return null;
}
public ServletInputStream getInputStream() throws IOException {
return null;
}
public Locale getLocale() {
return null;
}
public Enumeration getLocales() {
return null;
}
public String getParameter(String name) {
return null;
}
public Map getParameterMap() {
return null;
}
public Enumeration getParameterNames() {
return null;
}
public String[] getParameterValues(String parameter) {
return null;
}
public String getProtocol() {
return null;
}
public BufferedReader getReader() throws IOException {
return null;
}
public String getRemoteAddr() {
return null;
}
public String getRemoteHost() {
return null;
}
public String getScheme() {
return null;
}
public String getServerName() {
return null;
}
public int getServerPort() {
return 0;
}
public void removeAttribute(String attribute) { }
public void setAttribute(String key, Object value) { }
public void setCharacterEncoding(String encoding)
throws UnsupportedEncodingException { }
}
package ex02.pyrmont;在getWriter方法中,PrintWriter类的构造方法的第二个参数是一个布尔值代表是否容许自动刷新。传递true做为第二个参数将会使任何println方法的调用都会刷新输出(output)。不过,print方法不会刷新输出。
import java.io.OutputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.File;
import java.io.PrintWriter;
import java.util.Locale;
import javax.servlet.ServletResponse;
import javax.servlet.ServletOutputStream;
public class Response implements ServletResponse {
private static final int BUFFER_SIZE = 1024;
Request request;
OutputStream output;
PrintWriter writer;
public Response(OutputStream output) {
this.output = output;
}
public void setRequest(Request request) {
this.request = request;
}
/* This method is used to serve static pages */
public void sendStaticResource() throws IOException {
byte[] bytes = new byte[BUFFER_SIZE];
FileInputstream fis = null;
try {
/* request.getUri has been replaced by request.getRequestURI */
File file = new File(Constants.WEB_ROOT, request.getUri());
fis = new FileInputstream(file);
/*
HTTP Response = Status-Line
*(( general-header | response-header | entity-header ) CRLF)
CRLF
[ message-body ]
Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
*/
int ch = fis.read(bytes, 0, BUFFER_SIZE);
while (ch!=-1) {
output.write(bytes, 0, ch);
ch = fis.read(bytes, 0, BUFFER_SIZE);
}
}
catch (FileNotFoundException e) {
String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length: 23\r\n" +
"\r\n" +
"<h1>File Not Found</h1>";
output.write(errorMessage.getBytes());
}
finally {
if (fis!=null)
fis.close();
}
}
/** implementation of ServletResponse */
public void flushBuffer() throws IOException ( }
public int getBufferSize() {
return 0;
}
public String getCharacterEncoding() {
return null;
}
public Locale getLocale() {
return null;
}
public ServletOutputStream getOutputStream() throws IOException {
return null;
}
public PrintWriter getWriter() throws IOException {
// autoflush is true, println() will flush,
// but print() will not.
writer = new PrintWriter(output, true);
return writer;
}
public boolean isCommitted() {
return false;
}
public void reset() { }
public void resetBuffer() { }
public void setBufferSize(int size) { }
public void setContentLength(int length) { }
public void setContentType(String type) { }
public void setLocale(Locale locale) { }
}
package ex02.pyrmont;process方法接收两个参数:一个ex02.pyrmont.Request实例和一个ex02.pyrmont.Response实例。这个方法只是简单的呼叫Response对象的sendStaticResource方法。
import java.io.IOException;
public class StaticResourceProcessor {
public void process(Request request, Response response) {
try {
response.sendStaticResource();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
package ex02.pyrmont;ServletProcessor1类出奇的简单,仅仅由一个方法组成:process。这个方法接受两个参数:一个
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandler;
import java.io.File;
import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class ServletProcessor1 {
public void process(Request request, Response response) {
String uri = request.getUri();
String servletName = uri.substring(uri.lastIndexOf("/") + 1);
URLClassLoader loader = null;
try {
// create a URLClassLoader
URL[] urls = new URL[1];
URLStreamHandler streamHandler = null;
File classPath = new File(Constants.WEB_ROOT);
// the forming of repository is taken from the
// createClassLoader method in
// org.apache.catalina.startup.ClassLoaderFactory
String repository =(new URL("file", null, classPath.getCanonicalPath() +
File.separator)).toString() ;
// the code for forming the URL is taken from
// the addRepository method in
// org.apache.catalina.loader.StandardClassLoader.
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.println(e.toString());
}
Servlet servlet = null;
try {
servlet = (Servlet) myClass.newInstance();
servlet.service((ServletRequest) request,
(ServletResponse) response);
}
catch (Exception e) {
System.out.println(e.toString());
}
catch (Throwable e) {
System.out.println(e.toString());
}
}
}
String uri = request.getUri();请记住URI是如下形式的:
/servlet/servletName在这里servletName是servlet类的名字。
String servletName = uri.substring(uri.lastIndexOf("/") + 1);接下去,process方法加载servlet。要完成这个,你须要建立一个类加载器并告诉这个类加载器要加载的类的位置。对于这个servlet容器,类加载器直接在Constants指向的目录里边查找。WEB_ROOT就是指向工做目录下面的webroot目录。
public URLClassLoader(URL[] urls);这里urls是一个java.net.URL的对象数组,这些对象指向了加载类时候查找的位置。任何以/结尾的URL都假设是一个目录。不然,URL会Otherwise, the URL假定是一个将被下载并在须要的时候打开的JAR文件。
public URL(URL context, java.lang.String spec, URLStreamHandler hander)你可使用这个构造方法,并为第二个参数传递一个说明,为第一个和第三个参数都传递null。不过,这里有另一个接受三个参数的构造方法:
throws MalformedURLException
public URL(java.lang.String protocol, java.lang.String host,所以,假如你使用下面的代码时,编译器将不会知道你指的是那个构造方法:
java.lang.String file) throws MalformedURLException
new URL(null, aString, null);你能够经过告诉编译器第三个参数的类型来避开这个问题,例如。
URLStreamHandler streamHandler = null;你可使用下面的代码在组成一个包含资源库(servlet类能够被找到的地方)的字符串,并做为第二个参数,
new URL(null, aString, streamHandler);
String repository = (new URL("file", null,把全部的片断组合在一块儿,这就是用来构造适当的URLClassLoader实例的process方法中的一部分:
classPath.getCanonicalPath() + File.separator)).toString() ;
// create a URLClassLoader注意: 用来生成资源库的代码是从org.apache.catalina.startup.ClassLoaderFactory的createClassLoader方法来的,而生成URL的代码是从org.apache.catalina.loader.StandardClassLoader的addRepository方法来的。不过,在如下各章以前你不须要担忧这些类。
URL[] urls = new URL[1];
URLStreamHandler streamHandler = null;
File classPath = new File(Constants.WEB_ROOT);
String repository = (new URL("file", null,
classPath.getCanonicalPath() + File.separator)).toString() ;
urls[0] = new URL(null, repository, streamHandler);
loader = new URLClassLoader(urls);
Class myClass = null;而后,process方法建立一个servlet类加载器的实例, 把它向下转换(downcast)为javax.servlet.Servlet, 并调用servlet的service方法:
try {
myClass = loader.loadClass(servletName);
}
catch (ClassNotFoundException e) {
System.out.println(e.toString());
}
Servlet servlet = null;
try {
servlet = (Servlet) myClass.newInstance();
servlet.service((ServletRequest) request,(ServletResponse) response);
}
catch (Exception e) {
System.out.println(e.toString());
}
catch (Throwable e) {
System.out.println(e.toString());
}
java -classpath ./lib/servlet.jar;./ ex02.pyrmont.HttpServer1在Linux下,你使用一个冒号来分隔两个库:
java -classpath ./lib/servlet.jar:./ ex02.pyrmont.HttpServer1要测试该应用程序,在浏览器的地址栏或者网址框中敲入:
http://localhost:8080/index.html或者
http://localhost:8080/servlet/PrimitiveServlet当调用PrimitiveServlet的时候,你将会在你的浏览器看到下面的文本:
Hello. Roses are red.请注意,由于只是第一个字符串被刷新到浏览器,因此你不能看到第二个字符串Violets are blue。咱们将在第3章修复这个问题。
try {这会危害安全性。知道这个servlet容器的内部运做的Servlet程序员能够分别把ServletRequest和ServletResponse实例向下转换为ex02.pyrmont.Request和ex02.pyrmont.Response,并调用他们的公共方法。拥有一个Request实例,它们就能够调用parse方法。拥有一个Response实例,就能够调用sendStaticResource方法。
servlet = (Servlet) myClass.newInstance();
servlet.service((ServletRequest) request,(ServletResponse) response);
}
package ex02.pyrmont;请注意RequestFacade的构造方法。它接受一个Request对象并立刻赋值给私有的servletRequest对象。还请注意,RequestFacade类的每一个方法调用ServletRequest对象的相应的方法。
public class RequestFacade implements ServletRequest {
private ServleLRequest request = null;
public RequestFacade(Request request) {
this.request = request;
}
/* implementation of the ServletRequest*/
public Object getAttribute(String attribute) {
return request.getAttribute(attribute);
}
public Enumeration getAttributeNames() {
return request.getAttributeNames();
}
...
}
if (request.getUri().startWith("/servlet/")) {ServletProcessor2类相似于ServletProcessor1,除了process方法中的如下部分:
servletProcessor2 processor = new ServletProcessor2();
processor.process(request, response);
}
else {
...
}
Servlet servlet = null;
RequestFacade requestFacade = new RequestFacade(request);
ResponseFacade responseFacade = new ResponseFacade(response);
try {
servlet = (Servlet) myClass.newInstance();
servlet.service((ServletRequest) requestFacade,(ServletResponse)responseFacade);
}
java -classpath ./lib/servlet.jar;./ ex02.pyrmont.HttpServer2在Linux下,你使用一个冒号来分隔两个库:
java -classpath ./lib/servlet.jar:./ ex02.pyrmont.HttpServer2你可使用与应用程序1同样的地址,并获得相同的结果。
private static Hashtable managers = new Hashtable();注意:一篇关于单例模式的题为"The Singleton Pattern"的文章能够在附带的ZIP文件中找到。
public synchronized static StringManager
getManager(String packageName) {
StringManager mgr = (StringManager)managers.get(packageName);
if (mgr == null) {
mgr = new StringManager(packageName);
managers.put(packageName, mgr);
}
return mgr;
}
StringManager sm =在包ex03.pyrmont.connector.http中,你会找到三个属性文件:LocalStrings.properties, LocalStrings_es.properties和LocalStrings_ja.properties。StringManager实例是根据运行程序的服务器的区域设置来决定使用哪一个文件的。假如你打开LocalStrings.properties,非注释的第一行是这样的:
StringManager.getManager("ex03.pyrmont.connector.http");
httpConnector.alreadyInitialized=HTTP connector has already been initialized要得到一个错误信息,可使用StringManager类的getString,并传递一个错误代号。这是其中一个重载方法:
public String getString(String key)经过传递httpConnector.alreadyInitialized做为getString的参数,将会返回"HTTP connector has already been initialized"。
package ex03.pyrmont.startup;Bootstrap类中的main方法实例化HttpConnector类并调用它的start方法。HttpConnector类在Listing 3.2给出。
import ex03.pyrmont.connector.http.HttpConnector;
public final class Bootstrap {
public static void main(String[] args) {
HttpConnector connector = new HttpConnector();
connector.start();
}
}
package ex03.pyrmont.connector.http;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class HttpConnector implements Runnable {
boolean stopped;
private String scheme = "http";
public String getScheme() {
return scheme;
}
public void run() {
ServerSocket serverSocket = null;
int port = 8080;
try {
serverSocket = new
ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));
}
catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
while (!stopped) {
// Accept the next incoming connection from the server socket
Socket socket = null;
try {
socket = serverSocket.accept();
}
catch (Exception e) {
continue;
}
// Hand this socket off to an HttpProcessor
HttpProcessor processor = new HttpProcessor(this);
processor.process(socket);
}
}
public void start() {
Thread thread = new Thread(this);
thread.start ();
}
}
public void process(Socket socket) {process首先得到套接字的输入流和输出流。请注意,在这个方法中,咱们适合继承了java.io.InputStream的SocketInputStream类。
SocketInputStream input = null;
OutputStream output = null;
try {
input = new SocketInputStream(socket.getInputStream(), 2048);
output = socket.getOutputStream();
// create HttpRequest object and parse
request = new HttpRequest(input);
// create HttpResponse object
response = new HttpResponse(output);
response.setRequest(request);
response.setHeader("Server", "Pyrmont Servlet Container");
parseRequest(input, output);
parseHeaders(input);
//check if this is a request for a servlet or a static resource
//a request for a servlet begins with "/servlet/"
if (request.getRequestURI().startsWith("/servlet/")) {
ServletProcessor processor = new ServletProcessor();
processor.process(request, response);
}
else {
StaticResourceProcessor processor = new
StaticResourceProcessor();
processor.process(request, response);
}
// Close the socket
socket.close();
// no shutdown for this application
}
catch (Exception e) {
e.printStackTrace ();
}
}
SocketInputStream input = null;而后,它建立一个HttpRequest实例和一个 instance and an HttpResponse instance and assigns
OutputStream output = null;
try {
input = new SocketInputStream(socket.getInputStream(), 2048);
output = socket.getOutputStream();
// create HttpRequest object and parse本章应用程序的HttpResponse类要比第2章中的Response类复杂得多。举例来讲,你能够经过调用他的setHeader方法来发送头部到一个客户端。
request = new HttpRequest(input);
// create HttpResponse object
response = new HttpResponse(output);
response.setRequest(request);
response.setHeader("Server", "Pyrmont Servlet Container");接下去,process方法调用HttpProcessor类中的两个私有方法来解析请求。
parseRequest(input, output);而后,它根据请求URI的形式把HttpRequest和HttpResponse对象传给ServletProcessor或者StaticResourceProcessor进行处理。
parseHeaders (input);
if (request.getRequestURI().startsWith("/servlet/")) {最后,它关闭套接字。
ServletProcessor processor = new ServletProcessor();
processor.process(request, response);
}
else {
StaticResourceProcessor processor =
new StaticResourceProcessor();
processor.process(request, response);
}
socket.close();也要注意的是,HttpProcessor类使用org.apache.catalina.util.StringManager类来发送错误信息:
protected StringManager sm =HttpProcessor类中的私有方法--parseRequest,parseHeaders和normalize,是用来帮助填充HttpRequest的。这些方法将会在下节"建立一个HttpRequest对象"中进行讨论。
StringManager.getManager("ex03.pyrmont.connector.http");
protected HashMap headers = new HashMap();注意:ParameterMap类将会在“获取参数”这节中解释。
protected ArrayList cookies = new ArrayList();
protected ParameterMap parameters = null;
byte[] buffer = new byte [2048];你没有试图为那两个应用程序去进一步解析请求。不过,在本章的应用程序中,你拥有 ex03.pyrmont.connector.http.SocketInputStream类,这是 org.apache.catalina.connector.http.SocketInputStream的一个拷贝。这个类提供了方法不只用来获取请求行,还有请求头部。
try {
// input is the InputStream from the socket.
i = input.read(buffer);
}
SocketInputStream input = null;就像前面提到的同样,拥有一个SocketInputStream是为了两个重要方法:readRequestLine和readHeader。请继续往下阅读。
OutputStream output = null;
try {
input = new SocketInputStream(socket.getInputStream(), 2048);
...
GET /myApp/ModernServlet?userName=tarzan&password=pwd HTTP/1.1请求行的第二部分是URI加上一个查询字符串。在上面的例子中,URI是这样的:
/myApp/ModernServlet另外,在问好后面的任何东西都是查询字符串。所以,查询字符串是这样的:
userName=tarzan&password=pwd查询字符串能够包括零个或多个参数。在上面的例子中,有两个参数名/值对,userName/tarzan和password/pwd。在servlet/JSP编程中,参数名jsessionid是用来携带一个会话标识符。会话标识符常常被做为cookie来嵌入,可是程序员能够选择把它嵌入到查询字符串去,例如,当浏览器的cookie被禁用的时候。
private void parseRequest(SocketInputStream input, OutputStream output)parseRequest方法首先调用SocketInputStream类的readRequestLine方法:
throws IOException, ServletException {
// Parse the incoming request line
input.readRequestLine(requestLine);
String method =
new String(requestLine.method, 0, requestLine.methodEnd);
String uri = null;
String protocol = new String(requestLine.protocol, 0,
requestLine.protocolEnd);
// Validate the incoming request line
if (method, length () < 1) {
throw new ServletException("Missing HTTP request method");
}
else if (requestLine.uriEnd < 1) {
throw new ServletException("Missing HTTP request URI");
}
// Parse any query parameters out of the request URI
int question = requestLine.indexOf("?");
if (question >= 0) {
request.setQueryString(new String(requestLine.uri, question + 1,
requestLine.uriEnd - question - 1));
uri = new String(requestLine.uri, 0, question);
}
else {
request.setQueryString(null);
uri = new String(requestLine.uri, 0, requestLine.uriEnd);
}
// Checking for an absolute URI (with the HTTP protocol)
if (!uri.startsWith("/")) {
int pos = uri.indexOf("://");
// Parsing out protocol and host name
if (pos != -1) {
pos = uri.indexOf('/', pos + 3);
if (pos == -1) {
uri = "";
}
else {
uri = uri.substring(pos);
}
}
}
// Parse any requested session ID out of the request URI
String match = ";jsessionid=";
int semicolon = uri.indexOf(match);
if (semicolon >= 0) {
String rest = uri.substring(semicolon + match,length());
int semicolon2 = rest.indexOf(';');
if (semicolon2 >= 0) {
request.setRequestedSessionId(rest.substring(0, semicolon2));
rest = rest.substring(semicolon2);
}
else {
request.setRequestedSessionId(rest);
rest = "";
}
request.setRequestedSessionURL(true);
uri = uri.substring(0, semicolon) + rest;
}
else {
request.setRequestedSessionId(null);
request.setRequestedSessionURL(false);
}
// Normalize URI (using String operations at the moment)
String normalizedUri = normalize(uri);
// Set the corresponding request properties
((HttpRequest) request).setMethod(method);
request.setProtocol(protocol);
if (normalizedUri != null) {
((HttpRequest) request).setRequestURI(normalizedUri);
}
else {
((HttpRequest) request).setRequestURI(uri);
}
if (normalizedUri == null) {
throw new ServletException("Invalid URI: " + uri + "'");
}
}
input.readRequestLine(requestLine);在这里requestLine是HttpProcessor里边的HttpRequestLine的一个实例:
private HttpRequestLine requestLine = new HttpRequestLine();调用它的readRequestLine方法来告诉SocketInputStream去填入HttpRequestLine实例。
String method =不过,在URI后面能够有查询字符串,假如存在的话,查询字符串会被一个问好分隔开来。所以,parseRequest方法试图首先获取查询字符串。并调用setQueryString方法来填充HttpRequest对象:
new String(requestLine.method, 0, requestLine.methodEnd);
String uri = null;
String protocol = new String(requestLine.protocol, 0, requestLine.protocolEnd);
// Parse any query parameters out of the request URI不过,大多数状况下,URI指向一个相对资源,URI还能够是一个绝对值,就像下面所示:
int question = requestLine.indexOf("?");
if (question >= 0) { // there is a query string.
request.setQueryString(new String(requestLine.uri, question + 1,
requestLine.uriEnd - question - 1));
uri = new String(requestLine.uri, 0, question);
}
else {
request.setQueryString (null);
uri = new String(requestLine.uri, 0, requestLine.uriEnd);
}
http://www.brainysoftware.com/index.html?name=TarzanparseRequest方法一样也检查这种状况:
// Checking for an absolute URI (with the HTTP protocol)而后,查询字符串也能够包含一个会话标识符,用jsessionid参数名来指代。所以,parseRequest方法也检查一个会话标识符。假如在查询字符串里边找到jessionid,方法就取得会话标识符,并经过调用setRequestedSessionId方法把值交给HttpRequest实例:
if (!uri.startsWith("/")) {
// not starting with /, this is an absolute URI
int pos = uri.indexOf("://");
// Parsing out protocol and host name
if (pos != -1) {
pos = uri.indexOf('/', pos + 3);
if (pos == -1) {
uri = "";
}
else {
uri = uri.substring(pos);
}
}
}
// Parse any requested session ID out of the request URI当jsessionid被找到,也意味着会话标识符是携带在查询字符串里边,而不是在cookie里边。所以,传递true给request的 setRequestSessionURL方法。不然,传递false给setRequestSessionURL方法并传递null给 setRequestedSessionURL方法。
String match = ";jsessionid=";
int semicolon = uri.indexOf(match);
if (semicolon >= 0) {
String rest = uri.substring(semicolon + match.length());
int semicolon2 = rest.indexOf(';');
if (semicolon2 >= 0) {
request.setRequestedSessionId(rest.substring(0, semicolon2));
rest = rest.substring(semicolon2);
}
else {
request.setRequestedSessionId(rest);
rest = "";
}
request.setRequestedSessionURL (true);
uri = uri.substring(0, semicolon) + rest;
}
else {
request.setRequestedSessionId(null);
request.setRequestedSessionURL(false);
}
((HttpRequest) request).setMethod(method);还有,假如normalize方法的返回值是null的话,方法将会抛出一个异常:
request.setProtocol(protocol);
if (normalizedUri != null) {
((HttpRequest) request).setRequestURI(normalizedUri);
}
else {
((HttpRequest) request).setRequestURI(uri);
}
if (normalizedUri == null) {
throw new ServletException("Invalid URI: " + uri + "'");
}
HttpHeader header = new HttpHeader();而后,你能够经过检测HttpHeader实例的nameEnd和valueEnd字段来测试是否能够从输入流中读取下一个头部信息:
// Read the next header
input.readHeader(header);
if (header.nameEnd == 0) {假如存在下一个头部,那么头部的名称和值能够经过下面方法进行检索:
if (header.valueEnd == 0) {
return;
}
else {
throw new ServletException (sm.getString("httpProcessor.parseHeaders.colon"));
}
}
String name = new String(header.name, 0, header.nameEnd);一旦你获取到头部的名称和值,你经过调用HttpRequest对象的addHeader方法来把它加入headers这个HashMap中:
String value = new String(header.value, 0, header.valueEnd);
request.addHeader(name, value);一些头部也须要某些属性的设置。例如,当servlet调用javax.servlet.ServletRequest的getContentLength方法的时候,content-length头部的值将被返回。而包含cookies的cookie头部将会给添加到cookie集合中。就这样,下面是其中一些过程:
if (name.equals("cookie")) {Cookie的解析将会在下一节“解析Cookies”中讨论。
... // process cookies here
}
else if (name.equals("content-length")) {
int n = -1;
try {
n = Integer.parseInt (value);
}
catch (Exception e) {
throw new ServletException(sm.getString(
"httpProcessor.parseHeaders.contentLength"));
}
request.setContentLength(n);
}
else if (name.equals("content-type")) {
request.setContentType(value);
}
Cookie: userName=budi; password=pwd;Cookie的解析是经过类org.apache.catalina.util.RequestUtil的parseCookieHeader方法来处理的。这个方法接受cookie头部并返回一个javax.servlet.http.Cookie数组。数组内的元素数量和头部里边的cookie名/值对个数是同样的。parseCookieHeader方法在Listing 3.5中列出。
public static Cookie[] parseCookieHeader(String header) {还有,这里是HttpProcessor类的parseHeader方法中用于处理cookie的部分代码:
if ((header == null) || (header.length 0 < 1) )
return (new Cookie[0]);
ArrayList cookies = new ArrayList();
while (header.length() > 0) {
int semicolon = header.indexOf(';');
if (semicolon < 0)
semicolon = header.length();
if (semicolon == 0)
break;
String token = header.substring(0, semicolon);
if (semicolon < header.length())
header = header.substring(semicolon + 1);
else
header = "";
try {
int equals = token.indexOf('=');
if (equals > 0) {
String name = token.substring(0, equals).trim();
String value = token.substring(equals+1).trim();
cookies.add(new Cookie(name, value));
}
}
catch (Throwable e) {
;
}
}
return ((Cookie[]) cookies.toArray (new Cookie [cookies.size ()]));
}
else if (header.equals(DefaultHeaders.COOKIE_NAME)) {
Cookie cookies[] = RequestUtil.ParseCookieHeader (value);
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals("jsessionid")) {
// Override anything requested in the URL
if (!request.isRequestedSessionIdFromCookie()) {
// Accept only the first session id cookie
request.setRequestedSessionId(cookies[i].getValue());
request.setRequestedSessionCookie(true);
request.setRequestedSessionURL(false);
}
}
request.addCookie(cookies[i]);
}
}
package org.apache.catalina.util;如今,让咱们来看parseParameters方法是怎么工做的。
import java.util.HashMap;
import java.util.Map;
public final class ParameterMap extends HashMap {
public ParameterMap() {
super ();
}
public ParameterMap(int initialCapacity) {
super(initialCapacity);
}
public ParameterMap(int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor);
}
public ParameterMap(Map map) {
super(map);
}
private boolean locked = false;
public boolean isLocked() {
return (this.locked);
}
public void setLocked(boolean locked) {
this.locked = locked;
}
private static final StringManager sm =
StringManager.getManager("org.apache.catalina.util");
public void clear() {
if (locked)
throw new IllegalStateException
(sm.getString("parameterMap.locked"));
super.clear();
}
public Object put(Object key, Object value) {
if (locked)
throw new IllegalStateException
(sm.getString("parameterMap.locked"));
return (super.put(key, value));
}
public void putAll(Map map) {
if (locked)
throw new IllegalStateException
(sm.getString("parameterMap.locked"));
super.putAll(map);
}
public Object remove(Object key) {
if (locked)
throw new IllegalStateException
(sm.getString("parameterMap.locked"));
return (super.remove(key));
}
}
if (parsed)而后,parseParameters方法建立一个名为results的ParameterMap变量,并指向parameters。假如
return;
ParameterMap results = parameters;而后,parseParameters方法打开parameterMap的锁以便写值。
if (results == null)
results = new ParameterMap();
results.setLocked(false);下一步,parseParameters方法检查字符编码,并在字符编码为null的时候赋予默认字符编码。
String encoding = getCharacterEncoding();而后,parseParameters方法尝试解析查询字符串。解析参数是使用org.apache.Catalina.util.RequestUtil的parseParameters方法来处理的。
if (encoding == null)
encoding = "ISO-8859-1";
// Parse any parameters specified in the query string接下来,方法尝试查看HTTP请求内容是否包含参数。这种状况发生在当用户使用POST方法发送请求的时候,内容长度大于零,而且内容类型是application/x-www-form-urlencoded的时候。因此,这里是解析请求内容的代码:
String queryString = getQueryString();
try {
RequestUtil.parseParameters(results, queryString, encoding);
}
catch (UnsupportedEncodingException e) {
;
}
// Parse any parameters specified in the input stream最后,parseParameters方法锁定ParameterMap,设置parsed为true,并把results赋予parameters。
String contentType = getContentType();
if (contentType == null)
contentType = "";
int semicolon = contentType.indexOf(';');
if (semicolon >= 0) {
contentType = contentType.substring (0, semicolon).trim();
}
else {
contentType = contentType.trim();
}
if ("POST".equals(getMethod()) && (getContentLength() > 0)
&& "application/x-www-form-urlencoded".equals(contentType)) {
try {
int max = getContentLength();
int len = 0;
byte buf[] = new byte[getContentLength()];
ServletInputStream is = getInputStream();
while (len < max) {
int next = is.read(buf, len, max - len);
if (next < 0 ) {
break;
}
len += next;
}
is.close();
if (len < max) {
throw new RuntimeException("Content length mismatch");
}
RequestUtil.parseParameters(results, buf, encoding);
}
catch (UnsupportedEncodingException ue) {
;
}
catch (IOException e) {
throw new RuntimeException("Content read fail");
}
}
// Store the final results
results.setLocked(true);
parsed = true;
parameters = results;
public PrintWriter getWriter() {请看,咱们是如何构造一个PrintWriter对象的?就是经过传递一个java.io.OutputStream实例来实现的。你传递给PrintWriter的print或println方法的任何东西都是经过底下的OutputStream进行发送的。
// if autoflush is true, println() will flush,
// but print() will not.
// the output argument is an OutputStream
writer = new PrintWriter(output, true);
return writer;
}
public PrintWriter getWriter() throws IOException {
ResponseStream newStream = new ResponseStream(this);
newStream.setCommit(false);
OutputStreamWriter osr =
new OutputStreamWriter(newStream, getCharacterEncoding());
writer = new ResponseWriter(osr);
return writer;
}
public void process(HttpRequest request, HttpResponse response) {另外,process方法使用HttpRequestFacade和HttpResponseFacade做为
servlet = (Servlet) myClass.newInstance();类StaticResourceProcessor几乎等同于类ex02.pyrmont.StaticResourceProcessor。
HttpRequestFacade requestPacade = new HttpRequestFacade(request);
HttpResponseFacade responseFacade = new HttpResponseFacade(response);
servlet.service(requestFacade, responseFacade);
((HttpResponse) response).finishResponse();
java -classpath ./lib/servlet.jar;./ ex03.pyrmont.startup.Bootstrap在Linux下,你使用一个冒号来分隔两个库:
java -classpath ./lib/servlet.jar:./ ex03.pyrmont.startup.Bootstrap要显示index.html,使用下面的URL:
http://localhost:808O/index.html要调用PrimitiveServlet,让浏览器指向下面的URL:
http://localhost:8080/servlet/PrimitiveServlet在你的浏览器中将会看到下面的内容:
Hello. Roses are red.注意:在第2章中运行PrimitiveServlet不会看到第二行。
Violets are blue.
http://localhost:8080/servlet/ModernServlet注意:ModernServlet的源代码在工做目录的webroot文件夹能够找到。
http://localhost:8080/servlet/ModernServlet?userName=tarzan&password=pwd
public void invoke(在invoke方法里边,容器加载servlet,调用它的service方法,管理会话,记录出错日志等等。
org.apache.catalina.Request request,
org.apache.catalina.Response response);
connection: keep-alive
I'm as helpless as a kitten up a tree.你将这样发送:
1D\r\n1D,是29的十六进制,指示第一块由29个字节组成。0\r\n标识这个事务的结束。
I'm as helpless as a kitten u
9\r\n
p a tree.
0\r\n
HTTP/1.1 100 Continue接着,服务器应该会继续读取输入流。
private Stack processors = new Stack();在HttpConnector中,建立的HttpProcessor实例数量是有两个变量决定的:minProcessors和 maxProcessors。默认状况下,minProcessors为5而maxProcessors为20,可是你能够经过 setMinProcessors和setMaxProcessors方法来改变他们的值。
protected int minProcessors = 5;开始的时候,HttpConnector对象建立minProcessors个HttpProcessor实例。若是一次有比HtppProcessor 实例更多的请求须要处理时,HttpConnector建立更多的HttpProcessor实例,直到实例数量达到maxProcessors个。在到达这点以后,仍不够HttpProcessor实例的话,请来的请求将会给忽略掉。若是你想让HttpConnector继续建立 HttpProcessor实例的话,把maxProcessors设置为一个负数。还有就是变量curProcessors保存了 HttpProcessor实例的当前数量。
private int maxProcessors = 20;
while (curProcessors < minProcessors) {newProcessor方法构造一个HttpProcessor对象并增长curProcessors。recycle方法把HttpProcessor队会栈。
if ((maxProcessors > 0) && (curProcessors >= maxProcessors))
break;
HttpProcessor processor = newProcessor();
recycle(processor);
}
while (!stopped) {对每一个前来的HTTP请求,会经过调用私有方法createProcessor得到一个HttpProcessor实例。
Socket socket = null;
try {
socket = serverSocket.accept();
...
HttpProcessor processor = createProcessor();然而,大部分时候createProcessor方法并不建立一个新的HttpProcessor对象。相反,它从池子中获取一个。若是在栈中已经存在一个HttpProcessor实例,createProcessor将弹出一个。若是栈是空的而且没有超过HttpProcessor实例的最大数量,createProcessor将会建立一个。然而,若是已经达到最大数量的话,createProcessor将会返回null。出现这样的状况的话,套接字将会简单关闭而且前来的HTTP请求不会被处理。
if (processor == null) {若是createProcessor不是返回null,客户端套接字会传递给HttpProcessor类的assign方法:
try {
log(sm.getString("httpConnector.noProcessor"));
socket.close();
}
...
continue;
processor.assign(socket);如今就是HttpProcessor实例用于读取套接字的输入流和解析HTTP请求的工做了。重要的一点是,assign方法不会等到 HttpProcessor完成解析工做,而是必须立刻返回,以便下一个前来的HTTP请求能够被处理。每一个HttpProcessor实例有本身的线程用于解析,因此这点不是很难作到。你将会在下节“HttpProcessor类”中看到是怎么作的。
public void run() {第3章中的HttpProcessor类的process方法是同步的。所以,在接受另外一个请求以前,它的run方法要等待process方法运行结束。
...
while (!stopped) {
Socket socket = null;
try {
socket = serversocket.accept();
}
catch (Exception e) {
continue;
}
// Hand this socket off to an Httpprocessor
HttpProcessor processor = new Httpprocessor(this);
processor.process(socket);
}
}
public void run() {run方法中的while循环按照这样的循序进行:获取一个套接字,处理它,调用链接器的recycle方法把当前的HttpProcessor实例推回栈。这里是HttpConenctor类的recycle方法:
// Process requests until we receive a shutdown signal
while (!stopped) {
// Wait for the next socket to be assigned
Socket socket = await();
if (socket == null)
continue;
// Process the request from this socket
try {
process(socket);
}
catch (Throwable t) {
log("process.invoke", t);
}
// Finish up this request
connector.recycle(this);
}
// Tell threadStop() we have shut ourselves down successfully
synchronized (threadSync) {
threadSync.notifyAll();
}
}
void recycle(HttpProcessor processor) {须要注意的是,run中的while循环在await方法中结束。await方法持有处理线程的控制流,直到从HttpConnector中获取到一个新的套接字。用另一种说法就是,直到HttpConnector调用HttpProcessor实例的assign方法。可是,await方法和assign方法运行在不一样的线程上。assign方法从HttpConnector的run方法中调用。咱们就说这个线程是HttpConnector实例的run方法运行的处理线程。assign方法是如何通知已经被调用的await方法的?就是经过一个布尔变量available而且使用java.lang.Object的wait和notifyAll方法。
processors.push(processor);
}
synchronized void assign(Socket socket) {两个方法的程序流向在Table 4.1中总结。
// Wait for the processor to get the previous socket
while (available) {
try {
wait();
}
catch (InterruptedException e) {
}
}
// Store the newly available Socket and notify our thread
this.socket = socket;
available = true;
notifyAll();
...
}
private synchronized Socket await() {
// Wait for the Connector to provide a new Socket
while (!available) {
try {
wait();
}
catch (InterruptedException e) {
}
}
// Notify the Connector that we have received this Socket
Socket socket = this.socket;
available = false;
notifyAll();
if ((debug >= 1) && (socket != null))
log(" The incoming request has been awaited");
return (socket);
}
The processor thread (the await method) The connector thread (the assign method)刚开始的时候,当处理器线程刚启动的时候,available为false,线程在while循环里边等待(见Table 4.1的第1列)。它将等待另外一个线程调用notify或notifyAll。这就是说,调用wait方法让处理器线程暂停,直到链接器线程调用HttpProcessor实例的notifyAll方法。
while (!available) { while (available) {
wait(); wait();
} }
Socket socket = this.socket; this.socket = socket;
available = false; available = true;
notifyAll(); notifyAll();
return socket; // to the run ...
// method
this.socket = socket;链接器线程把available设置为true并调用notifyAll。这就唤醒了处理器线程,由于available为true,因此程序控制跳出while循环:把实例的socket赋值给一个本地变量,并把available设置为false,调用notifyAll,返回最后须要进行处理的socket。
boolean ok = true;另外,process方法也使用了布尔变量keepAlive,stopped和http11。keepAlive表示链接是不是持久的,stopped表示HttpProcessor实例是否已经被链接器终止来确认process是否也应该中止,http11表示 从web客户端过来的HTTP请求是否支持HTTP 1.1。
boolean finishResponse = true;
SocketInputStream input = null;而后,有个while循环用来保持从输入流中读取,直到HttpProcessor被中止,一个异常被抛出或者链接给关闭为止。
OutputStream output = null;
// Construct and initialize the objects we will need
try {
input = new SocketInputStream(socket.getInputstream(),
connector.getBufferSize());
}
catch (Exception e) {
ok = false;
}
keepAlive = true;在while循环的内部,process方法首先把finishResponse设置为true,并得到输出流,并对请求和响应对象作些初始化处理。
while (!stopped && ok && keepAlive) {
...
}
finishResponse = true;接着,process方法经过调用parseConnection,parseRequest和parseHeaders方法开始解析前来的HTTP请求,这些方法将在这节的小节中讨论。
try {
request.setStream(input);
request.setResponse(response);
output = socket.getOutputStream();
response.setStream(output);
response.setRequest(request);
((HttpServletResponse) response.getResponse()).setHeader("Server", SERVER_INFO);
}
catch (Exception e) {
log("process.create", e); //logging is discussed in Chapter 7
ok = false;
}
try {parseConnection方法得到协议的值,像HTTP0.9, HTTP1.0或HTTP1.1。若是协议是HTTP1.0,keepAlive设置为false,由于HTTP1.0不支持持久链接。若是在HTTP请求里边找到Expect: 100-continue的头部信息,则parseHeaders方法将把sendAck设置为true。
if (ok) {
parseConnection(socket);
parseRequest(input, output);
if (!request.getRequest().getProtocol().startsWith("HTTP/0"))
parseHeaders(input);
if (http11) {ackRequest方法测试sendAck的值,并在sendAck为true的时候发送下面的字符串:
// Sending a request acknowledge back to the client if requested.
ackRequest(output);
// If the protocol is HTTP/1.1, chunking is allowed.
if (connector.isChunkingAllowed())
response.setAllowChunking(true);
}
HTTP/1.1 100 Continue\r\n\r\n在解析HTTP请求的过程当中,有可能会抛出异常。任何异常将会把ok或者finishResponse设置为false。在解析事后,process方法把请求和响应对象传递给容器的invoke方法:
try {接着,若是finishResponse仍然是true,响应对象的finishResponse方法和请求对象的finishRequest方法将被调用,而且结束输出。
((HttpServletResponse) response).setHeader("Date", FastHttpDateFormat.getCurrentDate());
if (ok) {
connector.getContainer().invoke(request, response);
}
}
if (finishResponse) {while循环的最后一部分检查响应的Connection头部是否已经在servlet内部设为close,或者协议是HTTP1.0.若是是这种状况的话,keepAlive设置为false。一样,请求和响应对象接着会被回收利用。
...
response.finishResponse();
...
request.finishRequest();
...
output.flush();
if ( "close".equals(response.getHeader("Connection")) ) {在这个场景中,若是哦keepAlive是true的话,while循环将会在开头就启动。由于在前面的解析过程当中和容器的invoke方法中没有出现错误,或者HttpProcessor实例没有被中止。不然,shutdownInput方法将会调用,而套接字将被关闭。
keepAlive = false;
}
// End of request processing
status = Constants.PROCESSOR_IDLE;
// Recycling the request and the response objects
request.recycle();
response.recycle();
}
try {shutdownInput方法检查是否有未读取的字节。若是有的话,跳过那些字节。
shutdownInput(input);
socket.close();
}
...
private void parseConnection(Socket socket) throws IOException, ServletException {
if (debug >= 2)
log(" parseConnection: address=" + socket.getInetAddress() +
", port=" + connector.getPort());
((HttpRequestImpl) request).setInet(socket.getInetAddress());
if (proxyPort != 0)
request.setServerPort(proxyPort);
else
request.setServerPort(serverPort);
request.setSocket(socket);
}
standard HTTP request headers in character arrays:parseHeaders方法包含一个while循环,能够持续读取HTTP请求直到再也没有更多的头部能够读取到。while循环首先调用请求对象的allocateHeader方法来获取一个空的HttpHead实例。这个实例被传递给
static final char[] AUTHORIZATION_NAME = "authorization".toCharArray();
static final char[] ACCEPT_LANGUAGE_NAME = "accept-language".toCharArray();
static final char[] COOKIE_NAME = "cookie".toCharArray();
...
HttpHeader header = request.allocateHeader();假如全部的头部都被已经被读取的话,readHeader方法将不会赋值给HttpHeader实例,这个时候parseHeaders方法将会返回。
// Read the next header
input.readHeader(header);
if (header.nameEnd == 0) {若是存在一个头部的名称的话,这里必须一样会有一个头部的值:
if (header.valueEnd == 0) {
return;
}
else {
throw new ServletException(sm.getString("httpProcessor.parseHeaders.colon"));
}
}
String value = new String(header.value, 0, header.valueEnd);接下去,像第3章那样,parseHeaders方法将会把头部名称和DefaultHeaders里边的名称作对比。注意的是,这样的对比是基于两个字符数组之间,而不是两个字符串之间的。
if (header.equals(DefaultHeaders.AUTHORIZATION_NAME)) {
request.setAuthorization(value);
}
else if (header.equals(DefaultHeaders.ACCEPT_LANGUAGE_NAME)) {
parseAcceptLanguage(value);
}
else if (header.equals(DefaultHeaders.COOKIE_NAME)) {
// parse cookie
}
else if (header.equals(DefaultHeaders.CONTENT_LENGTH_NAME)) {
// get content length
}
else if (header.equals(DefaultHeaders.CONTENT_TYPE_NAME)) {
request.setContentType(value);
}
else if (header.equals(DefaultHeaders.HOST_NAME)) {
// get host name
}
else if (header.equals(DefaultHeaders.CONNECTION_NAME)) {
if (header.valueEquals(DefaultHeaders.CONNECTION_CLOSE_VALUE)) {
keepAlive = false;
response.setHeader("Connection", "close");
}
}
else if (header.equals(DefaultHeaders.EXPECT_NAME)) {
if (header.valueEquals(DefaultHeaders.EXPECT_100_VALUE))
sendAck = true;
else
throw new ServletException(sm.getstring
("httpProcessor.parseHeaders.unknownExpectation"));
}
else if (header.equals(DefaultHeaders.TRANSFER_ENCODING_NAME)) {
//request.setTransferEncoding(header);
}
request.nextHeader();
package ex04.pyrmont.core;我只是提供了SimpleContainer类的invoke方法的实现,由于默认链接器将会调用这个方法。invoke方法建立了一个类加载器,加载servlet类,并调用它的service方法。这个方法和第3章的ServletProcessor类在哦个的process方法很是相似。
import java.beans.PropertyChangeListener;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandler;
import java.io.File;
import java.io.IOException;
import javax.naming.directory.DirContext;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.catalina.Cluster;
import org.apache.catalina.Container;
import org.apache.catalina.ContainerListener;
import org.apache.catalina.Loader;
import org.apache.catalina.Logger;
import org.apache.catalina.Manager;
import org.apache.catalina.Mapper;
import org.apache.catalina.Realm;
import org.apache.catalina.Request;
import org.apache.catalina.Response;
public class SimpleContainer implements Container {
public static final String WEB_ROOT =
System.getProperty("user.dir") + File.separator + "webroot";
public SimpleContainer() { }
public String getInfo() {
return null;
}
public Loader getLoader() {
return null;
}
public void setLoader(Loader loader) { }
public Logger getLogger() {
return null;
}
public void setLogger(Logger logger) { }
public Manager getManager() {
return null;
}
public void setManager(Manager manager) { }
public Cluster getCluster() {
return null;
}
public void setCluster(Cluster cluster) { }
public String getName() {
return null;
}
public void setName(String name) { }
public Container getParent() {
return null;
}
public void setParent(Container container) { }
public ClassLoader getParentClassLoader() {
return null;
}
public void setParentClassLoader(ClassLoader parent) { }
public Realm getRealm() {
return null;
}
public void setRealm(Realm realm) { }
public DirContext getResources() {
return null;
}
public void setResources(DirContext resources) { }
public void addChild(Container child) { }
public void addContainerListener(ContainerListener listener) { }
public void addMapper(Mapper mapper) { }
public void addPropertyChangeListener(
PropertyChangeListener listener) { }
public Container findchild(String name) {
return null;
}
public Container[] findChildren() {
return null;
}
public ContainerListener[] findContainerListeners() {
return null;
}
public Mapper findMapper(String protocol) {
return null;
}
public Mapper[] findMappers() {
return null;
}
public void invoke(Request request, Response response)
throws IoException, ServletException {
string servletName = ( (Httpservletrequest)
request).getRequestURI();
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.println(e.toString());
}
servlet servlet = null;
try {
servlet = (Servlet) myClass.newInstance();
servlet.service((HttpServletRequest) request,
(HttpServletResponse) response);
}
catch (Exception e) {
System.out.println(e.toString());
}
catch (Throwable e) {
System.out.println(e.toString());
}
}
public Container map(Request request, boolean update) {
return null;
}
public void removeChild(Container child) { }
public void removeContainerListener(ContainerListener listener) { }
public void removeMapper(Mapper mapper) { }
public void removoPropertyChangeListener(
PropertyChangeListener listener) {
}
}
package ex04.pyrmont.startup;Bootstrap 类的main方法构造了一个org.apache.catalina.connector.http.HttpConnector实例和一个 SimpleContainer实例。它接下去调用conncetor的setContainer方法传递container,让connector和container关联起来。下一步,它调用connector的initialize和start方法。这将会使得connector为处理8080端口上的任何请求作好了准备。
import ex04.pyrmont.core.simplecontainer;
import org.apache.catalina.connector.http.HttpConnector;
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();
// make the application wait until we press any key.
System in.read();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
要在Windows中运行这个程序的话,在工做目录下输入如下内容: html
java -classpath ./lib/servlet.jar;./ ex04.pyrmont.startup.Bootstrap