基于SSM的单点登陆02

pom文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <project xmlns="http://maven.apache.org/POM/4.0.0"
 3          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 5     <parent>
 6         <groupId>io.guangsoft</groupId>
 7         <artifactId>market</artifactId>
 8         <version>1.0</version>
 9     </parent>
10     <modelVersion>4.0.0</modelVersion>
11 
12     <artifactId>market-utils</artifactId>
13     <packaging>jar</packaging>
14 
15     <!-- 完成真正的jar包注入 -->
16     <dependencies>
17         <!-- Apache工具组件 -->
18         <dependency>
19             <groupId>commons-net</groupId>
20             <artifactId>commons-net</artifactId>
21         </dependency>
22         <!-- Json处理工具包 -->
23         <dependency>
24             <groupId>com.fasterxml.jackson.core</groupId>
25             <artifactId>jackson-databind</artifactId>
26         </dependency>
27         <dependency>
28             <groupId>com.alibaba</groupId>
29             <artifactId>fastjson</artifactId>
30         </dependency>
31         <!-- httpclient -->
32         <dependency>
33             <groupId>org.apache.httpcomponents</groupId>
34             <artifactId>httpclient</artifactId>
35         </dependency>
36         <!-- Servet api -->
37         <dependency>
38             <groupId>javax.servlet</groupId>
39             <artifactId>javax.servlet-api</artifactId>
40             <scope>provided</scope>
41         </dependency>
42     </dependencies>
43 
44 </project>

GResult.java

 1 package io.guangsoft.market.util.bean;
 2 
 3 public class GResult {
 4 
 5     //状态码
 6     private Integer gCode;
 7 
 8     //状态信息
 9     private String gMsg;
10 
11     //响应数据
12     private Object gData;
13 
14     public GResult() {
15     }
16 
17     public GResult(Integer gCode, String gMsg) {
18         this.gCode = gCode;
19         this.gMsg = gMsg;
20     }
21 
22     public GResult(Integer gCode, String gMsg, Object gData) {
23         this.gCode = gCode;
24         this.gMsg = gMsg;
25         this.gData = gData;
26     }
27 
28     public Integer getgCode() {
29         return gCode;
30     }
31 
32     public void setgCode(Integer gCode) {
33         this.gCode = gCode;
34     }
35 
36     public String getgMsg() {
37         return gMsg;
38     }
39 
40     public void setgMsg(String gMsg) {
41         this.gMsg = gMsg;
42     }
43 
44     public Object getgData() {
45         return gData;
46     }
47 
48     public void setgData(Object gData) {
49         this.gData = gData;
50     }
51 
52 }

GResultUtil.java

 1 package io.guangsoft.market.util.utils;
 2 
 3 import com.alibaba.fastjson.JSONObject;
 4 import io.guangsoft.market.util.bean.GResult;
 5 
 6 import java.beans.BeanInfo;
 7 import java.beans.Introspector;
 8 import java.beans.PropertyDescriptor;
 9 import java.lang.reflect.Method;
10 import java.util.HashMap;
11 import java.util.Map;
12 
13 public class GResultUtil {
14 
15     public static GResult success() {
16         return new GResult(0, "操作成功!");
17     }
18 
19     public static GResult fail() {
20         return new GResult(1, "操作失败!");
21     }
22 
23     public static GResult fail(Integer gCode) {
24         return new GResult(gCode, "操作失败!");
25     }
26 
27     public static GResult fail(Integer gCode, String gMsg) {
28         return new GResult(gCode, gMsg);
29     }
30 
31     public static GResult build(Integer gCode, String gMsg, Object gData) {
32         return new GResult(gCode, gMsg, gData);
33     }
34 
35     /**
36      * 得到JSON格式的结果集
37      */
38     public static JSONObject toJSONResult(GResult gResult) {
39         Map gResultMap = transBean2Map(gResult);
40         return new JSONObject(gResultMap);
41     }
42 
43     /**
44      * 使用内省方式将bean转成map
45      */
46     public static Map<String, Object> transBean2Map(Object obj) {
47         if(obj == null){
48             return null;
49         }
50         Map<String, Object> map = new HashMap<String, Object>();
51         try {
52             BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
53             PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
54             for (PropertyDescriptor property : propertyDescriptors) {
55                 String key = property.getName();
56                 // 过滤class属性
57                 if (!key.equals("class")) {
58                     // 得到property对应的getter方法
59                     Method getter = property.getReadMethod();
60                     Object value = getter.invoke(obj);
61                     map.put(key, value);
62                 }
63             }
64         } catch (Exception e) {
65             e.printStackTrace();
66         }
67         return map;
68     }
69 }

