pom文件

 <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>io.guangsoft</groupId>
<artifactId>market</artifactId>
<version>1.0</version>
</parent>
<modelVersion>4.0.0</modelVersion> <artifactId>market-utils</artifactId>
<packaging>jar</packaging> <!-- 完成真正的jar包注入 -->
<dependencies>
<!-- Apache工具组件 -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
</dependency>
<!-- Json处理工具包 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<!-- httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<!-- Servet api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
</dependencies> </project>

GResult.java

 package io.guangsoft.market.util.bean;

 public class GResult {

     //状态码
private Integer gCode; //状态信息
private String gMsg; //响应数据
private Object gData; public GResult() {
} public GResult(Integer gCode, String gMsg) {
this.gCode = gCode;
this.gMsg = gMsg;
} public GResult(Integer gCode, String gMsg, Object gData) {
this.gCode = gCode;
this.gMsg = gMsg;
this.gData = gData;
} public Integer getgCode() {
return gCode;
} public void setgCode(Integer gCode) {
this.gCode = gCode;
} public String getgMsg() {
return gMsg;
} public void setgMsg(String gMsg) {
this.gMsg = gMsg;
} public Object getgData() {
return gData;
} public void setgData(Object gData) {
this.gData = gData;
} }

GResultUtil.java

 package io.guangsoft.market.util.utils;

 import com.alibaba.fastjson.JSONObject;
import io.guangsoft.market.util.bean.GResult; import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map; public class GResultUtil { public static GResult success() {
return new GResult(0, "操作成功!");
} public static GResult fail() {
return new GResult(1, "操作失败!");
} public static GResult fail(Integer gCode) {
return new GResult(gCode, "操作失败!");
} public static GResult fail(Integer gCode, String gMsg) {
return new GResult(gCode, gMsg);
} public static GResult build(Integer gCode, String gMsg, Object gData) {
return new GResult(gCode, gMsg, gData);
} /**
* 得到JSON格式的结果集
*/
public static JSONObject toJSONResult(GResult gResult) {
Map gResultMap = transBean2Map(gResult);
return new JSONObject(gResultMap);
} /**
* 使用内省方式将bean转成map
*/
public static Map<String, Object> transBean2Map(Object obj) {
if(obj == null){
return null;
}
Map<String, Object> map = new HashMap<String, Object>();
try {
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
// 过滤class属性
if (!key.equals("class")) {
// 得到property对应的getter方法
Method getter = property.getReadMethod();
Object value = getter.invoke(obj);
map.put(key, value);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
}

CookieUtil.java

 package io.guangsoft.market.util.utils;

 import java.net.URLDecoder;
import java.net.URLEncoder; import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class CookieUtil { /**
* 得到Cookie的值, 不编码
*/
public static String getCookieValue(HttpServletRequest request, String cookieName) {
return getCookieValue(request, cookieName, false);
} /**
* 得到Cookie的值,
*/
public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) {
Cookie[] cookieList = request.getCookies();
if (cookieList == null || cookieName == null) {
return null;
}
String retValue = null;
try {
for (int i = 0; i < cookieList.length; i++) {
if (cookieList[i].getName().equals(cookieName)) {
if (isDecoder) {
retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8");
} else {
retValue = cookieList[i].getValue();
}
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return retValue;
} /**
* 得到Cookie的值,
*/
public static String getCookieValue(HttpServletRequest request, String cookieName, String encodeString) {
Cookie[] cookieList = request.getCookies();
if (cookieList == null || cookieName == null) {
return null;
}
String retValue = null;
try {
for (int i = 0; i < cookieList.length; i++) {
if (cookieList[i].getName().equals(cookieName)) {
retValue = URLDecoder.decode(cookieList[i].getValue(), encodeString);
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return retValue;
} /**
* 设置Cookie的值 不设置生效时间默认浏览器关闭即失效,也不编码
*/
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
String cookieValue) {
setCookie(request, response, cookieName, cookieValue, -1);
} /**
* 设置Cookie的值 在指定时间内生效,但不编码
*/
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
String cookieValue, int cookieMaxage) {
setCookie(request, response, cookieName, cookieValue, cookieMaxage, false);
} /**
* 设置Cookie的值 不设置生效时间,但编码
*/
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
String cookieValue, boolean isEncode) {
setCookie(request, response, cookieName, cookieValue, -1, isEncode);
} /**
* 设置Cookie的值 在指定时间内生效, 编码参数
*/
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
String cookieValue, int cookieMaxage, boolean isEncode) {
doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, isEncode);
} /**
* 设置Cookie的值 在指定时间内生效, 编码参数(指定编码)
*/
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
String cookieValue, int cookieMaxage, String encodeString) {
doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, encodeString);
} /**
* 删除Cookie带cookie域名
*/
public static void deleteCookie(HttpServletRequest request, HttpServletResponse response,
String cookieName) {
doSetCookie(request, response, cookieName, "", -1, false);
} /**
* 设置Cookie的值,并使其在指定时间内生效
*
* @param cookieMaxage cookie生效的最大秒数
*/
private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response,
String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) {
try {
if (cookieValue == null) {
cookieValue = "";
} else if (isEncode) {
cookieValue = URLEncoder.encode(cookieValue, "utf-8");
}
Cookie cookie = new Cookie(cookieName, cookieValue);
if (cookieMaxage > 0) {
cookie.setMaxAge(cookieMaxage);
}
if (null != request) {// 设置域名的cookie
String domainName = getDomainName(request);
System.out.println(domainName);
if (!"localhost".equals(domainName) && !"127.0.0.1".equals(domainName)) {
cookie.setDomain(domainName);
}
}
cookie.setPath("/");
response.addCookie(cookie);
} catch (Exception e) {
e.printStackTrace();
}
} /**
* 设置Cookie的值,并使其在指定时间内生效
* @param cookieMaxage cookie生效的最大秒数
*/
private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response,
String cookieName, String cookieValue, int cookieMaxage, String encodeString) {
try {
if (cookieValue == null) {
cookieValue = "";
} else {
cookieValue = URLEncoder.encode(cookieValue, encodeString);
}
Cookie cookie = new Cookie(cookieName, cookieValue);
if (cookieMaxage > 0) {
cookie.setMaxAge(cookieMaxage);
}
if (null != request) {// 设置域名的cookie
String domainName = getDomainName(request);
System.out.println(domainName);
if (!"localhost".equals(domainName)) {
cookie.setDomain(domainName);
}
}
cookie.setPath("/");
response.addCookie(cookie);
} catch (Exception e) {
e.printStackTrace();
}
} /**
* 得到cookie的域名
*/
private static final String getDomainName(HttpServletRequest request) {
String domainName = null;
String serverName = request.getRequestURL().toString();
if (serverName == null || serverName.equals("")) {
domainName = "";
} else {
//http://www.baidu.com/aaa
//www.baidu.com.cn/aaa/bb/ccc
serverName = serverName.toLowerCase();
serverName = serverName.substring(7);
final int end = serverName.indexOf("/");
serverName = serverName.substring(0, end);
final String[] domains = serverName.split("\\.");
int len = domains.length;
if (len > 3) {
// www.xxx.com.cn
domainName = "." + domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1];
} else if (len <= 3 && len > 1) {
// xxx.com or xxx.cn
domainName = "." + domains[len - 2] + "." + domains[len - 1];
} else {
domainName = serverName;
}
}
if (domainName != null && domainName.indexOf(":") > 0) {
String[] ary = domainName.split("\\:");
domainName = ary[0];
}
return domainName;
}
}

