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="cacheEnabled" value="true"/> </settings> </configuration>
applicationContext-db.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans 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"> <!--数据源配置 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="filters" value="stat" /> <property name="maxActive" value="20" /> <property name="initialSize" value="1" /> <property name="maxWait" value="60000" /> <property name="minIdle" value="1" /> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <property name="minEvictableIdleTimeMillis" value="300000" /> <property name="validationQuery" value="SELECT 'x'" /> <property name="testWhileIdle" value="true" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mapping.xml文件,**表示迭代查找 --> <property name="mapperLocations" value="classpath*:mapper/*Mapper.xml" /> <!--mybatis配置文件位置 --> <property name="configLocation" value="classpath:mybatis/mybatis-config.xml" /> </bean> <!--扫描com.redis下的mapper接口 --> <bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
<!--org.mybatis.spring.mapper.MapperScannerConfigurer -->
<property name="basePackage" value="com.sso.demo" /> <!--使用mybatis通用mapper插件 --> <property name="properties"> <value> mappers=tk.mybatis.mapper.common.Mapper </value> </property> </bean> </beans>
applicationContext-redis.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans 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"> <!-- 配置redis自带的连接池配置(jedisPool) --> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> <!-- 最大连接数 --> <property name="maxTotal" value="30" /> <!-- 最大空闲连接数 --> <property name="maxIdle" value="10" /> <!-- 每次释放连接的最大数目 --> <property name="numTestsPerEvictionRun" value="1024" /> <!-- 释放连接的扫描间隔(毫秒) --> <property name="timeBetweenEvictionRunsMillis" value="30000" /> <!-- 连接最小空闲时间 --> <property name="minEvictableIdleTimeMillis" value="1800000" /> <!-- 连接空闲多久后释放, 当空闲时间>该值且空闲连接>最大空闲连接数时直接释放 --> <property name="softMinEvictableIdleTimeMillis" value="10000" /> <!-- 获取连接时的最大等待毫秒数,小于零:阻塞不确定的时间,默认-1 --> <property name="maxWaitMillis" value="1500" /> <!-- 在获取连接的时候检查有效性, 默认false --> <property name="testOnBorrow" value="false" /> <!-- 在空闲时检查有效性, 默认false --> <property name="testWhileIdle" value="true" /> <!-- 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true --> <property name="blockWhenExhausted" value="false" /> </bean> <!-- redis数据库集群连接池配置 --> <bean id="jedisCluster" class="redis.clients.jedis.JedisCluster"> <!-- 首先要把连接池的配置信息引入 --> <constructor-arg name="poolConfig" ref="jedisPoolConfig" /> <!-- 然后需要配置集群中各个节点信息 eg:因为redis最少需要6台服务器(称之为6个节点) --> <constructor-arg name="nodes"> <set> <bean class="redis.clients.jedis.HostAndPort"> <constructor-arg name="host" value="${redis.host1}" /><!-- 每一台节点的ip地址 --> <constructor-arg name="port" value="${redis.port1}" /><!-- 每一台redis节点的端口号 --> </bean> <bean class="redis.clients.jedis.HostAndPort"> <constructor-arg name="host" value="${redis.host2}" /> <constructor-arg name="port" value="${redis.port2}" /> </bean> <bean class="redis.clients.jedis.HostAndPort"> <constructor-arg name="host" value="${redis.host3}" /> <constructor-arg name="port" value="${redis.port3}" /> </bean> <bean class="redis.clients.jedis.HostAndPort"> <constructor-arg name="host" value="${redis.host4}" /> <constructor-arg name="port" value="${redis.port4}" /> </bean> <bean class="redis.clients.jedis.HostAndPort"> <constructor-arg name="host" value="${redis.host5}" /> <constructor-arg name="port" value="${redis.port5}" /> </bean> <bean class="redis.clients.jedis.HostAndPort"> <constructor-arg name="host" value="${redis.host6}" /> <constructor-arg name="port" value="${redis.port6}" /> </bean> </set> </constructor-arg> </bean> <bean id="redisService" class="com.sso.demo.service.impl.RedisServiceImpl"> <property name="jedisCluster" ref="jedisCluster"></property> </bean> </beans>
applicationContext-tx.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans 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"> <!-- 事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 事务详情 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- read-only="true" 该事务为只读事务 --> <tx:method name="select*" read-only="true" /> <tx:method name="find*" read-only="true" /> <tx:method name="get*" read-only="true" /> <tx:method name="query*" read-only="true" /> <tx:method name="*" /> </tx:attributes> </tx:advice> <!--支持基于注解的aspectj --> <aop:aspectj-autoproxy /> <!--aop编程,切入点表达式 确定增强的连接器,从而获得切入点 为什么aop这里切service而不是controller? --> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.sso.demo.service..*.*(..)))" /> </aop:config> </beans>
applicationContext-mvc.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans 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"> <!-- 自动扫描且只扫描@Controller 扫描的是controller --> <context:component-scan base-package="com.sso.demo.controller" /> <!-- DispatcherServlet是springmvc的入口类 --> <!-- 当在web.xml 中 DispatcherServlet使用 <url-pattern>/</url-pattern> 映射时,能映射静态资源 --> <!-- 除了动态资源以后,其他都不拦截(js,css,pictures,font...) --> <mvc:default-servlet-handler /> <!-- 可用在springmvc.xml配置文件中使用<mvc:annotation-driven>替代注解处理器和适配器的配置。 --> <mvc:annotation-driven> <mvc:message-converters> <!-- springmvc自带的中文编码转换器 --> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <constructor-arg index="0" value="UTF-8" /> </bean> <!-- json的格式化 --> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="prettyPrint" value="true" /> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- Jsp视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
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:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans 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"> <!-- 首先加载application.properties配置文件 --> <context:property-placeholder location="classpath:application.properties" /> <!-- spring扫描service --> <context:component-scan base-package="com.sso.demo.service" /> <!-- 分离核心配置,把spring和springmvc以及mybatis的配置单独成立一个xml文件,在applicationContext中导入 --> <!-- 导入jdbc配置文件 --> <import resource="spring/applicationContext-db.xml" /> <!-- 导入事务管理的配置文件 --> <import resource="spring/applicationContext-tx.xml" /> <!-- 导入redis集群的配置信息 --> <import resource="spring/applicationContext-redis.xml" /> </beans>
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:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'login.jsp' starting page</title> <script type="text/javascript" src="/sso/js/jquery-3.2.1.min.js"></script> <script type="text/javascript"> $(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; } } }); }); }); </script> </head> <body> <form id="forms" method="post"> Username:<input type="text" name="username" /> <br /> Passowrd:<input type="password" name="password" /> <br /> <input id="do_login_button" type="button" value="Login" /> </form> </body> </html>
web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <!--spring入口文件的配置 --> <!-- 确定配置文件位置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- 配置spring 监听器,加载xml配置文件 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 解决POST请求的中文乱码 --> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- DispatcherServlet:前端控制器 配置前端控制器servlet --> <servlet> <servlet-name>sso_demo</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--加载前端控制器配置文件 上下文配置位置 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc/applicationContext-mvc.xml</param-value> </init-param> <!-- 表示随WEB服务器启动 --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>sso_demo</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
pom.xml:
<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.sso.demo</groupId> <artifactId>sso</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>sso Maven Webapp</name> <url>http://maven.apache.org</url> <!-- 统一配置 --> <properties> <!-- junit begin --> <junit.version>4.12</junit.version> <!-- junit end --> <!-- spring begin --> <spring.version>4.3.4.RELEASE</spring.version> <!-- spring end --> <!-- json begin --> <jackson.version>2.8.1</jackson.version> <fastjson.version>1.2.17</fastjson.version> <!-- json end --> <!-- servlet jsp jstl begin --> <servlet-api.version>3.0.1</servlet-api.version> <jsp-api.version>2.0</jsp-api.version> <jstl.version>1.2</jstl.version> <!-- servlet jsp jstl end --> <!-- mysql begin --> <mysql.version>5.1.40</mysql.version> <!-- mysql begin --> <!-- druid begin --> <druid.version>1.0.26</druid.version> <!-- druid end --> <!-- mybatis begin --> <mybatis.version>3.3.0</mybatis.version> <mybatis.spring.version>1.2.3</mybatis.spring.version> <mybatis.paginator.version>1.2.15</mybatis.paginator.version> <mybatis.mapper.version>3.3.9</mybatis.mapper.version> <!-- mybatis end --> <!-- ehcache begin --> <ehcache.version>2.10.3</ehcache.version> <!-- ehcache end --> <!-- redis begin --> <jedis.version>2.9.0</jedis.version> <spring-data-redis.version>1.7.2.RELEASE</spring-data-redis.version> <!-- redis end --> </properties> <dependencies> <!-- 所需要的jar包 --> <!-- junit start --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <!-- junit end --> <!--spring start --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!--spring end --> <!--json start --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${fastjson.version}</version> </dependency> <!--json end --> <!-- servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${servlet-api.version}</version> <scope>provided</scope> </dependency> <!-- jsp --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jsp-api</artifactId> <version>${jsp-api.version}</version> <scope>provided</scope> </dependency> <!-- jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>${jstl.version}</version> <scope>runtime</scope> </dependency> <!-- database begin --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis.spring.version}</version> </dependency> <!-- database end --> <!-- mybatis plugins begin --> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> <version>${mybatis.mapper.version}</version> </dependency> <!-- mybatis plugins end --> <!--ehcache 缓存配置 --> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>${ehcache.version}</version> </dependency> <!-- redis begin --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>${jedis.version}</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>${spring-data-redis.version}</version> </dependency> <!-- redis end --> </dependencies> <build> <finalName>sso</finalName> </build> </project>
zzsxt_portal Maven Webapp:
TurnPageController.java:
package com.zzsxt.portal.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class TurnPageController { @RequestMapping("/index") public String turnIndexPage() { return "index"; } @RequestMapping("/buy") public String turnBuyPage() { return "buy"; } @RequestMapping("/nowBuy") public String doBuy() { // 处理立即购买请求的方法 return "success"; } }
Logininterceptor.java:
package com.zzsxt.portal.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import com.zzsxt.portal.service.UserService; import com.zzsxt.portal.utils.CookieUtil; public class Logininterceptor implements HandlerInterceptor { @Autowired private UserService userService; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 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,直接放行 } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
UserService.java:
package com.zzsxt.portal.service; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import com.zzsxt.portal.utils.HttpClientUtil; @Service public class UserService { @Value("${cookie_key}") public String cookieKey; @Value("${sso_base_url}") public String ssoBaseUrl; @Value("${sso_access_path}") public String ssoAccessPath; @Value("${sso_access_login_path}") public String ssoAccessLoginPath; @Value("${sso_login_param}") public String ssoLoginParam; public String checkLogin(String token) { return HttpClientUtil.doGet(ssoBaseUrl+ssoAccessPath+token);// 相当于模拟浏览器发送请求 } }
CookieUtil.java:
package com.zzsxt.portal.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; } }
HttpClientUtil.java:
package com.zzsxt.portal.utils; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; /** * * @description 通过http发送请求工具类 * @author Seven Lee * */ public class HttpClientUtil { public static String doGet(String url, Map<String, String> param) { // 创建Httpclient对象 CloseableHttpClient httpclient = HttpClients.createDefault(); String resultString = ""; CloseableHttpResponse response = null; try { // 创建uri URIBuilder builder = new URIBuilder(url); if (param != null) { for (String key : param.keySet()) { builder.addParameter(key, param.get(key)); } } URI uri = builder.build(); // 创建http GET请求 HttpGet httpGet = new HttpGet(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(); } } return resultString; } public static String doGet(String url) { return doGet(url, null); } public static String doPost(String url, Map<String, String> param) { // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); // 创建参数列表 if (param != null) { List<NameValuePair> paramList = new ArrayList<>(); for (String key : param.keySet()) { paramList.add(new BasicNameValuePair(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(); } } return resultString; } public static String doPost(String url) { return doPost(url, null); } /** * 请求的参数类型为json * * @param url * @param json * @return {username:"",pass:""} */ public static String doPostJson(String url, String json) { // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); // 创建请求内容 StringEntity entity = new StringEntity(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(); } } return resultString; } }
JSONUtil.java:
package com.zzsxt.portal.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.zzsxt.portal.utils; import java.util.UUID; /** * * @description UUID生成工具类 * @author Seven Lee * */ public class UUIDUtil { public static String getUUID() { return UUID.randomUUID().toString(); } }
applicationContext-mvc.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans 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"> <!-- 自动扫描且只扫描@Controller --> <context:component-scan base-package="com.zzsxt.portal.controller" /> <!-- 当在web.xml 中 DispatcherServlet使用 <url-pattern>/</url-pattern> 映射时,能映射静态资源 --> <mvc:default-servlet-handler /> <!-- 可用在springmvc.xml配置文件中使用<mvc:annotation-driven>替代注解处理器和适配器的配置。 --> <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <constructor-arg index="0" value="UTF-8" /> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- springmvc的拦截器 --> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/nowBuy" /><!-- 根据配置该路径来进行拦截 --> <!-- 自定义拦截器 --> <bean class="com.zzsxt.portal.interceptor.Logininterceptor"></bean> </mvc:interceptor> </mvc:interceptors> <!-- Jsp视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
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:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans 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"> <!-- 加载配置文件 --> <context:property-placeholder location="classpath:application.properties" /> <!-- 扫描的包路径 去掉mvc的注解 --> <context:component-scan base-package="com.zzsxt.portal.service" /> </beans>
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:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'header.jsp' starting page</title> <script type="text/javascript" src="js/jquery-3.2.1.min.js"></script> <script type="text/javascript" src="js/jquery.cookie.js"></script> <script type="text/javascript"> $(function() { var currentUrl = window.location.href; $("#turn_login_page").prop("href", "http://127.0.0.1:8080/sso/turnLogin?referPage=" + currentUrl); var token = $.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("<h1>Welcome:" + (data.substring(20, 27)) + " </h1>"); } }); }); </script> </head> <body> <div id="show_username"> <a id="turn_login_page">登录</a> </div> </body> </html>
buy.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'buy.jsp' starting page</title> </head> <body> <jsp:include page="common/header.jsp"></jsp:include> <h1>Iphone购买详情页</h1> <h2><a href="#">加入购物车</a></h2> <h2><a href="/zzsxt_portal/nowBuy">立即购买</a></h2> </body> </html>
index.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> </head> <body> <jsp:include page="common/header.jsp"></jsp:include> <h1>主网站页面</h1> <h2><a href="/zzsxt_portal/buy">购买Iphone X</a></h2> </body> </html>
success.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'success.jsp' starting page</title> </head> <body> <jsp:include page="common/header.jsp"></jsp:include> <h1>购买成功,5天之内为您发货!</h1> </body> </html>
web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <!--Spring入口文件的配置 --> <!-- 确定配置文件位置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- 配置spring 监听器,加载xml配置文件 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 解决POST请求的中文乱码 --> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- DispatcherServlet:前端控制器 配置前端控制器servlet --> <servlet> <servlet-name>portal</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--加载前端控制器配置文件 上下文配置位置 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc/applicationContext-mvc.xml</param-value> </init-param> <!-- 表示随WEB服务器启动 --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>portal</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
pom.xml:
<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.portal</groupId> <artifactId>zzsxt_portal</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>zzsxt_portal Maven Webapp</name> <url>http://maven.apache.org</url> <!-- 统一配置 --> <properties> <!-- junit begin --> <junit.version>4.12</junit.version> <!-- junit end --> <!-- httpClient begin --> <httpclient.version>4.3.5</httpclient.version> <!-- httpClient end --> <!-- spring begin --> <spring.version>4.3.4.RELEASE</spring.version> <!-- spring end --> <!-- json begin --> <jackson.version>2.8.1</jackson.version> <fastjson.version>1.2.17</fastjson.version> <!-- json end --> <!-- servlet jsp jstl begin --> <servlet-api.version>3.0.1</servlet-api.version> <jsp-api.version>2.0</jsp-api.version> <jstl.version>1.2</jstl.version> <!-- servlet jsp jstl end --> <!-- mysql begin --> <mysql.version>5.1.40</mysql.version> <!-- mysql begin --> <!-- druid begin --> <druid.version>1.0.26</druid.version> <!-- druid end --> <!-- mybatis begin --> <mybatis.version>3.3.0</mybatis.version> <mybatis.spring.version>1.2.3</mybatis.spring.version> <mybatis.paginator.version>1.2.15</mybatis.paginator.version> <mybatis.mapper.version>3.3.9</mybatis.mapper.version> <!-- mybatis end --> <!-- ehcache begin --> <ehcache.version>2.10.3</ehcache.version> <!-- ehcache end --> <!-- redis begin --> <jedis.version>2.9.0</jedis.version> <spring-data-redis.version>1.7.2.RELEASE</spring-data-redis.version> <!-- redis end --> </properties> <dependencies> <!-- 所需要的jar包 --> <!-- junit start --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <!-- junit end --> <!-- httpclient begin --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>${httpclient.version}</version> </dependency> <!-- httpclient end --> <!--spring start --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!--spring end --> <!--json start --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${fastjson.version}</version> </dependency> <!--json end --> <!-- servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${servlet-api.version}</version> <scope>provided</scope> </dependency> <!-- jsp --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jsp-api</artifactId> <version>${jsp-api.version}</version> <scope>provided</scope> </dependency> <!-- jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>${jstl.version}</version> <scope>runtime</scope> </dependency> <!-- database begin --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis.spring.version}</version> </dependency> <!-- database end --> <!-- mybatis plugins begin --> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> <version>${mybatis.mapper.version}</version> </dependency> <!-- mybatis plugins end --> <!--ehcache 缓存配置 --> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>${ehcache.version}</version> </dependency> <!-- redis begin --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>${jedis.version}</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>${spring-data-redis.version}</version> </dependency> <!-- redis end --> </dependencies> <build> <finalName>zzsxt_portal</finalName> </build> </project>