View Javadoc
1   package gboat2.base.bridge;
2   
3   import gboat2.base.bridge.exception.DefaultGboatNestedException;
4   import gboat2.base.bridge.model.UserSession;
5   import gboat2.base.bridge.util.json.JsonUtil;
6   
7   import java.io.PrintWriter;
8   
9   import javax.servlet.ServletContext;
10  import javax.servlet.http.HttpServletRequest;
11  import javax.servlet.http.HttpServletResponse;
12  import javax.servlet.http.HttpSession;
13  
14  import org.apache.commons.io.IOUtils;
15  import org.apache.struts2.ServletActionContext;
16  
17  /**
18   * 整个平台的上下文,提供一些通用的常规工具方法
19   * @date 2013-12-4
20   * @author hemw
21   * @since 2.1.2-SNAPSHOT
22   */
23  public class GboatAppContext implements GboatAppConstants{
24  
25      /**
26       * 返回web应用的根目录的绝对路径: eg: D:\apache-tomcat-7.0.23\webapps\G2\
27       * 
28       * @return web应用的根目录的绝对路径,如果因为某些原因未找到,则返回null
29       */
30      public static String getWebRootPath() {
31          String path = System.getProperty(WEBAPP_ROOT_KEY);
32          if (null == path) {
33              path = ServletActionContext.getServletContext().getRealPath("/");
34          }
35          return path;
36      }
37  
38      /**
39       * @return HTTP 请求的 Servlet 上下文实例
40       */
41      public static ServletContext getServletContext(){
42          return ServletActionContext.getServletContext();
43      }
44      
45      /**
46       * @return HTTP 请求实例
47       */
48      public static HttpServletRequest getRequest(){
49          return ServletActionContext.getRequest();
50      }
51      
52      /**
53       * @return HTTP 响应实例
54       */
55      public static HttpServletResponse getResponse(){
56          return ServletActionContext.getResponse();
57      }
58      
59      /**
60       * @return HTTP 请求的会话 Session 实例
61       */
62      public static HttpSession getSession(){
63          return getRequest().getSession();
64      }
65      
66      /**
67       * 根据 session 中的 key 获取对应的值
68       * @param name 保存在 session 中的 key
69       * @return session 中对应的值
70       */
71      public static Object getSessionAttr(String name){
72          return getSession().getAttribute(name);
73      }
74      
75      /**
76       * @return 用户 Session 实例
77       * @since 2.1.2
78       */
79      public static UserSession getUserSession() {
80          return getUserSession(null);
81      }
82      
83      /**
84       * 用户 Session 实例
85       * @param request
86       * @return
87       */
88      public static UserSession getUserSession(HttpServletRequest request){
89          if(request == null) {
90              request = getRequest();
91          }
92          
93  		Object userSessionObj = request.getSession().getAttribute(UserSession.USER_SESSION_KEY);
94  		if (userSessionObj instanceof UserSession) 
95  		    return (UserSession) userSessionObj;
96  
97  		return null;
98  	}
99      
100     /**
101      * @return 客户端的 IP 地址
102      */
103     public static String getRemoteAddr() {
104         HttpServletRequest request = getRequest();
105         String ip = request.getHeader("x-forwarded-for");
106         // 判断是否为反向代理,多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP值
107         // 是取X-Forwarded-For中第一个非unknown的有效IP字符串
108         if (ip != null && !"".equals(ip) && !"unknown".equalsIgnoreCase(ip)) {
109             String[] tempArray = ip.split(",");
110             for (int i = 0; i < tempArray.length; i++) {
111                 if (!"unknown".equalsIgnoreCase(tempArray[i])) {
112                     ip = tempArray[i].replaceAll("\\s", "");
113                     break;
114                 }
115             }
116         }
117         
118         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
119             ip = request.getHeader("Proxy-Client-IP");
120         }
121         
122         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
123             ip = request.getHeader("WL-Proxy-Client-IP");
124         }
125         
126         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
127             ip = request.getRemoteAddr();
128         }
129         
130         return ip;
131     }
132 
133     /**
134      * 向前台输出响应信息<br>
135      * 注意: 方法最后会调用HttpServletResponse.getWriter.close()
136      * @param obj 要输出到前台的响应对象
137      */
138     public static void output(Object obj) {
139         output(obj, null);
140     }
141     
142     /**
143      * 向前台输出响应信息<br>
144      * 注意: 方法最后会调用HttpServletResponse.getWriter.close()
145      * @param obj 要输出到前台的响应对象
146      */
147     public static void output(Object obj, HttpServletResponse response) {
148         if (obj == null)
149             throw new IllegalArgumentException("向前台输出的响应信息不能为 null");
150 
151         if(response == null) {
152             response = getResponse();
153         }
154         response.setContentType(CT_PLAIN_UTF8);
155         PrintWriter out = null;
156         try {
157             out = response.getWriter();
158             if (obj instanceof CharSequence) { // 如果是字符串,则直接输出
159                 out.print(obj);
160             } else {
161                 String objClass = obj.getClass().getName();
162                 if ("net.sf.json.JSONObject".equals(objClass)
163                         || "net.sf.json.JSONArray".equals(objClass)) { // 为了兼容低版本使用的 net.sf.json 包 
164                     out.print(obj);
165                 } else { // 输出 Json 格式字符串
166                     JsonUtil.object2Json(out, obj);
167                 }
168             }
169             out.flush();
170         } catch (Exception e) {
171             throw new DefaultGboatNestedException("向前台输出响应信息 [" + obj + "] 失败。", e);
172         } finally {
173             IOUtils.closeQuietly(out);
174             out = null;
175         }
176     }
177 }