CookieUtil.java

  1 package io.guangsoft.market.util.utils;
  2 
  3 
  4 import java.net.URLDecoder;
  5 import java.net.URLEncoder;
  6 
  7 import javax.servlet.http.Cookie;
  8 import javax.servlet.http.HttpServletRequest;
  9 import javax.servlet.http.HttpServletResponse;
 10 
 11 public class CookieUtil {
 12 
 13     /**
 14      * 得到Cookie的值, 不编码
 15      */
 16     public static String getCookieValue(HttpServletRequest request, String cookieName) {
 17         return getCookieValue(request, cookieName, false);
 18     }
 19 
 20     /**
 21      * 得到Cookie的值,
 22      */
 23     public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) {
 24         Cookie[] cookieList = request.getCookies();
 25         if (cookieList == null || cookieName == null) {
 26             return null;
 27         }
 28         String retValue = null;
 29         try {
 30             for (int i = 0; i < cookieList.length; i++) {
 31                 if (cookieList[i].getName().equals(cookieName)) {
 32                     if (isDecoder) {
 33                         retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8");
 34                     } else {
 35                         retValue = cookieList[i].getValue();
 36                     }
 37                     break;
 38                 }
 39             }
 40         } catch (Exception e) {
 41             e.printStackTrace();
 42         }
 43         return retValue;
 44     }
 45 
 46     /**
 47      * 得到Cookie的值,
 48      */
 49     public static String getCookieValue(HttpServletRequest request, String cookieName, String encodeString) {
 50         Cookie[] cookieList = request.getCookies();
 51         if (cookieList == null || cookieName == null) {
 52             return null;
 53         }
 54         String retValue = null;
 55         try {
 56             for (int i = 0; i < cookieList.length; i++) {
 57                 if (cookieList[i].getName().equals(cookieName)) {
 58                     retValue = URLDecoder.decode(cookieList[i].getValue(), encodeString);
 59                     break;
 60                 }
 61             }
 62         } catch (Exception e) {
 63             e.printStackTrace();
 64         }
 65         return retValue;
 66     }
 67 
 68     /**
 69      * 设置Cookie的值 不设置生效时间默认浏览器关闭即失效,也不编码
 70      */
 71     public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
 72                                  String cookieValue) {
 73         setCookie(request, response, cookieName, cookieValue, -1);
 74     }
 75 
 76     /**
 77      * 设置Cookie的值 在指定时间内生效,但不编码
 78      */
 79     public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
 80                                  String cookieValue, int cookieMaxage) {
 81         setCookie(request, response, cookieName, cookieValue, cookieMaxage, false);
 82     }
 83 
 84     /**
 85      * 设置Cookie的值 不设置生效时间,但编码
 86      */
 87     public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
 88                                  String cookieValue, boolean isEncode) {
 89         setCookie(request, response, cookieName, cookieValue, -1, isEncode);
 90     }
 91 
 92     /**
 93      * 设置Cookie的值 在指定时间内生效, 编码参数
 94      */
 95     public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
 96                                  String cookieValue, int cookieMaxage, boolean isEncode) {
 97         doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, isEncode);
 98     }
 99 