HttpClientUtil.java

 package io.guangsoft.market.util.utils;

 import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry; import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException; import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils; import com.alibaba.fastjson.JSONObject; public class HttpClientUtil { private static CloseableHttpClient httpClient = null;
static final int maxTotal = 5000;//最大并发数
static final int defaultMaxPerRoute = 1000;//每路最大并发数
static final int connectionRequestTimeout = 5000;// ms毫秒,从池中获取链接超时时间
static final int connectTimeout = 5000;// ms毫秒,建立链接超时时间
static final int socketTimeout = 30000;// ms毫秒,读取超时时间 private static CloseableHttpClient initHttpClient() {
ConnectionSocketFactory plainFactory = PlainConnectionSocketFactory.getSocketFactory();
LayeredConnectionSocketFactory sslFactory = SSLConnectionSocketFactory.getSocketFactory();
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().
register("http", plainFactory).register("https", sslFactory).build();
PoolingHttpClientConnectionManager poolManager = new PoolingHttpClientConnectionManager(registry);
poolManager.setMaxTotal(maxTotal);
poolManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
HttpRequestRetryHandler httpRetryHandler = new HttpRequestRetryHandler() {
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
if(executionCount >= 2) {
return false;
}
if(exception instanceof NoHttpResponseException) {
return false;
}
if(exception instanceof SSLHandshakeException) {
return false;
}
if(exception instanceof InterruptedIOException) {
return false;
}
if(exception instanceof UnknownHostException) {
return false;
}
if(exception instanceof ConnectTimeoutException) {
return false;
}
if(exception instanceof SSLException) {
return false;
}
HttpClientContext clientContext = HttpClientContext.adapt(context);
HttpRequest request = clientContext.getRequest();
if(!(request instanceof HttpEntityEnclosingRequest)) {
return true;
}
return false;
}
};
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(connectionRequestTimeout).
setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build();
CloseableHttpClient closeableHttpClient = HttpClients.custom().setConnectionManager(poolManager).setDefaultRequestConfig(requestConfig).
setRetryHandler(httpRetryHandler).build();
return closeableHttpClient;
} public static CloseableHttpClient getHttpClient() {
if(httpClient == null) {
synchronized (HttpClientUtil.class) {
if(httpClient == null) {
httpClient = initHttpClient();
}
}
}
return httpClient;
} public static JSONObject sendPost(JSONObject requestData) {
JSONObject result = new JSONObject();
String url = requestData.getString("url");
JSONObject parameter = requestData.getJSONObject("parameter");
try {
HttpClient httpClient = HttpClientUtil.getHttpClient();
HttpPost httpPost = new HttpPost();
httpPost.setURI(new URI(url));
List<NameValuePair> param = new ArrayList<NameValuePair>();
for(Entry<String, Object> entry : parameter.entrySet()) {
param.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
httpPost.setEntity(new UrlEncodedFormEntity(param, Consts.UTF_8));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String responseBody = EntityUtils.toString(entity);
int code = response.getStatusLine().getStatusCode();
result.put("CODE", code);
try {
JSONObject responseJson = JSONObject.parseObject(responseBody);
result.put("DATA", responseJson);
} catch(Exception e) {
result.put("DATA", responseBody);
}
httpPost.abort();
httpPost.releaseConnection();
} catch (Exception e) {
e.printStackTrace();
}
return result;
} }

