Struts2工具類

yefx 9年前發布 | 2K 次閱讀 Java Struts2

簡化獲取response,request及輸出操作

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils; import org.apache.struts2.ServletActionContext; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory;

/**

  • Struts2 Utils類.
  • 實現獲取Request/Response/Session與繞過jsp/freemaker直接輸出文本的簡化函數.
  • */ public class Struts2Utils {

     //header 常量定義
     private static final String ENCODING_PREFIX = "encoding:";
     private static final String NOCACHE_PREFIX = "no-cache:";
     private static final String ENCODING_DEFAULT = "UTF-8";
     private static final boolean NOCACHE_DEFAULT = true;
    
     private static Logger logger = LoggerFactory.getLogger(Struts2Utils.class);
    
     private Struts2Utils() {
     }
    
     // 取得Request/Response/Session的簡化函數 //
    
     /**
      * 取得HttpSession的簡化方法.
      */
     public static HttpSession getSession() {
             return ServletActionContext.getRequest().getSession();
     }
    
     /**
      * 取得HttpRequest的簡化方法.
      */
     public static HttpServletRequest getRequest() {
             return ServletActionContext.getRequest();
     }
    
     /**
      * 取得HttpResponse的簡化方法.
      */
     public static HttpServletResponse getResponse() {
             return ServletActionContext.getResponse();
     }
    
     /**
      * 取得Request Parameter的簡化方法.
      */
     public static String getParameter(String name) {
             return getRequest().getParameter(name);
     }
    
     // 繞過jsp/freemaker直接輸出文本的函數 //
    
     /**
      * 直接輸出內容的簡便函數.
    
      * eg.
      * render("text/plain", "hello", "encoding:GBK");
      * render("text/plain", "hello", "no-cache:false");
      * render("text/plain", "hello", "encoding:GBK", "no-cache:false");
      * 
      * @param headers 可變的header數組,目前接受的值為"encoding:"或"no-cache:",默認值分別為UTF-8和true.                 
      */
     public static void render(final String contentType, final String content, final String... headers) {
             try {
                     //分析headers參數
                     String encoding = ENCODING_DEFAULT;
                     boolean noCache = NOCACHE_DEFAULT;
                     for (String header : headers) {
                             String headerName = StringUtils.substringBefore(header, ":");
                             String headerValue = StringUtils.substringAfter(header, ":");
    
                             if (StringUtils.equalsIgnoreCase(headerName, ENCODING_PREFIX)) {
                                     encoding = headerValue;
                             } else if (StringUtils.equalsIgnoreCase(headerName, NOCACHE_PREFIX)) {
                                     noCache = Boolean.parseBoolean(headerValue);
                             } else
                                     throw new IllegalArgumentException(headerName + "不是一個合法的header類型");
                     }
    
                     HttpServletResponse response = ServletActionContext.getResponse();
    
                     //設置headers參數
                     String fullContentType = contentType + ";charset=" + encoding;
                     response.setContentType(fullContentType);
                     if (noCache) {
                             response.setHeader("Pragma", "No-cache");
                             response.setHeader("Cache-Control", "no-cache");
                             response.setDateHeader("Expires", 0);
                     }
    
                     response.getWriter().write(content);
    
             } catch (IOException e) {
                     logger.error(e.getMessage(), e);
             }
     }
    
     /**
      * 直接輸出文本.
      */
     public static void renderText(final String text, final String... headers) {
             render("text/plain", text, headers);
     }
    
     /**
      * 直接輸出HTML.
      */
     public static void renderHtml(final String html, final String... headers) {
             render("text/html", html, headers);
     }
    
     /**
      * 直接輸出XML.
      */
     public static void renderXml(final String xml, final String... headers) {
             render("text/xml", xml, headers);
     }
    
     /**
      * 直接輸出JSON.
      * 
      * @param string json字符串.
      */
     public static void renderJson(final String string, final String... headers) {
             render("application/json", string, headers);
     }
    
     /**
      * 直接輸出JSON.
      * 
      * @param map Map對象,將被轉化為json字符串.
      */
     @SuppressWarnings("unchecked")
     public static void renderJson(final Map map, final String... headers) {
             String jsonString = new JSONObject(map).toString();
             renderJson(jsonString, headers);
     }
    
     /**
      * 直接輸出JSON.
      * 
      * @param object Java對象,將被轉化為json字符串.
      */
     public static void renderJson(final Object object, final String... headers) {
             String jsonString = new JSONObject(object).toString();
             renderJson(jsonString, headers);
     }
    

    }</pre>

 本文由用戶 yefx 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!