100     /**
101      * 设置Cookie的值 在指定时间内生效, 编码参数(指定编码)
102      */
103     public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
104                                  String cookieValue, int cookieMaxage, String encodeString) {
105         doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, encodeString);
106     }
107 
108     /**
109      * 删除Cookie带cookie域名
110      */
111     public static void deleteCookie(HttpServletRequest request, HttpServletResponse response,
112                                     String cookieName) {
113         doSetCookie(request, response, cookieName, "", -1, false);
114     }
115 
116     /**
117      * 设置Cookie的值,并使其在指定时间内生效
118      *
119      * @param cookieMaxage cookie生效的最大秒数
120      */
121     private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response,
122                                           String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) {
123         try {
124             if (cookieValue == null) {
125                 cookieValue = "";
126             } else if (isEncode) {
127                 cookieValue = URLEncoder.encode(cookieValue, "utf-8");
128             }
129             Cookie cookie = new Cookie(cookieName, cookieValue);
130             if (cookieMaxage > 0) {
131                 cookie.setMaxAge(cookieMaxage);
132             }
133             if (null != request) {// 设置域名的cookie
134                 String domainName = getDomainName(request);
135                 System.out.println(domainName);
136                 if (!"localhost".equals(domainName) && !"127.0.0.1".equals(domainName)) {
137                     cookie.setDomain(domainName);
138                 }
139             }
140             cookie.setPath("/");
141             response.addCookie(cookie);
142         } catch (Exception e) {
143             e.printStackTrace();
144         }
145     }
146 
147     /**
148      * 设置Cookie的值,并使其在指定时间内生效
149      * @param cookieMaxage cookie生效的最大秒数
150      */
151     private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response,
152                                           String cookieName, String cookieValue, int cookieMaxage, String encodeString) {
153         try {
154             if (cookieValue == null) {
155                 cookieValue = "";
156             } else {
157                 cookieValue = URLEncoder.encode(cookieValue, encodeString);
158             }
159             Cookie cookie = new Cookie(cookieName, cookieValue);
160             if (cookieMaxage > 0) {
161                 cookie.setMaxAge(cookieMaxage);
162             }
163             if (null != request) {// 设置域名的cookie
164                 String domainName = getDomainName(request);
165                 System.out.println(domainName);
166                 if (!"localhost".equals(domainName)) {
167                     cookie.setDomain(domainName);
168                 }
169             }
170             cookie.setPath("/");
171             response.addCookie(cookie);
172         } catch (Exception e) {
173             e.printStackTrace();
174         }
175     }
176 
177     /**
178      * 得到cookie的域名
179      */
180     private static final String getDomainName(HttpServletRequest request) {
181         String domainName = null;
182         String serverName = request.getRequestURL().toString();
183         if (serverName == null || serverName.equals("")) {
184             domainName = "";
185         } else {
186             //http://www.baidu.com/aaa
187             //www.baidu.com.cn/aaa/bb/ccc
188             serverName = serverName.toLowerCase();
189             serverName = serverName.substring(7);
190             final int end = serverName.indexOf("/");
191             serverName = serverName.substring(0, end);
192             final String[] domains = serverName.split("\.");
193             int len = domains.length;
194             if (len > 3) {
195                 // www.xxx.com.cn
196                 domainName = "." + domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1];
197             } else if (len <= 3 && len > 1) {
198                 // xxx.com or xxx.cn
199                 domainName = "." + domains[len - 2] + "." + domains[len - 1];
200             } else {
201                 domainName = serverName;
202             }
203         }
204         if (domainName != null && domainName.indexOf(":") > 0) {
205             String[] ary = domainName.split("\:");
206             domainName = ary[0];
207         }
208         return domainName;
209     }
210 }

