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. Java基础03 构造器与方法重载(转载)

    显式初始化要求我们在写程序时就确定初始值,这有时很不方便.我们可以使用构造器(constructor)来初始化对象.构造器可以初始化数据成员,还可以规定特定的操作.这些操作会在创建对象时自动执行. 定 ...

  2. 关闭数据库时SHUTDOWN: waiting for active calls to complete.处理

    有时候在关闭数据库时,发出shutdown immediate;命令后一直未关闭.查看ALERT日志.在等待一段时间后日志中有提示: SHUTDOWN: waiting for active call ...

  3. 相对定位position: relative;

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  4. PID file found but no matching process was found. Stop aborted

    一般脚本部署时不会遇到这种情况,有时候自个手动处理会出现”PID file found but no matching process was found. Stop aborted”,根据意思就可以 ...

  5. Permutation Descent Counts(递推)

    1968: Permutation Descent Counts Submit Page   Summary   Time Limit: 1 Sec     Memory Limit: 128 Mb  ...

  6. hihoCoder 1549 或运算和

    #1549 : 或运算和 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 给定N个数A1...AN (0 <= Ai < 220) 和一个正整数K,我们用An ...

  7. 记录--java 分页 思路 (hibernate关键代码)

    有时会脑袋蒙圈,记录下分页的思路 下面代码是hibernate的分页,其分页就是从第几条数据为起点,取几条数据.比如在mysql中的limit(5,10)取的就是第6条到第10条 在下面代码中的pag ...

  8. VSpy之C Code Interface的使用

    Spy3 要运行 CCodeInterface 功能,需要安装运行环境,建议安装 Visual Studio2003,2005,2008,2010 或更新的版本.当然也可以安装 VC express ...

  9. Python菜鸟之路:Django 中间件

    前言 在正式说Django中间件之前需要先了解Django一个完整的request的处理流程.我从其他网站扒了几张图过来. 图片一: 文字流程说明:如图所示,一个 HTTP 请求,首先被转化成一个 H ...

  10. ES6学习笔记(三)——数值的扩展

    看到这条条目录有没有感觉很枯燥,觉得自己的工作中还用不到它所以实在没有耐心看下去,我也是最近得闲,逼自己静下心来去学习去总结,只有在别人浮躁的时候你能静下心来去学去看去总结,你才能进步.毕竟作为前端不 ...