From 6ef6384201c6a0b3d209e7b29e902fe2516ccfbf Mon Sep 17 00:00:00 2001 From: xiaour Date: Tue, 25 Apr 2017 09:38:01 +0800 Subject: [PATCH 01/23] =?UTF-8?q?=E9=A6=96=E6=AC=A1=E5=AF=BC=E5=85=A5?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- SpringBootDemo/.gitignore | 1 + SpringBootDemo/pom.xml | 93 ++++++++++ .../com/tony/spring/boot/Application.java | 41 +++++ .../boot/config/DataBaseConfiguration.java | 68 ++++++++ .../boot/config/MybatisConfiguration.java | 89 ++++++++++ .../tony/spring/boot/config/RedisConfig.java | 46 +++++ .../tony/spring/boot/controller/TestCtrl.java | 76 ++++++++ .../com/tony/spring/boot/entity/UserInfo.java | 125 +++++++++++++ .../com/tony/spring/boot/filter/MyFilter.java | 46 +++++ .../spring/boot/mapper/UserInfoMapper.java | 19 ++ .../spring/boot/mapper/UserInfoMapper.xml | 165 ++++++++++++++++++ .../com/tony/spring/boot/utils/JsonUtil.java | 66 +++++++ .../com/tony/spring/boot/utils/RedisUtil.java | 56 ++++++ .../src/main/resources/application.yml | 45 +++++ .../src/main/resources/mybatis-config.xml | 36 ++++ 15 files changed, 972 insertions(+) create mode 100644 SpringBootDemo/.gitignore create mode 100644 SpringBootDemo/pom.xml create mode 100644 SpringBootDemo/src/main/java/com/tony/spring/boot/Application.java create mode 100644 SpringBootDemo/src/main/java/com/tony/spring/boot/config/DataBaseConfiguration.java create mode 100644 SpringBootDemo/src/main/java/com/tony/spring/boot/config/MybatisConfiguration.java create mode 100644 SpringBootDemo/src/main/java/com/tony/spring/boot/config/RedisConfig.java create mode 100644 SpringBootDemo/src/main/java/com/tony/spring/boot/controller/TestCtrl.java create mode 100644 SpringBootDemo/src/main/java/com/tony/spring/boot/entity/UserInfo.java create mode 100644 SpringBootDemo/src/main/java/com/tony/spring/boot/filter/MyFilter.java create mode 100644 SpringBootDemo/src/main/java/com/tony/spring/boot/mapper/UserInfoMapper.java create mode 100644 SpringBootDemo/src/main/java/com/tony/spring/boot/mapper/UserInfoMapper.xml create mode 100644 SpringBootDemo/src/main/java/com/tony/spring/boot/utils/JsonUtil.java create mode 100644 SpringBootDemo/src/main/java/com/tony/spring/boot/utils/RedisUtil.java create mode 100644 SpringBootDemo/src/main/resources/application.yml create mode 100644 SpringBootDemo/src/main/resources/mybatis-config.xml diff --git a/SpringBootDemo/.gitignore b/SpringBootDemo/.gitignore new file mode 100644 index 0000000..b83d222 --- /dev/null +++ b/SpringBootDemo/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/SpringBootDemo/pom.xml b/SpringBootDemo/pom.xml new file mode 100644 index 0000000..49a2094 --- /dev/null +++ b/SpringBootDemo/pom.xml @@ -0,0 +1,93 @@ + + + 4.0.0 + + com.tony + com.tony.spring.boot + 1.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 1.5.2.RELEASE + + + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + org.springframework.boot + spring-boot-devtools + true + + + + org.springframework.boot + spring-boot-configuration-processor + true + + + + org.springframework.boot + spring-boot-starter-redis + 1.3.8.RELEASE + + + + org.mybatis.spring.boot + mybatis-spring-boot-starter + 1.3.0 + + + + com.alibaba + druid + 1.0.19 + + + + mysql + mysql-connector-java + + + + com.github.pagehelper + pagehelper + 3.7.5 + + + + + javax.inject + javax.inject + 1 + + + javax + javaee-api + 7.0 + provided + + + + + + 1.8 + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/SpringBootDemo/src/main/java/com/tony/spring/boot/Application.java b/SpringBootDemo/src/main/java/com/tony/spring/boot/Application.java new file mode 100644 index 0000000..e0c546f --- /dev/null +++ b/SpringBootDemo/src/main/java/com/tony/spring/boot/Application.java @@ -0,0 +1,41 @@ +package com.tony.spring.boot; + +import org.mybatis.spring.annotation.MapperScan; +import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer; +import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer; +import org.springframework.boot.web.servlet.ServletComponentScan; +import org.springframework.boot.web.support.SpringBootServletInitializer; + +/** + * Created by Administrator on 2017/4/19. + */ +@SpringBootApplication(exclude = MybatisAutoConfiguration.class) +@ServletComponentScan +@EnableAutoConfiguration +@MapperScan("com.tony.spring.boot.mapper") +public class Application extends SpringBootServletInitializer implements EmbeddedServletContainerCustomizer { + + @Value("${server.port}") + private int port;//应用的端口 + /** + * 启动入口 + * @param args + */ + public static void main(String ... args){ + SpringApplication.run(Application.class, args); + } + + /** + * 自定义端口 + */ + @Override + public void customize(ConfigurableEmbeddedServletContainer container) { + container.setPort(port); + } + +} diff --git a/SpringBootDemo/src/main/java/com/tony/spring/boot/config/DataBaseConfiguration.java b/SpringBootDemo/src/main/java/com/tony/spring/boot/config/DataBaseConfiguration.java new file mode 100644 index 0000000..0d0d12f --- /dev/null +++ b/SpringBootDemo/src/main/java/com/tony/spring/boot/config/DataBaseConfiguration.java @@ -0,0 +1,68 @@ +package com.tony.spring.boot.config; + +import java.sql.SQLException; + +import javax.sql.DataSource; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.bind.RelaxedPropertyResolver; +import org.springframework.context.EnvironmentAware; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import com.alibaba.druid.pool.DruidDataSource; + +@Configuration +@EnableTransactionManagement +public class DataBaseConfiguration implements EnvironmentAware { + + private RelaxedPropertyResolver propertyResolver; + + private static Logger log = LoggerFactory.getLogger(DataBaseConfiguration.class); + + private Environment env; + + @Override + public void setEnvironment(Environment env) { + this.env = env; + this.propertyResolver = new RelaxedPropertyResolver(env, "jdbc.datasource."); + } + + /** + * 配置数据源 + * @Description TODO + * @return + */ + @Bean(name = "dataSource",destroyMethod = "close") + public DataSource dataSource() { + log.debug(env.getActiveProfiles().toString()); + + DruidDataSource dataSource = new DruidDataSource(); + dataSource.setUrl(propertyResolver.getProperty("url")); + dataSource.setUsername(propertyResolver.getProperty("username"));//用户名 + dataSource.setPassword(propertyResolver.getProperty("password"));//密码 + dataSource.setDriverClassName(propertyResolver.getProperty("driver-class-name")); + dataSource.setInitialSize(Integer.parseInt(propertyResolver.getProperty("initialSize"))); + dataSource.setMaxActive(Integer.parseInt(propertyResolver.getProperty("maxActive"))); + dataSource.setMinIdle(Integer.parseInt(propertyResolver.getProperty("minIdle"))); + dataSource.setMaxWait(Integer.parseInt(propertyResolver.getProperty("maxWait"))); + dataSource.setTimeBetweenEvictionRunsMillis(Integer.parseInt(propertyResolver.getProperty("timeBetweenEvictionRunsMillis"))); + dataSource.setMinEvictableIdleTimeMillis(Integer.parseInt(propertyResolver.getProperty("minEvictableIdleTimeMillis"))); + dataSource.setValidationQuery(propertyResolver.getProperty("validationQuery")); + dataSource.setTestOnBorrow(Boolean.getBoolean(propertyResolver.getProperty("testOnBorrow"))); + dataSource.setTestWhileIdle(Boolean.getBoolean(propertyResolver.getProperty("testWhileIdle"))); + dataSource.setTestOnReturn(Boolean.getBoolean(propertyResolver.getProperty("testOnReturn"))); + dataSource.setPoolPreparedStatements(Boolean.getBoolean(propertyResolver.getProperty("poolPreparedStatements"))); + dataSource.setMaxPoolPreparedStatementPerConnectionSize(Integer.parseInt(propertyResolver.getProperty("maxOpenPreparedStatements"))); + try { + dataSource.init(); + } catch (SQLException e) { + + } + return dataSource; + } + +} diff --git a/SpringBootDemo/src/main/java/com/tony/spring/boot/config/MybatisConfiguration.java b/SpringBootDemo/src/main/java/com/tony/spring/boot/config/MybatisConfiguration.java new file mode 100644 index 0000000..67165b7 --- /dev/null +++ b/SpringBootDemo/src/main/java/com/tony/spring/boot/config/MybatisConfiguration.java @@ -0,0 +1,89 @@ +package com.tony.spring.boot.config; + +import javax.annotation.Resource; +import javax.persistence.EntityManager; +import javax.sql.DataSource; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.ibatis.session.SqlSessionFactory; +import org.mybatis.spring.SqlSessionFactoryBean; +import org.springframework.boot.autoconfigure.AutoConfigureAfter; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.bind.RelaxedPropertyResolver; +import org.springframework.context.EnvironmentAware; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.core.io.DefaultResourceLoader; +import org.springframework.core.io.support.PathMatchingResourcePatternResolver; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +/** + * 初始化SqlSessionFactory + * Java Lib For OIS, Powered By BeiJing FanTongTianXia. + * Copyright (c) 2014-2017 FanTongTianXia Co.,Ltd + * http://www.chifaner.com/ + * + * @ClassName MybatisConfiguration + * @author Zhang.Tao + * @Date 2017年4月24日 下午5:24:56 + * @version V2.0.0 + */ +@Configuration +@ConditionalOnClass({ EnableTransactionManagement.class, EntityManager.class }) +@AutoConfigureAfter({ DataBaseConfiguration.class }) +public class MybatisConfiguration implements EnvironmentAware { + + private static Log logger = LogFactory.getLog(MybatisConfiguration.class); + + private RelaxedPropertyResolver propertyResolver; + + @Resource(name = "dataSource") + DataSource dataSource; + + @Override + public void setEnvironment(Environment environment) { + this.propertyResolver = new RelaxedPropertyResolver(environment,"mybatis."); + } + + /** + * 初始化SessionFactory + * @Description TODO + * @return + */ + @Bean + @ConditionalOnMissingBean + public SqlSessionFactory sqlSessionFactory() { + try { + + System.err.println(propertyResolver.getProperty("mapperLocations")); + SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); + sessionFactory.setDataSource(dataSource); + sessionFactory.setTypeAliasesPackage(propertyResolver + .getProperty("typeAliasesPackage")); + sessionFactory + .setMapperLocations(new PathMatchingResourcePatternResolver() + .getResources(propertyResolver + .getProperty("mapperLocations"))); + sessionFactory + .setConfigLocation(new DefaultResourceLoader() + .getResource(propertyResolver + .getProperty("configLocation"))); + + return sessionFactory.getObject(); + } catch (Exception e) { + e.printStackTrace(); + logger.warn("Could not confiure mybatis session factory"); + return null; + } + } + + @Bean + @ConditionalOnMissingBean + public DataSourceTransactionManager transactionManager() { + return new DataSourceTransactionManager(dataSource); + } +} diff --git a/SpringBootDemo/src/main/java/com/tony/spring/boot/config/RedisConfig.java b/SpringBootDemo/src/main/java/com/tony/spring/boot/config/RedisConfig.java new file mode 100644 index 0000000..48f4448 --- /dev/null +++ b/SpringBootDemo/src/main/java/com/tony/spring/boot/config/RedisConfig.java @@ -0,0 +1,46 @@ +package com.tony.spring.boot.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; + +/** + * 配置redis数据源 + * Java Lib For OIS, Powered By BeiJing FanTongTianXia. + * Copyright (c) 2014-2017 FanTongTianXia Co.,Ltd + * http://www.chifaner.com/ + * + * @ClassName RedisConfig + * @author Zhang.Tao + * @Date 2017年4月24日 下午5:25:30 + * @version V2.0.0 + */ +@Configuration +public class RedisConfig { + + + @Bean(name= "jedis.pool") + @Autowired + public JedisPool jedisPool(@Qualifier("jedis.pool.config") JedisPoolConfig config, + @Value("${jedis.pool.host}")String host, + @Value("${jedis.pool.port}")int port) { + return new JedisPool(config, host, port); + } + + @Bean(name= "jedis.pool.config") + public JedisPoolConfig jedisPoolConfig (@Value("${jedis.pool.config.maxTotal}")int maxTotal, + @Value("${jedis.pool.config.maxIdle}")int maxIdle, + @Value("${jedis.pool.config.maxWaitMillis}")int maxWaitMillis) { + JedisPoolConfig config = new JedisPoolConfig(); + config.setMaxTotal(maxTotal); + config.setMaxIdle(maxIdle); + config.setMaxWaitMillis(maxWaitMillis); + return config; + } + +} diff --git a/SpringBootDemo/src/main/java/com/tony/spring/boot/controller/TestCtrl.java b/SpringBootDemo/src/main/java/com/tony/spring/boot/controller/TestCtrl.java new file mode 100644 index 0000000..30c94a0 --- /dev/null +++ b/SpringBootDemo/src/main/java/com/tony/spring/boot/controller/TestCtrl.java @@ -0,0 +1,76 @@ +package com.tony.spring.boot.controller; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.tony.spring.boot.entity.UserInfo; +import com.tony.spring.boot.mapper.UserInfoMapper; +import com.tony.spring.boot.utils.JsonUtil; +import com.tony.spring.boot.utils.RedisUtil; + +/** + * Created by Administrator on 2017/4/19. + */ +@RestController +@RequestMapping(value="/test") +public class TestCtrl { + + @Autowired + private RedisUtil redisUtil; + + @Autowired + private UserInfoMapper userInfoMapper; + + @RequestMapping(value="/index") + public String index(){ + return "hello world"; + } + + /** + * 向redis存储值 + * @param key + * @param value + * @return + * @throws Exception + */ + @RequestMapping("/set") + public String set(String key, String value) throws Exception{ + redisUtil.set(key, value); + return "success"; + } + + /** + * 获取redis中的值 + * @param key + * @return + */ + @RequestMapping("/get") + public String get(String key){ + try { + return redisUtil.get(key); + } catch (Exception e) { + e.printStackTrace(); + } + return ""; + } + + /** + * 获取数据库中的用户 + * @Description TODO + * @param id + * @return + */ + @RequestMapping("/getUser/{id}") + public String get(@PathVariable("id")int id){ + try { + System.err.println(id); + UserInfo user= userInfoMapper.selectByPrimaryKey(id); + return JsonUtil.getJsonString(user); + } catch (Exception e) { + e.printStackTrace(); + } + return ""; + } +} diff --git a/SpringBootDemo/src/main/java/com/tony/spring/boot/entity/UserInfo.java b/SpringBootDemo/src/main/java/com/tony/spring/boot/entity/UserInfo.java new file mode 100644 index 0000000..c9e4376 --- /dev/null +++ b/SpringBootDemo/src/main/java/com/tony/spring/boot/entity/UserInfo.java @@ -0,0 +1,125 @@ +package com.tony.spring.boot.entity; + +import java.util.Date; + +public class UserInfo { + private Integer oid; + + private String userId; + + private String userName; + + private String password; + + private String region; + + private Integer userType; + + private Integer status; + + private String cellphoneNo; + + private String telephoneNo; + + private Date lastLoginDate; + + private String groupId; + + private String description; + + public Integer getOid() { + return oid; + } + + public void setOid(Integer oid) { + this.oid = oid; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId == null ? null : userId.trim(); + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName == null ? null : userName.trim(); + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password == null ? null : password.trim(); + } + + public String getRegion() { + return region; + } + + public void setRegion(String region) { + this.region = region == null ? null : region.trim(); + } + + public Integer getUserType() { + return userType; + } + + public void setUserType(Integer userType) { + this.userType = userType; + } + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } + + public String getCellphoneNo() { + return cellphoneNo; + } + + public void setCellphoneNo(String cellphoneNo) { + this.cellphoneNo = cellphoneNo == null ? null : cellphoneNo.trim(); + } + + public String getTelephoneNo() { + return telephoneNo; + } + + public void setTelephoneNo(String telephoneNo) { + this.telephoneNo = telephoneNo == null ? null : telephoneNo.trim(); + } + + public Date getLastLoginDate() { + return lastLoginDate; + } + + public void setLastLoginDate(Date lastLoginDate) { + this.lastLoginDate = lastLoginDate; + } + + public String getGroupId() { + return groupId; + } + + public void setGroupId(String groupId) { + this.groupId = groupId == null ? null : groupId.trim(); + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description == null ? null : description.trim(); + } +} \ No newline at end of file diff --git a/SpringBootDemo/src/main/java/com/tony/spring/boot/filter/MyFilter.java b/SpringBootDemo/src/main/java/com/tony/spring/boot/filter/MyFilter.java new file mode 100644 index 0000000..54d87d8 --- /dev/null +++ b/SpringBootDemo/src/main/java/com/tony/spring/boot/filter/MyFilter.java @@ -0,0 +1,46 @@ +package com.tony.spring.boot.filter; + +import java.io.IOException; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.annotation.WebFilter; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +/** + * Created by Administrator on 2017/4/19. + */ + +@ConfigurationProperties("cacheServer") +@WebFilter(filterName="myFilter",urlPatterns="/*") +public class MyFilter implements Filter{ + + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + System.out.println("过滤器初始化"); + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { + HttpServletRequest request = (HttpServletRequest) servletRequest; + HttpServletResponse response = (HttpServletResponse) servletResponse; + System.out.println("执行过滤器"); + filterChain.doFilter(request, response); + } + + @Override + public void destroy() { + + } + + + +} diff --git a/SpringBootDemo/src/main/java/com/tony/spring/boot/mapper/UserInfoMapper.java b/SpringBootDemo/src/main/java/com/tony/spring/boot/mapper/UserInfoMapper.java new file mode 100644 index 0000000..9590109 --- /dev/null +++ b/SpringBootDemo/src/main/java/com/tony/spring/boot/mapper/UserInfoMapper.java @@ -0,0 +1,19 @@ +package com.tony.spring.boot.mapper; + +import com.tony.spring.boot.entity.UserInfo; + +public interface UserInfoMapper { + int deleteByPrimaryKey(Integer oid); + + int insert(UserInfo record); + + int insertSelective(UserInfo record); + + UserInfo selectByPrimaryKey(Integer oid); + + int updateByPrimaryKeySelective(UserInfo record); + + int updateByPrimaryKeyWithBLOBs(UserInfo record); + + int updateByPrimaryKey(UserInfo record); +} \ No newline at end of file diff --git a/SpringBootDemo/src/main/java/com/tony/spring/boot/mapper/UserInfoMapper.xml b/SpringBootDemo/src/main/java/com/tony/spring/boot/mapper/UserInfoMapper.xml new file mode 100644 index 0000000..bb8c4cf --- /dev/null +++ b/SpringBootDemo/src/main/java/com/tony/spring/boot/mapper/UserInfoMapper.xml @@ -0,0 +1,165 @@ + + + + + + + + + + + + + + + + + + + + + + + OID, USER_ID, USER_NAME, PASSWORD, REGION, USER_TYPE, STATUS, CELLPHONE_NO, TELEPHONE_NO, + LAST_LOGIN_DATE, GROUP_ID + + + + DESCRIPTION + + + + + + delete from user + where OID = #{oid,jdbcType=INTEGER} + + + + insert into user + + + OID, + + + USER_ID, + + + USER_NAME, + + + PASSWORD, + + + REGION, + + + USER_TYPE, + + + STATUS, + + + CELLPHONE_NO, + + + TELEPHONE_NO, + + + LAST_LOGIN_DATE, + + + GROUP_ID, + + + DESCRIPTION, + + + + + #{oid,jdbcType=INTEGER}, + + + #{userId,jdbcType=VARCHAR}, + + + #{userName,jdbcType=VARCHAR}, + + + #{password,jdbcType=VARCHAR}, + + + #{region,jdbcType=VARCHAR}, + + + #{userType,jdbcType=INTEGER}, + + + #{status,jdbcType=INTEGER}, + + + #{cellphoneNo,jdbcType=VARCHAR}, + + + #{telephoneNo,jdbcType=VARCHAR}, + + + #{lastLoginDate,jdbcType=TIMESTAMP}, + + + #{groupId,jdbcType=VARCHAR}, + + + #{description,jdbcType=LONGVARCHAR}, + + + + + + update user + + + USER_ID = #{userId,jdbcType=VARCHAR}, + + + USER_NAME = #{userName,jdbcType=VARCHAR}, + + + PASSWORD = #{password,jdbcType=VARCHAR}, + + + REGION = #{region,jdbcType=VARCHAR}, + + + USER_TYPE = #{userType,jdbcType=INTEGER}, + + + STATUS = #{status,jdbcType=INTEGER}, + + + CELLPHONE_NO = #{cellphoneNo,jdbcType=VARCHAR}, + + + TELEPHONE_NO = #{telephoneNo,jdbcType=VARCHAR}, + + + LAST_LOGIN_DATE = #{lastLoginDate,jdbcType=TIMESTAMP}, + + + GROUP_ID = #{groupId,jdbcType=VARCHAR}, + + + DESCRIPTION = #{description,jdbcType=LONGVARCHAR}, + + + where OID = #{oid,jdbcType=INTEGER} + + + \ No newline at end of file diff --git a/SpringBootDemo/src/main/java/com/tony/spring/boot/utils/JsonUtil.java b/SpringBootDemo/src/main/java/com/tony/spring/boot/utils/JsonUtil.java new file mode 100644 index 0000000..997e614 --- /dev/null +++ b/SpringBootDemo/src/main/java/com/tony/spring/boot/utils/JsonUtil.java @@ -0,0 +1,66 @@ +package com.tony.spring.boot.utils; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class JsonUtil { + + public static String getJsonString(Object javaObj) { + String ret = "{}"; + ObjectMapper mapper = new ObjectMapper(); + try { + ret = mapper.writeValueAsString(javaObj); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + + return ret.replaceAll(":null",":\"\""); + + } + + public static T readJson2Obj(String json, Class classObj) { + T ret = null; + ObjectMapper mapper = new ObjectMapper(); + try { + ret = mapper.readValue(json, classObj); + } catch (JsonParseException e) { + e.printStackTrace(); + } catch (JsonMappingException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + return ret; + } + + public static T[] readJson2Array(String json, Class classObj) { + T[] ret = null; + ObjectMapper mapper = new ObjectMapper(); + try { + ret = mapper.readValue(json, classObj); + } catch (JsonParseException e) { + e.printStackTrace(); + } catch (JsonMappingException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + return ret; + } + + public static void main(String [] args){ + Map map= new HashMap<>(); + map.put("name","xiaochouyu"); + map.put("stak","小丑鱼"); + System.out.println(getJsonString(map)); + } + +} \ No newline at end of file diff --git a/SpringBootDemo/src/main/java/com/tony/spring/boot/utils/RedisUtil.java b/SpringBootDemo/src/main/java/com/tony/spring/boot/utils/RedisUtil.java new file mode 100644 index 0000000..c7f5c73 --- /dev/null +++ b/SpringBootDemo/src/main/java/com/tony/spring/boot/utils/RedisUtil.java @@ -0,0 +1,56 @@ +package com.tony.spring.boot.utils; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; +@Component +public class RedisUtil { + + @Autowired + private JedisPool jedisPool; + + public void set(String key, String value) throws Exception { + Jedis jedis = null; + try { + jedis = jedisPool.getResource(); + jedis.set(key, value); + } finally { + //返还到连接池 + jedis.close(); + } + } + + public String get(String key) throws Exception { + + Jedis jedis = null; + try { + jedis = jedisPool.getResource(); + return jedis.get(key); + } finally { + //返还到连接池 + jedis.close(); + } + } + + public boolean exists(String key) { + Jedis jedis=null ; + try { + jedis = jedisPool.getResource(); + return jedis.exists(key); + } finally { + jedis.close(); + } + } + + public Long delete(String key) { + Jedis jedis=null ; + try { + jedis = jedisPool.getResource(); + return jedis.del(key); + } finally { + jedis.close(); + } + } +} diff --git a/SpringBootDemo/src/main/resources/application.yml b/SpringBootDemo/src/main/resources/application.yml new file mode 100644 index 0000000..559b106 --- /dev/null +++ b/SpringBootDemo/src/main/resources/application.yml @@ -0,0 +1,45 @@ +jedis : + pool : + host : 127.0.0.1 + port : 6379 + config : + maxTotal: 100 + maxIdle: 10 + maxWaitMillis : 100000 + +server : + port : 8080 + +jdbc: + datasource: + name: test + url: jdbc:mysql://192.168.2.5:3335/fantong_tm + username: root + password: chifaner159 + # 使用druid数据源 + type: com.alibaba.druid.pool.DruidDataSource + driver-class-name: com.mysql.jdbc.Driver + filters: stat + maxActive: 20 + initialSize: 1 + maxWait: 60000 + minIdle: 1 + timeBetweenEvictionRunsMillis: 60000 + minEvictableIdleTimeMillis: 300000 + validationQuery: select 'x' + testWhileIdle: true + testOnBorrow: false + testOnReturn: false + poolPreparedStatements: true + maxOpenPreparedStatements: 20 +# MyBatis +mybatis: + typeAliasesPackage: com.tony.spring.boot.entity + mapperLocations: classpath*:/com/tony/spring/boot/mapper/*.xml + configLocation: classpath:mybatis-config.xml + +# LOGGING +logging: + level: + com.ibatis:DEBUG + \ No newline at end of file diff --git a/SpringBootDemo/src/main/resources/mybatis-config.xml b/SpringBootDemo/src/main/resources/mybatis-config.xml new file mode 100644 index 0000000..c90e2a5 --- /dev/null +++ b/SpringBootDemo/src/main/resources/mybatis-config.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file From 0390fd4a24652f3ffc6a616ba44f3e7bcedb8b17 Mon Sep 17 00:00:00 2001 From: xiaour Date: Tue, 25 Apr 2017 09:49:24 +0800 Subject: [PATCH 02/23] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=BA=86=E5=8C=85?= =?UTF-8?q?=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../{tony => xiaour}/spring/boot/Application.java | 4 ++-- .../spring/boot/config/DataBaseConfiguration.java | 3 +-- .../spring/boot/config/MybatisConfiguration.java | 7 ++----- .../spring/boot/config/RedisConfig.java | 7 ++----- .../spring/boot/controller/TestCtrl.java | 12 ++++++------ .../spring/boot/entity/UserInfo.java | 2 +- .../spring/boot/filter/MyFilter.java | 4 ++-- .../spring/boot/mapper/UserInfoMapper.java | 4 ++-- .../spring/boot/mapper/UserInfoMapper.xml | 0 .../{tony => xiaour}/spring/boot/utils/JsonUtil.java | 2 +- .../spring/boot/utils/RedisUtil.java | 2 +- 11 files changed, 20 insertions(+), 27 deletions(-) rename SpringBootDemo/src/main/java/com/{tony => xiaour}/spring/boot/Application.java (91%) rename SpringBootDemo/src/main/java/com/{tony => xiaour}/spring/boot/config/DataBaseConfiguration.java (95%) rename SpringBootDemo/src/main/java/com/{tony => xiaour}/spring/boot/config/MybatisConfiguration.java (91%) rename SpringBootDemo/src/main/java/com/{tony => xiaour}/spring/boot/config/RedisConfig.java (86%) rename SpringBootDemo/src/main/java/com/{tony => xiaour}/spring/boot/controller/TestCtrl.java (81%) rename SpringBootDemo/src/main/java/com/{tony => xiaour}/spring/boot/entity/UserInfo.java (93%) rename SpringBootDemo/src/main/java/com/{tony => xiaour}/spring/boot/filter/MyFilter.java (90%) rename SpringBootDemo/src/main/java/com/{tony => xiaour}/spring/boot/mapper/UserInfoMapper.java (77%) rename SpringBootDemo/src/main/java/com/{tony => xiaour}/spring/boot/mapper/UserInfoMapper.xml (100%) rename SpringBootDemo/src/main/java/com/{tony => xiaour}/spring/boot/utils/JsonUtil.java (95%) rename SpringBootDemo/src/main/java/com/{tony => xiaour}/spring/boot/utils/RedisUtil.java (92%) diff --git a/SpringBootDemo/src/main/java/com/tony/spring/boot/Application.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/Application.java similarity index 91% rename from SpringBootDemo/src/main/java/com/tony/spring/boot/Application.java rename to SpringBootDemo/src/main/java/com/xiaour/spring/boot/Application.java index e0c546f..64f9692 100644 --- a/SpringBootDemo/src/main/java/com/tony/spring/boot/Application.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/Application.java @@ -1,4 +1,4 @@ -package com.tony.spring.boot; +package com.xiaour.spring.boot; import org.mybatis.spring.annotation.MapperScan; import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration; @@ -17,7 +17,7 @@ @SpringBootApplication(exclude = MybatisAutoConfiguration.class) @ServletComponentScan @EnableAutoConfiguration -@MapperScan("com.tony.spring.boot.mapper") +@MapperScan("com.xiaour.spring.boot.mapper") public class Application extends SpringBootServletInitializer implements EmbeddedServletContainerCustomizer { @Value("${server.port}") diff --git a/SpringBootDemo/src/main/java/com/tony/spring/boot/config/DataBaseConfiguration.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/DataBaseConfiguration.java similarity index 95% rename from SpringBootDemo/src/main/java/com/tony/spring/boot/config/DataBaseConfiguration.java rename to SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/DataBaseConfiguration.java index 0d0d12f..a831dcd 100644 --- a/SpringBootDemo/src/main/java/com/tony/spring/boot/config/DataBaseConfiguration.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/DataBaseConfiguration.java @@ -1,4 +1,4 @@ -package com.tony.spring.boot.config; +package com.xiaour.spring.boot.config; import java.sql.SQLException; @@ -33,7 +33,6 @@ public void setEnvironment(Environment env) { /** * 配置数据源 - * @Description TODO * @return */ @Bean(name = "dataSource",destroyMethod = "close") diff --git a/SpringBootDemo/src/main/java/com/tony/spring/boot/config/MybatisConfiguration.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/MybatisConfiguration.java similarity index 91% rename from SpringBootDemo/src/main/java/com/tony/spring/boot/config/MybatisConfiguration.java rename to SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/MybatisConfiguration.java index 67165b7..2ad5b27 100644 --- a/SpringBootDemo/src/main/java/com/tony/spring/boot/config/MybatisConfiguration.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/MybatisConfiguration.java @@ -1,4 +1,4 @@ -package com.tony.spring.boot.config; +package com.xiaour.spring.boot.config; import javax.annotation.Resource; import javax.persistence.EntityManager; @@ -23,9 +23,7 @@ /** * 初始化SqlSessionFactory - * Java Lib For OIS, Powered By BeiJing FanTongTianXia. - * Copyright (c) 2014-2017 FanTongTianXia Co.,Ltd - * http://www.chifaner.com/ + * Java Lib For OIS, Powered By xiaour. * * @ClassName MybatisConfiguration * @author Zhang.Tao @@ -51,7 +49,6 @@ public void setEnvironment(Environment environment) { /** * 初始化SessionFactory - * @Description TODO * @return */ @Bean diff --git a/SpringBootDemo/src/main/java/com/tony/spring/boot/config/RedisConfig.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/RedisConfig.java similarity index 86% rename from SpringBootDemo/src/main/java/com/tony/spring/boot/config/RedisConfig.java rename to SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/RedisConfig.java index 48f4448..9d11a34 100644 --- a/SpringBootDemo/src/main/java/com/tony/spring/boot/config/RedisConfig.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/RedisConfig.java @@ -1,4 +1,4 @@ -package com.tony.spring.boot.config; +package com.xiaour.spring.boot.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; @@ -11,10 +11,7 @@ /** * 配置redis数据源 - * Java Lib For OIS, Powered By BeiJing FanTongTianXia. - * Copyright (c) 2014-2017 FanTongTianXia Co.,Ltd - * http://www.chifaner.com/ - * + * Java Lib For OIS, Powered By xiaour. * @ClassName RedisConfig * @author Zhang.Tao * @Date 2017年4月24日 下午5:25:30 diff --git a/SpringBootDemo/src/main/java/com/tony/spring/boot/controller/TestCtrl.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/controller/TestCtrl.java similarity index 81% rename from SpringBootDemo/src/main/java/com/tony/spring/boot/controller/TestCtrl.java rename to SpringBootDemo/src/main/java/com/xiaour/spring/boot/controller/TestCtrl.java index 30c94a0..51cfe5a 100644 --- a/SpringBootDemo/src/main/java/com/tony/spring/boot/controller/TestCtrl.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/controller/TestCtrl.java @@ -1,17 +1,17 @@ -package com.tony.spring.boot.controller; +package com.xiaour.spring.boot.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import com.tony.spring.boot.entity.UserInfo; -import com.tony.spring.boot.mapper.UserInfoMapper; -import com.tony.spring.boot.utils.JsonUtil; -import com.tony.spring.boot.utils.RedisUtil; +import com.xiaour.spring.boot.entity.UserInfo; +import com.xiaour.spring.boot.mapper.UserInfoMapper; +import com.xiaour.spring.boot.utils.JsonUtil; +import com.xiaour.spring.boot.utils.RedisUtil; /** - * Created by Administrator on 2017/4/19. + * Created by xiaour on 2017/4/19. */ @RestController @RequestMapping(value="/test") diff --git a/SpringBootDemo/src/main/java/com/tony/spring/boot/entity/UserInfo.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/entity/UserInfo.java similarity index 93% rename from SpringBootDemo/src/main/java/com/tony/spring/boot/entity/UserInfo.java rename to SpringBootDemo/src/main/java/com/xiaour/spring/boot/entity/UserInfo.java index c9e4376..61f6104 100644 --- a/SpringBootDemo/src/main/java/com/tony/spring/boot/entity/UserInfo.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/entity/UserInfo.java @@ -1,4 +1,4 @@ -package com.tony.spring.boot.entity; +package com.xiaour.spring.boot.entity; import java.util.Date; diff --git a/SpringBootDemo/src/main/java/com/tony/spring/boot/filter/MyFilter.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/filter/MyFilter.java similarity index 90% rename from SpringBootDemo/src/main/java/com/tony/spring/boot/filter/MyFilter.java rename to SpringBootDemo/src/main/java/com/xiaour/spring/boot/filter/MyFilter.java index 54d87d8..66b051a 100644 --- a/SpringBootDemo/src/main/java/com/tony/spring/boot/filter/MyFilter.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/filter/MyFilter.java @@ -1,4 +1,4 @@ -package com.tony.spring.boot.filter; +package com.xiaour.spring.boot.filter; import java.io.IOException; @@ -15,7 +15,7 @@ import org.springframework.boot.context.properties.ConfigurationProperties; /** - * Created by Administrator on 2017/4/19. + * Created by xiaour on 2017/4/19. */ @ConfigurationProperties("cacheServer") diff --git a/SpringBootDemo/src/main/java/com/tony/spring/boot/mapper/UserInfoMapper.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/mapper/UserInfoMapper.java similarity index 77% rename from SpringBootDemo/src/main/java/com/tony/spring/boot/mapper/UserInfoMapper.java rename to SpringBootDemo/src/main/java/com/xiaour/spring/boot/mapper/UserInfoMapper.java index 9590109..689b0c9 100644 --- a/SpringBootDemo/src/main/java/com/tony/spring/boot/mapper/UserInfoMapper.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/mapper/UserInfoMapper.java @@ -1,6 +1,6 @@ -package com.tony.spring.boot.mapper; +package com.xiaour.spring.boot.mapper; -import com.tony.spring.boot.entity.UserInfo; +import com.xiaour.spring.boot.entity.UserInfo; public interface UserInfoMapper { int deleteByPrimaryKey(Integer oid); diff --git a/SpringBootDemo/src/main/java/com/tony/spring/boot/mapper/UserInfoMapper.xml b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/mapper/UserInfoMapper.xml similarity index 100% rename from SpringBootDemo/src/main/java/com/tony/spring/boot/mapper/UserInfoMapper.xml rename to SpringBootDemo/src/main/java/com/xiaour/spring/boot/mapper/UserInfoMapper.xml diff --git a/SpringBootDemo/src/main/java/com/tony/spring/boot/utils/JsonUtil.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/JsonUtil.java similarity index 95% rename from SpringBootDemo/src/main/java/com/tony/spring/boot/utils/JsonUtil.java rename to SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/JsonUtil.java index 997e614..0adb0ae 100644 --- a/SpringBootDemo/src/main/java/com/tony/spring/boot/utils/JsonUtil.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/JsonUtil.java @@ -1,4 +1,4 @@ -package com.tony.spring.boot.utils; +package com.xiaour.spring.boot.utils; import java.io.IOException; import java.util.HashMap; diff --git a/SpringBootDemo/src/main/java/com/tony/spring/boot/utils/RedisUtil.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/RedisUtil.java similarity index 92% rename from SpringBootDemo/src/main/java/com/tony/spring/boot/utils/RedisUtil.java rename to SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/RedisUtil.java index c7f5c73..7d8c7af 100644 --- a/SpringBootDemo/src/main/java/com/tony/spring/boot/utils/RedisUtil.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/RedisUtil.java @@ -1,4 +1,4 @@ -package com.tony.spring.boot.utils; +package com.xiaour.spring.boot.utils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; From 53599c4a0ec049fd4e6420907596c983aa04ca55 Mon Sep 17 00:00:00 2001 From: xiaour Date: Tue, 25 Apr 2017 09:58:03 +0800 Subject: [PATCH 03/23] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=BA=86Mapper?= =?UTF-8?q?=E6=98=A0=E5=B0=84=E7=9A=84=E5=AE=9E=E4=BD=93=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/xiaour/spring/boot/mapper/UserInfoMapper.xml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/mapper/UserInfoMapper.xml b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/mapper/UserInfoMapper.xml index bb8c4cf..fc04391 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/mapper/UserInfoMapper.xml +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/mapper/UserInfoMapper.xml @@ -1,7 +1,7 @@ - - + + @@ -15,7 +15,7 @@ - + @@ -42,7 +42,7 @@ where OID = #{oid,jdbcType=INTEGER} - + insert into user @@ -122,7 +122,7 @@ - + update user From 57ce1a43b4f4f76be1b0ba4974fe9a3932276cb8 Mon Sep 17 00:00:00 2001 From: xiaour Date: Tue, 25 Apr 2017 10:31:52 +0800 Subject: [PATCH 04/23] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BA=86druid=E7=9B=91?= =?UTF-8?q?=E6=8E=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- SpringBootDemo/pom.xml | 7 ++++++- .../boot/config/DataBaseConfiguration.java | 4 +++- .../spring/boot/filter/DruidStatFilter.java | 14 +++++++++++++ .../xiaour/spring/boot/filter/MyFilter.java | 21 ++++++++++++++++--- .../src/main/resources/application.yml | 4 ++-- 5 files changed, 43 insertions(+), 7 deletions(-) create mode 100644 SpringBootDemo/src/main/java/com/xiaour/spring/boot/filter/DruidStatFilter.java diff --git a/SpringBootDemo/pom.xml b/SpringBootDemo/pom.xml index 49a2094..2137e11 100644 --- a/SpringBootDemo/pom.xml +++ b/SpringBootDemo/pom.xml @@ -74,7 +74,12 @@ 7.0 provided - + + + javax.servlet + javax.servlet-api + + diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/DataBaseConfiguration.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/DataBaseConfiguration.java index a831dcd..a0feade 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/DataBaseConfiguration.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/DataBaseConfiguration.java @@ -55,8 +55,10 @@ public DataSource dataSource() { dataSource.setTestWhileIdle(Boolean.getBoolean(propertyResolver.getProperty("testWhileIdle"))); dataSource.setTestOnReturn(Boolean.getBoolean(propertyResolver.getProperty("testOnReturn"))); dataSource.setPoolPreparedStatements(Boolean.getBoolean(propertyResolver.getProperty("poolPreparedStatements"))); - dataSource.setMaxPoolPreparedStatementPerConnectionSize(Integer.parseInt(propertyResolver.getProperty("maxOpenPreparedStatements"))); + dataSource.setMaxPoolPreparedStatementPerConnectionSize(Integer.parseInt(propertyResolver.getProperty("maxOpenPreparedStatements"))); try { + //开启druid监控 + dataSource.setFilters("stat"); dataSource.init(); } catch (SQLException e) { diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/filter/DruidStatFilter.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/filter/DruidStatFilter.java new file mode 100644 index 0000000..e044d5f --- /dev/null +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/filter/DruidStatFilter.java @@ -0,0 +1,14 @@ +package com.xiaour.spring.boot.filter; + +import javax.servlet.annotation.WebFilter; +import javax.servlet.annotation.WebInitParam; + +import com.alibaba.druid.support.http.WebStatFilter; + +@WebFilter(filterName="druidWebStatFilter",urlPatterns="/*", +initParams={ + @WebInitParam(name="exclusions",value="*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")// 忽略资源 +}) +public class DruidStatFilter extends WebStatFilter{ + +} diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/filter/MyFilter.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/filter/MyFilter.java index 66b051a..9bc999e 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/filter/MyFilter.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/filter/MyFilter.java @@ -9,21 +9,36 @@ import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; +import javax.servlet.annotation.WebInitParam; +import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.boot.context.properties.ConfigurationProperties; +import com.alibaba.druid.support.http.StatViewServlet; + /** * Created by xiaour on 2017/4/19. */ - +@WebServlet(urlPatterns = "/druid/*", +initParams={ + @WebInitParam(name="allow",value="192.168.0.230,127.0.0.1"),// IP白名单 (没有配置或者为空,则允许所有访问) + @WebInitParam(name="deny",value="192.168.0.1"),// IP黑名单 (存在共同时,deny优先于allow) + @WebInitParam(name="loginUsername",value="root"),// 用户名 + @WebInitParam(name="loginPassword",value="123456"),// 密码 + @WebInitParam(name="resetEnable",value="false")// 禁用HTML页面上的“Reset All”功能 +}) @ConfigurationProperties("cacheServer") @WebFilter(filterName="myFilter",urlPatterns="/*") -public class MyFilter implements Filter{ +public class MyFilter extends StatViewServlet implements Filter{ - @Override + /** + */ + private static final long serialVersionUID = 1L; + + @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("过滤器初始化"); } diff --git a/SpringBootDemo/src/main/resources/application.yml b/SpringBootDemo/src/main/resources/application.yml index 559b106..29a317d 100644 --- a/SpringBootDemo/src/main/resources/application.yml +++ b/SpringBootDemo/src/main/resources/application.yml @@ -34,8 +34,8 @@ jdbc: maxOpenPreparedStatements: 20 # MyBatis mybatis: - typeAliasesPackage: com.tony.spring.boot.entity - mapperLocations: classpath*:/com/tony/spring/boot/mapper/*.xml + typeAliasesPackage: com.xiaour.spring.boot.entity + mapperLocations: classpath*:/com/xiaour/spring/boot/mapper/*.xml configLocation: classpath:mybatis-config.xml # LOGGING From 1c133463480a0d5d8cf01dc248fd23581d297e6a Mon Sep 17 00:00:00 2001 From: xiaour Date: Tue, 25 Apr 2017 13:59:10 +0800 Subject: [PATCH 05/23] =?UTF-8?q?=E5=8E=BB=E6=8E=89=E4=BA=86=E4=B8=80?= =?UTF-8?q?=E4=BA=9B=E4=B8=8D=E5=BF=85=E8=A6=81=E7=9A=84=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../xiaour/spring/boot/config/DataBaseConfiguration.java | 2 +- .../java/com/xiaour/spring/boot/controller/TestCtrl.java | 1 - .../main/java/com/xiaour/spring/boot/filter/MyFilter.java | 4 ++-- .../main/java/com/xiaour/spring/boot/utils/RedisUtil.java | 7 +++++++ 4 files changed, 10 insertions(+), 4 deletions(-) diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/DataBaseConfiguration.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/DataBaseConfiguration.java index a0feade..278e62f 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/DataBaseConfiguration.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/DataBaseConfiguration.java @@ -58,7 +58,7 @@ public DataSource dataSource() { dataSource.setMaxPoolPreparedStatementPerConnectionSize(Integer.parseInt(propertyResolver.getProperty("maxOpenPreparedStatements"))); try { //开启druid监控 - dataSource.setFilters("stat"); + dataSource.setFilters("stat,wall"); dataSource.init(); } catch (SQLException e) { diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/controller/TestCtrl.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/controller/TestCtrl.java index 51cfe5a..ed736b3 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/controller/TestCtrl.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/controller/TestCtrl.java @@ -65,7 +65,6 @@ public String get(String key){ @RequestMapping("/getUser/{id}") public String get(@PathVariable("id")int id){ try { - System.err.println(id); UserInfo user= userInfoMapper.selectByPrimaryKey(id); return JsonUtil.getJsonString(user); } catch (Exception e) { diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/filter/MyFilter.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/filter/MyFilter.java index 9bc999e..cdab22d 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/filter/MyFilter.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/filter/MyFilter.java @@ -40,14 +40,14 @@ public class MyFilter extends StatViewServlet implements Filter{ @Override public void init(FilterConfig filterConfig) throws ServletException { - System.out.println("过滤器初始化"); + } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; - System.out.println("执行过滤器"); + filterChain.doFilter(request, response); } diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/RedisUtil.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/RedisUtil.java index 7d8c7af..bd711bd 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/RedisUtil.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/RedisUtil.java @@ -1,5 +1,7 @@ package com.xiaour.spring.boot.utils; +import java.util.UUID; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -53,4 +55,9 @@ public Long delete(String key) { jedis.close(); } } + + public static void main(String [] args){ + String uuid=UUID.randomUUID().toString().replaceAll("-","").toUpperCase(); + System.out.println(uuid); + } } From 2a19859011b726a5730f5e3627261963a29eb343 Mon Sep 17 00:00:00 2001 From: xiaour Date: Tue, 25 Apr 2017 16:56:14 +0800 Subject: [PATCH 06/23] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E4=BA=86=E6=97=A5?= =?UTF-8?q?=E5=BF=97=E8=BE=93=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../boot/config/DataBaseConfiguration.java | 3 +++ .../xiaour/spring/boot/controller/TestCtrl.java | 1 - .../src/main/resources/application.yml | 16 +++++++++++----- 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/DataBaseConfiguration.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/DataBaseConfiguration.java index 278e62f..2cf6d9b 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/DataBaseConfiguration.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/DataBaseConfiguration.java @@ -25,6 +25,9 @@ public class DataBaseConfiguration implements EnvironmentAware { private Environment env; + /** + * 初始化yml配置 + */ @Override public void setEnvironment(Environment env) { this.env = env; diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/controller/TestCtrl.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/controller/TestCtrl.java index ed736b3..bb16a3d 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/controller/TestCtrl.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/controller/TestCtrl.java @@ -58,7 +58,6 @@ public String get(String key){ /** * 获取数据库中的用户 - * @Description TODO * @param id * @return */ diff --git a/SpringBootDemo/src/main/resources/application.yml b/SpringBootDemo/src/main/resources/application.yml index 29a317d..63c2b0c 100644 --- a/SpringBootDemo/src/main/resources/application.yml +++ b/SpringBootDemo/src/main/resources/application.yml @@ -1,3 +1,4 @@ +#redis服务配置 jedis : pool : host : 127.0.0.1 @@ -7,9 +8,11 @@ jedis : maxIdle: 10 maxWaitMillis : 100000 +#服务启动端口 server : port : 8080 - + +#数据库配置 jdbc: datasource: name: test @@ -38,8 +41,11 @@ mybatis: mapperLocations: classpath*:/com/xiaour/spring/boot/mapper/*.xml configLocation: classpath:mybatis-config.xml -# LOGGING -logging: - level: - com.ibatis:DEBUG +# 日志输出 +logging: + file: D:/boot.log + level: + com.ibatis:DEBUG + root:DEBUG + \ No newline at end of file From b18d152e578bb656b4059393dc1d88d90e2ef6f6 Mon Sep 17 00:00:00 2001 From: xiaour Date: Wed, 26 Apr 2017 13:43:44 +0800 Subject: [PATCH 07/23] =?UTF-8?q?=E5=8E=BB=E9=99=A4=E4=BA=86=E4=B8=8D?= =?UTF-8?q?=E5=BF=85=E8=A6=81=E7=9A=84=E6=A0=BC=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../spring/boot/config/MybatisConfiguration.java | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/MybatisConfiguration.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/MybatisConfiguration.java index 2ad5b27..a0d028d 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/MybatisConfiguration.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/MybatisConfiguration.java @@ -56,19 +56,11 @@ public void setEnvironment(Environment environment) { public SqlSessionFactory sqlSessionFactory() { try { - System.err.println(propertyResolver.getProperty("mapperLocations")); SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(dataSource); - sessionFactory.setTypeAliasesPackage(propertyResolver - .getProperty("typeAliasesPackage")); - sessionFactory - .setMapperLocations(new PathMatchingResourcePatternResolver() - .getResources(propertyResolver - .getProperty("mapperLocations"))); - sessionFactory - .setConfigLocation(new DefaultResourceLoader() - .getResource(propertyResolver - .getProperty("configLocation"))); + sessionFactory.setTypeAliasesPackage(propertyResolver.getProperty("typeAliasesPackage")); + sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(propertyResolver.getProperty("mapperLocations"))); + sessionFactory.setConfigLocation(new DefaultResourceLoader().getResource(propertyResolver.getProperty("configLocation"))); return sessionFactory.getObject(); } catch (Exception e) { From 5860373d32e947e4ef62c7d901aa9930ccbccbd0 Mon Sep 17 00:00:00 2001 From: xiaour Date: Wed, 26 Apr 2017 13:45:54 +0800 Subject: [PATCH 08/23] =?UTF-8?q?=E7=99=BD=E5=90=8D=E5=8D=95=E6=9B=B4?= =?UTF-8?q?=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/main/java/com/xiaour/spring/boot/filter/MyFilter.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/filter/MyFilter.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/filter/MyFilter.java index cdab22d..b7a6d62 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/filter/MyFilter.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/filter/MyFilter.java @@ -23,7 +23,7 @@ */ @WebServlet(urlPatterns = "/druid/*", initParams={ - @WebInitParam(name="allow",value="192.168.0.230,127.0.0.1"),// IP白名单 (没有配置或者为空,则允许所有访问) + @WebInitParam(name="allow",value=""),// IP白名单 (没有配置或者为空,则允许所有访问) @WebInitParam(name="deny",value="192.168.0.1"),// IP黑名单 (存在共同时,deny优先于allow) @WebInitParam(name="loginUsername",value="root"),// 用户名 @WebInitParam(name="loginPassword",value="123456"),// 密码 From 2438f158e6b60ffc6821e4c6aaa371c02d0f8962 Mon Sep 17 00:00:00 2001 From: xiaour Date: Wed, 26 Apr 2017 14:06:23 +0800 Subject: [PATCH 09/23] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BA=86=E5=AE=9A?= =?UTF-8?q?=E6=97=B6=E4=BB=BB=E5=8A=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/xiaour/spring/boot/task/Task.java | 15 +++++++++++++++ SpringBootDemo/src/main/resources/application.yml | 3 +++ 2 files changed, 18 insertions(+) create mode 100644 SpringBootDemo/src/main/java/com/xiaour/spring/boot/task/Task.java diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/task/Task.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/task/Task.java new file mode 100644 index 0000000..0954d2e --- /dev/null +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/task/Task.java @@ -0,0 +1,15 @@ +package com.xiaour.spring.boot.task; + +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.annotation.Scheduled; + +@Configuration +@EnableScheduling // 启用定时任务 +public class Task { + + @Scheduled(cron="0 0/1 * * * ?") + public void run(){ + System.out.println("定时任务执行"); + } +} diff --git a/SpringBootDemo/src/main/resources/application.yml b/SpringBootDemo/src/main/resources/application.yml index 63c2b0c..ba005eb 100644 --- a/SpringBootDemo/src/main/resources/application.yml +++ b/SpringBootDemo/src/main/resources/application.yml @@ -47,5 +47,8 @@ logging: level: com.ibatis:DEBUG root:DEBUG + +task: + cron:0 0/1 * * * ? \ No newline at end of file From b9d84fb50bbaf404a7cb64fad0afec2b5dd090c9 Mon Sep 17 00:00:00 2001 From: xiaour Date: Thu, 27 Apr 2017 10:11:46 +0800 Subject: [PATCH 10/23] =?UTF-8?q?=E6=A0=BC=E5=BC=8F=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/main/java/com/xiaour/spring/boot/Application.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/Application.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/Application.java index 64f9692..f2832f8 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/Application.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/Application.java @@ -35,7 +35,7 @@ public static void main(String ... args){ */ @Override public void customize(ConfigurableEmbeddedServletContainer container) { - container.setPort(port); + container.setPort(port); } } From 95c83666cb0e7964dc3fa695c5f9f56994343a16 Mon Sep 17 00:00:00 2001 From: xiaour Date: Thu, 27 Apr 2017 17:29:40 +0800 Subject: [PATCH 11/23] =?UTF-8?q?=E5=A4=84=E7=90=86=E5=BC=82=E5=B8=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../boot/config/DataBaseConfiguration.java | 3 +- .../boot/config/MybatisConfiguration.java | 1 - .../spring/boot/config/RedisConfig.java | 20 +++++--- .../xiaour/spring/boot/utils/JsonUtil.java | 48 ++++++++----------- 4 files changed, 35 insertions(+), 37 deletions(-) diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/DataBaseConfiguration.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/DataBaseConfiguration.java index 2cf6d9b..ee7bca8 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/DataBaseConfiguration.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/DataBaseConfiguration.java @@ -40,7 +40,6 @@ public void setEnvironment(Environment env) { */ @Bean(name = "dataSource",destroyMethod = "close") public DataSource dataSource() { - log.debug(env.getActiveProfiles().toString()); DruidDataSource dataSource = new DruidDataSource(); dataSource.setUrl(propertyResolver.getProperty("url")); @@ -64,7 +63,7 @@ public DataSource dataSource() { dataSource.setFilters("stat,wall"); dataSource.init(); } catch (SQLException e) { - + log.error(e.getMessage()); } return dataSource; } diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/MybatisConfiguration.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/MybatisConfiguration.java index a0d028d..af59d1f 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/MybatisConfiguration.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/MybatisConfiguration.java @@ -64,7 +64,6 @@ public SqlSessionFactory sqlSessionFactory() { return sessionFactory.getObject(); } catch (Exception e) { - e.printStackTrace(); logger.warn("Could not confiure mybatis session factory"); return null; } diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/RedisConfig.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/RedisConfig.java index 9d11a34..5333733 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/RedisConfig.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/RedisConfig.java @@ -1,5 +1,7 @@ package com.xiaour.spring.boot.config; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; @@ -19,7 +21,8 @@ */ @Configuration public class RedisConfig { - + private static Logger log = LoggerFactory.getLogger(RedisConfig.class); + @Bean(name= "jedis.pool") @Autowired @@ -33,11 +36,16 @@ public JedisPool jedisPool(@Qualifier("jedis.pool.config") JedisPoolConfig confi public JedisPoolConfig jedisPoolConfig (@Value("${jedis.pool.config.maxTotal}")int maxTotal, @Value("${jedis.pool.config.maxIdle}")int maxIdle, @Value("${jedis.pool.config.maxWaitMillis}")int maxWaitMillis) { - JedisPoolConfig config = new JedisPoolConfig(); - config.setMaxTotal(maxTotal); - config.setMaxIdle(maxIdle); - config.setMaxWaitMillis(maxWaitMillis); - return config; + try { + JedisPoolConfig config = new JedisPoolConfig(); + config.setMaxTotal(maxTotal); + config.setMaxIdle(maxIdle); + config.setMaxWaitMillis(maxWaitMillis); + return config; + } catch (Exception e) { + log.error(e.getMessage()); + } + return null; } } diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/JsonUtil.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/JsonUtil.java index 0adb0ae..105aa95 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/JsonUtil.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/JsonUtil.java @@ -10,48 +10,36 @@ import com.fasterxml.jackson.databind.ObjectMapper; public class JsonUtil { + + - public static String getJsonString(Object javaObj) { + public static String getJsonString(Object javaObj) throws JsonProcessingException { String ret = "{}"; + ObjectMapper mapper = new ObjectMapper(); - try { - ret = mapper.writeValueAsString(javaObj); - } catch (JsonProcessingException e) { - e.printStackTrace(); - } + + ret = mapper.writeValueAsString(javaObj); return ret.replaceAll(":null",":\"\""); } - public static T readJson2Obj(String json, Class classObj) { + public static T readJson2Obj(String json, Class classObj) throws JsonParseException,JsonMappingException,IOException { T ret = null; + ObjectMapper mapper = new ObjectMapper(); - try { - ret = mapper.readValue(json, classObj); - } catch (JsonParseException e) { - e.printStackTrace(); - } catch (JsonMappingException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - + + ret = mapper.readValue(json, classObj); + return ret; } - public static T[] readJson2Array(String json, Class classObj) { + public static T[] readJson2Array(String json, Class classObj) throws JsonParseException,JsonMappingException,IOException { T[] ret = null; + ObjectMapper mapper = new ObjectMapper(); - try { - ret = mapper.readValue(json, classObj); - } catch (JsonParseException e) { - e.printStackTrace(); - } catch (JsonMappingException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } + + ret = mapper.readValue(json, classObj); return ret; } @@ -60,7 +48,11 @@ public static void main(String [] args){ Map map= new HashMap<>(); map.put("name","xiaochouyu"); map.put("stak","小丑鱼"); - System.out.println(getJsonString(map)); + try { + System.out.println(getJsonString(map)); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } } } \ No newline at end of file From 032a965168f114600cc1103ea6e383442006a89d Mon Sep 17 00:00:00 2001 From: xiaour Date: Fri, 28 Apr 2017 14:22:03 +0800 Subject: [PATCH 12/23] =?UTF-8?q?=E9=83=A8=E5=88=86=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../main/java/com/xiaour/spring/boot/Application.java | 11 ++++++++++- .../java/com/xiaour/spring/boot/utils/JsonUtil.java | 2 -- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/Application.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/Application.java index f2832f8..d42d984 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/Application.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/Application.java @@ -12,8 +12,17 @@ import org.springframework.boot.web.support.SpringBootServletInitializer; /** - * Created by Administrator on 2017/4/19. + * + * Java Lib For OIS, Powered By BeiJing FanTongTianXia. + * Copyright (c) 2014-2017 FanTongTianXia Co.,Ltd + * http://www.chifaner.com/ + * + * @ClassName Application + * @author Zhang.Tao + * @Date 2017年4月27日 下午5:30:34 + * @version V2.0.0 */ + @SpringBootApplication(exclude = MybatisAutoConfiguration.class) @ServletComponentScan @EnableAutoConfiguration diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/JsonUtil.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/JsonUtil.java index 105aa95..f93b6bf 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/JsonUtil.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/JsonUtil.java @@ -11,8 +11,6 @@ public class JsonUtil { - - public static String getJsonString(Object javaObj) throws JsonProcessingException { String ret = "{}"; From 2832d2f9ff4d54a413f0bb13091831d8cf6290a1 Mon Sep 17 00:00:00 2001 From: xiaour Date: Wed, 3 May 2017 11:27:32 +0800 Subject: [PATCH 13/23] =?UTF-8?q?=E5=8E=BB=E6=8E=89=E4=BA=86=E4=B8=8D?= =?UTF-8?q?=E5=BF=85=E8=A6=81=E7=9A=84=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/xiaour/spring/boot/config/DataBaseConfiguration.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/DataBaseConfiguration.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/DataBaseConfiguration.java index ee7bca8..ab8d982 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/DataBaseConfiguration.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/DataBaseConfiguration.java @@ -23,14 +23,12 @@ public class DataBaseConfiguration implements EnvironmentAware { private static Logger log = LoggerFactory.getLogger(DataBaseConfiguration.class); - private Environment env; /** * 初始化yml配置 */ @Override public void setEnvironment(Environment env) { - this.env = env; this.propertyResolver = new RelaxedPropertyResolver(env, "jdbc.datasource."); } From 9306a8c5c9a6326b14979969f88778ccba7bc792 Mon Sep 17 00:00:00 2001 From: xiaour Date: Thu, 4 May 2017 17:49:33 +0800 Subject: [PATCH 14/23] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E9=92=89=E9=92=89?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- SpringBootDemo/pom.xml | 33 ++++++++++++++++++- .../spring/boot/controller/TestCtrl.java | 21 ++++++++++++ .../xiaour/spring/boot/filter/MyFilter.java | 2 +- 3 files changed, 54 insertions(+), 2 deletions(-) diff --git a/SpringBootDemo/pom.xml b/SpringBootDemo/pom.xml index 2137e11..e70f5ae 100644 --- a/SpringBootDemo/pom.xml +++ b/SpringBootDemo/pom.xml @@ -79,7 +79,38 @@ javax.servlet javax.servlet-api - + + + commons-codec + commons-codec + 1.10 + + + + com.alibaba + fastjson + 1.2.31 + + + + commons-io + commons-io + 2.5 + + + + org.apache.httpcomponents + httpclient + 4.5 + + + + org.apache.httpcomponents + httpmime + 4.5 + + + diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/controller/TestCtrl.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/controller/TestCtrl.java index bb16a3d..06de70c 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/controller/TestCtrl.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/controller/TestCtrl.java @@ -1,5 +1,8 @@ package com.xiaour.spring.boot.controller; +import java.util.HashMap; +import java.util.Map; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; @@ -9,6 +12,7 @@ import com.xiaour.spring.boot.mapper.UserInfoMapper; import com.xiaour.spring.boot.utils.JsonUtil; import com.xiaour.spring.boot.utils.RedisUtil; +import com.xiaour.spring.boot.utils.aes.AuthHelper; /** * Created by xiaour on 2017/4/19. @@ -71,4 +75,21 @@ public String get(@PathVariable("id")int id){ } return ""; } + + /** + * 获取数据库中的用户 + * @param id + * @return + */ + @RequestMapping("/getAccessToken") + public String getAccessToken(){ + try { + Map data= new HashMap<>(); + data.put("access_token", AuthHelper.getAccessToken()); + return JsonUtil.getJsonString(data); + } catch (Exception e) { + e.printStackTrace(); + } + return ""; + } } diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/filter/MyFilter.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/filter/MyFilter.java index b7a6d62..3b342b8 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/filter/MyFilter.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/filter/MyFilter.java @@ -47,7 +47,7 @@ public void init(FilterConfig filterConfig) throws ServletException { public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; - + System.err.println(request.getParameter("code")); filterChain.doFilter(request, response); } From 301a204060fc44e9004be6b0329faa698977ccee Mon Sep 17 00:00:00 2001 From: xiaour Date: Thu, 4 May 2017 17:50:09 +0800 Subject: [PATCH 15/23] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E9=92=89=E9=92=89?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../exception/DingTalkEncryptException.java | 53 ++++ .../spring/boot/exception/OApiException.java | 8 + .../boot/exception/OApiResultException.java | 11 + .../xiaour/spring/boot/utils/FileUtils.java | 136 ++++++++++ .../xiaour/spring/boot/utils/HttpHelper.java | 252 ++++++++++++++++++ .../spring/boot/utils/aes/AuthHelper.java | 218 +++++++++++++++ .../boot/utils/aes/DingTalkEncryptor.java | 217 +++++++++++++++ .../utils/aes/DingTalkJsApiSingnature.java | 62 +++++ .../com/xiaour/spring/boot/utils/aes/Env.java | 25 ++ .../spring/boot/utils/aes/PKCS7Padding.java | 50 ++++ .../xiaour/spring/boot/utils/aes/Utils.java | 52 ++++ .../xiaour/spring/boot/utils/aes/Vars.java | 10 + 12 files changed, 1094 insertions(+) create mode 100644 SpringBootDemo/src/main/java/com/xiaour/spring/boot/exception/DingTalkEncryptException.java create mode 100644 SpringBootDemo/src/main/java/com/xiaour/spring/boot/exception/OApiException.java create mode 100644 SpringBootDemo/src/main/java/com/xiaour/spring/boot/exception/OApiResultException.java create mode 100644 SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/FileUtils.java create mode 100644 SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/HttpHelper.java create mode 100644 SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/AuthHelper.java create mode 100644 SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/DingTalkEncryptor.java create mode 100644 SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/DingTalkJsApiSingnature.java create mode 100644 SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/Env.java create mode 100644 SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/PKCS7Padding.java create mode 100644 SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/Utils.java create mode 100644 SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/Vars.java diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/exception/DingTalkEncryptException.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/exception/DingTalkEncryptException.java new file mode 100644 index 0000000..f279b8e --- /dev/null +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/exception/DingTalkEncryptException.java @@ -0,0 +1,53 @@ +package com.xiaour.spring.boot.exception; + +import java.util.HashMap; +import java.util.Map; + +/** + * 钉钉开放平台加解密异常类 + */ +public class DingTalkEncryptException extends Exception { + /**成功**/ + public static final int SUCCESS = 0; + /**加密明文文本非法**/ + public final static int ENCRYPTION_PLAINTEXT_ILLEGAL = 900001; + /**加密时间戳参数非法**/ + public final static int ENCRYPTION_TIMESTAMP_ILLEGAL = 900002; + /**加密随机字符串参数非法**/ + public final static int ENCRYPTION_NONCE_ILLEGAL = 900003; + /**不合法的aeskey**/ + public final static int AES_KEY_ILLEGAL = 900004; + /**签名不匹配**/ + public final static int SIGNATURE_NOT_MATCH = 900005; + /**计算签名错误**/ + public final static int COMPUTE_SIGNATURE_ERROR = 900006; + /**计算加密文字错误**/ + public final static int COMPUTE_ENCRYPT_TEXT_ERROR = 900007; + /**计算解密文字错误**/ + public final static int COMPUTE_DECRYPT_TEXT_ERROR = 900008; + /**计算解密文字长度不匹配**/ + public final static int COMPUTE_DECRYPT_TEXT_LENGTH_ERROR = 900009; + /**计算解密文字corpid不匹配**/ + public final static int COMPUTE_DECRYPT_TEXT_CORPID_ERROR = 900010; + + private static Map msgMap = new HashMap(); + static{ + msgMap.put(SUCCESS,"成功"); + msgMap.put(ENCRYPTION_PLAINTEXT_ILLEGAL,"加密明文文本非法"); + msgMap.put(ENCRYPTION_TIMESTAMP_ILLEGAL,"加密时间戳参数非法"); + msgMap.put(ENCRYPTION_NONCE_ILLEGAL,"加密随机字符串参数非法"); + msgMap.put(SIGNATURE_NOT_MATCH,"签名不匹配"); + msgMap.put(COMPUTE_SIGNATURE_ERROR,"签名计算失败"); + msgMap.put(AES_KEY_ILLEGAL,"不合法的aes key"); + msgMap.put(COMPUTE_ENCRYPT_TEXT_ERROR,"计算加密文字错误"); + msgMap.put(COMPUTE_DECRYPT_TEXT_ERROR,"计算解密文字错误"); + msgMap.put(COMPUTE_DECRYPT_TEXT_LENGTH_ERROR,"计算解密文字长度不匹配"); + msgMap.put(COMPUTE_DECRYPT_TEXT_CORPID_ERROR,"计算解密文字corpid或者suiteKey不匹配"); + } + + public Integer code; + public DingTalkEncryptException(Integer exceptionCode){ + super(msgMap.get(exceptionCode)); + this.code = exceptionCode; + } +} diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/exception/OApiException.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/exception/OApiException.java new file mode 100644 index 0000000..0e7c1cb --- /dev/null +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/exception/OApiException.java @@ -0,0 +1,8 @@ +package com.xiaour.spring.boot.exception; + +public class OApiException extends Exception { + + public OApiException(int errCode, String errMsg) { + super("error code: " + errCode + ", error message: " + errMsg); + } +} diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/exception/OApiResultException.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/exception/OApiResultException.java new file mode 100644 index 0000000..b3c8d15 --- /dev/null +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/exception/OApiResultException.java @@ -0,0 +1,11 @@ +package com.xiaour.spring.boot.exception; + +public class OApiResultException extends OApiException { + + public static final int ERR_RESULT_RESOLUTION = -2; + + public OApiResultException(String field) { + super(ERR_RESULT_RESOLUTION, "Cannot resolve field " + field + " from oapi resonpse"); + } + +} diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/FileUtils.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/FileUtils.java new file mode 100644 index 0000000..9b177aa --- /dev/null +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/FileUtils.java @@ -0,0 +1,136 @@ +package com.xiaour.spring.boot.utils; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import org.apache.http.util.TextUtils; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +public class FileUtils { + public static final String FILEPATH = "Permanent_Data"; + + // json写入文件 + public synchronized static void write2File(Object json, String fileName) { + BufferedWriter writer = null; + File filePath = new File(FILEPATH); + JSONObject eJSON = null; + + if (!filePath.exists() && !filePath.isDirectory()) { + filePath.mkdirs(); + } + + File file = new File(FILEPATH + File.separator + fileName + ".xml"); + System.out.println("path:" + file.getPath() + " abs path:" + file.getAbsolutePath()); + if (!file.exists()) { + try { + file.createNewFile(); + } catch (Exception e) { + System.out.println("createNewFile,出现异常:"); + e.printStackTrace(); + } + } else { + eJSON = (JSONObject) read2JSON(fileName); + } + + try { + writer = new BufferedWriter(new FileWriter(file)); + + if (eJSON==null) { + writer.write(json.toString()); + } else { + Object[] array = ((JSONObject) json).keySet().toArray(); + for(int i=0;i values = JSON.parseObject(eJSON.toString(), Map.class); + return values.get(key); + } else { + return null; + } + } + public static HashMap toHashMap(JSONObject js) + { + if(js == null){ + return null; + } + HashMap data = new HashMap(); + // 将json字符串转换成jsonObject + Set set = js.keySet(); + // 遍历jsonObject数据,添加到Map对象 + Iterator it = set.iterator(); + while (it.hasNext()) + { + String key = String.valueOf(it.next()); + Long keyLong = Long.valueOf(key); + + String value = js.getString(key); + Long valueLong; + if(TextUtils.isEmpty(value)){ + valueLong = js.getLong(key); + }else{ + valueLong = Long.valueOf(value); + } + data.put(keyLong, valueLong); + } + return data; + } + + +} diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/HttpHelper.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/HttpHelper.java new file mode 100644 index 0000000..98dbda3 --- /dev/null +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/HttpHelper.java @@ -0,0 +1,252 @@ +package com.xiaour.spring.boot.utils; + +import java.io.File; +import java.io.IOException; +import java.net.URI; + +import org.apache.commons.io.FileUtils; +import org.apache.http.HttpEntity; +import org.apache.http.client.config.RequestConfig; +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.protocol.HttpClientContext; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.entity.mime.MultipartEntityBuilder; +import org.apache.http.entity.mime.content.FileBody; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.impl.client.RedirectLocations; +import org.apache.http.protocol.BasicHttpContext; +import org.apache.http.protocol.HttpContext; +import org.apache.http.util.EntityUtils; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.xiaour.spring.boot.exception.OApiException; + + +public class HttpHelper { + + public static JSONObject httpGet(String url) throws OApiException{ + HttpGet httpGet = new HttpGet(url); + CloseableHttpResponse response = null; + CloseableHttpClient httpClient = HttpClients.createDefault(); + RequestConfig requestConfig = RequestConfig.custom(). + setSocketTimeout(2000).setConnectTimeout(2000).build(); + httpGet.setConfig(requestConfig); + + try { + response = httpClient.execute(httpGet, new BasicHttpContext()); + + if (response.getStatusLine().getStatusCode() != 200) { + + System.out.println("request url failed, http code=" + response.getStatusLine().getStatusCode() + + ", url=" + url); + return null; + } + HttpEntity entity = response.getEntity(); + if (entity != null) { + String resultStr = EntityUtils.toString(entity, "utf-8"); + + JSONObject result = JSON.parseObject(resultStr); + if (result.getInteger("errcode") == 0) { +// result.remove("errcode"); +// result.remove("errmsg"); + return result; + } else { + System.out.println("request url=" + url + ",return value="); + System.out.println(resultStr); + int errCode = result.getInteger("errcode"); + String errMsg = result.getString("errmsg"); + throw new OApiException(errCode, errMsg); + } + } + } catch (IOException e) { + System.out.println("request url=" + url + ", exception, msg=" + e.getMessage()); + e.printStackTrace(); + } finally { + if (response != null) try { + response.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + return null; + } + + + public static JSONObject httpPost(String url, Object data) throws OApiException { + HttpPost httpPost = new HttpPost(url); + CloseableHttpResponse response = null; + CloseableHttpClient httpClient = HttpClients.createDefault(); + RequestConfig requestConfig = RequestConfig.custom(). + setSocketTimeout(2000).setConnectTimeout(2000).build(); + httpPost.setConfig(requestConfig); + httpPost.addHeader("Content-Type", "application/json"); + + try { + StringEntity requestEntity = new StringEntity(JSON.toJSONString(data), "utf-8"); + httpPost.setEntity(requestEntity); + + response = httpClient.execute(httpPost, new BasicHttpContext()); + + if (response.getStatusLine().getStatusCode() != 200) { + + System.out.println("request url failed, http code=" + response.getStatusLine().getStatusCode() + + ", url=" + url); + return null; + } + HttpEntity entity = response.getEntity(); + if (entity != null) { + String resultStr = EntityUtils.toString(entity, "utf-8"); + + JSONObject result = JSON.parseObject(resultStr); + if (result.getInteger("errcode") == 0) { + result.remove("errcode"); + result.remove("errmsg"); + return result; + } else { + System.out.println("request url=" + url + ",return value="); + System.out.println(resultStr); + int errCode = result.getInteger("errcode"); + String errMsg = result.getString("errmsg"); + throw new OApiException(errCode, errMsg); + } + } + } catch (IOException e) { + System.out.println("request url=" + url + ", exception, msg=" + e.getMessage()); + e.printStackTrace(); + } finally { + if (response != null) try { + response.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + return null; + } + + + public static JSONObject uploadMedia(String url, File file) throws OApiException { + HttpPost httpPost = new HttpPost(url); + CloseableHttpResponse response = null; + CloseableHttpClient httpClient = HttpClients.createDefault(); + RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build(); + httpPost.setConfig(requestConfig); + + HttpEntity requestEntity = MultipartEntityBuilder.create().addPart("media", + new FileBody(file, ContentType.APPLICATION_OCTET_STREAM, file.getName())).build(); + httpPost.setEntity(requestEntity); + + try { + response = httpClient.execute(httpPost, new BasicHttpContext()); + + if (response.getStatusLine().getStatusCode() != 200) { + + System.out.println("request url failed, http code=" + response.getStatusLine().getStatusCode() + + ", url=" + url); + return null; + } + HttpEntity entity = response.getEntity(); + if (entity != null) { + String resultStr = EntityUtils.toString(entity, "utf-8"); + + JSONObject result = JSON.parseObject(resultStr); + if (result.getInteger("errcode") == 0) { + // 成功 + result.remove("errcode"); + result.remove("errmsg"); + return result; + } else { + System.out.println("request url=" + url + ",return value="); + System.out.println(resultStr); + int errCode = result.getInteger("errcode"); + String errMsg = result.getString("errmsg"); + throw new OApiException(errCode, errMsg); + } + } + } catch (IOException e) { + System.out.println("request url=" + url + ", exception, msg=" + e.getMessage()); + e.printStackTrace(); + } finally { + if (response != null) try { + response.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + return null; + } + + + public static JSONObject downloadMedia(String url, String fileDir) throws OApiException { + HttpGet httpGet = new HttpGet(url); + CloseableHttpResponse response = null; + CloseableHttpClient httpClient = HttpClients.createDefault(); + RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build(); + httpGet.setConfig(requestConfig); + + try { + HttpContext localContext = new BasicHttpContext(); + + response = httpClient.execute(httpGet, localContext); + + RedirectLocations locations = (RedirectLocations) localContext.getAttribute(HttpClientContext.REDIRECT_LOCATIONS); + if (locations != null) { + URI downloadUrl = locations.getAll().get(0); + String filename = downloadUrl.toURL().getFile(); + System.out.println("downloadUrl=" + downloadUrl); + File downloadFile = new File(fileDir + File.separator + filename); + FileUtils.writeByteArrayToFile(downloadFile, EntityUtils.toByteArray(response.getEntity())); + JSONObject obj = new JSONObject(); + obj.put("downloadFilePath", downloadFile.getAbsolutePath()); + obj.put("httpcode", response.getStatusLine().getStatusCode()); + + + + return obj; + } else { + if (response.getStatusLine().getStatusCode() != 200) { + + System.out.println("request url failed, http code=" + response.getStatusLine().getStatusCode() + + ", url=" + url); + return null; + } + HttpEntity entity = response.getEntity(); + if (entity != null) { + String resultStr = EntityUtils.toString(entity, "utf-8"); + + JSONObject result = JSON.parseObject(resultStr); + if (result.getInteger("errcode") == 0) { + // 成功 + result.remove("errcode"); + result.remove("errmsg"); + return result; + } else { + System.out.println("request url=" + url + ",return value="); + System.out.println(resultStr); + int errCode = result.getInteger("errcode"); + String errMsg = result.getString("errmsg"); + throw new OApiException(errCode, errMsg); + } + } + } + } catch (IOException e) { + System.out.println("request url=" + url + ", exception, msg=" + e.getMessage()); + e.printStackTrace(); + } finally { + if (response != null) try { + response.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + return null; + } +} diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/AuthHelper.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/AuthHelper.java new file mode 100644 index 0000000..d1d415a --- /dev/null +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/AuthHelper.java @@ -0,0 +1,218 @@ +package com.xiaour.spring.boot.utils.aes; + +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.text.SimpleDateFormat; +import java.util.Formatter; +import java.util.Timer; + +import javax.servlet.http.HttpServletRequest; + +import com.alibaba.fastjson.JSONObject; +import com.dingtalk.open.client.ServiceFactory; +import com.dingtalk.open.client.api.model.corp.JsapiTicket; +import com.dingtalk.open.client.api.service.corp.CorpConnectionService; +import com.dingtalk.open.client.api.service.corp.JsapiService; +import com.dingtalk.open.client.common.SdkInitException; +import com.dingtalk.open.client.common.ServiceException; +import com.dingtalk.open.client.common.ServiceNotExistException; +import com.xiaour.spring.boot.exception.OApiException; +import com.xiaour.spring.boot.exception.OApiResultException; +import com.xiaour.spring.boot.utils.FileUtils; +import com.xiaour.spring.boot.utils.HttpHelper; + +public class AuthHelper { + + // public static String jsapiTicket = null; + // public static String accessToken = null; + public static Timer timer = null; + // 调整到1小时50分钟 + public static final long cacheTime = 1000 * 60 * 55 * 2; + public static long currentTime = 0 + cacheTime + 1; + public static long lastTime = 0; + public static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + + /* + * 在此方法中,为了避免频繁获取access_token, + * 在距离上一次获取access_token时间在两个小时之内的情况, + * 将直接从持久化存储中读取access_token + * + * 因为access_token和jsapi_ticket的过期时间都是7200秒 + * 所以在获取access_token的同时也去获取了jsapi_ticket + * 注:jsapi_ticket是在前端页面JSAPI做权限验证配置的时候需要使用的 + * 具体信息请查看开发者文档--权限验证配置 + */ + public static String getAccessToken() throws OApiException { + long curTime = System.currentTimeMillis(); + JSONObject accessTokenValue = (JSONObject) FileUtils.getValue("accesstoken", Env.CORP_ID); + String accToken = ""; + String jsTicket = ""; + JSONObject jsontemp = new JSONObject(); + if (accessTokenValue == null || curTime - accessTokenValue.getLong("begin_time") >= cacheTime) { + try + { + ServiceFactory serviceFactory = ServiceFactory.getInstance(); + CorpConnectionService corpConnectionService = serviceFactory.getOpenService(CorpConnectionService.class); + accToken = corpConnectionService.getCorpToken(Env.CORP_ID, Env.CORP_SECRET); + // save accessToken + JSONObject jsonAccess = new JSONObject(); + jsontemp.clear(); + jsontemp.put("access_token", accToken); + jsontemp.put("begin_time", curTime); + jsonAccess.put(Env.CORP_ID, jsontemp); + FileUtils.write2File(jsonAccess, "accesstoken"); + + if(accToken.length() > 0){ + + JsapiService jsapiService = serviceFactory.getOpenService(JsapiService.class); + + JsapiTicket JsapiTicket = jsapiService.getJsapiTicket(accToken, "jsapi"); + jsTicket = JsapiTicket.getTicket(); + JSONObject jsonTicket = new JSONObject(); + jsontemp.clear(); + jsontemp.put("ticket", jsTicket); + jsontemp.put("begin_time", curTime); + jsonTicket.put(Env.CORP_ID, jsontemp); + FileUtils.write2File(jsonTicket, "jsticket"); + } + } catch (SdkInitException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (ServiceException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (ServiceNotExistException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } else { + return accessTokenValue.getString("access_token"); + } + + return accToken; + } + + // 正常的情况下,jsapi_ticket的有效期为7200秒,所以开发者需要在某个地方设计一个定时器,定期去更新jsapi_ticket + public static String getJsapiTicket(String accessToken) throws OApiException { + JSONObject jsTicketValue = (JSONObject) FileUtils.getValue("jsticket", Env.CORP_ID); + long curTime = System.currentTimeMillis(); + String jsTicket = ""; + + if (jsTicketValue == null || curTime - + jsTicketValue.getLong("begin_time") >= cacheTime) { + ServiceFactory serviceFactory; + try { + serviceFactory = ServiceFactory.getInstance(); + JsapiService jsapiService = serviceFactory.getOpenService(JsapiService.class); + + JsapiTicket JsapiTicket = jsapiService.getJsapiTicket(accessToken, "jsapi"); + jsTicket = JsapiTicket.getTicket(); + + JSONObject jsonTicket = new JSONObject(); + JSONObject jsontemp = new JSONObject(); + jsontemp.clear(); + jsontemp.put("ticket", jsTicket); + jsontemp.put("begin_time", curTime); + jsonTicket.put(Env.CORP_ID, jsontemp); + FileUtils.write2File(jsonTicket, "jsticket"); + } catch (SdkInitException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (ServiceException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (ServiceNotExistException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return jsTicket; + } else { + return jsTicketValue.getString("ticket"); + } + } + + public static String sign(String ticket, String nonceStr, long timeStamp, String url) throws OApiException { + String plain = "jsapi_ticket=" + ticket + "&noncestr=" + nonceStr + "×tamp=" + String.valueOf(timeStamp) + + "&url=" + url; + try { + MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); + sha1.reset(); + sha1.update(plain.getBytes("UTF-8")); + return bytesToHex(sha1.digest()); + } catch (NoSuchAlgorithmException e) { + throw new OApiResultException(e.getMessage()); + } catch (UnsupportedEncodingException e) { + throw new OApiResultException(e.getMessage()); + } + } + + private static String bytesToHex(byte[] hash) { + Formatter formatter = new Formatter(); + for (byte b : hash) { + formatter.format("%02x", b); + } + String result = formatter.toString(); + formatter.close(); + return result; + } + + public static String getConfig(HttpServletRequest request) { + String urlString = request.getRequestURL().toString(); + String queryString = request.getQueryString(); + + String queryStringEncode = null; + String url; + if (queryString != null) { + try { + queryStringEncode = URLDecoder.decode(queryString,"UTF-8"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + url = urlString + "?" + queryStringEncode; + } else { + url = urlString; + } + + String nonceStr = "abcdefg"; + long timeStamp = System.currentTimeMillis() / 1000; + String signedUrl = url; + String accessToken = null; + String ticket = null; + String signature = null; + String agentid = null; + + try { + accessToken = AuthHelper.getAccessToken(); + + ticket = AuthHelper.getJsapiTicket(accessToken); + signature = AuthHelper.sign(ticket, nonceStr, timeStamp, signedUrl); + agentid = ""; + + } catch (OApiException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + String configValue = "{jsticket:'" + ticket + "',signature:'" + signature + "',nonceStr:'" + nonceStr + "',timeStamp:'" + + timeStamp + "',corpId:'" + Env.CORP_ID + "',agentid:'" + agentid+ "'}"; + System.out.println(configValue); + return configValue; + } + + + public static String getSsoToken() throws OApiException { + String url = "https://oapi.dingtalk.com/sso/gettoken?corpid=" + Env.CORP_ID + "&corpsecret=" + Env.SSO_Secret; + JSONObject response = HttpHelper.httpGet(url); + String ssoToken; + if (response.containsKey("access_token")) { + ssoToken = response.getString("access_token"); + } else { + throw new OApiResultException("Sso_token"); + } + return ssoToken; + + } + +} diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/DingTalkEncryptor.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/DingTalkEncryptor.java new file mode 100644 index 0000000..767cd6f --- /dev/null +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/DingTalkEncryptor.java @@ -0,0 +1,217 @@ +package com.xiaour.spring.boot.utils.aes; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.Charset; +import java.security.MessageDigest; +import java.util.*; + +import javax.crypto.Cipher; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; + +import org.apache.commons.codec.binary.Base64; + +import com.xiaour.spring.boot.exception.DingTalkEncryptException; + + +/** + * 钉钉开放平台加解密方法 + * 在ORACLE官方网站下载JCE无限制权限策略文件 + * JDK6的下载地址:http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html + * JDK7的下载地址: http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html + */ +public class DingTalkEncryptor { + + private static final Charset CHARSET = Charset.forName("utf-8"); + private static final Base64 base64 = new Base64(); + private byte[] aesKey; + private String token; + private String corpId; + /**ask getPaddingBytes key固定长度**/ + private static final Integer AES_ENCODE_KEY_LENGTH = 43; + /**加密随机字符串字节长度**/ + private static final Integer RANDOM_LENGTH = 16; + + /** + * 构造函数 + * @param token 钉钉开放平台上,开发者设置的token + * @param encodingAesKey 钉钉开放台上,开发者设置的EncodingAESKey + * @param corpId ISV进行配置的时候应该传对应套件的SUITE_KEY,普通企业是Corpid + * @throws DingTalkEncryptException 执行失败,请查看该异常的错误码和具体的错误信息 + */ + public DingTalkEncryptor(String token, String encodingAesKey, String corpId) throws DingTalkEncryptException{ + if (null==encodingAesKey || encodingAesKey.length() != AES_ENCODE_KEY_LENGTH) { + throw new DingTalkEncryptException(DingTalkEncryptException.AES_KEY_ILLEGAL); + } + this.token = token; + this.corpId = corpId; + aesKey = Base64.decodeBase64(encodingAesKey + "="); + } + + /** + * 将和钉钉开放平台同步的消息体加密,返回加密Map + * @param plaintext 传递的消息体明文 + * @param timeStamp 时间戳 + * @param nonce 随机字符串 + * @return + * @throws DingTalkEncryptException + */ + public Map getEncryptedMap(String plaintext, Long timeStamp, String nonce) throws DingTalkEncryptException { + if(null==plaintext){ + throw new DingTalkEncryptException(DingTalkEncryptException.ENCRYPTION_PLAINTEXT_ILLEGAL); + } + if(null==timeStamp){ + throw new DingTalkEncryptException(DingTalkEncryptException.ENCRYPTION_TIMESTAMP_ILLEGAL); + } + if(null==nonce){ + throw new DingTalkEncryptException(DingTalkEncryptException.ENCRYPTION_NONCE_ILLEGAL); + } + // 加密 + String encrypt = encrypt(Utils.getRandomStr(RANDOM_LENGTH), plaintext); + String signature = getSignature(token, String.valueOf(timeStamp), nonce, encrypt); + Map resultMap = new HashMap(); + resultMap.put("msg_signature", signature); + resultMap.put("encrypt", encrypt); + resultMap.put("timeStamp", String.valueOf(timeStamp)); + resultMap.put("nonce", nonce); + return resultMap; + } + + /** + * 密文解密 + * @param msgSignature 签名串 + * @param timeStamp 时间戳 + * @param nonce 随机串 + * @param encryptMsg 密文 + * @return 解密后的原文 + * @throws DingTalkEncryptException + */ + public String getDecryptMsg(String msgSignature, String timeStamp, String nonce, String encryptMsg)throws DingTalkEncryptException { + //校验签名 + String signature = getSignature(token, timeStamp, nonce, encryptMsg); + if (!signature.equals(msgSignature)) { + throw new DingTalkEncryptException(DingTalkEncryptException.COMPUTE_SIGNATURE_ERROR); + } + // 解密 + String result = decrypt(encryptMsg); + return result; + } + + + /* + * 对明文加密. + * @param text 需要加密的明文 + * @return 加密后base64编码的字符串 + */ + private String encrypt(String random, String plaintext) throws DingTalkEncryptException { + try { + byte[] randomBytes = random.getBytes(CHARSET); + byte[] plainTextBytes = plaintext.getBytes(CHARSET); + byte[] lengthByte = Utils.int2Bytes(plainTextBytes.length); + byte[] corpidBytes = corpId.getBytes(CHARSET); + ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); + byteStream.write(randomBytes); + byteStream.write(lengthByte); + byteStream.write(plainTextBytes); + byteStream.write(corpidBytes); + byte[] padBytes = PKCS7Padding.getPaddingBytes(byteStream.size()); + byteStream.write(padBytes); + byte[] unencrypted = byteStream.toByteArray(); + byteStream.close(); + Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); + SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES"); + IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16); + cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv); + byte[] encrypted = cipher.doFinal(unencrypted); + String result = base64.encodeToString(encrypted); + return result; + } catch (Exception e) { + throw new DingTalkEncryptException(DingTalkEncryptException.COMPUTE_ENCRYPT_TEXT_ERROR); + } + } + + /* + * 对密文进行解密. + * @param text 需要解密的密文 + * @return 解密得到的明文 + */ + private String decrypt(String text) throws DingTalkEncryptException { + byte[] originalArr; + try { + // 设置解密模式为AES的CBC模式 + Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); + SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES"); + IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(aesKey, 0, 16)); + cipher.init(Cipher.DECRYPT_MODE, keySpec, iv); + // 使用BASE64对密文进行解码 + byte[] encrypted = Base64.decodeBase64(text); + // 解密 + originalArr = cipher.doFinal(encrypted); + } catch (Exception e) { + throw new DingTalkEncryptException(DingTalkEncryptException.COMPUTE_DECRYPT_TEXT_ERROR); + } + + String plainText; + String fromCorpid; + try { + // 去除补位字符 + byte[] bytes = PKCS7Padding.removePaddingBytes(originalArr); + // 分离16位随机字符串,网络字节序和corpId + byte[] networkOrder = Arrays.copyOfRange(bytes, 16, 20); + int plainTextLegth = Utils.bytes2int(networkOrder); + plainText = new String(Arrays.copyOfRange(bytes, 20, 20 + plainTextLegth), CHARSET); + fromCorpid = new String(Arrays.copyOfRange(bytes, 20 + plainTextLegth, bytes.length), CHARSET); + } catch (Exception e) { + throw new DingTalkEncryptException(DingTalkEncryptException.COMPUTE_DECRYPT_TEXT_LENGTH_ERROR); + } + + // corpid不相同的情况 + if (!fromCorpid.equals(corpId)) { + throw new DingTalkEncryptException(DingTalkEncryptException.COMPUTE_DECRYPT_TEXT_CORPID_ERROR); + } + return plainText; + } + + /** + * 数字签名 + * @param token isv token + * @param timestamp 时间戳 + * @param nonce 随机串 + * @param encrypt 加密文本 + * @return + * @throws DingTalkEncryptException + */ + public String getSignature(String token, String timestamp, String nonce, String encrypt) throws DingTalkEncryptException { + try { + String[] array = new String[] { token, timestamp, nonce, encrypt }; + Arrays.sort(array); + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < 4; i++) { + sb.append(array[i]); + } + String str = sb.toString(); + MessageDigest md = MessageDigest.getInstance("SHA-1"); + md.update(str.getBytes()); + byte[] digest = md.digest(); + + StringBuffer hexstr = new StringBuffer(); + String shaHex = ""; + for (int i = 0; i < digest.length; i++) { + shaHex = Integer.toHexString(digest[i] & 0xFF); + if (shaHex.length() < 2) { + hexstr.append(0); + } + hexstr.append(shaHex); + } + return hexstr.toString(); + } catch (Exception e) { + throw new DingTalkEncryptException(DingTalkEncryptException.COMPUTE_SIGNATURE_ERROR); + } + } + + + + + + +} diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/DingTalkJsApiSingnature.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/DingTalkJsApiSingnature.java new file mode 100644 index 0000000..82f049d --- /dev/null +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/DingTalkJsApiSingnature.java @@ -0,0 +1,62 @@ +package com.xiaour.spring.boot.utils.aes; + +import java.io.UnsupportedEncodingException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Formatter; +import java.util.HashMap; +import java.util.Map; + +import com.xiaour.spring.boot.exception.DingTalkEncryptException; + +/** + * 钉钉jsapi签名工具类 + */ +public class DingTalkJsApiSingnature { + /** + * 获取jsapi签名 + * @param url + * @param nonce + * @param timeStamp + * @param jsTicket + * @return + * @throws DingTalkEncryptException + */ + public static String getJsApiSingnature(String url,String nonce,Long timeStamp,String jsTicket) throws DingTalkEncryptException{ + String plainTex = "jsapi_ticket=" + jsTicket +"&noncestr=" + nonce +"×tamp=" + timeStamp + "&url=" + url; + System.out.println(plainTex); + String signature = ""; + try{ + MessageDigest crypt = MessageDigest.getInstance("SHA-1"); + crypt.reset(); + crypt.update(plainTex.getBytes("UTF-8")); + signature = byteToHex(crypt.digest()); + return signature; + }catch (Exception e){ + throw new DingTalkEncryptException(DingTalkEncryptException.COMPUTE_SIGNATURE_ERROR); + } + } + + private static String byteToHex(final byte[] hash) { + Formatter formatter = new Formatter(); + for (byte b : hash){ + formatter.format("%02x", b); + } + String result = formatter.toString(); + formatter.close(); + return result; + } + + + public static void main(String args[]) throws Exception{ + + + + // signature:810e6657e9f411e6491b3e97dfaf7660e89eb874,serverSign:0e781e79966d6f27e2b6456b83d5cee0ebaeb81b + String url="http://10.62.53.138:3000/jsapi"; + String nonce="abcdefgh"; + Long timeStamp = 1437027269927L; + String tikcet="zHoQdGJuH0ZDebwo7sLqLzHGUueLmkWCC4RycYgkuvDu3eoROgN5qhwnQLgfzwEXtuR9SDzh6BdhyVngzAjrxV"; + System.err.println(getJsApiSingnature(url,nonce,timeStamp,tikcet)); + } +} diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/Env.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/Env.java new file mode 100644 index 0000000..378b8d6 --- /dev/null +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/Env.java @@ -0,0 +1,25 @@ +package com.xiaour.spring.boot.utils.aes; + + + +public class Env { + + public static final String OAPI_HOST = "https://oapi.dingtalk.com"; + public static final String OA_BACKGROUND_URL = ""; + public static final String CORP_ID = ""; + + public static final String CORP_SECRET = "ding103b3ec2abc362c135c2f4657eb6378f"; + public static final String SSO_Secret = "7d6IsFc_Vs1VmY2YFvOKRtBth7f8N-EFKtEswWDlEBN6g5NfWwJ7InLW5OoeJFCV"; + + + public static String suiteTicket; + public static String authCode; + public static String suiteToken; + + public static final String CREATE_SUITE_KEY = "suite4xxxxxxxxxxxxxxx"; + public static final String SUITE_KEY = ""; + public static final String SUITE_SECRET = ""; + public static final String TOKEN = ""; + public static final String ENCODING_AES_KEY = ""; + +} diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/PKCS7Padding.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/PKCS7Padding.java new file mode 100644 index 0000000..a32656c --- /dev/null +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/PKCS7Padding.java @@ -0,0 +1,50 @@ +package com.xiaour.spring.boot.utils.aes; + +import java.nio.charset.Charset; +import java.util.Arrays; + +/* + * PKCS7算法的加密填充 + */ + +public class PKCS7Padding { + private final static Charset CHARSET = Charset.forName("utf-8"); + private final static int BLOCK_SIZE = 32; + + /** + * 填充mode字节 + * @param count + * @return + */ + public static byte[] getPaddingBytes(int count) { + int amountToPad = BLOCK_SIZE - (count % BLOCK_SIZE); + if (amountToPad == 0) { + amountToPad = BLOCK_SIZE; + } + char padChr = chr(amountToPad); + String tmp = new String(); + for (int index = 0; index < amountToPad; index++) { + tmp += padChr; + } + return tmp.getBytes(CHARSET); + } + + /** + * 移除mode填充字节 + * @param decrypted + * @return + */ + public static byte[] removePaddingBytes(byte[] decrypted) { + int pad = (int) decrypted[decrypted.length - 1]; + if (pad < 1 || pad > BLOCK_SIZE) { + pad = 0; + } + return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad); + } + + private static char chr(int a) { + byte target = (byte) (a & 0xFF); + return (char) target; + } + +} diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/Utils.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/Utils.java new file mode 100644 index 0000000..e47a10c --- /dev/null +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/Utils.java @@ -0,0 +1,52 @@ +package com.xiaour.spring.boot.utils.aes; + +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.Random; + +/** + * 加解密工具类 + */ +public class Utils { + /** + * + * @return + */ + public static String getRandomStr(int count) { + String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + Random random = new Random(); + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < count; i++) { + int number = random.nextInt(base.length()); + sb.append(base.charAt(number)); + } + return sb.toString(); + } + + + /* + * int转byte数组,高位在前 + */ + public static byte[] int2Bytes(int count) { + byte[] byteArr = new byte[4]; + byteArr[3] = (byte) (count & 0xFF); + byteArr[2] = (byte) (count >> 8 & 0xFF); + byteArr[1] = (byte) (count >> 16 & 0xFF); + byteArr[0] = (byte) (count >> 24 & 0xFF); + return byteArr; + } + + /** + * 高位在前bytes数组转int + * @param byteArr + * @return + */ + public static int bytes2int(byte[] byteArr) { + int count = 0; + for (int i = 0; i < 4; i++) { + count <<= 8; + count |= byteArr[i] & 0xff; + } + return count; + } +} diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/Vars.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/Vars.java new file mode 100644 index 0000000..b186519 --- /dev/null +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/Vars.java @@ -0,0 +1,10 @@ +package com.xiaour.spring.boot.utils.aes; + +public class Vars { + + public static String TO_USER = ""; + public static String TO_PARTY = ""; + public static String AGENT_ID = ""; + public static String SENDER = ""; + public static String CID = "";//cid需要通过jsapi获取,具体详情请查看开放平台文档--->客户端文档--->会话 +} From ee89867dce370d6cc2c4cf3c0f742412b012bc7b Mon Sep 17 00:00:00 2001 From: xiaour Date: Fri, 5 May 2017 09:31:30 +0800 Subject: [PATCH 16/23] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BA=86=E9=92=89?= =?UTF-8?q?=E9=92=89=E6=8E=A5=E5=8F=A3=E7=9A=84=E4=B8=9C=E8=A5=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../spring/boot/controller/TestCtrl.java | 29 +++++++++++++ .../xiaour/spring/boot/filter/MyFilter.java | 2 +- .../spring/boot/utils/aes/AuthHelper.java | 42 +++++++++++++++---- .../utils/aes/DingTalkJsApiSingnature.java | 4 -- .../com/xiaour/spring/boot/utils/aes/Env.java | 4 +- .../xiaour/spring/boot/utils/aes/Utils.java | 2 - 6 files changed, 67 insertions(+), 16 deletions(-) diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/controller/TestCtrl.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/controller/TestCtrl.java index 06de70c..41ca1e4 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/controller/TestCtrl.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/controller/TestCtrl.java @@ -3,6 +3,8 @@ import java.util.HashMap; import java.util.Map; +import javax.servlet.http.HttpServletRequest; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; @@ -92,4 +94,31 @@ public String getAccessToken(){ } return ""; } + + /** + * 获取数据库中的用户 + * @param id + * @return + */ + @RequestMapping("/ding") + public String ding(HttpServletRequest request){ + try { + return AuthHelper.getConfig(request); + } catch (Exception e) { + e.printStackTrace(); + } + return ""; + } + + @RequestMapping("/userinfo") + public String userinfo(String code){ + try { + String jsonStr=AuthHelper.getUserinfo(code); + System.err.println(jsonStr); + return jsonStr; + } catch (Exception e) { + e.printStackTrace(); + } + return ""; + } } diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/filter/MyFilter.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/filter/MyFilter.java index 3b342b8..d588f50 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/filter/MyFilter.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/filter/MyFilter.java @@ -46,8 +46,8 @@ public void init(FilterConfig filterConfig) throws ServletException { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; + System.out.println(request.getRequestURI()); HttpServletResponse response = (HttpServletResponse) servletResponse; - System.err.println(request.getParameter("code")); filterChain.doFilter(request, response); } diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/AuthHelper.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/AuthHelper.java index d1d415a..ae0c2ee 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/AuthHelper.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/AuthHelper.java @@ -6,6 +6,8 @@ import java.security.NoSuchAlgorithmException; import java.text.SimpleDateFormat; import java.util.Formatter; +import java.util.HashMap; +import java.util.Map; import java.util.Timer; import javax.servlet.http.HttpServletRequest; @@ -18,10 +20,12 @@ import com.dingtalk.open.client.common.SdkInitException; import com.dingtalk.open.client.common.ServiceException; import com.dingtalk.open.client.common.ServiceNotExistException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.xiaour.spring.boot.exception.OApiException; import com.xiaour.spring.boot.exception.OApiResultException; import com.xiaour.spring.boot.utils.FileUtils; import com.xiaour.spring.boot.utils.HttpHelper; +import com.xiaour.spring.boot.utils.JsonUtil; public class AuthHelper { @@ -162,10 +166,11 @@ private static String bytesToHex(byte[] hash) { public static String getConfig(HttpServletRequest request) { String urlString = request.getRequestURL().toString(); String queryString = request.getQueryString(); + String agentId=request.getParameter("agentId"); String queryStringEncode = null; String url; - if (queryString != null) { +/* if (queryString != null) { try { queryStringEncode = URLDecoder.decode(queryString,"UTF-8"); } catch (UnsupportedEncodingException e) { @@ -174,30 +179,43 @@ public static String getConfig(HttpServletRequest request) { url = urlString + "?" + queryStringEncode; } else { url = urlString; - } + }*/ String nonceStr = "abcdefg"; long timeStamp = System.currentTimeMillis() / 1000; - String signedUrl = url; + String signedUrl = urlString; String accessToken = null; String ticket = null; String signature = null; - String agentid = null; try { accessToken = AuthHelper.getAccessToken(); ticket = AuthHelper.getJsapiTicket(accessToken); signature = AuthHelper.sign(ticket, nonceStr, timeStamp, signedUrl); - agentid = ""; } catch (OApiException e) { - // TODO Auto-generated catch block e.printStackTrace(); } + + Map data= new HashMap<>(); + + data.put("jsticket", ticket); + data.put("signature", signature); + data.put("nonceStr", nonceStr); + data.put("timeStamp", timeStamp); + data.put("corpId", Env.CORP_ID); + data.put("agentid",agentId); + String configValue = "{jsticket:'" + ticket + "',signature:'" + signature + "',nonceStr:'" + nonceStr + "',timeStamp:'" - + timeStamp + "',corpId:'" + Env.CORP_ID + "',agentid:'" + agentid+ "'}"; + + timeStamp + "',corpId:'" + Env.CORP_ID + "',agentid:'" + agentId+ "'}"; + System.out.println(configValue); + try { + return JsonUtil.getJsonString(data); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } return configValue; } @@ -214,5 +232,15 @@ public static String getSsoToken() throws OApiException { return ssoToken; } + + public static String getUserinfo(String code) throws OApiException { + String url = "https://oapi.dingtalk.com/user/getuserinfo?access_token="+getAccessToken()+"&code="+code; + JSONObject response = HttpHelper.httpGet(url); + String json= response.toJSONString(); + return json; + + } + + } diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/DingTalkJsApiSingnature.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/DingTalkJsApiSingnature.java index 82f049d..3b9e387 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/DingTalkJsApiSingnature.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/DingTalkJsApiSingnature.java @@ -1,11 +1,7 @@ package com.xiaour.spring.boot.utils.aes; -import java.io.UnsupportedEncodingException; import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.util.Formatter; -import java.util.HashMap; -import java.util.Map; import com.xiaour.spring.boot.exception.DingTalkEncryptException; diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/Env.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/Env.java index 378b8d6..ad57aee 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/Env.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/Env.java @@ -6,9 +6,9 @@ public class Env { public static final String OAPI_HOST = "https://oapi.dingtalk.com"; public static final String OA_BACKGROUND_URL = ""; - public static final String CORP_ID = ""; + public static final String CORP_ID = "ding103b3ec2abc362c135c2f4657eb6378f"; - public static final String CORP_SECRET = "ding103b3ec2abc362c135c2f4657eb6378f"; + public static final String CORP_SECRET = "2wZtuw6dbf4o8KY8qEY1CrRUmMn78s51jNz0PXxBm9ylVZ3Mju56BZZKeiUEnvan"; public static final String SSO_Secret = "7d6IsFc_Vs1VmY2YFvOKRtBth7f8N-EFKtEswWDlEBN6g5NfWwJ7InLW5OoeJFCV"; diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/Utils.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/Utils.java index e47a10c..6208dad 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/Utils.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/Utils.java @@ -1,7 +1,5 @@ package com.xiaour.spring.boot.utils.aes; -import java.security.MessageDigest; -import java.util.Arrays; import java.util.Random; /** From b40058607c01aadf75f15b9644fa392dd076646f Mon Sep 17 00:00:00 2001 From: xiaour Date: Fri, 5 May 2017 15:35:42 +0800 Subject: [PATCH 17/23] =?UTF-8?q?=E9=92=89=E9=92=89=E8=8E=B7=E5=8F=96?= =?UTF-8?q?=E6=99=AE=E9=80=9A=E7=94=A8=E6=88=B7=E7=99=BB=E5=BD=95=E4=BF=A1?= =?UTF-8?q?=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- SpringBootDemo/pom.xml | 2 - .../spring/boot/controller/TestCtrl.java | 12 +++++ .../xiaour/spring/boot/utils/HttpHelper.java | 1 - .../spring/boot/utils/aes/AuthHelper.java | 51 +++++++++++++++++++ .../com/xiaour/spring/boot/utils/aes/Env.java | 6 +++ 5 files changed, 69 insertions(+), 3 deletions(-) diff --git a/SpringBootDemo/pom.xml b/SpringBootDemo/pom.xml index e70f5ae..8f9d6ee 100644 --- a/SpringBootDemo/pom.xml +++ b/SpringBootDemo/pom.xml @@ -101,13 +101,11 @@ org.apache.httpcomponents httpclient - 4.5 org.apache.httpcomponents httpmime - 4.5 diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/controller/TestCtrl.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/controller/TestCtrl.java index 41ca1e4..eedbd14 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/controller/TestCtrl.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/controller/TestCtrl.java @@ -121,4 +121,16 @@ public String userinfo(String code){ } return ""; } + + @RequestMapping("/snsUser") + public String snsUser(String code){ + try { + String jsonStr=AuthHelper.snsTokenUser(code); + System.err.println(jsonStr); + return jsonStr; + } catch (Exception e) { + e.printStackTrace(); + } + return ""; + } } diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/HttpHelper.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/HttpHelper.java index 98dbda3..f366645 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/HttpHelper.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/HttpHelper.java @@ -86,7 +86,6 @@ public static JSONObject httpPost(String url, Object data) throws OApiException setSocketTimeout(2000).setConnectTimeout(2000).build(); httpPost.setConfig(requestConfig); httpPost.addHeader("Content-Type", "application/json"); - try { StringEntity requestEntity = new StringEntity(JSON.toJSONString(data), "utf-8"); httpPost.setEntity(requestEntity); diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/AuthHelper.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/AuthHelper.java index ae0c2ee..51acc9b 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/AuthHelper.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/AuthHelper.java @@ -233,6 +233,57 @@ public static String getSsoToken() throws OApiException { } + + public static String snsTokenUser(String userCode) throws OApiException { + String accessToken; + String url = "https://oapi.dingtalk.com/sns/gettoken?appid="+Env.SNS_APP_ID+"&appsecret="+Env.SNS_APP_SECRET; + JSONObject response = HttpHelper.httpGet(url); + + if (response.containsKey("access_token")) { + accessToken = response.getString("access_token"); + JSONObject json1=getPersistentCode(accessToken,userCode); + + JSONObject json2=getSnsToken(accessToken,json1.getString("openid"),json1.getString("persistent_code")); + + String userInfo=getSnsUserinfo(json2.getString("sns_token")); + return userInfo; + } else { + throw new OApiResultException("Sso_token"); + } + + } + + + private static JSONObject getPersistentCode(String accessToken,String userCode) throws OApiException{ + String snsUrl = "https://oapi.dingtalk.com/sns/get_persistent_code?access_token="+accessToken; + + JSONObject data=new JSONObject(); + data.put("tmp_auth_code", userCode); + //String jsonStr="{\"tmp_auth_code\": \""+userCode+"\"}"; + JSONObject snsResult = HttpHelper.httpPost(snsUrl, data); + return snsResult; + } + + private static JSONObject getSnsToken(String accessToken,String openid,String persistentCode) throws OApiException{ + String snsUrl = "https://oapi.dingtalk.com/sns/get_sns_token?access_token="+accessToken; + JSONObject data=new JSONObject(); + data.put("openid", openid); + data.put("persistent_code", persistentCode); + + //String jsonStr="{\"openid\": \""+openid+"\",\"persistent_code\": \""+persistentCode+"\"}"; + JSONObject snsResult = HttpHelper.httpPost(snsUrl, data); + return snsResult; + } + + private static String getSnsUserinfo(String snsToken) throws OApiException{ + String snsUrl = "https://oapi.dingtalk.com/sns/getuserinfo?sns_token="+snsToken; + JSONObject snsResult = HttpHelper.httpGet(snsUrl); + return snsResult.toJSONString(); + } + + + + public static String getUserinfo(String code) throws OApiException { String url = "https://oapi.dingtalk.com/user/getuserinfo?access_token="+getAccessToken()+"&code="+code; JSONObject response = HttpHelper.httpGet(url); diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/Env.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/Env.java index ad57aee..9e189c7 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/Env.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/aes/Env.java @@ -22,4 +22,10 @@ public class Env { public static final String TOKEN = ""; public static final String ENCODING_AES_KEY = ""; + + + public static final String SNS_APP_ID = "dingoates0filrnnxqbetd"; + public static final String SNS_APP_SECRET = "KQgORLyXYMcnfE1C6iXVSv1epdfiH_xiWARV6lApPgcAFOTr1SLzAFpr3ErBkpBQ"; + + } From 9d4199d6c87a4b0dc4d26a33c9c8e790e2ff078d Mon Sep 17 00:00:00 2001 From: "tony.zhang" Date: Tue, 9 May 2017 16:35:08 +0800 Subject: [PATCH 18/23] Create README --- README | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 README diff --git a/README b/README new file mode 100644 index 0000000..cc99905 --- /dev/null +++ b/README @@ -0,0 +1,2 @@ +# SpringBootDemo +SpringBoot+MyBatis+Redis+MySql From fb273791c89829c475764ca0ecf7a1c269c1710e Mon Sep 17 00:00:00 2001 From: "tony.zhang" Date: Wed, 16 Aug 2017 10:53:07 +0800 Subject: [PATCH 19/23] Update Application.java --- .../src/main/java/com/xiaour/spring/boot/Application.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/Application.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/Application.java index d42d984..db70642 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/Application.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/Application.java @@ -13,10 +13,6 @@ /** * - * Java Lib For OIS, Powered By BeiJing FanTongTianXia. - * Copyright (c) 2014-2017 FanTongTianXia Co.,Ltd - * http://www.chifaner.com/ - * * @ClassName Application * @author Zhang.Tao * @Date 2017年4月27日 下午5:30:34 From 243f51de4346fc7da9d3647b458ad6156e1f5aaa Mon Sep 17 00:00:00 2001 From: "tony.zhang" Date: Wed, 16 Aug 2017 10:54:20 +0800 Subject: [PATCH 20/23] Update MybatisConfiguration.java --- .../com/xiaour/spring/boot/config/MybatisConfiguration.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/MybatisConfiguration.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/MybatisConfiguration.java index af59d1f..fee3549 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/MybatisConfiguration.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/MybatisConfiguration.java @@ -23,8 +23,6 @@ /** * 初始化SqlSessionFactory - * Java Lib For OIS, Powered By xiaour. - * * @ClassName MybatisConfiguration * @author Zhang.Tao * @Date 2017年4月24日 下午5:24:56 From 7440b67d8c97e1efb68001038f787159ee443cb7 Mon Sep 17 00:00:00 2001 From: "tony.zhang" Date: Tue, 17 Oct 2017 15:01:21 +0800 Subject: [PATCH 21/23] Update application.yml --- SpringBootDemo/src/main/resources/application.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/SpringBootDemo/src/main/resources/application.yml b/SpringBootDemo/src/main/resources/application.yml index ba005eb..b5add87 100644 --- a/SpringBootDemo/src/main/resources/application.yml +++ b/SpringBootDemo/src/main/resources/application.yml @@ -16,7 +16,7 @@ server : jdbc: datasource: name: test - url: jdbc:mysql://192.168.2.5:3335/fantong_tm + url: jdbc:mysql://192.168.2.5:3335/springboot username: root password: chifaner159 # 使用druid数据源 @@ -51,4 +51,4 @@ logging: task: cron:0 0/1 * * * ? - \ No newline at end of file + From 4d6eb932fdc2026a0bdf1411a4bbd61077d32d3c Mon Sep 17 00:00:00 2001 From: xiaour Date: Tue, 17 Oct 2017 15:45:41 +0800 Subject: [PATCH 22/23] =?UTF-8?q?=E5=8F=96=E6=8E=89=E4=BA=86=E4=B8=8D?= =?UTF-8?q?=E5=BF=85=E8=A6=81=E7=9A=84=E6=95=B0=E6=8D=AE=E5=BA=93=E4=B8=8E?= =?UTF-8?q?MyBatis=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- SpringBootDemo/pom.xml | 3 +- .../spring/boot/controller/TestCtrl.java | 62 +------ .../xiaour/spring/boot/entity/UserInfo.java | 131 +++----------- .../spring/boot/mapper/UserInfoMapper.java | 12 +- .../spring/boot/mapper/UserInfoMapper.xml | 164 +----------------- .../src/main/resources/application.yml | 12 +- 6 files changed, 38 insertions(+), 346 deletions(-) diff --git a/SpringBootDemo/pom.xml b/SpringBootDemo/pom.xml index 8f9d6ee..1c831f9 100644 --- a/SpringBootDemo/pom.xml +++ b/SpringBootDemo/pom.xml @@ -83,8 +83,7 @@ commons-codec commons-codec - 1.10 - + com.alibaba diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/controller/TestCtrl.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/controller/TestCtrl.java index eedbd14..8526e54 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/controller/TestCtrl.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/controller/TestCtrl.java @@ -1,9 +1,5 @@ package com.xiaour.spring.boot.controller; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; @@ -14,7 +10,7 @@ import com.xiaour.spring.boot.mapper.UserInfoMapper; import com.xiaour.spring.boot.utils.JsonUtil; import com.xiaour.spring.boot.utils.RedisUtil; -import com.xiaour.spring.boot.utils.aes.AuthHelper; + /** * Created by xiaour on 2017/4/19. @@ -78,59 +74,5 @@ public String get(@PathVariable("id")int id){ return ""; } - /** - * 获取数据库中的用户 - * @param id - * @return - */ - @RequestMapping("/getAccessToken") - public String getAccessToken(){ - try { - Map data= new HashMap<>(); - data.put("access_token", AuthHelper.getAccessToken()); - return JsonUtil.getJsonString(data); - } catch (Exception e) { - e.printStackTrace(); - } - return ""; - } - - /** - * 获取数据库中的用户 - * @param id - * @return - */ - @RequestMapping("/ding") - public String ding(HttpServletRequest request){ - try { - return AuthHelper.getConfig(request); - } catch (Exception e) { - e.printStackTrace(); - } - return ""; - } - - @RequestMapping("/userinfo") - public String userinfo(String code){ - try { - String jsonStr=AuthHelper.getUserinfo(code); - System.err.println(jsonStr); - return jsonStr; - } catch (Exception e) { - e.printStackTrace(); - } - return ""; - } - - @RequestMapping("/snsUser") - public String snsUser(String code){ - try { - String jsonStr=AuthHelper.snsTokenUser(code); - System.err.println(jsonStr); - return jsonStr; - } catch (Exception e) { - e.printStackTrace(); - } - return ""; - } + } diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/entity/UserInfo.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/entity/UserInfo.java index 61f6104..2a41cb4 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/entity/UserInfo.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/entity/UserInfo.java @@ -3,123 +3,34 @@ import java.util.Date; public class UserInfo { - private Integer oid; + private Integer id; - private String userId; + private String name; - private String userName; + private String age; - private String password; + public Integer getId() { + return id; + } - private String region; + public void setId(Integer id) { + this.id = id; + } - private Integer userType; + public String getName() { + return name; + } - private Integer status; + public void setName(String name) { + this.name = name; + } - private String cellphoneNo; + public String getAge() { + return age; + } - private String telephoneNo; + public void setAge(String age) { + this.age = age; + } - private Date lastLoginDate; - - private String groupId; - - private String description; - - public Integer getOid() { - return oid; - } - - public void setOid(Integer oid) { - this.oid = oid; - } - - public String getUserId() { - return userId; - } - - public void setUserId(String userId) { - this.userId = userId == null ? null : userId.trim(); - } - - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName == null ? null : userName.trim(); - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password == null ? null : password.trim(); - } - - public String getRegion() { - return region; - } - - public void setRegion(String region) { - this.region = region == null ? null : region.trim(); - } - - public Integer getUserType() { - return userType; - } - - public void setUserType(Integer userType) { - this.userType = userType; - } - - public Integer getStatus() { - return status; - } - - public void setStatus(Integer status) { - this.status = status; - } - - public String getCellphoneNo() { - return cellphoneNo; - } - - public void setCellphoneNo(String cellphoneNo) { - this.cellphoneNo = cellphoneNo == null ? null : cellphoneNo.trim(); - } - - public String getTelephoneNo() { - return telephoneNo; - } - - public void setTelephoneNo(String telephoneNo) { - this.telephoneNo = telephoneNo == null ? null : telephoneNo.trim(); - } - - public Date getLastLoginDate() { - return lastLoginDate; - } - - public void setLastLoginDate(Date lastLoginDate) { - this.lastLoginDate = lastLoginDate; - } - - public String getGroupId() { - return groupId; - } - - public void setGroupId(String groupId) { - this.groupId = groupId == null ? null : groupId.trim(); - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description == null ? null : description.trim(); - } } \ No newline at end of file diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/mapper/UserInfoMapper.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/mapper/UserInfoMapper.java index 689b0c9..9850a58 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/mapper/UserInfoMapper.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/mapper/UserInfoMapper.java @@ -3,17 +3,7 @@ import com.xiaour.spring.boot.entity.UserInfo; public interface UserInfoMapper { - int deleteByPrimaryKey(Integer oid); - int insert(UserInfo record); + UserInfo selectByPrimaryKey(Integer id); - int insertSelective(UserInfo record); - - UserInfo selectByPrimaryKey(Integer oid); - - int updateByPrimaryKeySelective(UserInfo record); - - int updateByPrimaryKeyWithBLOBs(UserInfo record); - - int updateByPrimaryKey(UserInfo record); } \ No newline at end of file diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/mapper/UserInfoMapper.xml b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/mapper/UserInfoMapper.xml index fc04391..563ff4a 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/mapper/UserInfoMapper.xml +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/mapper/UserInfoMapper.xml @@ -2,164 +2,18 @@ - - - - - - - - - - - - - - - + + + + + + - - OID, USER_ID, USER_NAME, PASSWORD, REGION, USER_TYPE, STATUS, CELLPHONE_NO, TELEPHONE_NO, - LAST_LOGIN_DATE, GROUP_ID - - - - DESCRIPTION - - - + select * from user_info where id = #{id,jdbcType=INTEGER} - - delete from user - where OID = #{oid,jdbcType=INTEGER} - - - - insert into user - - - OID, - - - USER_ID, - - - USER_NAME, - - - PASSWORD, - - - REGION, - - - USER_TYPE, - - - STATUS, - - - CELLPHONE_NO, - - - TELEPHONE_NO, - - - LAST_LOGIN_DATE, - - - GROUP_ID, - - - DESCRIPTION, - - - - - #{oid,jdbcType=INTEGER}, - - - #{userId,jdbcType=VARCHAR}, - - - #{userName,jdbcType=VARCHAR}, - - - #{password,jdbcType=VARCHAR}, - - - #{region,jdbcType=VARCHAR}, - - - #{userType,jdbcType=INTEGER}, - - - #{status,jdbcType=INTEGER}, - - - #{cellphoneNo,jdbcType=VARCHAR}, - - - #{telephoneNo,jdbcType=VARCHAR}, - - - #{lastLoginDate,jdbcType=TIMESTAMP}, - - - #{groupId,jdbcType=VARCHAR}, - - - #{description,jdbcType=LONGVARCHAR}, - - - - - - update user - - - USER_ID = #{userId,jdbcType=VARCHAR}, - - - USER_NAME = #{userName,jdbcType=VARCHAR}, - - - PASSWORD = #{password,jdbcType=VARCHAR}, - - - REGION = #{region,jdbcType=VARCHAR}, - - - USER_TYPE = #{userType,jdbcType=INTEGER}, - - - STATUS = #{status,jdbcType=INTEGER}, - - - CELLPHONE_NO = #{cellphoneNo,jdbcType=VARCHAR}, - - - TELEPHONE_NO = #{telephoneNo,jdbcType=VARCHAR}, - - - LAST_LOGIN_DATE = #{lastLoginDate,jdbcType=TIMESTAMP}, - - - GROUP_ID = #{groupId,jdbcType=VARCHAR}, - - - DESCRIPTION = #{description,jdbcType=LONGVARCHAR}, - - - where OID = #{oid,jdbcType=INTEGER} - + \ No newline at end of file diff --git a/SpringBootDemo/src/main/resources/application.yml b/SpringBootDemo/src/main/resources/application.yml index b5add87..3fcd6f7 100644 --- a/SpringBootDemo/src/main/resources/application.yml +++ b/SpringBootDemo/src/main/resources/application.yml @@ -16,9 +16,9 @@ server : jdbc: datasource: name: test - url: jdbc:mysql://192.168.2.5:3335/springboot + url: jdbc:mysql://127.0.0.1:3306/world username: root - password: chifaner159 + password: 123456 # 使用druid数据源 type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.jdbc.Driver @@ -35,11 +35,7 @@ jdbc: testOnReturn: false poolPreparedStatements: true maxOpenPreparedStatements: 20 -# MyBatis -mybatis: - typeAliasesPackage: com.xiaour.spring.boot.entity - mapperLocations: classpath*:/com/xiaour/spring/boot/mapper/*.xml - configLocation: classpath:mybatis-config.xml + # 日志输出 logging: @@ -49,6 +45,6 @@ logging: root:DEBUG task: - cron:0 0/1 * * * ? + cron:0 0/5 * * * ? From 97e6f5e06ac6cc3c96198109e53a2d102d81966e Mon Sep 17 00:00:00 2001 From: "tony.zhang" Date: Tue, 17 Oct 2017 15:57:11 +0800 Subject: [PATCH 23/23] Update README --- README | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/README b/README index cc99905..5efbbf3 100644 --- a/README +++ b/README @@ -1,2 +1,20 @@ # SpringBootDemo -SpringBoot+MyBatis+Redis+MySql +本代码集成了SpringBoot+MyBatis+Redis+MySql。 +最新的部分经网友指正已经把冗余的代码去掉了,大家clone到本地后直接转成maven项目应该就可以运行了,项目中使用到的数据库表如下 + +-- ---------------------------- +-- Table structure for `user_info` +-- ---------------------------- +DROP TABLE IF EXISTS `user_info`; +CREATE TABLE `user_info` ( + `id` int(8) NOT NULL AUTO_INCREMENT, + `name` varchar(20) NOT NULL, + `age` int(2) DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; + +-- ---------------------------- +-- Records of user_info +-- ---------------------------- +INSERT INTO `user_info` VALUES ('1', 'xiaour', '1231'); +