servlet填充Response時,數據轉換之content-type


 在Http請求中,我們每天都在使用Content-type來指定不同格式的請求信息,但是卻很少有人去全面了解content-type中允許的值有多少,這里將講解Content-Type的可用值。

1.  Content-Type

  MediaType,即是Internet Media Type,互聯網媒體類型;也叫做MIME類型,在Http協議消息頭中,使用Content-Type來表示具體請求中的媒體類型信息。  

  類型格式:type/subtype(;parameter)? type
  主類型,任意的字符串,如text,如果是*號代表所有; 
  subtype 子類型,任意的字符串,如html,如果是*號代表所有; 
  parameter 可選,一些參數,如Accept請求頭的q參數, Content-Type的 charset參數。 

例如: Content-Type: text/html;charset:utf-8;

 

常見的媒體格式類型如下:

  •     text/html : HTML格式
  •     text/plain :純文本格式     
  •     text/xml :  XML格式
  •     image/gif :gif圖片格式   
  •     image/jpeg :jpg圖片格式
  •     image/png:png圖片格式

   以application開頭的媒體格式類型:

  •    application/xhtml+xml :XHTML格式
  •    application/xml     : XML數據格式
  •    application/atom+xml  :Atom XML聚合格式   
  •    application/json    : JSON數據格式
  •    application/pdf       :pdf格式 
  •    application/msword  : Word文檔格式
  •    application/octet-stream : 二進制流數據(如常見的文件下載)
  •    application/x-www-form-urlencoded : <form encType=””>中默認的encType,form表單數據被編碼為key/value格式發送到服務器(表單默認的提交數據的格式)

   另外一種常見的媒體格式是上傳文件之時使用的:

  •     multipart/form-data : 需要在表單中進行文件上傳時,就需要使用該格式

     以上就是我們在日常的開發中,經常會用到的若干content-type的內容格式。

 

demo:Response JSON數據返回

簡述:

在servlet填充Response的時候,做JSON格式的數據轉換

使用的類是net.sf.json.JSONObject,傳入response對象和返回的顯示類,修改response,返回前台JSON格式數據

  • /**
  • * 以JSON格式輸出
  • * @param response
  • */ 
  • protected void responseOutWithJson(HttpServletResponse response, 
  •         Object responseObject) { 
  •     //將實體對象轉換為JSON Object轉換 
  •     JSONObject responseJSONObject = JSONObject.fromObject(responseObject); 
  •     response.setCharacterEncoding("UTF-8"); 
  •     response.setContentType("application/json; charset=utf-8"); 
  •     PrintWriter out = null; 
  •     try { 
  •         out = response.getWriter(); 
  •         out.append(responseJSONObject.toString()); 
  •         logger.debug("返回是\n"); 
  •         logger.debug(responseJSONObject.toString()); 
  •     } catch (IOException e) { 
  •         e.printStackTrace(); 
  •     } finally { 
  •         if (out != null) { 
  •             out.close(); 
  •         } 
  •     } 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM