java:sso(单点登录(single sign on),jsp文件动静态导入方式,session跨域)
Posted 咫尺天涯是路人丶
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java:sso(单点登录(single sign on),jsp文件动静态导入方式,session跨域)相关的知识,希望对你有一定的参考价值。
1.jsp文件导入:
2.session跨域:
3.sso(单点登录(single sign on):
sso Maven Webapp:
LoginController.java:
package com.sso.demo.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.converter.json.MappingJacksonValue; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.sso.demo.model.User; import com.sso.demo.service.LoginService; @Controller public class LoginController { @Autowired private LoginService loginService; /** * @description 跳转到登录页面 * @return */ @RequestMapping("/turnLogin") public String turnLoginPage(String referPage, Model model) { model.addAttribute("redirect", referPage); return "login"; } /** * @description 检查该用户是否已经登录 * @param token * @return */ @RequestMapping(value = "/token/{token}", method = RequestMethod.GET) @ResponseBody public Object checkLogin(@PathVariable("token") String token, String callback) { String userJson = loginService.checkLogin(token); if(callback == null) { // 就是一个普通请求,并不是跨域请求 return userJson; } else { // 一定产生跨域 // MappingJacksonValue对象是spring4.0版本以后支持跨域封装对象 // MappingJacksonValue是专门返回跨域请求的class // 自动把userJson转换为跨域所需要的发送数据 // 最终返回mappingJacksonValue,也就是返回了跨域所需要的数据 // setJsonpFunction(callback)-->处理callback参数,让js知道我已经接收到了你传递给过来的callback,也就是知道 // 该请求为一个跨域请求 MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(userJson); mappingJacksonValue.setJsonpFunction(callback); return mappingJacksonValue; } } /** * @description 登录功能 * @param user * @return */ @RequestMapping("/doLogin") @ResponseBody public String doLogin(User user, HttpServletRequest request, HttpServletResponse response) { // 直接调用service return loginService.doLogin(user, request, response); } }
UserMapper.java:
package com.sso.demo.mapper; import com.sso.demo.model.User; import tk.mybatis.mapper.common.Mapper; public interface UserMapper extends Mapper<User> { }
User.java:
package com.sso.demo.model; import javax.persistence.*; public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String username; private String password; private String email; private Integer phone; @Column(name = "head_pic_path") private String headPicPath; /** * @return id */ public Long getId() { return id; } /** * @param id */ public void setId(Long id) { this.id = id; } /** * @return username */ public String getUsername() { return username; } /** * @param username */ public void setUsername(String username) { this.username = username == null ? null : username.trim(); } /** * @return password */ public String getPassword() { return password; } /** * @param password */ public void setPassword(String password) { this.password = password == null ? null : password.trim(); } /** * @return email */ public String getEmail() { return email; } /** * @param email */ public void setEmail(String email) { this.email = email == null ? null : email.trim(); } /** * @return phone */ public Integer getPhone() { return phone; } /** * @param phone */ public void setPhone(Integer phone) { this.phone = phone; } /** * @return head_pic_path */ public String getHeadPicPath() { return headPicPath; } /** * @param headPicPath */ public void setHeadPicPath(String headPicPath) { this.headPicPath = headPicPath == null ? null : headPicPath.trim(); } }
RedisServiceImpl.java:
package com.sso.demo.service.impl; import com.sso.demo.service.IRedisService; import redis.clients.jedis.JedisCluster; public class RedisServiceImpl implements IRedisService { private JedisCluster jedisCluster; public JedisCluster getJedisCluster() { return jedisCluster; } public void setJedisCluster(JedisCluster jedisCluster) { this.jedisCluster = jedisCluster; } @Override public String get(String key) { return jedisCluster.get(key); } @Override public String set(String key, String value) { return jedisCluster.set(key, value); } @Override public Long del(String... keys) { return jedisCluster.del(keys); } @Override public Long expire(String key, Integer seconds) { return jedisCluster.expire(key, seconds); } }
IRedisService.java:
package com.sso.demo.service; public interface IRedisService { /** * @description 通过key来获取数据 * @param key * @return */ public String get(String key); /** * @description 往redis集群中存入数据 * @param key * @param value * @return */ public String set(String key, String value); /** * @description 通过key删除redis中的数据 * @param key * @return */ public Long del(String... keys); /** * @description 通过key为redis中的缓存设置失效时间 * @param key * @param seconds */ public Long expire(String key, Integer seconds); }
LoginService.java:
package com.sso.demo.service; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import com.sso.demo.mapper.UserMapper; import com.sso.demo.model.User; import com.sso.demo.utils.CookieUtil; import com.sso.demo.utils.JSONUtil; import com.sso.demo.utils.UUIDUtil; @Service public class LoginService { @Value("${session_key}") private String sessionKey; @Value("${cookie_key}") private String cookieKey; @Value("${expire_time_out}") private Integer expireTimeOut; @Autowired private IRedisService redisService; @Autowired private UserMapper userMapper; public String checkLogin(String token) { String userJson = redisService.get(sessionKey + ":" + token); if (userJson == null) { return null; } return userJson; } public String 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); return token; } } return null; } }
CookieUtil.java:
package com.sso.demo.utils; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @description Cookie工具类 * @author Seven Lee * */ public class CookieUtil { /** * 得到Cookie的值, 不编码 * * @param request * @param cookieName * @return */ public static String getCookieValue(HttpServletRequest request, String cookieName) { return getCookieValue(request, cookieName, false); } /** * 得到Cookie的值, * * @param request * @param cookieName * @return */ 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 (UnsupportedEncodingException e) { e.printStackTrace(); } return retValue; } /** * 得到Cookie的值, * * @param request * @param cookieName * @return */ 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 (UnsupportedEncodingException 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)) { 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(); 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]; } return domainName; } }
JSONUtil.java:
package com.sso.demo.utils; import java.util.List; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; /** * * @description json转换工具类 * @author Seven Lee * */ public class JSONUtil { // 定义jackson对象 private static final ObjectMapper mapper = new ObjectMapper(); /** * 将对象转换成json字符串 * @param data * @return */ public static String toJSONString(Object data) { try { String string = mapper.writeValueAsString(data); return string; } catch (JsonProcessingException e) { e.printStackTrace(); } return null; } /** * 将json结果集转化为对象 * @param jsonData * @param beanType * @return */ public static <T> T parseObject(String jsonData, Class<T> beanType) { try { T t = mapper.readValue(jsonData, beanType); return t; } catch (Exception e) { e.printStackTrace(); } return null; } /** * 将json数据转换成list * @param jsonData * @param beanType * @return */ public static <T> List<T> parseArray(String jsonData, Class<T> beanType) { JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, beanType); try { List<T> list = mapper.readValue(jsonData, javaType); return list; } catch (Exception e) { e.printStackTrace(); } return null; } }
UUIDUtil.java:
package com.sso.demo.utils; import java.util.UUID; /** * * @description UUID生成工具类 * @author Seven Lee * */ public class UUIDUtil { public static String getUUID() { return UUID.randomUUID().toString(); } }
UserMapper.xml:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.sso.demo.mapper.UserMapper"> <resultMap id="BaseResultMap" type="com.sso.demo.model.User"> <!-- WARNING - @mbg.generated --> <id column="id" property="id" jdbcType="BIGINT" /> <result column="username" property="username" jdbcType="VARCHAR" /> <result column="password" property="password" jdbcType="VARCHAR" /> <result column="email" property="email" jdbcType="VARCHAR" /> <result column="phone" property="phone" jdbcType="INTEGER" /> <result column="head_pic_path" property="headPicPath" jdbcType="VARCHAR" /> </resultMap> </mapper>
mybatis-config.xml:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- mybatis默认是没有开启延迟加载的 需要手动开启 --> <settings> <!-- 延迟加载 默认false --> <setting name="lazyLoadingEnabled" value="true" /> <!-- 积极加载 默认true --> <setting name="aggressiveLazyLoading" value="false" /> <!--开启缓存--> <setting name<以上是关于java:sso(单点登录(single sign on),jsp文件动静态导入方式,session跨域)的主要内容,如果未能解决你的问题,请参考以下文章
SSO(single sign on)模式 --单点登录三种登录方式
SSO(single sign on)模式 --单点登录三种登录方式