基于SSM的单点登陆02的更多相关文章

  1. 基于SSM的单点登陆04

    jdbc.properties JDBC_DRIVER=org.mariadb.jdbc.Driver JDBC_URL=jdbc:mariadb://127.0.0.1:3306/market JD ...

  2. 基于SSM的单点登陆01

    使用SSM的Maven聚合项目 建立父项目market的pom文件 <?xml version="1.0" encoding="UTF-8"?> & ...

  3. 基于SSM的单点登陆05

    springmvc.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns=" ...

  4. 基于SSM的单点登陆03

    TbUser.java和TbUserExample.java,TbUserMapper.java,TbUserMapper.xml由mybatis框架生成. generatorConfig.xml & ...

  5. Spring Security 解析(六) —— 基于JWT的单点登陆(SSO)开发及原理解析

    Spring Security 解析(六) -- 基于JWT的单点登陆(SSO)开发及原理解析   在学习Spring Cloud 时,遇到了授权服务oauth 相关内容时,总是一知半解,因此决定先把 ...

  6. 集成基于OAuth协议的单点登陆

    在之前的一篇文章中,我们已经介绍了如何为一个应用添加对CAS协议的支持,进而使得我们的应用可以与所有基于CAS协议的单点登陆服务通讯.但是现在的单点登陆服务实际上并不全是通过实现CAS协议来完成的.例 ...

  7. 集成基于CAS协议的单点登陆

    相信大家对单点登陆(SSO,Single Sign On)这个名词并不感到陌生吧?简单地说,单点登陆允许多个应用使用同一个登陆服务.一旦一个用户登陆了一个支持单点登陆的应用,那么在进入其它使用同一单点 ...

  8. ASP.NET 单点登陆

    第一种:同主域但不同子域之间实现单点登陆 Form验证其实是基于身份cookie的验证.客户登陆后,生成一个包含用户身份信息(包含一个ticket)的cookie,这个cookie的名字就是在web. ...

  9. ASP.NET在不同情况下实现单点登陆(SSO)的方法

    第一种:同主域但不同子域之间实现单点登陆 Form验证其实是基于身份cookie的验证.客户登陆后,生成一个包含用户身份信息(包含一个ticket)的cookie,这个cookie的名字就是在web. ...

随机推荐

  1. linux 分区格式查看

    Linux分区格式查看 两个文件 /etc/fstab 和/etc/mtab /etc/fstab是用来存放文件系统的静态信息的文件,当系统启动的时候. 系统会自动地从这个文件读取信息,并且会自动将此 ...

  2. Hive查询错误:FAILED: RuntimeException Cannot make directory: hdfs://

    解决方法,关闭hadoop安全模式: hadoop dfsadmin -safemode leave

  3. OpenGL ES andoid学习————2

    package com.xhm.getaccount; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.F ...

  4. 【剑指Offer面试题】 九度OJ1518:反转链表

    与其非常快写出一段漏洞百出的代码,倒不如细致分析再写出鲁棒的代码. 提前想好測试用例(输入非空等等)进行測试改动代码. 题目链接地址: http://ac.jobdu.com/problem.php? ...

  5. 【BZOJ1731】[Usaco2005 dec]Layout 排队布局 差分约束

    [BZOJ1731][Usaco2005 dec]Layout 排队布局 Description Like everyone else, cows like to stand close to the ...

  6. Sleep Buddies

    Sleep Buddies time limit per test 2.0 s memory limit per test 256 MB input standard input output sta ...

  7. [JavaScript] this、call和apply详解

    在JavaScript编程中,理解this.call和apply是道槛,如果能正确的理解它们的本质及其应用.那么在以后的JavaScript中会得心应手. this 跟别的语言大相径庭的是,JavaS ...

  8. eclipse content assist 出现错误

    解决方法是,在Window->preference->java->editor>Content Assist->advanced ,将 time out 由50 ms 改 ...

  9. make tree install 目录树状结构工具安装

    http://futeng.iteye.com/blog/2071867 http://zhou123.blog.51cto.com/4355617/1196415 wget ftp://mama.i ...

  10. 【python】-- Django ORM(进阶)

    Django ORM(进阶) 上一篇博文简述了Django ORM的单表操作,在本篇博文中主要简述Django ORM的连表操作. 一.一对多:models.ForeignKey() 应用场景:当一张 ...