Commit 84d5074c by 魏文甫

init

1 parent a4e5382e
Showing with 5059 additions and 0 deletions
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.kzy-wx</groupId>
<artifactId>kzy-wx</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>kzy-wx</name>
<description>Demo project for Spring Boot</description>
<inceptionYear>2018</inceptionYear>
<organization>
<name>YXVZB Technical Team-</name>
<url>http://www.yxvzb.com</url>
</organization>
<repositories>
<repository>
<id>nexus</id>
<name>local private nexus</name>
<url>http://192.168.0.105:8081/nexus/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix</artifactId>
<version>1.3.5.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j</artifactId>
<version>1.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>1.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.8</version>
</dependency>
<dependency>
<groupId>com.jfinal</groupId>
<artifactId>jfinal-weixin</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[7.2.0, 7.2.99]</version>
</dependency>
<dependency>
<groupId>org.jodd</groupId>
<artifactId>jodd-core</artifactId>
<version>3.7</version>
</dependency>
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<dependency>
<groupId>io.reactivex.rxjava2</groupId>
<artifactId>rxjava</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk16</artifactId>
<version>1.45</version>
</dependency>
<dependency>
<groupId>com.upyun</groupId>
<artifactId>java-sdk</artifactId>
<version>3.10</version>
</dependency>
<dependency>
<groupId>ytx</groupId>
<artifactId>ytx</artifactId>
<version>4</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/lib/CCP_REST_SDK_JAVA_v2.7r.jar</systemPath>
</dependency>
<dependency>
<groupId>com.alipay</groupId>
<artifactId>sdk-java</artifactId>
<version>20170615110434</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/lib/alipay-sdk-java20170615110434.jar</systemPath>
</dependency>
<dependency>
<groupId>fakepath</groupId>
<artifactId>distributed-kit</artifactId>
<version>0.0.1</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>
</dependencies>
<profiles>
<profile>
<id>105</id>
<properties>
<package.environment>105</package.environment>
</properties>
</profile>
<profile>
<id>online</id>
<properties>
<package.environment>online</package.environment>
</properties>
<!-- 设置默认使用的环境 -->
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
</profiles>
<build>
<!-- jar包名字,{名字+环境} -->
<finalName>kzy_wx_${package.environment}</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>*.xml</include>
<include>**/*.xml</include>
<include>**/application.properties</include>
<include>banner.txt</include>
</includes>
<excludes>
<exclude>generatorConfig.xml</exclude>
<exclude>mbg/*</exclude>
</excludes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources/servers/${package.environment}</directory>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources/lib</directory>
<targetPath>BOOT-INF/lib/</targetPath>
<includes>
<include>*.jar</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<encoding>utf-8</encoding>
<useDefaultDelimiters>true</useDefaultDelimiters>
</configuration>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
</build>
</project>
package com.server;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@SpringBootApplication
@EnableTransactionManagement
@ServletComponentScan
@MapperScan("com.server.web.common.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication application = new SpringApplication(Application.class);
application.run(args);
}
}
package com.server.common.configure;
import com.github.pagehelper.PageHelper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
/**
* Created by dell on 2017/8/22.
*/
@Configuration
public class ConfigMybatis {
@Bean
public PageHelper pageHelper() {
System.out.println("MyBatisConfiguration.pageHelper()");
PageHelper pageHelper = new PageHelper();
Properties p = new Properties();
p.setProperty("offsetAsPageNum", "true");
p.setProperty("rowBoundsWithCount", "true");
p.setProperty("reasonable", "true");
pageHelper.setProperties(p);
return pageHelper;
}
}
package com.server.common.configure;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
/**
* Created by yinbin on 2018/1/11.
* session 共享配置类,通过使用redis共享session,默认过期时间1800秒
*/
@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds=1800,redisNamespace = "kzy_wx")
public class ConfigRedisSession {
}
\ No newline at end of file
package com.server.common.configure;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
/**
* Created by yinbin on 2018/1/11.
* 线程池配置类
*/
@Configuration
@EnableAsync
public class ConfigThreadPoolExecutor implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor taskExecutor=new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(5);
taskExecutor.setMaxPoolSize(20);
taskExecutor.setQueueCapacity(25);
taskExecutor.initialize();
return taskExecutor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
package com.server.common.configure;
import com.server.web.interceptor.InterceptorLocal;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* Created by yinbin on 2018/1/9.
* web相关配置类
* 只配置了拦截器配置
*/
@Configuration
public class ConfigWebApp extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 多个拦截器组成一个拦截器链
// addPathPatterns 用于添加拦截规则
// excludePathPatterns 用户排除拦截
registry.addInterceptor(new InterceptorLocal()).addPathPatterns("/**");
super.addInterceptors(registry);
}
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
return restTemplate;
}
}
package com.server.common.configure;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
/**
* Created by yinbin on 2018/1/16.
* 启用此配置,任务采用多线程执行
* 不启用所有任务串行执行,即单线程执行任务
*/
@Configuration
@EnableScheduling
public class ScheduleConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(taskExecutor());
}
@Bean(destroyMethod="shutdown")
public Executor taskExecutor() {
return Executors.newScheduledThreadPool(100);
}
}
package com.server.common.filter;
import com.server.common.filter.util.SecretUtil;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
/**
* Created by yinbin on 2018/1/9.
* 过滤器,过滤请求,此过滤器在为对外提供api时,签名过滤器
* Order其实不起作用,请注意
*/
@Order(10)
@WebFilter(urlPatterns = "/*", filterName = "apiFilter")
public class ApiFilter implements Filter {
final static Logger logger = LogManager.getLogger(ApiFilter.class);
@Value("${rest.api.debug}")
private String isdebug="false";
@Value("${rest.api.secretkey}")
private String secretKey;
@Value("${rest.api.charset}")
private String charset;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
logger.info("API Filter");
if(isdebug.equals("false")) {
boolean flag=SecretUtil.signByMd5(servletRequest,secretKey,charset);
if(flag){
filterChain.doFilter(servletRequest, servletResponse);
}
}else {
filterChain.doFilter(servletRequest, servletResponse);
}
}
@Override
public void destroy() {
}
}
\ No newline at end of file
package com.server.common.filter;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
/**
* Created by yinbin on 2018/1/9.
* 过滤器,session过滤器
* Order其实不起作用,请注意
*/
@Order(2)
@WebFilter(urlPatterns = "/*", filterName = "sessionFilter")
public class SessionFilter implements Filter {
final static Logger logger = LogManager.getLogger(ApiFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// SysUser user= (SysUser) userRepository.getByUsernameIsAndPasswordIs("admin","123456");
// logger.info("user_name is :"+user.getUsername());
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
logger.info("SessionFilter Filter");
filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
}
}
\ No newline at end of file
package com.server.common.filter.util;
import org.apache.commons.codec.digest.DigestUtils;
import javax.servlet.ServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.*;
/**
* Created by yinbin on 2018/1/12.
* 签名工具
*/
public class SecretUtil {
public static boolean signByMd5(ServletRequest servletRequest,String secretKey,String charset) throws UnsupportedEncodingException {
Map<String,String> params = new HashMap<String,String>();
Map<String,String[]> requestParams = servletRequest.getParameterMap();
for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
String name = (String) iter.next();
String[] values = (String[]) requestParams.get(name);
String valueStr = "";
for (int i = 0; i < values.length; i++) {
valueStr = (i == values.length - 1) ? valueStr + values[i]
: valueStr + values[i] + ",";
}
//乱码解决,这段代码在出现乱码时使用
valueStr = new String(valueStr.getBytes("ISO-8859-1"), charset);
params.put(name, valueStr);
}
return rsaCheckV1(params,secretKey,charset);
}
public static boolean rsaCheckV1(Map<String, String> params, String publicKey,
String charset) {
String sign = params.get("sign");
String content = getSignCheckContentV1(params);
return rsaCheckContent(content, sign, publicKey, charset);
}
public static boolean rsaCheckContent(String content, String sign, String publicKey,
String charset) {
String sign_check= DigestUtils.md5Hex(content + publicKey);
return sign.equals(sign_check)?true:false;
}
public static String getSignCheckContentV1(Map<String, String> params) {
if (params == null) {
return null;
}
params.remove("sign");
StringBuffer content = new StringBuffer();
List<String> keys = new ArrayList<String>(params.keySet());
Collections.sort(keys);
for (int i = 0; i < keys.size(); i++) {
String key = keys.get(i);
String value = params.get(key);
content.append((i == 0 ? "" : "&") + key + "=" + value);
}
return content.toString();
}
}
package com.server.utils;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
/**
* Created by stone on 2017/4/27.
*/
public class BufferedImageUtil {
/**
* 图片设置圆角
* @param srcImage
* @param radius
* @param border
* @param padding
* @return
* @throws IOException
*/
public static BufferedImage setRadius(BufferedImage srcImage, int radius, int border, int padding) throws IOException {
int width = srcImage.getWidth();
int height = srcImage.getHeight();
int canvasWidth = width + padding * 2;
int canvasHeight = height + padding * 2;
BufferedImage image = new BufferedImage(canvasWidth, canvasHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D gs = image.createGraphics();
gs.setComposite(AlphaComposite.Src);
gs.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
gs.setColor(Color.WHITE);
gs.fill(new RoundRectangle2D.Float(0, 0, canvasWidth, canvasHeight, radius, radius));
gs.setComposite(AlphaComposite.SrcAtop);
gs.drawImage(setClip(srcImage, radius), padding, padding, null);
if(border !=0){
gs.setColor(Color.GRAY);
gs.setStroke(new BasicStroke(border));
gs.drawRoundRect(padding, padding, canvasWidth - 2 * padding, canvasHeight - 2 * padding, radius, radius);
}
gs.dispose();
return image;
}
/**
* 图片设置圆角
* @param srcImage
* @return
* @throws IOException
*/
public static BufferedImage setRadius(BufferedImage srcImage) throws IOException{
int radius = srcImage.getWidth();
return setRadius(srcImage, radius, 2, 5);
}
/**
* 图片切圆角
* @param srcImage
* @param radius
* @return
*/
public static BufferedImage setClip(BufferedImage srcImage, int radius){
int width = srcImage.getWidth();
int height = srcImage.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D gs = image.createGraphics();
gs.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
gs.setClip(new RoundRectangle2D.Double(0, 0, width, height, radius, radius));
gs.drawImage(srcImage, 0, 0, null);
gs.dispose();
return image;
}
}
package com.server.utils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* Created by stone on 2017/6/14.
*/
public class HTTPClientUtil {
public static String getPublicService(Map<String, String> map, String url,String charset)
throws Exception {
HttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
try{
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(url);
//设置参数
List<NameValuePair> list = new ArrayList<NameValuePair>();
Iterator iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Entry<String,String> elem = (Entry<String, String>) iterator.next();
list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));
}
if(list.size() > 0){
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset);
httpPost.setEntity(entity);
}
HttpResponse response = httpClient.execute(httpPost);
if(response != null){
HttpEntity resEntity = response.getEntity();
if(resEntity != null){
result = EntityUtils.toString(resEntity,charset);
}
}
}catch(Exception ex){
ex.printStackTrace();
}
return result;
}
public static String getUrl(HttpServletRequest request){
StringBuffer url = request.getRequestURL();
String visitUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
return visitUrl;
}
}
package com.server.utils;
import com.google.zxing.common.BitMatrix;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
/**
* Created by stone on 2017/4/21.
*/
public class MatrixToImageWriter {
private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF;
private MatrixToImageWriter() {}
public static BufferedImage toBufferedImage(BitMatrix matrix) {
int width = matrix.getWidth();
int height = matrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
}
}
return image;
}
public static void writeToFile(BitMatrix matrix, String format, File file)
throws IOException {
BufferedImage image = toBufferedImage(matrix);
if (!ImageIO.write(image, format, file)) {
throw new IOException("Could not write an image of format " + format + " to " + file);
}
}
public static void writeToStream(BitMatrix matrix, String format, OutputStream stream)
throws IOException {
BufferedImage image = toBufferedImage(matrix);
if (!ImageIO.write(image, format, stream)) {
throw new IOException("Could not write an image of format " + format);
}
}
}
package com.server.utils;
import java.security.MessageDigest;
/**
* Created by dell on 2018/3/7.
*/
public class SHA1 {
private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
/**
* Takes the raw bytes from the digest and formats them correct.
*
* @param bytes the raw bytes from the digest.
* @return the formatted bytes.
*/
private static String getFormattedText(byte[] bytes) {
int len = bytes.length;
StringBuilder buf = new StringBuilder(len * 2);
// 把密文转换成十六进制的字符串形式
for (int j = 0; j < len; j++) {
buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
}
return buf.toString();
}
public static String encode(String str) {
if (str == null) {
return null;
}
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
messageDigest.update(str.getBytes());
return getFormattedText(messageDigest.digest());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
package com.server.utils;
import com.cloopen.rest.sdk.CCPRestSDK;
import java.util.HashMap;
/**
* Created by dell on 2017/8/15.
*/
public class SendSMSUtil {
public static HashMap<String, Object> sendTemplateSMS(String phone,String templateId,String[] dataS){
HashMap<String, Object> result = null;
//初始化SDK
CCPRestSDK restAPI = new CCPRestSDK();
//******************************注释*********************************************
//*初始化服务器地址和端口 *
//*沙盒环境(用于应用开发调试):restAPI.init("sandboxapp.cloopen.com", "8883");*
//*生产环境(用户应用上线使用):restAPI.init("app.cloopen.com", "8883"); *
//*******************************************************************************
restAPI.init("app.cloopen.com", "8883");
//******************************注释*********************************************
//*初始化主帐号和主帐号令牌,对应官网开发者主账号下的ACCOUNT SID和AUTH TOKEN *
//*ACOUNT SID和AUTH TOKEN在登陆官网后,在“应用-管理控制台”中查看开发者主账号获取*
//*参数顺序:第一个参数是ACOUNT SID,第二个参数是AUTH TOKEN。 *
//*******************************************************************************
restAPI.setAccount("8a48b55150ccc4290150d0985f88117c", "d7b0743958264ba69a98c5ce0ea5291d");
//******************************注释*********************************************
//*初始化应用ID *
//*测试开发可使用“测试Demo”的APP ID,正式上线需要使用自己创建的应用的App ID *
//*应用ID的获取:登陆官网,在“应用-应用列表”,点击应用名称,看应用详情获取APP ID*
//*******************************************************************************
restAPI.setAppId("8a48b55150ccc4290150d0a7a07d1227");
//******************************注释****************************************************************
//*调用发送模板短信的接口发送短信 *
//*参数顺序说明: *
//*第一个参数:是要发送的手机号码,可以用逗号分隔,一次最多支持100个手机号 *
//*第二个参数:是模板ID,在平台上创建的短信模板的ID值;测试的时候可以使用系统的默认模板,id为1。 *
//*系统默认模板的内容为“【云通讯】您使用的是云通讯短信模板,您的验证码是{1},请于{2}分钟内正确输入”*
//*第三个参数是要替换的内容数组。 *
//**************************************************************************************************
//**************************************举例说明***********************************************************************
//*假设您用测试Demo的APP ID,则需使用默认模板ID 1,发送手机号是13800000000,传入参数为6532和5,则调用方式为 *
//*result = restAPI.sendTemplateSMS("13800000000","1" ,new String[]{"6532","5"}); *
//*则13800000000手机号收到的短信内容是:【云通讯】您使用的是云通讯短信模板,您的验证码是6532,请于5分钟内正确输入 *
//*********************************************************************************************************************
result = restAPI.sendTemplateSMS(phone,templateId ,dataS);
return result;
}
public static HashMap<String, Object> voiceVerify(String code,String phone){
HashMap<String, Object> result = null;
//初始化SDK
CCPRestSDK restAPI = new CCPRestSDK();
//******************************注释*********************************************
//*初始化服务器地址和端口 *
//*沙盒环境(用于应用开发调试):restAPI.init("sandboxapp.cloopen.com", "8883");*
//*生产环境(用户应用上线使用):restAPI.init("app.cloopen.com", "8883"); *
//*******************************************************************************
restAPI.init("sandboxapp.cloopen.com", "8883");
//******************************注释*********************************************
//*初始化主帐号和主帐号令牌,对应官网开发者主账号下的ACCOUNT SID和AUTH TOKEN *
//*ACOUNT SID和AUTH TOKEN在登陆官网后,在“应用-管理控制台”中查看开发者主账号获取*
//*参数顺序:第一个参数是ACOUNT SID,第二个参数是AUTH TOKEN。 *
//*******************************************************************************
restAPI.setAccount("8a48b55150ccc4290150d0985f88117c", "d7b0743958264ba69a98c5ce0ea5291d");
//******************************注释*********************************************
//*初始化应用ID *
//*测试开发可使用“测试Demo”的APP ID,正式上线需要使用自己创建的应用的App ID *
//*应用ID的获取:登陆官网,在“应用-应用列表”,点击应用名称,看应用详情获取APP ID*
//*******************************************************************************
restAPI.setAppId("8a48b55150ccc4290150d0a7a07d1227");
//******************************注释****************************************************************
//*调用发送模板短信的接口发送短信 *
//*参数顺序说明: *
//*第一个参数:是要发送的手机号码,可以用逗号分隔,一次最多支持100个手机号 *
//*第二个参数:是模板ID,在平台上创建的短信模板的ID值;测试的时候可以使用系统的默认模板,id为1。 *
//*系统默认模板的内容为“【云通讯】您使用的是云通讯短信模板,您的验证码是{1},请于{2}分钟内正确输入”*
//*第三个参数是要替换的内容数组。 *
//**************************************************************************************************
//**************************************举例说明***********************************************************************
//*假设您用测试Demo的APP ID,则需使用默认模板ID 1,发送手机号是13800000000,传入参数为6532和5,则调用方式为 *
//*result = restAPI.sendTemplateSMS("13800000000","1" ,new String[]{"6532","5"}); *
//*则13800000000手机号收到的短信内容是:【云通讯】您使用的是云通讯短信模板,您的验证码是6532,请于5分钟内正确输入 *
//*********************************************************************************************************************
result = restAPI.voiceVerify(code, phone,"01056177183","3", "", "", "");
return result;
}
}
package com.server.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext ctx;
public void setApplicationContext(ApplicationContext ctx) throws BeansException {
SpringContextUtil.ctx = ctx;
}
public static ApplicationContext getCtx() {
return ctx;
}
}
package com.server.utils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Random;
/**
* Created by weiwenfu@163.com on 2018/11/16 上午 10:51.
*/
public class VerifyCodeUtils {
private static Random random = new Random();
public static Font font = null;
public static void outputImagePC(int w, int h, OutputStream os, String code) throws IOException {
int verifySize = code.length();
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Random rand = new Random();
Graphics2D g2 = image.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Color[] colors = new Color[5];
Color[] colorSpaces = new Color[]{Color.WHITE, Color.CYAN,
Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
Color.PINK, Color.YELLOW};
float[] fractions = new float[colors.length];
for (int i = 0; i < colors.length; i++) {
colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
fractions[i] = rand.nextFloat();
}
Arrays.sort(fractions);
g2.setColor(Color.GRAY);// 设置边框色
g2.fillRect(0, 0, w, h);
Color c = getRandColor(200, 250);
g2.setColor(c);// 设置背景色
g2.fillRect(0, 0, w, h);
shear(g2, w, h, c);// 使图片扭曲
Random random = new Random();
g2.setColor(new Color(10,10,10));// 设置线条的颜色
for (int i = 0; i < 1; i++) {
int x = random.nextInt(w - 1);
int y = random.nextInt(h - 1);
int xl = random.nextInt(6) + 1;
int yl = random.nextInt(12) + 1;
//设置线条粗度
BasicStroke basicStroke = new BasicStroke(0.6f);
g2.setStroke(basicStroke);
//绘制干扰线
g2.drawLine(5, 15, 90, 10);
}
// 添加噪点
float yawpRate = 0.1f;// 噪声率
int area = (int) (yawpRate * w * h);
for (int i = 0; i < area; i++) {
int x = random.nextInt(w);
int y = random.nextInt(h);
int rgb = getRandomIntColor();
image.setRGB(x, y, rgb);
}
g2.setColor(new Color(10,10,10));
int fontSize = h - 16;
g2.setFont(getFont(fontSize));
char[] chars = code.toCharArray();
for (int i = 0; i < verifySize; i++) {
AffineTransform affine = new AffineTransform();
affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize / 2, h / 2);
g2.setTransform(affine);
g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10);
}
g2.dispose();
ImageIO.write(image, "jpeg", os);
os.close();
}
public static Font getFont(int fontSize) {
if (font == null) {
font = new Font("Algerian", Font.ITALIC, fontSize);
}
return font;
}
private static Color getRandColor(int fc, int bc) {
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
private static int getRandomIntColor() {
int[] rgb = getRandomRgb();
int color = 0;
for (int c : rgb) {
color = color << 8;
color = color | c;
}
return color;
}
private static int[] getRandomRgb() {
int[] rgb = new int[3];
for (int i = 0; i < 3; i++) {
rgb[i] = random.nextInt(255);
}
return rgb;
}
private static void shear(Graphics g, int w1, int h1, Color color) {
shearX(g, w1, h1, color);
shearY(g, w1, h1, color);
}
private static void shearX(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(2);
boolean borderGap = true;
int frames = 1;
int phase = random.nextInt(2);
for (int i = 0; i < h1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(0, i, w1, 1, (int) d, 0);
if (borderGap) {
g.setColor(color);
g.drawLine((int) d, i, 0, i);
g.drawLine((int) d + w1, i, w1, i);
}
}
}
private static void shearY(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(40) + 10; // 50;
boolean borderGap = true;
int frames = 20;
int phase = 7;
for (int i = 0; i < w1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(i, 0, 1, h1, 0, (int) d);
if (borderGap) {
g.setColor(color);
g.drawLine(i, (int) d, i, 0);
g.drawLine(i, (int) d + h1, i, h1);
}
}
}
}
package com.server.utils.blob;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.sql.*;
/**
* Created by dell on 2017/7/19.
*/
public class BlobTypeHandler extends BaseTypeHandler<String> {
// 指定字符集
private static final String DEFAULT_CHARSET = "utf-8";
@Override
public void setNonNullParameter(PreparedStatement ps, int i,
String parameter, JdbcType jdbcType) throws SQLException
{
ByteArrayInputStream bis;
try
{
// 把String转化成byte流
bis = new ByteArrayInputStream(parameter.getBytes(DEFAULT_CHARSET));
} catch (UnsupportedEncodingException e)
{
throw new RuntimeException("Blob Encoding Error!");
}
ps.setBinaryStream(i, bis, parameter.length());
}
@Override
public String getNullableResult(ResultSet rs, String columnName)
throws SQLException
{
Blob blob = rs.getBlob(columnName);
byte[] returnValue = null;
String result = null;
if (null != blob)
{
returnValue = blob.getBytes(1, (int) blob.length());
}
try
{
if (null != returnValue)
{
// 把byte转化成string
result = new String(returnValue, DEFAULT_CHARSET);
}
} catch (UnsupportedEncodingException e)
{
throw new RuntimeException("Blob Encoding Error!");
}
return result;
}
@Override
public String getNullableResult(CallableStatement cs, int columnIndex)
throws SQLException
{
Blob blob = cs.getBlob(columnIndex);
byte[] returnValue = null;
String result = null;
if (null != blob)
{
returnValue = blob.getBytes(1, (int) blob.length());
}
try
{
if (null != returnValue)
{
result = new String(returnValue, DEFAULT_CHARSET);
}
} catch (UnsupportedEncodingException e)
{
throw new RuntimeException("Blob Encoding Error!");
}
return result;
}
/**
* @Description:
*
* @return
* @throws SQLException
*
* @see BaseTypeHandler#getNullableResult(ResultSet,
* int)
*
*/
@Override
public String getNullableResult(ResultSet rs, int columnName)
throws SQLException
{
String result = null;
Blob blob = rs.getBlob(columnName);
byte[] returnValue = null;
if (null != blob)
{
returnValue = blob.getBytes(1, (int) blob.length());
}
try
{
// 把byte转化成string
if (null != returnValue)
{
result = new String(returnValue, DEFAULT_CHARSET);
}
} catch (UnsupportedEncodingException e)
{
throw new RuntimeException("Blob Encoding Error!");
}
return result;
}
}
package com.server.utils.redis;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPool;
import javax.crypto.KeyGenerator;
/**
* Created by dell on 2017/11/6.
*/
@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport {
@Value("${spring.redis.host}")
private String REDIS_IP;
@Value("${spring.redis.port}")
private Integer REDIS_PORT;
@Value("${spring.redis.password}")
private String REDIS_PASSWORD;
@Value("${spring.redis.database}")
private Integer REDIS_DATABASE;
@Value("${spring.redis.timeout}")
private Integer REDIS_TIMEOUT;
@Bean
public JedisPool jedisPool() {
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
JedisPool pool = new JedisPool(poolConfig,REDIS_IP,REDIS_PORT,REDIS_TIMEOUT,REDIS_PASSWORD,REDIS_DATABASE);
return pool;
}
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
//设置缓存过期时间
//rcm.setDefaultExpiration(60);//秒
return rcm;
}
@Bean
public RedisTemplate<String, String> stringRedisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
RedisSerializer stringSerializer = new StringRedisSerializer();
template.setKeySerializer(stringSerializer);
template.afterPropertiesSet();
return template;
}
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate template = new RedisTemplate();
template.setConnectionFactory(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setKeySerializer(jackson2JsonRedisSerializer);
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.setHashKeySerializer(jackson2JsonRedisSerializer);
RedisSerializer stringSerializer = new StringRedisSerializer();
template.setKeySerializer(stringSerializer);
template.afterPropertiesSet();
return template;
}
}
package com.server.utils.weixin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Iterator;
import java.util.Map;
/**
* Created by dell on 2018/2/28.
*/
public class HttpURLUtil {
private Logger logger = LoggerFactory.getLogger(getClass());
private static final String GET = "GET";
private static final String POST = "POST";
private static String CHARSET = "UTF-8";
private HttpURLUtil() {
}
private static HttpURLConnection getHttpConnection(String url, String method, Map<String, String> headers) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
URL _url = new URL(url);
HttpURLConnection conn = (HttpURLConnection)_url.openConnection();
conn.setRequestMethod(method);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setConnectTimeout(19000);
conn.setReadTimeout(19000);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
if(headers != null && !headers.isEmpty()) {
Iterator i$ = headers.entrySet().iterator();
while(i$.hasNext()) {
Map.Entry entry = (Map.Entry)i$.next();
conn.setRequestProperty((String)entry.getKey(), (String)entry.getValue());
}
}
return conn;
}
public static String get(String url, Map<String, String> queryParas, Map<String, String> headers) {
HttpURLConnection conn = null;
String e;
try {
conn = getHttpConnection(buildUrlWithQueryString(url, queryParas), HttpURLUtil.GET, headers);
conn.connect();
e = readResponseString(conn);
} catch (Exception var8) {
throw new RuntimeException(var8);
} finally {
if(conn != null) {
conn.disconnect();
}
}
return e;
}
public static String get(String url, Map<String, String> queryParas) {
return get(url, queryParas, (Map)null);
}
public static String get(String url) {
return get(url, (Map)null, (Map)null);
}
public static String post(String url, Map<String, String> queryParas, String data, Map<String, String> headers) {
HttpURLConnection conn = null;
String var6;
try {
conn = getHttpConnection(buildUrlWithQueryString(url, queryParas), HttpURLUtil.POST, headers);
conn.connect();
OutputStream e = conn.getOutputStream();
e.write(data != null?data.getBytes(CHARSET):null);
e.flush();
e.close();
var6 = readResponseString(conn);
} catch (Exception var10) {
throw new RuntimeException(var10);
} finally {
if(conn != null) {
conn.disconnect();
}
}
return var6;
}
public static String post(String url, Map<String, String> queryParas, String data) {
return post(url, queryParas, data, (Map)null);
}
public static String post(String url, String data, Map<String, String> headers) {
return post(url, (Map)null, data, headers);
}
public static String post(String url, String data) {
return post(url, (Map)null, data, (Map)null);
}
private static String readResponseString(HttpURLConnection conn) {
StringBuilder sb = new StringBuilder();
InputStream inputStream = null;
try {
inputStream = conn.getInputStream();
BufferedReader e = new BufferedReader(new InputStreamReader(inputStream, CHARSET));
String line = null;
while((line = e.readLine()) != null) {
sb.append(line).append("\n");
}
String var5 = sb.toString();
return var5;
} catch (Exception var14) {
throw new RuntimeException(var14);
} finally {
if(inputStream != null) {
try {
inputStream.close();
} catch (IOException var13) {
var13.printStackTrace();
}
}
}
}
private static String buildUrlWithQueryString(String url, Map<String, String> queryParas) {
if(queryParas != null && !queryParas.isEmpty()) {
StringBuilder sb = new StringBuilder(url);
boolean isFirst;
if(!url.contains("?")) {
isFirst = true;
sb.append("?");
} else {
isFirst = false;
}
String key;
String value;
for(Iterator i$ = queryParas.entrySet().iterator(); i$.hasNext(); sb.append(key).append("=").append(value)) {
Map.Entry entry = (Map.Entry)i$.next();
if(isFirst) {
isFirst = false;
} else {
sb.append("&");
}
key = (String)entry.getKey();
value = (String)entry.getValue();
if(StringUtils.hasText(value)) {
try {
value = URLEncoder.encode(value, CHARSET);
} catch (UnsupportedEncodingException var9) {
throw new RuntimeException(var9);
}
}
}
return sb.toString();
} else {
return url;
}
}
public static String readData(HttpServletRequest request) {
BufferedReader br = null;
try {
StringBuilder e = new StringBuilder();
String line;
for(br = request.getReader(); (line = br.readLine()) != null; e.append(line)) {
if(e.length() > 0) {
e.append("\n");
}
}
line = e.toString();
return line;
} catch (IOException var12) {
throw new RuntimeException(var12);
} finally {
if(br != null) {
try {
br.close();
} catch (IOException var11) {
var11.printStackTrace();
}
}
}
}
}
package com.server.utils.weixin;
import com.alibaba.fastjson.JSON;
import com.jfinal.kit.StrKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.utils.Charsets;
import com.jfinal.weixin.sdk.utils.IOUtils;
import com.jfinal.weixin.sdk.utils.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
* 公众号发送图片等
* Created by dell on 2018/2/28.
*/
public class MessageUtil {
private static Logger logger = LoggerFactory.getLogger(MessageUtil.class);
private static String customMessageUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=";
//素材上传地址
private static String MEDIA_UPLOADURL = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=";
public MessageUtil() {
}
private static Map<String,Object> sendMsg(Map<String, Object> message,String accessToken) {
String jsonResult = HttpURLUtil.post(customMessageUrl + accessToken, JsonUtils.toJson(message));
Map resultMap = (Map) JSON.parseObject(jsonResult, Map.class);
// Number number = (Number)resultMap.get("errcode");
// Integer errorCode = (number == null?null:Integer.valueOf(number.intValue()));
// if(errorCode == null || errorCode.intValue() == 0){
// return resultMap;
// }else{
// logger.error("MessageUtil.sendMsg==="+jsonResult+";message="+ReturnCode.get(errorCode));
// return resultMap;
// }
return resultMap;
}
/**
* 发送文本消息
* @param openId
* @param text
* @param accessToken
* @return
*/
public static Map<String,Object> sendText(String openId, String text,String accessToken) {
HashMap json = new HashMap();
json.put("touser", openId);
json.put("msgtype", "text");
HashMap textObj = new HashMap();
textObj.put("content", text);
json.put("text", textObj);
return sendMsg(json,accessToken);
}
/**
* 发送图片消息
* @param openId
* @param media_id
* @param accessToken
* @return
*/
public static Map<String,Object> sendImage(String openId, String media_id,String accessToken) {
HashMap json = new HashMap();
json.put("touser", openId);
json.put("msgtype", "image");
HashMap image = new HashMap();
image.put("media_id", media_id);
json.put("image", image);
return sendMsg(json,accessToken);
}
/**
* 上传临时素材库
* @param accessToken
* @param fileUrl
* @return
*/
public static Map<String,Object> mediaUploadImageMedia(String accessToken,String fileUrl) {
Map<String,Object> resultMap = new HashMap<String,Object>();
String url = MEDIA_UPLOADURL + accessToken + "&type=image";
String jsonStr = null;
try {
jsonStr = uploadMedia(url, fileUrl, (String)null);
} catch (IOException e) {
e.printStackTrace();
}
ApiResult apiResult = new ApiResult(jsonStr);
resultMap.put("jsonStr",jsonStr);
if(apiResult.isSucceed()){
resultMap.put("mediaId",apiResult.get("media_id"));
}else{
resultMap.put("mediaId","");
}
return resultMap;
}
protected static String uploadMedia(String url, String fileUrl,String params) throws IOException {
URL urlGet = new URL(url);
HttpURLConnection conn = (HttpURLConnection)urlGet.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
conn.setRequestProperty("Charsert", "UTF-8");
String BOUNDARY = "----WebKitFormBoundaryiDGnV9zdZA1eM1yL";
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
StringBuilder mediaData = new StringBuilder();
mediaData.append("--").append(BOUNDARY).append("\r\n");
mediaData.append("Content-Disposition: form-data;name=\"media\";filename=\"" + new File(fileUrl).getName()+ "\"\r\n");
mediaData.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] mediaDatas = mediaData.toString().getBytes();
out.write(mediaDatas);
out.write(downLoadFromUrl(fileUrl));
out.write("\r\n".getBytes());
if(StrKit.notBlank(params)) {
StringBuilder end_data = new StringBuilder();
end_data.append("--").append(BOUNDARY).append("\r\n");
end_data.append("Content-Disposition: form-data;name=\"description\";");
byte[] in = end_data.toString().getBytes();
out.write(in);
out.write(params.getBytes(Charsets.UTF_8));
}
byte[] end_data1 = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
out.write(end_data1);
out.flush();
IOUtils.closeQuietly(out);
InputStream in1 = conn.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in1, Charsets.UTF_8));
String valueString = null;
StringBuffer bufferRes = null;
bufferRes = new StringBuffer();
while((valueString = read.readLine()) != null) {
bufferRes.append(valueString);
}
IOUtils.closeQuietly(in1);
if(conn != null) {
conn.disconnect();
}
return bufferRes.toString();
}
/**
* 从网络Url中下载文件
* @param urlStr
* @throws IOException
*/
public static byte[] downLoadFromUrl(String urlStr) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置超时间为3秒
conn.setConnectTimeout(3*1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到输入流
InputStream inputStream = conn.getInputStream();
//获取自己数组
byte[] getData = readInputStream(inputStream);
// //文件保存位置
// File saveDir = new File(savePath);
// if(!saveDir.exists()){
// saveDir.mkdir();
// }
// File file = new File(saveDir+File.separator+fileName);
// FileOutputStream fos = new FileOutputStream(file);
// fos.write(getData);
// if(fos!=null){
// fos.close();
// }
// if(inputStream!=null){
// inputStream.close();
// }
return getData;
}
/**
* 从输入流中获取字节数组
* @param inputStream
* @return
* @throws IOException
*/
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
}
package com.server.utils.weixin;
/**
* Created by lemon_bar on 15/7/1.
*/
public enum WXMessageType {
text,
image,
voice,
video,
news,
shortvideo,
location,
link,
event;
}
package com.server.utils.weixin;
import com.alibaba.fastjson.JSON;
import com.jfinal.weixin.sdk.api.JsTicket;
import com.jfinal.weixin.sdk.api.JsTicketApi;
import com.jfinal.weixin.sdk.kit.ParaMap;
import com.jfinal.weixin.sdk.utils.HttpUtils;
import com.server.utils.weixin.bean.SnsAccessTokenBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* Created by 豆腐干Sama on 2018/12/5.
*/
public class WeixinBaseUtil {
static Logger logger = LoggerFactory.getLogger(WeixinBaseUtil.class);
//获取微信accesstockenurl
public static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
//获取网页access_token
private static String SNS_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={appid}&secret={secret}&code={code}&grant_type=authorization_code";
//获取用户信息url
private static String USER_INFO_URL = "https://api.weixin.qq.com/sns/userinfo";
private static String JsapiTicketURL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
public static Map<String, Object> authorization(String appId, String appSecret, String code) {
if (StringUtils.hasText(appId) && StringUtils.hasText(appSecret) && StringUtils.hasText(code)) {
final String queryAccessTokeUrl = SNS_ACCESS_TOKEN_URL.replace("{appid}", appId).replace("{secret}", appSecret).replace("{code}", code);
RestTemplate restTemplate = new RestTemplate();
String json = restTemplate.getForObject(queryAccessTokeUrl, String.class);
SnsAccessTokenBean snsAccessTokenBean = new SnsAccessTokenBean(json);
String accessToken = snsAccessTokenBean.getAccessToken();
String openid = snsAccessTokenBean.getOpenid();
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
String userInfoJsonStr = restTemplate.getForObject(USER_INFO_URL + "?access_token=" + accessToken + "&openid=" + openid + "&lang=zh_CN", String.class);
Map userInfoResultMap = JSON.parseObject(userInfoJsonStr, Map.class);
Number errCode = (Number) userInfoResultMap.get("errcode");
Integer errorCode = (errCode == null ? null : Integer.valueOf(errCode.intValue()));
if (errorCode == null || errorCode.intValue() == 0) {
userInfoResultMap.put("wxAccessToken", snsAccessTokenBean.getAccessToken());
userInfoResultMap.put("wxRefreshToken", snsAccessTokenBean.getRefresh_token());
return userInfoResultMap;
}
} else {
logger.error("参数有误");
return null;
}
return null;
}
/**
* 获取微信 ticket
*
* @param appId
* @param accesstoken
* @param url
* @param redisTemplate
* @return
*/
public static String getTicket(String appId, String accesstoken, String url, RedisTemplate redisTemplate) {
String key = appId + '_' + JsTicketApi.JsApiType.jsapi.name();
final ParaMap pm = ParaMap.create("access_token", accesstoken).put("type", JsTicketApi.JsApiType.jsapi.name());
boolean redisTicket = true;
String json = "";
if (redisTemplate.hasKey("wx_ticket_" + key)) {
json = (String) redisTemplate.opsForValue().get("wx_ticket_" + appId);
if (StringUtils.hasText(json)) {
redisTicket = false;
}
}
if (redisTicket) {
json = HttpUtils.get(WeixinBaseUtil.JsapiTicketURL, pm.getData());
}
JsTicket jsTicket = new JsTicket(json);
return jsTicket.getTicket();
}
public static Map<String, Object> sign(String jsapi_ticket, String url, String appId) {
Map<String, Object> ret = new HashMap<String, Object>();
String nonce_str = UUID.randomUUID().toString();
String timestamp = Long.toString(System.currentTimeMillis() / 1000);
String str;
String signature = "";
//注意这里参数名必须全部小写,且必须有序
str = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str + "&timestamp=" + timestamp + "&url=" + url;
try {
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(str.getBytes("UTF-8"));
signature = byteToHex(crypt.digest());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
ret.put("appId", appId);
ret.put("url", url);
ret.put("jsapi_ticket", jsapi_ticket);
ret.put("nonceStr", nonce_str);
ret.put("timestamp", timestamp);
ret.put("signature", signature);
return ret;
}
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;
}
}
\ No newline at end of file
package com.server.utils.weixin.bean;
import com.alibaba.fastjson.JSON;
import com.server.utils.weixin.ReturnCode;
import java.io.Serializable;
import java.util.Map;
/**
* Created by dell on 2018/2/28.
*/
public class AccessTokenBean implements Serializable {
private String access_token;
private Integer expires_in;
private Integer errcode;
private String errmsg;
private Long expiredTime;
private String json;
public AccessTokenBean(String jsonStr) {
this.json = jsonStr;
try {
Map e = (Map) JSON.parseObject(jsonStr, Map.class);
this.access_token = (String)e.get("access_token");
this.expires_in = (Integer)e.get("expires_in");
this.errcode = (Integer)e.get("errcode");
this.errmsg = (String)e.get("errmsg");
if(this.expires_in != null) {
this.expiredTime = Long.valueOf(System.currentTimeMillis() + (long)((this.expires_in.intValue() - 5) * 1000));
}
if(e.containsKey("expiredTime")) {
this.expiredTime = (Long)e.get("expiredTime");
}
} catch (Exception var3) {
throw new RuntimeException(var3);
}
}
public String getJson() {
return this.json;
}
public String getAccessToken() {
return this.access_token;
}
public Integer getExpiresIn() {
return this.expires_in;
}
public Long getExpiredTime() {
return this.expiredTime;
}
public Integer getErrorCode() {
return this.errcode;
}
public String getErrorMsg() {
if(this.errcode != null) {
String result = ReturnCode.get(this.errcode.intValue());
if(result != null) {
return result;
}
}
return this.errmsg;
}
}
package com.server.utils.weixin.bean;
import com.alibaba.fastjson.JSON;
import com.server.utils.weixin.ReturnCode;
import java.util.Map;
/**
* Created by dell on 2018/2/28.
*/
public class SnsAccessTokenBean {
private String access_token;
private Integer expires_in;
private String refresh_token;
private String openid;
private String scope;
private String unionid;
private Integer errcode;
private String errmsg;
private Long expiredTime;
private String json;
public SnsAccessTokenBean(String jsonStr) {
this.json = jsonStr;
try {
Map e = (Map) JSON.parseObject(jsonStr, Map.class);
this.access_token = (String)e.get("access_token");
this.expires_in = this.getInt(e, "expires_in");
this.refresh_token = (String)e.get("refresh_token");
this.openid = (String)e.get("openid");
this.unionid = (String)e.get("unionid");
this.scope = (String)e.get("scope");
this.errcode = this.getInt(e, "errcode");
this.errmsg = (String)e.get("errmsg");
if(this.expires_in != null) {
this.expiredTime = Long.valueOf(System.currentTimeMillis() + (long)((this.expires_in.intValue() - 5) * 1000));
}
} catch (Exception var3) {
throw new RuntimeException(var3);
}
}
public String getJson() {
return this.json;
}
private Integer getInt(Map<String, Object> temp, String key) {
Number number = (Number)temp.get(key);
return number == null?null:Integer.valueOf(number.intValue());
}
public String getAccessToken() {
return this.access_token;
}
public Integer getExpiresIn() {
return this.expires_in;
}
public String getRefresh_token() {
return this.refresh_token;
}
public String getOpenid() {
return this.openid;
}
public String getScope() {
return this.scope;
}
public Integer getErrorCode() {
return this.errcode;
}
public String getErrorMsg() {
if(this.errcode != null) {
String result = ReturnCode.get(this.errcode.intValue());
if(result != null) {
return result;
}
}
return this.errmsg;
}
public String getUnionid() {
return this.unionid;
}
}
package com.server.web.common.mapper;
import com.server.web.common.model.TBaseBanner;
import com.server.web.common.model.TBaseBannerExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface TBaseBannerMapper {
long countByExample(TBaseBannerExample example);
int deleteByExample(TBaseBannerExample example);
int deleteByPrimaryKey(Long id);
int insert(TBaseBanner record);
int insertSelective(TBaseBanner record);
List<TBaseBanner> selectByExample(TBaseBannerExample example);
TBaseBanner selectByPrimaryKey(Long id);
int updateByExampleSelective(@Param("record") TBaseBanner record, @Param("example") TBaseBannerExample example);
int updateByExample(@Param("record") TBaseBanner record, @Param("example") TBaseBannerExample example);
int updateByPrimaryKeySelective(TBaseBanner record);
int updateByPrimaryKey(TBaseBanner record);
}
\ No newline at end of file
package com.server.web.common.mapper;
import com.server.web.common.model.TBaseFirstClass;
import com.server.web.common.model.TBaseFirstClassExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface TBaseFirstClassMapper {
long countByExample(TBaseFirstClassExample example);
int deleteByExample(TBaseFirstClassExample example);
int deleteByPrimaryKey(Long id);
int insert(TBaseFirstClass record);
int insertSelective(TBaseFirstClass record);
List<TBaseFirstClass> selectByExample(TBaseFirstClassExample example);
TBaseFirstClass selectByPrimaryKey(Long id);
int updateByExampleSelective(@Param("record") TBaseFirstClass record, @Param("example") TBaseFirstClassExample example);
int updateByExample(@Param("record") TBaseFirstClass record, @Param("example") TBaseFirstClassExample example);
int updateByPrimaryKeySelective(TBaseFirstClass record);
int updateByPrimaryKey(TBaseFirstClass record);
}
\ No newline at end of file
package com.server.web.common.mapper;
import com.server.web.common.model.TBaseSecondClass;
import com.server.web.common.model.TBaseSecondClassExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface TBaseSecondClassMapper {
long countByExample(TBaseSecondClassExample example);
int deleteByExample(TBaseSecondClassExample example);
int deleteByPrimaryKey(Long id);
int insert(TBaseSecondClass record);
int insertSelective(TBaseSecondClass record);
List<TBaseSecondClass> selectByExample(TBaseSecondClassExample example);
TBaseSecondClass selectByPrimaryKey(Long id);
int updateByExampleSelective(@Param("record") TBaseSecondClass record, @Param("example") TBaseSecondClassExample example);
int updateByExample(@Param("record") TBaseSecondClass record, @Param("example") TBaseSecondClassExample example);
int updateByPrimaryKeySelective(TBaseSecondClass record);
int updateByPrimaryKey(TBaseSecondClass record);
}
\ No newline at end of file
package com.server.web.common.mapper;
import com.server.web.common.model.TKzyComment;
import com.server.web.common.model.TKzyCommentExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface TKzyCommentMapper {
long countByExample(TKzyCommentExample example);
int deleteByExample(TKzyCommentExample example);
int deleteByPrimaryKey(Long id);
int insert(TKzyComment record);
int insertSelective(TKzyComment record);
List<TKzyComment> selectByExample(TKzyCommentExample example);
TKzyComment selectByPrimaryKey(Long id);
int updateByExampleSelective(@Param("record") TKzyComment record, @Param("example") TKzyCommentExample example);
int updateByExample(@Param("record") TKzyComment record, @Param("example") TKzyCommentExample example);
int updateByPrimaryKeySelective(TKzyComment record);
int updateByPrimaryKey(TKzyComment record);
}
\ No newline at end of file
package com.server.web.common.mapper;
import com.server.web.common.model.TKzyCourse;
import com.server.web.common.model.TKzyCourseExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface TKzyCourseMapper {
long countByExample(TKzyCourseExample example);
int deleteByExample(TKzyCourseExample example);
int deleteByPrimaryKey(Long id);
int insert(TKzyCourse record);
int insertSelective(TKzyCourse record);
List<TKzyCourse> selectByExampleWithBLOBs(TKzyCourseExample example);
List<TKzyCourse> selectByExample(TKzyCourseExample example);
TKzyCourse selectByPrimaryKey(Long id);
int updateByExampleSelective(@Param("record") TKzyCourse record, @Param("example") TKzyCourseExample example);
int updateByExampleWithBLOBs(@Param("record") TKzyCourse record, @Param("example") TKzyCourseExample example);
int updateByExample(@Param("record") TKzyCourse record, @Param("example") TKzyCourseExample example);
int updateByPrimaryKeySelective(TKzyCourse record);
int updateByPrimaryKeyWithBLOBs(TKzyCourse record);
int updateByPrimaryKey(TKzyCourse record);
}
\ No newline at end of file
package com.server.web.common.mapper;
import com.server.web.common.model.TKzyInformation;
import com.server.web.common.model.TKzyInformationExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface TKzyInformationMapper {
long countByExample(TKzyInformationExample example);
int deleteByExample(TKzyInformationExample example);
int deleteByPrimaryKey(Long id);
int insert(TKzyInformation record);
int insertSelective(TKzyInformation record);
List<TKzyInformation> selectByExampleWithBLOBs(TKzyInformationExample example);
List<TKzyInformation> selectByExample(TKzyInformationExample example);
TKzyInformation selectByPrimaryKey(Long id);
int updateByExampleSelective(@Param("record") TKzyInformation record, @Param("example") TKzyInformationExample example);
int updateByExampleWithBLOBs(@Param("record") TKzyInformation record, @Param("example") TKzyInformationExample example);
int updateByExample(@Param("record") TKzyInformation record, @Param("example") TKzyInformationExample example);
int updateByPrimaryKeySelective(TKzyInformation record);
int updateByPrimaryKeyWithBLOBs(TKzyInformation record);
int updateByPrimaryKey(TKzyInformation record);
}
\ No newline at end of file
package com.server.web.common.mapper;
import com.server.web.common.model.TKzyRelationClass;
import com.server.web.common.model.TKzyRelationClassExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface TKzyRelationClassMapper {
long countByExample(TKzyRelationClassExample example);
int deleteByExample(TKzyRelationClassExample example);
int deleteByPrimaryKey(Long id);
int insert(TKzyRelationClass record);
int insertSelective(TKzyRelationClass record);
List<TKzyRelationClass> selectByExample(TKzyRelationClassExample example);
TKzyRelationClass selectByPrimaryKey(Long id);
int updateByExampleSelective(@Param("record") TKzyRelationClass record, @Param("example") TKzyRelationClassExample example);
int updateByExample(@Param("record") TKzyRelationClass record, @Param("example") TKzyRelationClassExample example);
int updateByPrimaryKeySelective(TKzyRelationClass record);
int updateByPrimaryKey(TKzyRelationClass record);
}
\ No newline at end of file
package com.server.web.common.mapper;
import com.server.web.common.model.TKzyUserIntegralFlowing;
import com.server.web.common.model.TKzyUserIntegralFlowingExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface TKzyUserIntegralFlowingMapper {
long countByExample(TKzyUserIntegralFlowingExample example);
int deleteByExample(TKzyUserIntegralFlowingExample example);
int deleteByPrimaryKey(Long id);
int insert(TKzyUserIntegralFlowing record);
int insertSelective(TKzyUserIntegralFlowing record);
List<TKzyUserIntegralFlowing> selectByExample(TKzyUserIntegralFlowingExample example);
TKzyUserIntegralFlowing selectByPrimaryKey(Long id);
int updateByExampleSelective(@Param("record") TKzyUserIntegralFlowing record, @Param("example") TKzyUserIntegralFlowingExample example);
int updateByExample(@Param("record") TKzyUserIntegralFlowing record, @Param("example") TKzyUserIntegralFlowingExample example);
int updateByPrimaryKeySelective(TKzyUserIntegralFlowing record);
int updateByPrimaryKey(TKzyUserIntegralFlowing record);
}
\ No newline at end of file
package com.server.web.common.mapper;
import com.server.web.common.model.TKzyUser;
import com.server.web.common.model.TKzyUserExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface TKzyUserMapper {
long countByExample(TKzyUserExample example);
int deleteByExample(TKzyUserExample example);
int deleteByPrimaryKey(Long id);
int insert(TKzyUser record);
int insertSelective(TKzyUser record);
List<TKzyUser> selectByExample(TKzyUserExample example);
TKzyUser selectByPrimaryKey(Long id);
int updateByExampleSelective(@Param("record") TKzyUser record, @Param("example") TKzyUserExample example);
int updateByExample(@Param("record") TKzyUser record, @Param("example") TKzyUserExample example);
int updateByPrimaryKeySelective(TKzyUser record);
int updateByPrimaryKey(TKzyUser record);
}
\ No newline at end of file
package com.server.web.common.mapping;
import java.util.List;
import java.util.Map;
/**
* Created by weiwenfu@163.com on 2020/3/12 下午 2:58.
*/
public interface CommentMapper {
List<Map<String,Object>> commentList(Long courseId, int i, Integer pageSize);
Integer commentListTotal(Long courseId);
}
package com.server.web.common.mapping;
import java.util.List;
import java.util.Map;
/**
* Created by weiwenfu@163.com on 2020/3/12 下午 2:58.
*/
public interface CourseMapper {
List<Map<String,Object>> recordCourse(Map<String, Object> param);
List<Map<String,Object>> livingCourse(Map<String, Object> param);
List<Map<String,Object>> hotCourse(Map<String, Object> param);
}
package com.server.web.common.model;
import java.io.Serializable;
public class BaseModel implements Serializable {
}
package com.server.web.common.model;
import java.util.Date;
public class TBaseBanner extends BaseModel {
private Long id;
private String title;
private String picUrl;
private Integer weight;
private Integer jumpType;
private String jumpAddress;
private String remark;
private Integer isDelete;
private Integer isUp;
private Date createDt;
public TBaseBanner(Long id, String title, String picUrl, Integer weight, Integer jumpType, String jumpAddress, String remark, Integer isDelete, Integer isUp, Date createDt) {
this.id = id;
this.title = title;
this.picUrl = picUrl;
this.weight = weight;
this.jumpType = jumpType;
this.jumpAddress = jumpAddress;
this.remark = remark;
this.isDelete = isDelete;
this.isUp = isUp;
this.createDt = createDt;
}
public TBaseBanner() {
super();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title == null ? null : title.trim();
}
public String getPicUrl() {
return picUrl;
}
public void setPicUrl(String picUrl) {
this.picUrl = picUrl == null ? null : picUrl.trim();
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
public Integer getJumpType() {
return jumpType;
}
public void setJumpType(Integer jumpType) {
this.jumpType = jumpType;
}
public String getJumpAddress() {
return jumpAddress;
}
public void setJumpAddress(String jumpAddress) {
this.jumpAddress = jumpAddress == null ? null : jumpAddress.trim();
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark == null ? null : remark.trim();
}
public Integer getIsDelete() {
return isDelete;
}
public void setIsDelete(Integer isDelete) {
this.isDelete = isDelete;
}
public Integer getIsUp() {
return isUp;
}
public void setIsUp(Integer isUp) {
this.isUp = isUp;
}
public Date getCreateDt() {
return createDt;
}
public void setCreateDt(Date createDt) {
this.createDt = createDt;
}
}
\ No newline at end of file
package com.server.web.common.model;
import java.util.Date;
public class TBaseFirstClass extends BaseModel {
private Long id;
private String className;
private Integer status;
private String picUrl;
private Integer weight;
private Date createDt;
public TBaseFirstClass(Long id, String className, Integer status, String picUrl, Integer weight, Date createDt) {
this.id = id;
this.className = className;
this.status = status;
this.picUrl = picUrl;
this.weight = weight;
this.createDt = createDt;
}
public TBaseFirstClass() {
super();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className == null ? null : className.trim();
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getPicUrl() {
return picUrl;
}
public void setPicUrl(String picUrl) {
this.picUrl = picUrl == null ? null : picUrl.trim();
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
public Date getCreateDt() {
return createDt;
}
public void setCreateDt(Date createDt) {
this.createDt = createDt;
}
}
\ No newline at end of file
package com.server.web.common.model;
import java.util.Date;
public class TBaseSecondClass extends BaseModel {
private Long id;
private String className;
private Integer status;
private Integer type;
private String picUrl;
private Long firstId;
private Integer weight;
private Date createDt;
public TBaseSecondClass(Long id, String className, Integer status, Integer type, String picUrl, Long firstId, Integer weight, Date createDt) {
this.id = id;
this.className = className;
this.status = status;
this.type = type;
this.picUrl = picUrl;
this.firstId = firstId;
this.weight = weight;
this.createDt = createDt;
}
public TBaseSecondClass() {
super();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className == null ? null : className.trim();
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public String getPicUrl() {
return picUrl;
}
public void setPicUrl(String picUrl) {
this.picUrl = picUrl == null ? null : picUrl.trim();
}
public Long getFirstId() {
return firstId;
}
public void setFirstId(Long firstId) {
this.firstId = firstId;
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
public Date getCreateDt() {
return createDt;
}
public void setCreateDt(Date createDt) {
this.createDt = createDt;
}
}
\ No newline at end of file
package com.server.web.common.model;
import java.util.Date;
public class TKzyComment extends BaseModel {
private Long id;
private Long userId;
private Long relationId;
private Integer type;
private String replyContent;
private Integer isDelete;
private Integer authStatus;
private Date authDt;
private Date createDt;
public TKzyComment(Long id, Long userId, Long relationId, Integer type, String replyContent, Integer isDelete, Integer authStatus, Date authDt, Date createDt) {
this.id = id;
this.userId = userId;
this.relationId = relationId;
this.type = type;
this.replyContent = replyContent;
this.isDelete = isDelete;
this.authStatus = authStatus;
this.authDt = authDt;
this.createDt = createDt;
}
public TKzyComment() {
super();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Long getRelationId() {
return relationId;
}
public void setRelationId(Long relationId) {
this.relationId = relationId;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public String getReplyContent() {
return replyContent;
}
public void setReplyContent(String replyContent) {
this.replyContent = replyContent == null ? null : replyContent.trim();
}
public Integer getIsDelete() {
return isDelete;
}
public void setIsDelete(Integer isDelete) {
this.isDelete = isDelete;
}
public Integer getAuthStatus() {
return authStatus;
}
public void setAuthStatus(Integer authStatus) {
this.authStatus = authStatus;
}
public Date getAuthDt() {
return authDt;
}
public void setAuthDt(Date authDt) {
this.authDt = authDt;
}
public Date getCreateDt() {
return createDt;
}
public void setCreateDt(Date createDt) {
this.createDt = createDt;
}
}
\ No newline at end of file
package com.server.web.common.model;
import java.util.Date;
public class TKzyCourse extends BaseModel {
private Long id;
private String courseName;
private String picUrl;
private Date startDt;
private Date endDt;
private Integer weight;
private String liveUrl;
private Integer courseType;
private Integer isUp;
private Long editorId;
private String editorName;
private Integer isDelete;
private Date createDt;
private Date updateDt;
private String courseIntroduce;
public TKzyCourse(Long id, String courseName, String picUrl, Date startDt, Date endDt, Integer weight, String liveUrl, Integer courseType, Integer isUp, Long editorId, String editorName, Integer isDelete, Date createDt, Date updateDt, String courseIntroduce) {
this.id = id;
this.courseName = courseName;
this.picUrl = picUrl;
this.startDt = startDt;
this.endDt = endDt;
this.weight = weight;
this.liveUrl = liveUrl;
this.courseType = courseType;
this.isUp = isUp;
this.editorId = editorId;
this.editorName = editorName;
this.isDelete = isDelete;
this.createDt = createDt;
this.updateDt = updateDt;
this.courseIntroduce = courseIntroduce;
}
public TKzyCourse() {
super();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName == null ? null : courseName.trim();
}
public String getPicUrl() {
return picUrl;
}
public void setPicUrl(String picUrl) {
this.picUrl = picUrl == null ? null : picUrl.trim();
}
public Date getStartDt() {
return startDt;
}
public void setStartDt(Date startDt) {
this.startDt = startDt;
}
public Date getEndDt() {
return endDt;
}
public void setEndDt(Date endDt) {
this.endDt = endDt;
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
public String getLiveUrl() {
return liveUrl;
}
public void setLiveUrl(String liveUrl) {
this.liveUrl = liveUrl == null ? null : liveUrl.trim();
}
public Integer getCourseType() {
return courseType;
}
public void setCourseType(Integer courseType) {
this.courseType = courseType;
}
public Integer getIsUp() {
return isUp;
}
public void setIsUp(Integer isUp) {
this.isUp = isUp;
}
public Long getEditorId() {
return editorId;
}
public void setEditorId(Long editorId) {
this.editorId = editorId;
}
public String getEditorName() {
return editorName;
}
public void setEditorName(String editorName) {
this.editorName = editorName == null ? null : editorName.trim();
}
public Integer getIsDelete() {
return isDelete;
}
public void setIsDelete(Integer isDelete) {
this.isDelete = isDelete;
}
public Date getCreateDt() {
return createDt;
}
public void setCreateDt(Date createDt) {
this.createDt = createDt;
}
public Date getUpdateDt() {
return updateDt;
}
public void setUpdateDt(Date updateDt) {
this.updateDt = updateDt;
}
public String getCourseIntroduce() {
return courseIntroduce;
}
public void setCourseIntroduce(String courseIntroduce) {
this.courseIntroduce = courseIntroduce == null ? null : courseIntroduce.trim();
}
}
\ No newline at end of file
package com.server.web.common.model;
import java.util.Date;
public class TKzyInformation extends BaseModel {
private Long id;
private String title;
private String author;
private String picUrl;
private String iconUrl;
private Integer isDelete;
private Date createDt;
private Date updateDt;
private byte[] content;
public TKzyInformation(Long id, String title, String author, String picUrl, String iconUrl, Integer isDelete, Date createDt, Date updateDt, byte[] content) {
this.id = id;
this.title = title;
this.author = author;
this.picUrl = picUrl;
this.iconUrl = iconUrl;
this.isDelete = isDelete;
this.createDt = createDt;
this.updateDt = updateDt;
this.content = content;
}
public TKzyInformation() {
super();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title == null ? null : title.trim();
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author == null ? null : author.trim();
}
public String getPicUrl() {
return picUrl;
}
public void setPicUrl(String picUrl) {
this.picUrl = picUrl == null ? null : picUrl.trim();
}
public String getIconUrl() {
return iconUrl;
}
public void setIconUrl(String iconUrl) {
this.iconUrl = iconUrl == null ? null : iconUrl.trim();
}
public Integer getIsDelete() {
return isDelete;
}
public void setIsDelete(Integer isDelete) {
this.isDelete = isDelete;
}
public Date getCreateDt() {
return createDt;
}
public void setCreateDt(Date createDt) {
this.createDt = createDt;
}
public Date getUpdateDt() {
return updateDt;
}
public void setUpdateDt(Date updateDt) {
this.updateDt = updateDt;
}
public byte[] getContent() {
return content;
}
public void setContent(byte[] content) {
this.content = content;
}
}
\ No newline at end of file
package com.server.web.common.model;
import java.util.Date;
public class TKzyRelationClass extends BaseModel {
private Long id;
private Long relationId;
private Long firstClassId;
private Long secondClassId;
private Date createDt;
public TKzyRelationClass(Long id, Long relationId, Long firstClassId, Long secondClassId, Date createDt) {
this.id = id;
this.relationId = relationId;
this.firstClassId = firstClassId;
this.secondClassId = secondClassId;
this.createDt = createDt;
}
public TKzyRelationClass() {
super();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getRelationId() {
return relationId;
}
public void setRelationId(Long relationId) {
this.relationId = relationId;
}
public Long getFirstClassId() {
return firstClassId;
}
public void setFirstClassId(Long firstClassId) {
this.firstClassId = firstClassId;
}
public Long getSecondClassId() {
return secondClassId;
}
public void setSecondClassId(Long secondClassId) {
this.secondClassId = secondClassId;
}
public Date getCreateDt() {
return createDt;
}
public void setCreateDt(Date createDt) {
this.createDt = createDt;
}
}
\ No newline at end of file
package com.server.web.common.model;
import java.util.Date;
public class TKzyUser extends BaseModel {
private Long id;
private String fullName;
private String headPhoto;
private String phone;
private Integer userCategory;
private String duty;
private Integer status;
private String wxOpenid;
private Integer integral;
private Integer signInCount;
private Date lastSignDt;
private Date createDt;
private Date lastLoginDt;
public TKzyUser(Long id, String fullName, String headPhoto, String phone, Integer userCategory, String duty, Integer status, String wxOpenid, Integer integral, Integer signInCount, Date lastSignDt, Date createDt, Date lastLoginDt) {
this.id = id;
this.fullName = fullName;
this.headPhoto = headPhoto;
this.phone = phone;
this.userCategory = userCategory;
this.duty = duty;
this.status = status;
this.wxOpenid = wxOpenid;
this.integral = integral;
this.signInCount = signInCount;
this.lastSignDt = lastSignDt;
this.createDt = createDt;
this.lastLoginDt = lastLoginDt;
}
public TKzyUser() {
super();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName == null ? null : fullName.trim();
}
public String getHeadPhoto() {
return headPhoto;
}
public void setHeadPhoto(String headPhoto) {
this.headPhoto = headPhoto == null ? null : headPhoto.trim();
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone == null ? null : phone.trim();
}
public Integer getUserCategory() {
return userCategory;
}
public void setUserCategory(Integer userCategory) {
this.userCategory = userCategory;
}
public String getDuty() {
return duty;
}
public void setDuty(String duty) {
this.duty = duty == null ? null : duty.trim();
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getWxOpenid() {
return wxOpenid;
}
public void setWxOpenid(String wxOpenid) {
this.wxOpenid = wxOpenid == null ? null : wxOpenid.trim();
}
public Integer getIntegral() {
return integral;
}
public void setIntegral(Integer integral) {
this.integral = integral;
}
public Integer getSignInCount() {
return signInCount;
}
public void setSignInCount(Integer signInCount) {
this.signInCount = signInCount;
}
public Date getLastSignDt() {
return lastSignDt;
}
public void setLastSignDt(Date lastSignDt) {
this.lastSignDt = lastSignDt;
}
public Date getCreateDt() {
return createDt;
}
public void setCreateDt(Date createDt) {
this.createDt = createDt;
}
public Date getLastLoginDt() {
return lastLoginDt;
}
public void setLastLoginDt(Date lastLoginDt) {
this.lastLoginDt = lastLoginDt;
}
}
\ No newline at end of file
package com.server.web.common.model;
import java.util.Date;
public class TKzyUserIntegralFlowing extends BaseModel {
private Long id;
private Long userId;
private Integer integral;
private Integer sourceType;
private Integer type;
private Date createDt;
private String remark;
public TKzyUserIntegralFlowing(Long id, Long userId, Integer integral, Integer sourceType, Integer type, Date createDt, String remark) {
this.id = id;
this.userId = userId;
this.integral = integral;
this.sourceType = sourceType;
this.type = type;
this.createDt = createDt;
this.remark = remark;
}
public TKzyUserIntegralFlowing() {
super();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Integer getIntegral() {
return integral;
}
public void setIntegral(Integer integral) {
this.integral = integral;
}
public Integer getSourceType() {
return sourceType;
}
public void setSourceType(Integer sourceType) {
this.sourceType = sourceType;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public Date getCreateDt() {
return createDt;
}
public void setCreateDt(Date createDt) {
this.createDt = createDt;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark == null ? null : remark.trim();
}
}
\ No newline at end of file
package com.server.web.common.service.Impl;
import com.server.web.common.mapper.TBaseBannerMapper;
import com.server.web.common.model.TBaseBanner;
import com.server.web.common.model.TBaseBannerExample;
import com.server.web.common.service.IndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by weiwenfu@163.com on 2018/12/12 下午 3:05.
*/
@Service
public class IndexServiceImpl implements IndexService {
@Autowired
private TBaseBannerMapper tBaseBannerMapper;
@Override
public Map<String, Object> banner() {
TBaseBannerExample tBaseBannerExample = new TBaseBannerExample();
tBaseBannerExample.createCriteria().andIsUpEqualTo(1).andIsDeleteEqualTo(0);
tBaseBannerExample.setOrderByClause(" weight desc ");
List<TBaseBanner> list = tBaseBannerMapper.selectByExample(tBaseBannerExample);
Map<String, Object> resultMap = new HashMap<String, Object>();
resultMap.put("status", "1");
resultMap.put("message", "");
resultMap.put("data", list);
return resultMap;
}
}
package com.server.web.common.service.Impl;
import com.server.web.common.service.OpenSqlRingsService;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 指环王工具
* Created by yinbin on 2018/1/12.
* 自定义sql执行工具类
* 功能:通过sql的命名空间,指定执行xml里的sql
* 1、增删改查
* 2、批量增加
*/
@Service
public class OpenSqlRingsServiceImpl implements OpenSqlRingsService {
@Autowired
private SqlSessionTemplate sqlSession;
// @Autowired
// private DataSourceTransactionManager transactionManager;
@Override
public Object selectOne_Rings(String statement, Map<String, Object> params) {
Object obj = sqlSession.selectOne(statement, params);
return obj;
}
@Override
public ArrayList<Object> selectList_Rings(String statement, Map<String, Object> params) {
ArrayList<Object> resultList = (ArrayList<Object>) sqlSession.selectList(statement, params);
return resultList;
}
@Override
@Transactional
public void insert_Rings(String statement, Map<String, Object> params) {
sqlSession.insert(statement, params);
}
@Override
@Transactional
public void delete_Rings(String statement, Map<String, Object> params) {
sqlSession.delete(statement, params);
}
@Override
@Transactional
public void update_Rings(String statement, Map<String, Object> params) {
sqlSession.update(statement, params);
}
@Override
@Transactional
public void insert_batch_Rings(String statement, List<Map<String, Object>> params) {
for (Map<String, Object> map : params) {
sqlSession.insert(statement, map);
}
}
@Override
public void insert_batch11_Rings(String statement, List<Map<String, Object>> params, int per) {
//
// //事物定义类
// DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED);
// //获取事物对象
// TransactionStatus status = transactionManager.getTransaction(transactionDefinition);
//
// try {
// for (Map<String, Object> map : params) {
// sqlSession.insert(statement, map);
// }
// //插入成功提交事物
// transactionManager.commit(status);
// } catch (Exception e) {
// //异常回滚事物
// transactionManager.rollback(status);
// }
}
}
package com.server.web.common.service.Impl;
import com.server.web.common.model.TKzyUser;
import com.server.web.common.service.UserService;
/**
* Created by 豆腐干Sama on 2018/12/6.
*/
public class UserServiceImpl implements UserService {
@Override
public void save(TKzyUser user) {
}
}
package com.server.web.common.service;
import java.util.Map;
/**
* Created by weiwenfu@163.com on 2018/12/12 下午 3:05.
*/
public interface IndexService {
Map<String,Object> banner();
}
package com.server.web.common.service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Created by yinbin on 2018/1/15.
*/
public interface OpenSqlRingsService {
Object selectOne_Rings(String statement, Map<String, Object> params);
ArrayList<Object> selectList_Rings(String statement, Map<String, Object> params);
@Transactional
void insert_Rings(String statement, Map<String, Object> params);
@Transactional
void delete_Rings(String statement, Map<String, Object> params);
@Transactional
void update_Rings(String statement, Map<String, Object> params);
@Transactional
void insert_batch_Rings(String statement, List<Map<String, Object>> params);
void insert_batch11_Rings(String statement, List<Map<String, Object>> params, int per);
}
package com.server.web.common.service;
import com.server.web.common.model.TKzyCourse;
import java.util.Map;
/**
* Created by weiwenfu@163.com on 2018/12/5 下午 1:45.
*/
public interface TKzyCourseService {
Map<String,Object> hotCourse();
Map<String,Object> livingCourse();
Map<String,Object> recordCourse(Long typeId,Integer pageNo, Integer pageSize);
Map<String,Object> livingCourseDetail(Long courseId,Long userId);
Map<String,Object> recordCourseDetail(Long courseId,Long userId);
Map<String,Object> commentList(Long courseId,Integer pageNo, Integer pageSize);
Map<String,Object> comment(Long courseId, Long userId, String comment);
Map<String,Object> courseType();
TKzyCourse selectByPrimaryKey(Long courseId);
}
package com.server.web.common.service;
import com.server.web.common.model.TKzyUser;
/**
* Created by 豆腐干Sama on 2018/12/6.
*/
public interface UserService {
void save(TKzyUser user);
}
package com.server.web.controller;
import com.server.utils.weixin.WeixinBaseUtil;
import com.server.utils.weixin.bean.AccessTokenBean;
import com.server.web.common.mapper.TKzyUserMapper;
import com.server.web.common.model.TKzyUser;
import com.server.web.common.model.TKzyUserExample;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* Created by dell on 2018/8/27.
*/
public class BaseController {
public final static String WX_NAMESPACE = "/rest";
@Autowired
RedisTemplate redisTemplate;
@Autowired
TKzyUserMapper userMapper;
Logger logger = LoggerFactory.getLogger(getClass());
public final static String WX_USER_SESSION_KEY = "weixin_user_session_key";
/**
* 获取appaccessToken
* @param appId
* @return
*/
public String getAccessToken(String appId,String appSecret){
if(StringUtils.hasText(appSecret)){
String json ="";
boolean redisAccessToken = true;
if(redisTemplate.hasKey("wx_accessToken_"+appId)){
json = (String)redisTemplate.opsForValue().get("wx_accessToken_"+appId);
if(StringUtils.hasText(json)){
redisAccessToken =false;
}
}
if(redisAccessToken){
String url = WeixinBaseUtil.ACCESS_TOKEN_URL + "&appid=" + appId + "&secret=" + appSecret;
RestTemplate restTemplate = new RestTemplate();
json = restTemplate.getForObject(url, String.class);
redisTemplate.opsForValue().set("wx_accessToken_"+appId,json,60*60, TimeUnit.SECONDS);
}
AccessTokenBean accessTokenBean = new AccessTokenBean(json);
return accessTokenBean.getAccessToken();
}else{
return null;
}
}
public Map<String,Object> returnSuccess(Object obj){
Map<String,Object> returnResult = new HashMap<String,Object>();
returnResult.put("status", "1");
returnResult.put("message","操作成功");
returnResult.put("data",obj);
return returnResult;
}
public Map<String,Object> returnError(String code, String message ,Object obj){
Map<String,Object> returnResult = new HashMap<String,Object>();
returnResult.put("status", code);
returnResult.put("message",message);
returnResult.put("data",obj);
return returnResult;
}
public TKzyUser getLoginUser(HttpServletRequest request){
TKzyUser user;
if(request.getSession().getAttribute(WX_USER_SESSION_KEY)!=null){
user = (TKzyUser)request.getSession().getAttribute(WX_USER_SESSION_KEY);
return user;
}
String userId = request.getParameter("userId");
String wxOpenId = request.getParameter("wxOpenId");
if(StringUtils.isEmpty(userId) || StringUtils.isEmpty(wxOpenId)){
return null;
}
TKzyUserExample example = new TKzyUserExample();
example.createCriteria().andWxOpenidEqualTo(wxOpenId).andIdEqualTo(Long.parseLong(userId));
List<TKzyUser> users = userMapper.selectByExample(example);
if (CollectionUtils.isEmpty(users)) {
return null;
}
user = users.get(0);
request.getSession().setAttribute(WX_USER_SESSION_KEY,user);
return user;
}
}
package com.server.web.controller;
import com.server.web.common.mapper.TKzyUserMapper;
import com.server.web.common.model.TKzyCourse;
import com.server.web.common.model.TKzyUser;
import com.server.web.common.service.TKzyCourseService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* 课程相关action
* Created by weiwenfu@163.com on 2018/12/5 上午 11:56.
*/
@SpringBootApplication
@RestController
@RequestMapping(BaseController.WX_NAMESPACE + "/course")
@ControllerAdvice
public class CourseController extends BaseController{
@Autowired
private TKzyCourseService tKzyCourseService;
@Autowired
private TKzyUserMapper tKzyUserMapper;
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private RestTemplate restTemplate;
@Value("${wx.http.danmu.url}")
private String danmuUrl;
/**
* 热门课程
* @return
*/
@RequestMapping("/hotCourse")
public Map<String,Object> hotCourse(){
return tKzyCourseService.hotCourse();
}
/**
* 录播课列表
* @return
*/
@RequestMapping("/recordCourse")
public Map<String,Object> recordCourse(@RequestParam(value = "typeId",required = false) Long typeId, @RequestParam(value = "pageNo",required = false) Integer pageNo, @RequestParam(value = "pageSize",required = false) Integer pageSize){
return tKzyCourseService.recordCourse(typeId,pageNo,pageSize);
}
/**
* 直播课列表(全查)
* @return
*/
@RequestMapping("/livingCourse")
public Map<String,Object> livingCourse(){
return tKzyCourseService.livingCourse();
}
/**
* 直播课详情页
* @return
*/
@RequestMapping("/livingCourseDetail")
public Map<String,Object> livingCourseDetail(HttpServletRequest request,@RequestParam(value = "courseId",required = true) Long courseId){
TKzyUser tKzyUser = getLoginUser(request);
Long userId = null;
if(tKzyUser!=null){
userId = tKzyUser.getId();
}
return tKzyCourseService.livingCourseDetail(courseId,userId);
}
/**
* 录播课详情页
* @return
*/
@RequestMapping("/recordCourseDetail")
public Map<String,Object> recordCourseDetail(HttpServletRequest request,@RequestParam(value = "courseId",required = true) Long courseId){
TKzyUser tKzyUser = getLoginUser(request);
Long userId = null;
if(tKzyUser!=null){
userId = tKzyUser.getId();
}
return tKzyCourseService.recordCourseDetail(courseId,userId);
}
/**
* 评论列表
* @param courseId
* @return
*/
@RequestMapping("/commentList")
public Map<String,Object> commentList(@RequestParam(value = "courseId",required = true) Long courseId,@RequestParam(value = "pageNo",required = false) Integer pageNo, @RequestParam(value = "pageSize",required = false) Integer pageSize){
return tKzyCourseService.commentList(courseId,pageNo,pageSize);
}
/**
* 提交评论
* @param courseId
* @param comment
* @return
*/
@RequestMapping("/comment")
public Map<String,Object> comment(HttpServletRequest request,@RequestParam(value = "courseId",required = true) Long courseId, @RequestParam(value = "comment",required = true) String comment){
TKzyUser tKzyUser = getLoginUser(request);
Long userId = null;
if(tKzyUser!=null){
userId = tKzyUser.getId();
}
return tKzyCourseService.comment(courseId,userId,comment);
}
/**
* 课程分类
* @return
*/
@RequestMapping("/courseType")
public Map<String,Object> courseType(){
return tKzyCourseService.courseType();
}
/**
* 送花(此处只是调用前端的服务)
* @return
*/
@RequestMapping("/sendFlower")
public Map<String,Object> sendFlower(HttpServletRequest request,@RequestParam(value = "courseId") Long courseId){
Map<String,Object> resultMap = new HashMap<String,Object>();
resultMap.put("status","0");
resultMap.put("message","");
String giftUrl = "http://cdn.yxvzb.com/WEB/wx-master/images/gift1.png";
TKzyUser tKzyUser = getLoginUser(request);
if(tKzyUser==null){
resultMap.put("message","请先登录~");
resultMap.put("status","-1");
return resultMap;
}
TKzyCourse tKzyCourse = tKzyCourseService.selectByPrimaryKey(courseId);
if(tKzyCourse==null){
resultMap.put("message","课程信息有误,请确认~");
return resultMap;
}
//每分钟可赠送五次礼物,超出则吐丝提示:礼物赠送频繁,请稍后赠送
ValueOperations vv = redisTemplate.opsForValue();
Integer count = (Integer) vv.get("WX_FLOWER_COURSE_"+tKzyUser.getId()+"_"+courseId);
if(count!=null && count>=5){
resultMap.put("message","礼物赠送频繁,请稍后赠送~");
return resultMap;
}
try {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, Object> valueMap = new LinkedMultiValueMap<>();
valueMap.add("type",2+"");
valueMap.add("courseId", courseId+"");
valueMap.add("giftType", 2+"");
valueMap.add("userId",tKzyUser.getId()+"");
valueMap.add("giftCount",1+"");
valueMap.add("giftImg",giftUrl);
valueMap.add("giftName","鲜花");
valueMap.add("channelId","Kzy"+courseId+"");
if (StringUtils.isEmpty(tKzyUser.getFullName())) {
valueMap.add("userName",tKzyUser.getFullName());
}else {
valueMap.add("userName",tKzyUser.getFullName());
}
Date liveEndTime = tKzyCourse.getEndDt();
valueMap.add("liveEndTime",liveEndTime.getTime()+"");
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(valueMap, headers);
ResponseEntity<String> response = restTemplate.exchange(danmuUrl + "/sendGift", HttpMethod.POST, requestEntity, String.class);
System.out.println(tKzyUser.getId()+"送花返回:"+response);
vv.set("WX_FLOWER_COURSE_"+tKzyUser.getId()+"_"+courseId,(count==null?1:count+1),1, TimeUnit.MINUTES);
} catch (Exception e) {
e.printStackTrace();
}
resultMap.put("status","1");
return resultMap;
}
/**
* 临时设置登录信息
* @param request
* @param userId
* @return
*/
@RequestMapping("/tmpSetSession")
public Map<String,Object> tmpSetSession(HttpServletRequest request,@RequestParam(value = "userId",required = true) Long userId){
Map<String,Object> resultMap = new HashMap<String,Object>();
resultMap.put("status","0");
resultMap.put("message","");
if(userId==null||userId<=0l){
resultMap.put("message","用户ID不能为空~");
return resultMap;
}
TKzyUser tKzyUser = tKzyUserMapper.selectByPrimaryKey(userId);
if(tKzyUser!=null){
request.getSession().setAttribute(WX_USER_SESSION_KEY,tKzyUser);
resultMap.put("message","操作成功~");
return resultMap;
}else{
resultMap.put("message","未查到该用户信息~");
return resultMap;
}
}
}
package com.server.web.controller;
import com.server.web.common.service.IndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
/**
* 首页相关
* Created by weiwenfu@163.com on 2018/12/12 下午 3:03.
*/
@RestController
@RequestMapping(value = BaseController.WX_NAMESPACE + "/index",produces = "application/json")
public class IndexController {
@Autowired
private IndexService indexService;
/**
* banner
* @return
*/
@RequestMapping("/banner")
public Map<String,Object> banner(){
return indexService.banner();
}
}
package com.server.web.controller;
import com.server.utils.SendSMSUtil;
import com.server.utils.VerifyCodeUtils;
import com.server.web.common.model.TKzyUser;
import com.server.web.common.model.TKzyUserExample;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
* Created by 豆腐干Sama on 2018/12/6.
*/
@RestController
@RequestMapping(value = BaseController.WX_NAMESPACE + "/user",produces = "application/json")
public class UserController extends BaseController {
@GetMapping("/userData")
public Map userData(HttpServletRequest request) {
TKzyUser loginUser = getLoginUser(request);
return returnSuccess(loginUser);
}
@PostMapping("/register")
public Map register(HttpServletRequest request) {
TKzyUser user= getLoginUser(request);
String phone = request.getParameter("phone");
String verifyCode = request.getParameter("verifyCode");
String wxOpenId = request.getParameter("wxOpenId");
if(phone==null||!phone.matches("^((1[3-9]))\\d{9}$")){
return returnError("0","请输入有效的手机号码",null);
}
if(verifyCode==null){
return returnError("0","请输入有效的验证码!",null);
}
if (user== null) {
return returnError("0","未登录",null);
}
ValueOperations operations = redisTemplate.opsForValue();
String cacheCode = (String)operations.get("Kzy_WX_LOGIN_SMS_PHONE_" + phone);
if (StringUtils.isEmpty(cacheCode) || !cacheCode.equals(verifyCode)) {
return returnError("0","短信验证码有误,或已失效!",null);
} else {
redisTemplate.delete("Kzy_WX_LOGIN_SMS_PHONE_" + phone);
}
TKzyUserExample example = new TKzyUserExample();
example.createCriteria().andPhoneEqualTo(phone);
List<TKzyUser> users = userMapper.selectByExample(example);
if (!CollectionUtils.isEmpty(users)) {
TKzyUser user1 = users.get(0);
if (!StringUtils.isEmpty(user1.getWxOpenid()) && !wxOpenId.equals(user1.getWxOpenid())) {
return returnError("0","该微信已绑定其他手机号",null);
}
}
String fullName = request.getParameter("fullName");
String duty = request.getParameter("duty");
user.setWxOpenid(wxOpenId);
user.setCreateDt(new Date());
user.setDuty(duty);
user.setFullName(fullName);
user.setPhone(phone);
user.setStatus(1);
userMapper.insertSelective(user);
request.getSession().setAttribute(WX_USER_SESSION_KEY,user);
return returnSuccess(user);
}
@PostMapping("/update")
public Map update(HttpServletRequest request) {
TKzyUser loginUser = getLoginUser(request);
if (loginUser == null) {
return returnError("0","用户未登录",null);
}
String wxOpenId = request.getParameter("wxOpenId");
String fullName = request.getParameter("fullName");
String duty = request.getParameter("duty");
loginUser.setWxOpenid(wxOpenId);
loginUser.setDuty(duty);
loginUser.setFullName(fullName);
userMapper.updateByPrimaryKeySelective(loginUser);
request.getSession().setAttribute(WX_USER_SESSION_KEY,loginUser);
return returnSuccess(loginUser);
}
/**
* 发送短信
* @param request
* @return
*/
@ResponseBody
@RequestMapping(path = "/sendMessageCode", method = {RequestMethod.POST, RequestMethod.GET}, produces = "application/json")
public Map<String, Object> sendMessageCode(HttpServletRequest request) {
Map<String,Object> resultMap = new HashMap<String,Object>();
resultMap.put("status","0");
resultMap.put("message","");
String imgVerifyCode = request.getParameter("imgVerifyCode");
String phone = request.getParameter("phone");
String failPhone = request.getSession().getAttribute("fail_"+phone)==null?null:request.getSession().getAttribute("fail_"+phone).toString();
int count = 0;
if(failPhone!=null && org.apache.commons.lang.math.NumberUtils.isNumber(failPhone)){
count = Integer.valueOf(failPhone);
}
if(phone==null||!phone.matches("^((1[3-9]))\\d{9}$")){
resultMap.put("message","请输入有效的手机号码!");
request.getSession().setAttribute("fail_"+phone,count+1);
if(count+1>=3){
resultMap.put("imgFlag","1");
}
return resultMap;
}
ValueOperations vv = redisTemplate.opsForValue();
if(imgVerifyCode!=null&&!"".equals(imgVerifyCode)){
String redisImageCode = (String)vv.get("Kzy_IMAGE_CODE_" + phone);
if(redisImageCode==null||!redisImageCode.toUpperCase().equals(imgVerifyCode.toUpperCase())){
resultMap.put("message","请输入正确的图形验证码!");
return resultMap;
} else {
redisTemplate.delete("Kzy_IMAGE_CODE_"+phone);
}
}
if(vv.get("Kzy_WX_LOGIN_SMS_PHONE_FLAG_" + phone)!=null){//缓存标识,缓存里存在,表示还在有效期内,不重复发送
resultMap.put("message","您发送的短信验证码尚在有效期,无需重复发送");
request.getSession().setAttribute("fail_"+phone,count+1);
if(count+1>=3){
resultMap.put("imgFlag","1");
}
return resultMap;
}
String randomCode = getRandomStringByLength(4);
try {
boolean sendFlag = sendSmsCode(phone, "46886", randomCode);
if (sendFlag) {
logger.error("短信验证码发送成功");
vv.set("Kzy_WX_LOGIN_SMS_PHONE_" + phone,randomCode,5, TimeUnit.MINUTES);//缓存验证码,验证成功之后再手动销毁
//测试用,上线去掉
System.out.println(phone+"999微信注册登录验证码为:"+randomCode);
resultMap.put("data","");
resultMap.put("status","1");
resultMap.put("message","发送成功~");
} else {
resultMap.put("message","短信验证码发送失败");
}
} catch (Exception e) {
resultMap.put("message","发送短信验证码服务异常");
}
return resultMap;
}
public static String getRandomStringByLength(int length) {
String base = "0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
@RequestMapping(value = "/verifyImgCode", method = {RequestMethod.POST, RequestMethod.GET}, produces = "application/json")
public void verifyImgCode(HttpServletRequest request, HttpServletResponse response) {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE");
response.setHeader("Access-Control-Max-Age", "1728000");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
try {
String verifyImgCode = generateVerifyCode(5);
response.setContentType("image/jpeg");
response.setDateHeader("expries", -1);
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
VerifyCodeUtils.outputImagePC(100, 40, response.getOutputStream(), verifyImgCode);
// request.getSession().setAttribute("WEIXIN_USER_IMAGE_CODE_SESSION",verifyImgCode);
ValueOperations vv = redisTemplate.opsForValue();
String phone = request.getParameter("phone");
if (!StringUtils.isEmpty(phone)) {
logger.error("获取图形验证码手机号:" + phone);
vv.set("Kzy_IMAGE_CODE_"+phone,verifyImgCode,1,TimeUnit.MINUTES);
}
} catch (IOException e) {
e.printStackTrace();
logger.error("生成验证码失败", e);
}
}
public static String generateVerifyCode(int verifySize) {
String sources = "ABCDEFGHJKMNPQRSTUVWXYZ2345689";
int codesLen = sources.length();
Random rand = new Random(System.currentTimeMillis());
StringBuilder verifyCode = new StringBuilder(verifySize);
for (int i = 0; i < verifySize; i++) {
verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));
}
return verifyCode.toString();
}
public boolean sendSmsCode(String phone, String templateId, String code) throws Exception{
if(StringUtils.hasText(phone)&&StringUtils.hasText(templateId)&&StringUtils.hasText(code)){
HashMap<String, Object> smsResult = SendSMSUtil.sendTemplateSMS(phone,templateId,new String[]{code});
logger.error("/sendSmsCode =============>sendSmsCode-smsResult=" + smsResult);
if("000000".equals(smsResult.get("statusCode"))){
return true;
}else{
return false;
}
}else{
return false;
}
}
}
package com.server.web.controller;
import com.server.utils.SHA1;
import com.server.utils.weixin.WXMessageType;
import com.server.utils.weixin.WeixinBaseUtil;
import com.server.web.common.mapper.TKzyUserMapper;
import com.server.web.common.model.TKzyUser;
import com.server.web.common.model.TKzyUserExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import static com.jfinal.weixin.sdk.kit.PaymentKit.xmlToMap;
/**
* Created by 豆腐干Sama on 2018/12/5.
*/
@RestController
@RequestMapping(value = BaseController.WX_NAMESPACE + "/wxIndex",produces = "application/json")
public class WeixinIndexController extends BaseController{
@Autowired
private TKzyUserMapper userMapper;
@RequestMapping(value = "/authorizeCallback",method = {RequestMethod.GET,RequestMethod.POST})
public void authorizeCallback(HttpServletRequest request, HttpServletResponse response) {
try {
String code = request.getParameter("code");// 授权码
String redirectUri = request.getParameter("redirectUri");// redirectUri参数,验证成功跳转
WeixinBaseUtil weixinBaseUtil = new WeixinBaseUtil();
logger.error("授权回调参数:code " + code + " appId " + appId + " appSecret:" + appSecret);
Map<String, Object> _AuthMap = weixinBaseUtil.authorization(appId, appSecret, code);
if (_AuthMap == null) {
response.sendRedirect(redirectUri);
return;
}
String openId = (String)_AuthMap.get("openid");
String nickname = (String) _AuthMap.get("nickname");
String headimgurl = (String) _AuthMap.get("headimgurl");
logger.error("nickname:" + nickname + "");
TKzyUser user;
TKzyUserExample example = new TKzyUserExample();
example.createCriteria().andWxOpenidEqualTo(openId);
List<TKzyUser> users = userMapper.selectByExample(example);
if (CollectionUtils.isEmpty(users)) {
user = new TKzyUser();
user.setHeadPhoto(headimgurl);
user.setFullName(nickname);
user.setWxOpenid(openId);
} else {
user = users.get(0);
user.setLastLoginDt(new Date());
if (StringUtils.isEmpty(user.getFullName())) {
user.setFullName(nickname);
}
if (StringUtils.isEmpty(user.getHeadPhoto())) {
user.setHeadPhoto(headimgurl);
}
userMapper.updateByPrimaryKeySelective(user);
}
request.getSession().setAttribute(WX_USER_SESSION_KEY,user);
logger.error("user.getNickName:" + user.getFullName());
response.sendRedirect(redirectUri);
} catch (Exception e) {
e.printStackTrace();
}
}
@Value("${wx.app.secret}")
private String appSecret;
@Value("${wx.app.id}")
private String appId;
public Map<String,Object> getAccessToken() {
String accessToken = getAccessToken(appId, appSecret);
if (StringUtils.hasText(accessToken)) {
return returnSuccess(accessToken);
} else {
return returnError("0","获取access_toke失败",null);
}
}
public void textWrite(String text,HttpServletResponse response) {
response.setContentType("text/html; charset=UTF-8");
try {
response.getWriter().write(text);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 处理接受参数
* @param request
* @return
*/
public static String readRequestStr(HttpServletRequest request) {
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(request.getInputStream(), "utf-8"));
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != reader) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
@RequestMapping(value = "/callback", method = {RequestMethod.POST, RequestMethod.GET})
public void callback(HttpServletRequest request, HttpServletResponse response){
try{
String signature = request.getParameter("signature");
String nonce = request.getParameter("nonce");
String echostr = request.getParameter("echostr");
String timestamp = request.getParameter("timestamp");
boolean isPass =checkSignature(signature, timestamp, nonce);
if (!isPass) {
logger.error("isPass 验证错误!!");
return;
} else if (StringUtils.hasText(echostr)) {
textWrite(echostr,response);
return;
}
String xmlStr =readRequestStr(request);
Map<String, String> map = xmlToMap(xmlStr);
if (map == null) {
logger.error("callback-map is null !!");
}else{
String msgType = map.get("MsgType");
String content ="";
if (WXMessageType.event.toString().equals(msgType)) {//点击事件
// FIXME: 2018/12/5
}else if(WXMessageType.text.toString().equals(msgType)){//关键字回复
// FIXME: 2018/12/5
}
String openId = map.get("ToUserName");
String wx_id = map.get("FromUserName");
if(content!=null&&!"".equals(content.trim())){
textWrite(getWxStringMsg(openId,wx_id, content),response);
}
}
}catch (Exception e){
e.printStackTrace();
}
}
@ResponseBody
@RequestMapping(value = "/jsApiSignature", method = {RequestMethod.POST, RequestMethod.GET}, produces = "application/json")
public Map<String,Object> jsApiSignature(HttpServletRequest request) throws Exception{
try{
String urlTicket = request.getParameter("url");
if(StringUtils.hasText(urlTicket)){
Map<String, Object> signature = jsApiSignature(urlTicket);
if(signature!=null) {
return returnSuccess(signature);
}
}else{
return returnError("0","参数url缺失",null);
}
}catch (Exception e){
e.printStackTrace();
return returnError("0","服务器异常",null);
}
return returnError("0","获取签名失败","");
}
@Value("${wx.tocken}")
private String wxTocken;
public boolean checkSignature(String signature,String timestamp,String nonce) {
String[] str = new String[]{wxTocken, timestamp, nonce};
//排序
Arrays.sort(str);
//拼接字符串
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < str.length; i++) {
buffer.append(str[i]);
}
//进行sha1加密
String temp = SHA1.encode(buffer.toString());
//与微信提供的signature进行匹对
return signature.equals(temp);
}
public String getWxStringMsg(String fromUserName, String toUserName, String content) {
String msg = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[%s]]></MsgType><Content><![CDATA[%s]]></Content></xml>";
return String.format(msg, new String[]{toUserName, fromUserName, Long.valueOf(System.currentTimeMillis() / 1000).toString(), "text", content});
}
public Map<String,Object> jsApiSignature(String url) throws Exception{
if(StringUtils.hasText(appId)&&StringUtils.hasText(appId)&&StringUtils.hasText(url)){
String jsapi_ticket =WeixinBaseUtil.getTicket(appId,getAccessToken(appId,appSecret),url,redisTemplate);
Map<String, Object> sign = WeixinBaseUtil.sign(jsapi_ticket, url, appId);
return sign;
}else{
return null;
}
}
}
package com.server.web.interceptor;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created by yinbin on 2018/1/9.
*/
@Component
public class InterceptorLocal implements HandlerInterceptor {
final static Logger logger = LogManager.getLogger(InterceptorLocal.class);
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
logger.debug("preHandle");
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
logger.debug("postHandle");
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
logger.debug("afterCompletion");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!--导入属性配置 -->
<properties resource="mbg/generator.properties"></properties>
<!--指定特定数据库的jdbc驱动jar包的位置 -->
<classPathEntry location="C:\mysql-connector-java-5.1.44.jar"/>
<context id="default" targetRuntime="MyBatis3">
<!-- optional,旨在创建class时,对注释进行控制 -->
<commentGenerator>
<property name="suppressDate" value="true"/>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--jdbc的数据库连接 -->
<jdbcConnection driverClass="${jdbc.driverClass}" connectionURL="${jdbc.url}" userId="${jdbc.userId}"
password="${jdbc.password}">
</jdbcConnection>
<!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制-->
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
targetPackage 指定生成的model生成所在的包名
targetProject 指定在该项目下所在的路径
-->
<javaModelGenerator targetPackage="com.server.web.common.model" targetProject="src/main/java">
<!-- 是否对model添加 构造函数 -->
<property name="constructorBased" value="true"/>
<!-- 是否允许子包,即targetPackage.schemaName.tableName -->
<property name="enableSubPackages" value="false"/>
<!-- 建立的Model对象是否 不可改变 即生成的Model对象不会有 setter方法,只有构造方法 -->
<property name="immutable" value="false"/>
<!-- 给Model添加一个父类 -->
<!--
<property name="rootClass" value="test.model.Person"/>
-->
<!-- 是否对类CHAR类型的列的数据进行trim操作 -->
<property name="trimStrings" value="true"/>
<property name="rootClass" value="com.server.web.common.model.BaseModel"/>
</javaModelGenerator>
<!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->
<sqlMapGenerator targetPackage="mybatis.mapper" targetProject="src/main/resources">
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!--
客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口
-->
<javaClientGenerator targetPackage="com.server.web.common.mapper" targetProject="src/main/java" type="XMLMAPPER">
<property name="exampleMethodVisibility" value="public"/>
</javaClientGenerator>
<table tableName="t_base_banner" schema="sc"><generatedKey column="ID" sqlStatement="MySql" identity="true"/></table>
<table tableName="t_base_first_class" schema="sc"><generatedKey column="ID" sqlStatement="MySql" identity="true"/></table>
<table tableName="t_base_second_class" schema="sc"><generatedKey column="ID" sqlStatement="MySql" identity="true"/></table>
<table tableName="t_kzy_comment" schema="sc"><generatedKey column="ID" sqlStatement="MySql" identity="true"/></table>
<table tableName="t_kzy_course" schema="sc"><generatedKey column="ID" sqlStatement="MySql" identity="true"/></table>
<table tableName="t_kzy_information" schema="sc"><generatedKey column="ID" sqlStatement="MySql" identity="true"/></table>
<table tableName="t_kzy_relation_class" schema="sc"><generatedKey column="ID" sqlStatement="MySql" identity="true"/></table>
<table tableName="t_kzy_user" schema="sc"><generatedKey column="ID" sqlStatement="MySql" identity="true"/></table>
<table tableName="t_kzy_user_integral_flowing" schema="sc"><generatedKey column="ID" sqlStatement="MySql" identity="true"/></table>
</context>
</generatorConfiguration>
\ No newline at end of file
jdbc.driverLocation=
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://39.97.246.118:3306/kzy_db_test?useUnicode=true&characterEncoding=utf-8
jdbc.userId=kzy_user
jdbc.password=Kzy2020#yY
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.server.web.common.mapper.TBaseFirstClassMapper">
<resultMap id="BaseResultMap" type="com.server.web.common.model.TBaseFirstClass">
<constructor>
<idArg column="id" javaType="java.lang.Long" jdbcType="BIGINT" />
<arg column="class_name" javaType="java.lang.String" jdbcType="VARCHAR" />
<arg column="status" javaType="java.lang.Integer" jdbcType="INTEGER" />
<arg column="pic_url" javaType="java.lang.String" jdbcType="VARCHAR" />
<arg column="weight" javaType="java.lang.Integer" jdbcType="INTEGER" />
<arg column="create_dt" javaType="java.util.Date" jdbcType="TIMESTAMP" />
</constructor>
</resultMap>
<sql id="Example_Where_Clause">
<where>
<foreach collection="oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Update_By_Example_Where_Clause">
<where>
<foreach collection="example.oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Base_Column_List">
id, class_name, status, pic_url, weight, create_dt
</sql>
<select id="selectByExample" parameterType="com.server.web.common.model.TBaseFirstClassExample" resultMap="BaseResultMap">
select
<if test="distinct">
distinct
</if>
<include refid="Base_Column_List" />
from t_base_first_class
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
</select>
<select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from t_base_first_class
where id = #{id,jdbcType=BIGINT}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
delete from t_base_first_class
where id = #{id,jdbcType=BIGINT}
</delete>
<delete id="deleteByExample" parameterType="com.server.web.common.model.TBaseFirstClassExample">
delete from t_base_first_class
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</delete>
<insert id="insert" parameterType="com.server.web.common.model.TBaseFirstClass">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long">
SELECT LAST_INSERT_ID()
</selectKey>
insert into t_base_first_class (class_name, status, pic_url,
weight, create_dt)
values (#{className,jdbcType=VARCHAR}, #{status,jdbcType=INTEGER}, #{picUrl,jdbcType=VARCHAR},
#{weight,jdbcType=INTEGER}, #{createDt,jdbcType=TIMESTAMP})
</insert>
<insert id="insertSelective" parameterType="com.server.web.common.model.TBaseFirstClass">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long">
SELECT LAST_INSERT_ID()
</selectKey>
insert into t_base_first_class
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="className != null">
class_name,
</if>
<if test="status != null">
status,
</if>
<if test="picUrl != null">
pic_url,
</if>
<if test="weight != null">
weight,
</if>
<if test="createDt != null">
create_dt,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="className != null">
#{className,jdbcType=VARCHAR},
</if>
<if test="status != null">
#{status,jdbcType=INTEGER},
</if>
<if test="picUrl != null">
#{picUrl,jdbcType=VARCHAR},
</if>
<if test="weight != null">
#{weight,jdbcType=INTEGER},
</if>
<if test="createDt != null">
#{createDt,jdbcType=TIMESTAMP},
</if>
</trim>
</insert>
<select id="countByExample" parameterType="com.server.web.common.model.TBaseFirstClassExample" resultType="java.lang.Long">
select count(*) from t_base_first_class
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</select>
<update id="updateByExampleSelective" parameterType="map">
update t_base_first_class
<set>
<if test="record.id != null">
id = #{record.id,jdbcType=BIGINT},
</if>
<if test="record.className != null">
class_name = #{record.className,jdbcType=VARCHAR},
</if>
<if test="record.status != null">
status = #{record.status,jdbcType=INTEGER},
</if>
<if test="record.picUrl != null">
pic_url = #{record.picUrl,jdbcType=VARCHAR},
</if>
<if test="record.weight != null">
weight = #{record.weight,jdbcType=INTEGER},
</if>
<if test="record.createDt != null">
create_dt = #{record.createDt,jdbcType=TIMESTAMP},
</if>
</set>
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByExample" parameterType="map">
update t_base_first_class
set id = #{record.id,jdbcType=BIGINT},
class_name = #{record.className,jdbcType=VARCHAR},
status = #{record.status,jdbcType=INTEGER},
pic_url = #{record.picUrl,jdbcType=VARCHAR},
weight = #{record.weight,jdbcType=INTEGER},
create_dt = #{record.createDt,jdbcType=TIMESTAMP}
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByPrimaryKeySelective" parameterType="com.server.web.common.model.TBaseFirstClass">
update t_base_first_class
<set>
<if test="className != null">
class_name = #{className,jdbcType=VARCHAR},
</if>
<if test="status != null">
status = #{status,jdbcType=INTEGER},
</if>
<if test="picUrl != null">
pic_url = #{picUrl,jdbcType=VARCHAR},
</if>
<if test="weight != null">
weight = #{weight,jdbcType=INTEGER},
</if>
<if test="createDt != null">
create_dt = #{createDt,jdbcType=TIMESTAMP},
</if>
</set>
where id = #{id,jdbcType=BIGINT}
</update>
<update id="updateByPrimaryKey" parameterType="com.server.web.common.model.TBaseFirstClass">
update t_base_first_class
set class_name = #{className,jdbcType=VARCHAR},
status = #{status,jdbcType=INTEGER},
pic_url = #{picUrl,jdbcType=VARCHAR},
weight = #{weight,jdbcType=INTEGER},
create_dt = #{createDt,jdbcType=TIMESTAMP}
where id = #{id,jdbcType=BIGINT}
</update>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.server.web.common.mapper.TBaseSecondClassMapper">
<resultMap id="BaseResultMap" type="com.server.web.common.model.TBaseSecondClass">
<constructor>
<idArg column="id" javaType="java.lang.Long" jdbcType="BIGINT" />
<arg column="class_name" javaType="java.lang.String" jdbcType="VARCHAR" />
<arg column="status" javaType="java.lang.Integer" jdbcType="INTEGER" />
<arg column="type" javaType="java.lang.Integer" jdbcType="INTEGER" />
<arg column="pic_url" javaType="java.lang.String" jdbcType="VARCHAR" />
<arg column="first_id" javaType="java.lang.Long" jdbcType="BIGINT" />
<arg column="weight" javaType="java.lang.Integer" jdbcType="INTEGER" />
<arg column="create_dt" javaType="java.util.Date" jdbcType="TIMESTAMP" />
</constructor>
</resultMap>
<sql id="Example_Where_Clause">
<where>
<foreach collection="oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Update_By_Example_Where_Clause">
<where>
<foreach collection="example.oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Base_Column_List">
id, class_name, status, type, pic_url, first_id, weight, create_dt
</sql>
<select id="selectByExample" parameterType="com.server.web.common.model.TBaseSecondClassExample" resultMap="BaseResultMap">
select
<if test="distinct">
distinct
</if>
<include refid="Base_Column_List" />
from t_base_second_class
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
</select>
<select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from t_base_second_class
where id = #{id,jdbcType=BIGINT}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
delete from t_base_second_class
where id = #{id,jdbcType=BIGINT}
</delete>
<delete id="deleteByExample" parameterType="com.server.web.common.model.TBaseSecondClassExample">
delete from t_base_second_class
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</delete>
<insert id="insert" parameterType="com.server.web.common.model.TBaseSecondClass">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long">
SELECT LAST_INSERT_ID()
</selectKey>
insert into t_base_second_class (class_name, status, type,
pic_url, first_id, weight,
create_dt)
values (#{className,jdbcType=VARCHAR}, #{status,jdbcType=INTEGER}, #{type,jdbcType=INTEGER},
#{picUrl,jdbcType=VARCHAR}, #{firstId,jdbcType=BIGINT}, #{weight,jdbcType=INTEGER},
#{createDt,jdbcType=TIMESTAMP})
</insert>
<insert id="insertSelective" parameterType="com.server.web.common.model.TBaseSecondClass">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long">
SELECT LAST_INSERT_ID()
</selectKey>
insert into t_base_second_class
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="className != null">
class_name,
</if>
<if test="status != null">
status,
</if>
<if test="type != null">
type,
</if>
<if test="picUrl != null">
pic_url,
</if>
<if test="firstId != null">
first_id,
</if>
<if test="weight != null">
weight,
</if>
<if test="createDt != null">
create_dt,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="className != null">
#{className,jdbcType=VARCHAR},
</if>
<if test="status != null">
#{status,jdbcType=INTEGER},
</if>
<if test="type != null">
#{type,jdbcType=INTEGER},
</if>
<if test="picUrl != null">
#{picUrl,jdbcType=VARCHAR},
</if>
<if test="firstId != null">
#{firstId,jdbcType=BIGINT},
</if>
<if test="weight != null">
#{weight,jdbcType=INTEGER},
</if>
<if test="createDt != null">
#{createDt,jdbcType=TIMESTAMP},
</if>
</trim>
</insert>
<select id="countByExample" parameterType="com.server.web.common.model.TBaseSecondClassExample" resultType="java.lang.Long">
select count(*) from t_base_second_class
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</select>
<update id="updateByExampleSelective" parameterType="map">
update t_base_second_class
<set>
<if test="record.id != null">
id = #{record.id,jdbcType=BIGINT},
</if>
<if test="record.className != null">
class_name = #{record.className,jdbcType=VARCHAR},
</if>
<if test="record.status != null">
status = #{record.status,jdbcType=INTEGER},
</if>
<if test="record.type != null">
type = #{record.type,jdbcType=INTEGER},
</if>
<if test="record.picUrl != null">
pic_url = #{record.picUrl,jdbcType=VARCHAR},
</if>
<if test="record.firstId != null">
first_id = #{record.firstId,jdbcType=BIGINT},
</if>
<if test="record.weight != null">
weight = #{record.weight,jdbcType=INTEGER},
</if>
<if test="record.createDt != null">
create_dt = #{record.createDt,jdbcType=TIMESTAMP},
</if>
</set>
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByExample" parameterType="map">
update t_base_second_class
set id = #{record.id,jdbcType=BIGINT},
class_name = #{record.className,jdbcType=VARCHAR},
status = #{record.status,jdbcType=INTEGER},
type = #{record.type,jdbcType=INTEGER},
pic_url = #{record.picUrl,jdbcType=VARCHAR},
first_id = #{record.firstId,jdbcType=BIGINT},
weight = #{record.weight,jdbcType=INTEGER},
create_dt = #{record.createDt,jdbcType=TIMESTAMP}
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByPrimaryKeySelective" parameterType="com.server.web.common.model.TBaseSecondClass">
update t_base_second_class
<set>
<if test="className != null">
class_name = #{className,jdbcType=VARCHAR},
</if>
<if test="status != null">
status = #{status,jdbcType=INTEGER},
</if>
<if test="type != null">
type = #{type,jdbcType=INTEGER},
</if>
<if test="picUrl != null">
pic_url = #{picUrl,jdbcType=VARCHAR},
</if>
<if test="firstId != null">
first_id = #{firstId,jdbcType=BIGINT},
</if>
<if test="weight != null">
weight = #{weight,jdbcType=INTEGER},
</if>
<if test="createDt != null">
create_dt = #{createDt,jdbcType=TIMESTAMP},
</if>
</set>
where id = #{id,jdbcType=BIGINT}
</update>
<update id="updateByPrimaryKey" parameterType="com.server.web.common.model.TBaseSecondClass">
update t_base_second_class
set class_name = #{className,jdbcType=VARCHAR},
status = #{status,jdbcType=INTEGER},
type = #{type,jdbcType=INTEGER},
pic_url = #{picUrl,jdbcType=VARCHAR},
first_id = #{firstId,jdbcType=BIGINT},
weight = #{weight,jdbcType=INTEGER},
create_dt = #{createDt,jdbcType=TIMESTAMP}
where id = #{id,jdbcType=BIGINT}
</update>
</mapper>
\ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!