JSP HTTP服务器对常规请求的支持
这里的常规请求是指请求的资源为文件类型,不需要进行解释,编译,执行等处理。例如:文本文件(*.TXT),超文本文件(*.HTM,*.HTML),脚本文件(*.JS,*.VBS等),图片文件(*.JPG,*.PNG,*.GIF,*.BMP)。
处理基于文件流的请求较为简单。只需要读取本地的文件资源,再发送给客户端即可。
1.JSP HTTP服务器文件流请求的处理示例代码
- //Create client socket output stream
- m_sout = new PrintWriter(m_s.getOutputStream(), true);
- m_soutx = null;
- m_sout.println("HTTP/1.0 200 OK/nMIME-Version:1.0/nContent-Type:text/html/n/n");
- File file = new File(fileName);
- if(file.exists() == true)
- {
- //Create local file input stream
- BufferedReader fin = new BufferedReader(new FileReader(file) );
- String line = null;
- String response = "";
- //Read file by lines
- while( (line = fin.readLine() ) != null)
- {
- responseresponse = response + line + "/n";
- }
- //Send the content to client socket
- m_sout.println(response);
- //Close local file handle
- fin.close();
- }
以上是处理基于文本流的请求,以下是处理基于二进制流的请求实例代码。
2.JSP HTTP服务器二进制流文件的处理示例代码
- //Create client socket output stream
- m_sm_soutx = m_s.getOutputStream();
- m_sout = null;
- String header = "HTTP/1.0 200 OK/nMIME-Version:1.0/n";
- //Send content to client socket
- m_soutx.write(header.getBytes() );
- String mime = "";
- //Get MIME by file type
- switch(typeFlag)
- {
- case TYPE_JPEG: //jpeg file
- {
- mime = "image/jpeg";
- break;
- }
- case TYPE_GIF: //gif file
- {
- mime = "image/gif";
- break;
- }
- case TYPE_BMP: //bmp file
- {
- mime = "image/bmp";
- break;
- }
- case TYPE_PNG: //png file
- {
- mime = "image/png";
- break;
- }
- }
- mime = "Content-Type:" + mime + "/n/n";
- m_soutx.write(mime.getBytes() );
- File file = new File(fileName);
- if(file.exists() == true) //Read image files and send to client socket
- {
- //Create local file input stream
- RandomAccessFile fin = new RandomAccessFile(fileName, "r");
- final long size = fin.length();
- byte [] buffer = new byte[(int)size];
- fin.readFully(buffer);
- fin.close();
- //Send data to client socket
- m_soutx.write(buffer);
- }
- //Close client socket output stream
- m_soutx.close();
从以上代码可以看出,处理文本流和二进制流的请求的方式是不相同的,文本流的文件是按照行进行处理,而二进制流的文件是以批量读取。
其中关键的是,对于不同的文件类型,发送数据给客户端时必须指明服务器端应答的媒体类型,即MIME(Multipurpose Internet Mail Extensions),这样应答给客户端的资源才能被客户端浏览器所识别,并调用相应的应用程序对资源进行读取。
文件类型 扩展名 MIME
文本文件 .TXT text/plain
HTML(HyperText Markup Language)文件 .HTML,.HTM text/html
JPEG(Joint Photographic Experts Group)文件 .JPG,.JPEG image/jpeg
PNG(Portable Network Graphic Format)文件 .PNG image/png
BMP(Bitmap)文件 .BMP application/x-MS-bmp
GIF(Graphics Interchange Format)文件 .GIF image/gif
XML(EXtensible Markup Language)文件 .XML text/xml
常用类型文件的MIME