HttpClientUtil.java

  1 package io.guangsoft.market.util.utils;
  2 
  3 import java.io.IOException;
  4 import java.io.InterruptedIOException;
  5 import java.net.URI;
  6 import java.net.UnknownHostException;
  7 import java.util.ArrayList;
  8 import java.util.List;
  9 import java.util.Map.Entry;
 10 
 11 import javax.net.ssl.SSLException;
 12 import javax.net.ssl.SSLHandshakeException;
 13 
 14 import org.apache.http.Consts;
 15 import org.apache.http.HttpEntity;
 16 import org.apache.http.HttpEntityEnclosingRequest;
 17 import org.apache.http.HttpRequest;
 18 import org.apache.http.HttpResponse;
 19 import org.apache.http.NameValuePair;
 20 import org.apache.http.NoHttpResponseException;
 21 import org.apache.http.client.HttpClient;
 22 import org.apache.http.client.HttpRequestRetryHandler;
 23 import org.apache.http.client.config.RequestConfig;
 24 import org.apache.http.client.entity.UrlEncodedFormEntity;
 25 import org.apache.http.client.methods.HttpPost;
 26 import org.apache.http.client.protocol.HttpClientContext;
 27 import org.apache.http.config.Registry;
 28 import org.apache.http.config.RegistryBuilder;
 29 import org.apache.http.conn.ConnectTimeoutException;
 30 import org.apache.http.conn.socket.ConnectionSocketFactory;
 31 import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
 32 import org.apache.http.conn.socket.PlainConnectionSocketFactory;
 33 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
 34 import org.apache.http.impl.client.CloseableHttpClient;
 35 import org.apache.http.impl.client.HttpClients;
 36 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
 37 import org.apache.http.message.BasicNameValuePair;
 38 import org.apache.http.protocol.HttpContext;
 39 import org.apache.http.util.EntityUtils;
 40 
 41 import com.alibaba.fastjson.JSONObject;
 42 
 43 public class HttpClientUtil {
 44     
 45     private static CloseableHttpClient httpClient = null;
 46     static final int maxTotal = 5000;//最大并发数
 47     static final int defaultMaxPerRoute = 1000;//每路最大并发数
 48     static final int connectionRequestTimeout = 5000;// ms毫秒,从池中获取链接超时时间  
 49     static final int connectTimeout = 5000;// ms毫秒,建立链接超时时间  
 50     static final int socketTimeout = 30000;// ms毫秒,读取超时时间  
 51     
 52     private static CloseableHttpClient initHttpClient() {
 53         ConnectionSocketFactory plainFactory = PlainConnectionSocketFactory.getSocketFactory();
 54         LayeredConnectionSocketFactory sslFactory = SSLConnectionSocketFactory.getSocketFactory();
 55         Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().
 56                 register("http", plainFactory).register("https", sslFactory).build();
 57         PoolingHttpClientConnectionManager poolManager = new PoolingHttpClientConnectionManager(registry);
 58         poolManager.setMaxTotal(maxTotal);
 59         poolManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
 60         HttpRequestRetryHandler httpRetryHandler = new HttpRequestRetryHandler() {
 61             @Override
 62             public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
 63                 if(executionCount >= 2) {                    
 64                     return false;
 65                 }
 66                 if(exception instanceof NoHttpResponseException) {
 67                     return false;
 68                 }
 69                 if(exception instanceof SSLHandshakeException) {
 70                     return false;
 71                 }
 72                 if(exception instanceof InterruptedIOException) {
 73                     return false;
 74                 }
 75                 if(exception instanceof UnknownHostException) {
 76                     return false;
 77                 }
 78                 if(exception instanceof ConnectTimeoutException) {
 79                     return false;
 80                 }
 81                 if(exception instanceof SSLException) {
 82                     return false;
 83                 }
 84                 HttpClientContext clientContext = HttpClientContext.adapt(context);
 85                 HttpRequest request = clientContext.getRequest();
 86                 if(!(request instanceof HttpEntityEnclosingRequest)) {
 87                     return true;
 88                 }
 89                 return false;
 90             }
 91         };
 92         RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(connectionRequestTimeout).
 93                 setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build();
 94         CloseableHttpClient closeableHttpClient = HttpClients.custom().setConnectionManager(poolManager).setDefaultRequestConfig(requestConfig).
 95                 setRetryHandler(httpRetryHandler).build();
 96         return closeableHttpClient;
 97     }
 98     
 99     public static CloseableHttpClient getHttpClient() {
100         if(httpClient == null) {
101             synchronized (HttpClientUtil.class) {
102                 if(httpClient == null) {
103                     httpClient = initHttpClient();
104                 }
105             }
106         }
107         return httpClient;
108     }
109     
110     public static JSONObject sendPost(JSONObject requestData) {
111         JSONObject result = new JSONObject();
112         String url = requestData.getString("url");
113         JSONObject parameter = requestData.getJSONObject("parameter");
114         try {
115             HttpClient httpClient = HttpClientUtil.getHttpClient();
116             HttpPost httpPost = new HttpPost();
117             httpPost.setURI(new URI(url));
118             List<NameValuePair> param = new ArrayList<NameValuePair>();
119             for(Entry<String, Object> entry : parameter.entrySet()) {                
120                 param.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
121             }
122             httpPost.setEntity(new UrlEncodedFormEntity(param, Consts.UTF_8));
123             HttpResponse response = httpClient.execute(httpPost);
124             HttpEntity entity = response.getEntity();
125             String responseBody = EntityUtils.toString(entity);
126             int code = response.getStatusLine().getStatusCode();
127             result.put("CODE", code);
128             try {
129                 JSONObject responseJson = JSONObject.parseObject(responseBody);
130                 result.put("DATA", responseJson);
131             } catch(Exception e) {
132                 result.put("DATA", responseBody);
133             }
134             httpPost.abort();  
135             httpPost.releaseConnection();  
136         } catch (Exception e) {
137             e.printStackTrace();
138         }
139         return result;
140     }
141     
142 }
原文地址:https://www.cnblogs.com/guanghe/p/9195932.html