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. 浅谈push推送的一点感受

    在手机已成为生活必不可分的一部分,push服务伴随而来.ios的apns,android随着谷歌退出中国市场,各家在android的推送不断展开.有厂商的推送,如小米.华为.魅族.oppo等,还有中间 ...

  2. 从git上拉下来的严选weex项目demo

    项目地址 https://github.com/zwwill/yanxuan-weex-demo 在package.json里"author"之类后面加上 "privat ...

  3. ftp uploadFileAction(重要)

    TelnetOUtputStream os = ftpClient.put(filename); File file_in = new File(localPath); FileInputStream ...

  4. Java快车读书笔记

    办公自动化:OA 客户关系管理:CRM人力资源:HR 企业资源计划:ERP知识管理:KM 供应链管理:SCM企业设备管理系统:EAM 产品生命周期管理:PLM面向服务体系架构:SOA 商业智能:BI项 ...

  5. 字符串匹配(KMP 算法 含代码)

    主要是针对字符串的匹配算法进行解说 有关字符串的基本知识 传统的串匹配法 模式匹配的一种改进算法KMP算法 网上一比較易懂的解说 小样例 1计算next 2计算nextval 代码 有关字符串的基本知 ...

  6. Wedding (poj 3648 2-SAT 输出随意一组解)

    Language: Default Wedding Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 9004   Accept ...

  7. 拍照权限,GPS权限的控制

    最近项目中会遇到一些手机用户权限的问题,从网上百度了一下,发现有一些方法不能解决判断用户权限的是否开关,下面我就介绍两种权限的判断 1 拍照的权限控制 public static boolean is ...

  8. Observable观察者模式的使用

    今天我们公司封装的类中没有加上Observable观察者模式,但是很多地方需要用到Observable观察者模式 接下来就向大家介绍一下我的使用吧! 在介绍之前我们写了一个方法 public clas ...

  9. TP分页

    ①在Home下设置Publics文件夹或在thinkPHP下library的vender 把page.class.php 考贝进入 ②通过new 实例化方式调用 $page=new \Home\Pub ...

  10. poj3481(splay tree 入门题)

    平衡树都能做. // // main.cpp // splay // // Created by 陈加寿 on 16/3/25. // Copyright © 2016年 chenhuan001. A ...