1.jsp文件导入:
2.session跨域:
3.sso(单点登录(single sign on):
sso Maven Webapp:
LoginController.java:
packagecom.sso.demo.controller;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.http.converter.json.MappingJacksonValue;importorg.springframework.stereotype.Controller;importorg.springframework.ui.Model;importorg.springframework.web.bind.annotation.PathVariable;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestMethod;importorg.springframework.web.bind.annotation.ResponseBody;importcom.sso.demo.model.User;importcom.sso.demo.service.LoginService;
@Controllerpublic classLoginController {
@AutowiredprivateLoginService loginService;/*** @description 跳转到登录页面
*@return
*/@RequestMapping("/turnLogin")publicString turnLoginPage(String referPage, Model model) {
model.addAttribute("redirect", referPage);return "login";
}/*** @description 检查该用户是否已经登录
*@paramtoken
*@return
*/@RequestMapping(value= "/token/{token}", method =RequestMethod.GET)
@ResponseBodypublic Object checkLogin(@PathVariable("token") String token, String callback) {
String userJson=loginService.checkLogin(token);if(callback == null) {//就是一个普通请求,并不是跨域请求
returnuserJson;
}else{//一定产生跨域//MappingJacksonValue对象是spring4.0版本以后支持跨域封装对象//MappingJacksonValue是专门返回跨域请求的class//自动把userJson转换为跨域所需要的发送数据//最终返回mappingJacksonValue,也就是返回了跨域所需要的数据//setJsonpFunction(callback)-->处理callback参数,让js知道我已经接收到了你传递给过来的callback,也就是知道//该请求为一个跨域请求
MappingJacksonValue mappingJacksonValue = newMappingJacksonValue(userJson);
mappingJacksonValue.setJsonpFunction(callback);returnmappingJacksonValue;
}
}/*** @description 登录功能
*@paramuser
*@return
*/@RequestMapping("/doLogin")
@ResponseBodypublicString doLogin(User user, HttpServletRequest request, HttpServletResponse response) {//直接调用service
returnloginService.doLogin(user, request, response);
}
}
UserMapper.java:
packagecom.sso.demo.mapper;importcom.sso.demo.model.User;importtk.mybatis.mapper.common.Mapper;public interface UserMapper extends Mapper{
}
User.java:
packagecom.sso.demo.model;import javax.persistence.*;public classUser {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)privateLong id;privateString username;privateString password;privateString email;privateInteger phone;
@Column(name= "head_pic_path")privateString headPicPath;/***@returnid*/
publicLong getId() {returnid;
}/***@paramid*/
public voidsetId(Long id) {this.id =id;
}/***@returnusername*/
publicString getUsername() {returnusername;
}/***@paramusername*/
public voidsetUsername(String username) {this.username = username == null ? null: username.trim();
}/***@returnpassword*/
publicString getPassword() {returnpassword;
}/***@parampassword*/
public voidsetPassword(String password) {this.password = password == null ? null: password.trim();
}/***@returnemail*/
publicString getEmail() {returnemail;
}/***@paramemail*/
public voidsetEmail(String email) {this.email = email == null ? null: email.trim();
}/***@returnphone*/
publicInteger getPhone() {returnphone;
}/***@paramphone*/
public voidsetPhone(Integer phone) {this.phone =phone;
}/***@returnhead_pic_path*/
publicString getHeadPicPath() {returnheadPicPath;
}/***@paramheadPicPath*/
public voidsetHeadPicPath(String headPicPath) {this.headPicPath = headPicPath == null ? null: headPicPath.trim();
}
}
RedisServiceImpl.java:
packagecom.sso.demo.service.impl;importcom.sso.demo.service.IRedisService;importredis.clients.jedis.JedisCluster;public class RedisServiceImpl implementsIRedisService {privateJedisCluster jedisCluster;publicJedisCluster getJedisCluster() {returnjedisCluster;
}public voidsetJedisCluster(JedisCluster jedisCluster) {this.jedisCluster =jedisCluster;
}
@OverridepublicString get(String key) {returnjedisCluster.get(key);
}
@OverridepublicString set(String key, String value) {returnjedisCluster.set(key, value);
}
@OverridepublicLong del(String... keys) {returnjedisCluster.del(keys);
}
@OverridepublicLong expire(String key, Integer seconds) {returnjedisCluster.expire(key, seconds);
}
}
IRedisService.java:
packagecom.sso.demo.service;public interfaceIRedisService {/*** @description 通过key来获取数据
*@paramkey
*@return
*/
publicString get(String key);/*** @description 往redis集群中存入数据
*@paramkey
*@paramvalue
*@return
*/
publicString set(String key, String value);/*** @description 通过key删除redis中的数据
*@paramkey
*@return
*/
publicLong del(String... keys);/*** @description 通过key为redis中的缓存设置失效时间
*@paramkey
*@paramseconds*/
publicLong expire(String key, Integer seconds);
}
LoginService.java:
packagecom.sso.demo.service;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.stereotype.Service;importcom.sso.demo.mapper.UserMapper;importcom.sso.demo.model.User;importcom.sso.demo.utils.CookieUtil;importcom.sso.demo.utils.JSONUtil;importcom.sso.demo.utils.UUIDUtil;
@Servicepublic classLoginService {
@Value("${session_key}")privateString sessionKey;
@Value("${cookie_key}")privateString cookieKey;
@Value("${expire_time_out}")privateInteger expireTimeOut;
@AutowiredprivateIRedisService redisService;
@AutowiredprivateUserMapper userMapper;publicString checkLogin(String token) {
String userJson= redisService.get(sessionKey + ":" +token);if (userJson == null) {return null;
}returnuserJson;
}publicString doLogin(User user, HttpServletRequest request, HttpServletResponse response) {
User u=userMapper.selectOne(user);
String token=UUIDUtil.getUUID();if (u != null) {
u.setPassword(null);//把user对象存入redis中,因为redis中需要String,所以首先要把user对象转换为json的字符串
String userString =JSONUtil.toJSONString(u);
String ok= redisService.set(sessionKey + ":" +token, userString);if ("ok".equals(ok.toLowerCase())) {//把token值存入cookie
System.out.println(cookieKey);
redisService.expire(sessionKey+ ":" +token, expireTimeOut);
CookieUtil.setCookie(request, response, cookieKey, token);returntoken;
}
}return null;
}
}
CookieUtil.java:
packagecom.sso.demo.utils;importjava.io.UnsupportedEncodingException;importjava.net.URLDecoder;importjava.net.URLEncoder;importjavax.servlet.http.Cookie;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;/***
* @description Cookie工具类
*@authorSeven Lee
**/
public classCookieUtil {/*** 得到Cookie的值, 不编码
*
*@paramrequest
*@paramcookieName
*@return
*/
public staticString getCookieValue(HttpServletRequest request, String cookieName) {return getCookieValue(request, cookieName, false);
}/*** 得到Cookie的值,
*
*@paramrequest
*@paramcookieName
*@return
*/
public static String getCookieValue(HttpServletRequest request, String cookieName, booleanisDecoder) {
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(UnsupportedEncodingException e) {
e.printStackTrace();
}returnretValue;
}/*** 得到Cookie的值,
*
*@paramrequest
*@paramcookieName
*@return
*/
public staticString 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(UnsupportedEncodingException e) {
e.printStackTrace();
}returnretValue;
}/*** 设置Cookie的值 不设置生效时间默认浏览器关闭即失效,也不编码*/
public static voidsetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
String cookieValue) {
setCookie(request, response, cookieName, cookieValue,-1);
}/*** 设置Cookie的值 在指定时间内生效,但不编码*/
public static voidsetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
String cookieValue,intcookieMaxage) {
setCookie(request, response, cookieName, cookieValue, cookieMaxage,false);
}/*** 设置Cookie的值 不设置生效时间,但编码*/
public static voidsetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
String cookieValue,booleanisEncode) {
setCookie(request, response, cookieName, cookieValue,-1, isEncode);
}/*** 设置Cookie的值 在指定时间内生效, 编码参数*/
public static voidsetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
String cookieValue,int cookieMaxage, booleanisEncode) {
doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, isEncode);
}/*** 设置Cookie的值 在指定时间内生效, 编码参数(指定编码)*/
public static voidsetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
String cookieValue,intcookieMaxage, String encodeString) {
doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, encodeString);
}/*** 删除Cookie带cookie域名*/
public static voiddeleteCookie(HttpServletRequest request, HttpServletResponse response, String cookieName) {
doSetCookie(request, response, cookieName,"", -1, false);
}/*** 设置Cookie的值,并使其在指定时间内生效
*
*@paramcookieMaxage
* cookie生效的最大秒数*/
private static final voiddoSetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
String cookieValue,int cookieMaxage, booleanisEncode) {try{if (cookieValue == null) {
cookieValue= "";
}else if(isEncode) {
cookieValue= URLEncoder.encode(cookieValue, "utf-8");
}
Cookie cookie= newCookie(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的值,并使其在指定时间内生效
*
*@paramcookieMaxage
* cookie生效的最大秒数*/
private static final voiddoSetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
String cookieValue,intcookieMaxage, String encodeString) {try{if (cookieValue == null) {
cookieValue= "";
}else{
cookieValue=URLEncoder.encode(cookieValue, encodeString);
}
Cookie cookie= newCookie(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 finalString getDomainName(HttpServletRequest request) {
String domainName= null;
String serverName=request.getRequestURL().toString();
System.out.println(serverName);if (serverName == null || serverName.equals("")) {
domainName= "";
}else{
serverName=serverName.toLowerCase();
serverName= serverName.substring(7);final int end = serverName.indexOf("/");
serverName= serverName.substring(0, end);if (serverName.contains("127.0.0.1")) {
domainName= "localhost";
}else{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];
}returndomainName;
}
}
JSONUtil.java:
packagecom.sso.demo.utils;importjava.util.List;importcom.fasterxml.jackson.core.JsonProcessingException;importcom.fasterxml.jackson.databind.JavaType;importcom.fasterxml.jackson.databind.ObjectMapper;/***
* @description json转换工具类
*@authorSeven Lee
**/
public classJSONUtil {//定义jackson对象
private static final ObjectMapper mapper = newObjectMapper();/*** 将对象转换成json字符串
*@paramdata
*@return
*/
public staticString toJSONString(Object data) {try{
String string=mapper.writeValueAsString(data);returnstring;
}catch(JsonProcessingException e) {
e.printStackTrace();
}return null;
}/*** 将json结果集转化为对象
*@paramjsonData
*@parambeanType
*@return
*/
public static T parseObject(String jsonData, ClassbeanType) {try{
T t=mapper.readValue(jsonData, beanType);returnt;
}catch(Exception e) {
e.printStackTrace();
}return null;
}/*** 将json数据转换成list
*@paramjsonData
*@parambeanType
*@return
*/
public static List parseArray(String jsonData, ClassbeanType) {
JavaType javaType= mapper.getTypeFactory().constructParametricType(List.class, beanType);try{
List list =mapper.readValue(jsonData, javaType);returnlist;
}catch(Exception e) {
e.printStackTrace();
}return null;
}
}
UUIDUtil.java:
packagecom.sso.demo.utils;importjava.util.UUID;/***
* @description UUID生成工具类
*@authorSeven Lee
**/
public classUUIDUtil {public staticString getUUID() {returnUUID.randomUUID().toString();
}
}
UserMapper.xml:
mybatis-config.xml:
/p>
"http://mybatis.org/dtd/mybatis-3-config.dtd">
applicationContext-db.xml:
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
mappers=tk.mybatis.mapper.common.Mapper
applicationContext-redis.xml:
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">
applicationContext-tx.xml:
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
applicationContext-mvc.xml:
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
application.properties:
#mysql connector
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root
#redis cluster connector
redis.host1=192.168.1.186
redis.port1=6380
redis.host2=192.168.1.186
redis.port2=6381
redis.host3=192.168.1.186
redis.port3=6382
redis.host4=192.168.1.186
redis.port4=6383
redis.host5=192.168.1.186
redis.port5=6384
redis.host6=192.168.1.186
redis.port6=6385
#SESSION_KEY
session_key=SESSION_KEY
#COOKIE_KEY
cookie_key=COOKIE_KEY
#EXPIRE's Seconds
expire_time_out=86400
applicationContext.xml:
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
log4j.properties:
log4j.rootLogger=DEBUG, Console
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%-5p - %m%n
log4j.logger.org.springframework=ERROR
log4j.logger.org.mybatis.spring=ERROR
log4j.logger.org.apache.ibatis.logging.LogFactory=ERROR
log4j.logger.com.alibaba.druid.pool.DruidDataSource=ERROR
login.jsp:
Stringpath= request.getContextPath();String basePath= request.getScheme()+ "://" + request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
">
My JSP 'login.jsp' starting page$(function() {
var redirect = "${redirect}";
$("#do_login_button").click(function() {
$.post("/sso/doLogin", $("#forms").serialize(), function(data) {
if (data != null) {
if (redirect == null) {
location.href = "http://127.0.0.1:8081/zzsxt_portal/index";
} else {
location.href = redirect;
}
}
});
});
});
Username:
Passowrd:
web.xml:
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"version="3.0">
contextConfigLocation
classpath:applicationContext.xml
org.springframework.web.context.ContextLoaderListener
CharacterEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
utf-8
CharacterEncodingFilter
/*
sso_demo
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:springmvc/applicationContext-mvc.xml
1
sso_demo
/
pom.xml:
4.0.0
com.sso.demo
sso
war
0.0.1-SNAPSHOT
sso Maven Webapp
http://maven.apache.org
4.12
4.3.4.RELEASE
2.8.1
1.2.17
3.0.1
2.0
1.2
5.1.40
1.0.26
3.3.0
1.2.3
1.2.15
3.3.9
2.10.3
2.9.0
1.7.2.RELEASE
junit
junit
${junit.version}
test
org.springframework
spring-context
${spring.version}
org.springframework
spring-aspects
${spring.version}
org.springframework
spring-jdbc
${spring.version}
org.springframework
spring-test
${spring.version}
test
org.springframework
spring-web
${spring.version}
org.springframework
spring-webmvc
${spring.version}
com.fasterxml.jackson.core
jackson-core
${jackson.version}
com.fasterxml.jackson.core
jackson-databind
${jackson.version}
com.fasterxml.jackson.core
jackson-annotations
${jackson.version}
com.alibaba
fastjson
${fastjson.version}
javax.servlet
javax.servlet-api
${servlet-api.version}
provided
javax.servlet
jsp-api
${jsp-api.version}
provided
javax.servlet
jstl
${jstl.version}
runtime
mysql
mysql-connector-java
${mysql.version}
runtime
com.alibaba
druid
${druid.version}
org.mybatis
mybatis
${mybatis.version}
org.mybatis
mybatis-spring
${mybatis.spring.version}
tk.mybatis
mapper
${mybatis.mapper.version}
net.sf.ehcache
ehcache
${ehcache.version}
redis.clients
jedis
${jedis.version}
org.springframework.data
spring-data-redis
${spring-data-redis.version}
sso
zzsxt_portal Maven Webapp:
TurnPageController.java:
packagecom.zzsxt.portal.controller;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestMapping;
@Controllerpublic classTurnPageController {
@RequestMapping("/index")publicString turnIndexPage() {return "index";
}
@RequestMapping("/buy")publicString turnBuyPage() {return "buy";
}
@RequestMapping("/nowBuy")publicString doBuy() {//处理立即购买请求的方法
return "success";
}
}
Logininterceptor.java:
packagecom.zzsxt.portal.interceptor;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.servlet.HandlerInterceptor;importorg.springframework.web.servlet.ModelAndView;importcom.zzsxt.portal.service.UserService;importcom.zzsxt.portal.utils.CookieUtil;public class Logininterceptor implementsHandlerInterceptor {
@AutowiredprivateUserService userService;
@Overridepublic booleanpreHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throwsException {//1.首先通过CookieUtil获取cookie的值(token)
String token =CookieUtil.getCookieValue(request, userService.cookieKey);//2.根据token值去redis中查询用户信息
String userJson =userService.checkLogin(token);//3.如果查询的到就说明该用户处于登录状态(return true)
if(userJson == null || "".equals(userJson)) {
response.sendRedirect(userService.ssoBaseUrl+userService.ssoAccessLoginPath+userService.ssoLoginParam+request.getRequestURL());return false;
}//4.否则让未登录的用户跳转到sso项目中进行登录-->return false
return true;//不让其访问目标路径-->如果return true,直接放行
}
@Overridepublic voidpostHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView)throwsException {
}
@Overridepublic voidafterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throwsException {
}
}
UserService.java:
packagecom.zzsxt.portal.service;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.stereotype.Service;importcom.zzsxt.portal.utils.HttpClientUtil;
@Servicepublic classUserService {
@Value("${cookie_key}")publicString cookieKey;
@Value("${sso_base_url}")publicString ssoBaseUrl;
@Value("${sso_access_path}")publicString ssoAccessPath;
@Value("${sso_access_login_path}")publicString ssoAccessLoginPath;
@Value("${sso_login_param}")publicString ssoLoginParam;publicString checkLogin(String token) {return HttpClientUtil.doGet(ssoBaseUrl+ssoAccessPath+token);//相当于模拟浏览器发送请求
}
}
CookieUtil.java:
packagecom.zzsxt.portal.utils;importjava.io.UnsupportedEncodingException;importjava.net.URLDecoder;importjava.net.URLEncoder;importjavax.servlet.http.Cookie;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;/***
* @description Cookie工具类
*@authorSeven Lee
**/
public classCookieUtil {/*** 得到Cookie的值, 不编码
*
*@paramrequest
*@paramcookieName
*@return
*/
public staticString getCookieValue(HttpServletRequest request, String cookieName) {return getCookieValue(request, cookieName, false);
}/*** 得到Cookie的值,
*
*@paramrequest
*@paramcookieName
*@return
*/
public static String getCookieValue(HttpServletRequest request, String cookieName, booleanisDecoder) {
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(UnsupportedEncodingException e) {
e.printStackTrace();
}returnretValue;
}/*** 得到Cookie的值,
*
*@paramrequest
*@paramcookieName
*@return
*/
public staticString 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(UnsupportedEncodingException e) {
e.printStackTrace();
}returnretValue;
}/*** 设置Cookie的值 不设置生效时间默认浏览器关闭即失效,也不编码*/
public static voidsetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
String cookieValue) {
setCookie(request, response, cookieName, cookieValue,-1);
}/*** 设置Cookie的值 在指定时间内生效,但不编码*/
public static voidsetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
String cookieValue,intcookieMaxage) {
setCookie(request, response, cookieName, cookieValue, cookieMaxage,false);
}/*** 设置Cookie的值 不设置生效时间,但编码*/
public static voidsetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
String cookieValue,booleanisEncode) {
setCookie(request, response, cookieName, cookieValue,-1, isEncode);
}/*** 设置Cookie的值 在指定时间内生效, 编码参数*/
public static voidsetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
String cookieValue,int cookieMaxage, booleanisEncode) {
doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, isEncode);
}/*** 设置Cookie的值 在指定时间内生效, 编码参数(指定编码)*/
public static voidsetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
String cookieValue,intcookieMaxage, String encodeString) {
doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, encodeString);
}/*** 删除Cookie带cookie域名*/
public static voiddeleteCookie(HttpServletRequest request, HttpServletResponse response, String cookieName) {
doSetCookie(request, response, cookieName,"", -1, false);
}/*** 设置Cookie的值,并使其在指定时间内生效
*
*@paramcookieMaxage
* cookie生效的最大秒数*/
private static final voiddoSetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
String cookieValue,int cookieMaxage, booleanisEncode) {try{if (cookieValue == null) {
cookieValue= "";
}else if(isEncode) {
cookieValue= URLEncoder.encode(cookieValue, "utf-8");
}
Cookie cookie= newCookie(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的值,并使其在指定时间内生效
*
*@paramcookieMaxage
* cookie生效的最大秒数*/
private static final voiddoSetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
String cookieValue,intcookieMaxage, String encodeString) {try{if (cookieValue == null) {
cookieValue= "";
}else{
cookieValue=URLEncoder.encode(cookieValue, encodeString);
}
Cookie cookie= newCookie(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 finalString getDomainName(HttpServletRequest request) {
String domainName= null;
String serverName=request.getRequestURL().toString();
System.out.println(serverName);if (serverName == null || serverName.equals("")) {
domainName= "";
}else{
serverName=serverName.toLowerCase();
serverName= serverName.substring(7);final int end = serverName.indexOf("/");
serverName= serverName.substring(0, end);if (serverName.contains("127.0.0.1")) {
domainName= "localhost";
}else{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];
}returndomainName;
}
}
HttpClientUtil.java:
packagecom.zzsxt.portal.utils;importjava.io.IOException;importjava.net.URI;importjava.util.ArrayList;importjava.util.List;importjava.util.Map;importorg.apache.http.NameValuePair;importorg.apache.http.client.entity.UrlEncodedFormEntity;importorg.apache.http.client.methods.CloseableHttpResponse;importorg.apache.http.client.methods.HttpGet;importorg.apache.http.client.methods.HttpPost;importorg.apache.http.client.utils.URIBuilder;importorg.apache.http.entity.ContentType;importorg.apache.http.entity.StringEntity;importorg.apache.http.impl.client.CloseableHttpClient;importorg.apache.http.impl.client.HttpClients;importorg.apache.http.message.BasicNameValuePair;importorg.apache.http.util.EntityUtils;/***
* @description 通过http发送请求工具类
*@authorSeven Lee
**/
public classHttpClientUtil {public static String doGet(String url, Mapparam) {//创建Httpclient对象
CloseableHttpClient httpclient =HttpClients.createDefault();
String resultString= "";
CloseableHttpResponse response= null;try{//创建uri
URIBuilder builder = newURIBuilder(url);if (param != null) {for(String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri=builder.build();//创建http GET请求
HttpGet httpGet = newHttpGet(uri);//执行请求
response =httpclient.execute(httpGet);//判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString= EntityUtils.toString(response.getEntity(), "UTF-8");
}
}catch(Exception e) {
e.printStackTrace();
}finally{try{if (response != null) {
response.close();
}
httpclient.close();
}catch(IOException e) {
e.printStackTrace();
}
}returnresultString;
}public staticString doGet(String url) {return doGet(url, null);
}public static String doPost(String url, Mapparam) {//创建Httpclient对象
CloseableHttpClient httpClient =HttpClients.createDefault();
CloseableHttpResponse response= null;
String resultString= "";try{//创建Http Post请求
HttpPost httpPost = newHttpPost(url);//创建参数列表
if (param != null) {
List paramList = new ArrayList<>();for(String key : param.keySet()) {
paramList.add(newBasicNameValuePair(key, param.get(key)));
}//模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
httpPost.setEntity(entity);
}//执行http请求
response =httpClient.execute(httpPost);
resultString= EntityUtils.toString(response.getEntity(), "utf-8");
}catch(Exception e) {
e.printStackTrace();
}finally{try{
response.close();
}catch(IOException e) {
e.printStackTrace();
}
}returnresultString;
}public staticString doPost(String url) {return doPost(url, null);
}/*** 请求的参数类型为json
*
*@paramurl
*@paramjson
*@return{username:"",pass:""}*/
public staticString doPostJson(String url, String json) {//创建Httpclient对象
CloseableHttpClient httpClient =HttpClients.createDefault();
CloseableHttpResponse response= null;
String resultString= "";try{//创建Http Post请求
HttpPost httpPost = newHttpPost(url);//创建请求内容
StringEntity entity = newStringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);//执行http请求
response =httpClient.execute(httpPost);
resultString= EntityUtils.toString(response.getEntity(), "utf-8");
}catch(Exception e) {
e.printStackTrace();
}finally{try{
response.close();
}catch(IOException e) {
e.printStackTrace();
}
}returnresultString;
}
}
JSONUtil.java:
packagecom.zzsxt.portal.utils;importjava.util.List;importcom.fasterxml.jackson.core.JsonProcessingException;importcom.fasterxml.jackson.databind.JavaType;importcom.fasterxml.jackson.databind.ObjectMapper;/***
* @description json转换工具类
*@authorSeven Lee
**/
public classJSONUtil {//定义jackson对象
private static final ObjectMapper mapper = newObjectMapper();/*** 将对象转换成json字符串
*@paramdata
*@return
*/
public staticString toJSONString(Object data) {try{
String string=mapper.writeValueAsString(data);returnstring;
}catch(JsonProcessingException e) {
e.printStackTrace();
}return null;
}/*** 将json结果集转化为对象
*@paramjsonData
*@parambeanType
*@return
*/
public static T parseObject(String jsonData, ClassbeanType) {try{
T t=mapper.readValue(jsonData, beanType);returnt;
}catch(Exception e) {
e.printStackTrace();
}return null;
}/*** 将json数据转换成list
*@paramjsonData
*@parambeanType
*@return
*/
public static List parseArray(String jsonData, ClassbeanType) {
JavaType javaType= mapper.getTypeFactory().constructParametricType(List.class, beanType);try{
List list =mapper.readValue(jsonData, javaType);returnlist;
}catch(Exception e) {
e.printStackTrace();
}return null;
}
}
UUIDUtil.java:
packagecom.zzsxt.portal.utils;importjava.util.UUID;/***
* @description UUID生成工具类
*@authorSeven Lee
**/
public classUUIDUtil {public staticString getUUID() {returnUUID.randomUUID().toString();
}
}
applicationContext-mvc.xml:
application.properties:
#COOKIE_KEY
cookie_key=COOKIE_KEY
#SSO's BASE URL
sso_base_url=http://127.0.0.1:8080
#SSO's controller path
sso_access_path=/sso/token/#SSO's controller path
sso_access_login_path=/sso/turnLogin
#SSO's login controller param
sso_login_param=?referPage\=
applicationContext.xml:
log4j.properties:
log4j.rootLogger=DEBUG, Console
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%-5p - %m%n
log4j.logger.org.springframework=ERROR
log4j.logger.org.mybatis.spring=ERROR
log4j.logger.org.apache.ibatis.logging.LogFactory=ERROR
log4j.logger.com.alibaba.druid.pool.DruidDataSource=ERROR
header.jsp:
Stringpath=request.getContextPath();StringbasePath=request.getScheme()+ "://" +request.getServerName()+ ":" +request.getServerPort()+path+ "/";%>
">
My JSP 'header.jsp' starting page$(function() {varcurrentUrl=window.location.href;
$("#turn_login_page").prop("href","http://127.0.0.1:8080/sso/turnLogin?referPage=" +currentUrl);vartoken=$.cookie("COOKIE_KEY");if(!token) {//!token 只要为null就会进来
return;
}
$.ajax({
url :"http://127.0.0.1:8080/sso/token/" +token,
type :"get",
dataType :"jsonp",
success :function(data) {//已经跨域了
$("#show_username").empty();
$("#show_username").append("
Welcome:" +(data.substring(20,27))+ "
");}
});
});
登录