溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

JSP HTTP服務器如何實現對常規請求的支持

發布時間:2021-11-22 10:53:50 來源:億速云 閱讀:161 作者:小新 欄目:編程語言

這篇文章主要介紹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

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女