温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JSP HTTP服务器如何实现对常规请求的支持

发布时间:2021-11-22 10:53:50 来源:亿速云 阅读:143 作者:小新 栏目:编程语言

这篇文章主要介绍JSP HTTP服务器如何实现对常规请求的支持,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

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

以上是“JSP HTTP服务器如何实现对常规请求的支持”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI