提交 c807d8e2 编写于 作者: snkkka163's avatar snkkka163

涛宝商城首次提交

上级 70599c4f
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="test" value="true"/>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
<attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.web.container"/>
<classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.module.container"/>
<classpathentry kind="output" path="target/classes"/>
</classpath>
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>taobaostore</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.wst.common.project.facet.core.builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.validation.validationbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.springframework.ide.eclipse.core.springbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.springframework.ide.eclipse.boot.validation.springbootbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.springframework.ide.eclipse.core.springnature</nature>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
<nature>org.eclipse.wst.jsdt.core.jsNature</nature>
</natures>
</projectDescription>
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry excluding="**/bower_components/*|**/node_modules/*|**/*.min.js" kind="src" path="WebContent"/>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.JRE_CONTAINER"/>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.WebProject">
<attributes>
<attribute name="hide" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.baseBrowserLibrary"/>
<classpathentry kind="output" path=""/>
</classpath>
eclipse.preferences.version=1
encoding//src/main/java=UTF-8
encoding//src/main/resources=UTF-8
encoding//src/main/resources/ftpDataSource.properties=UTF-8
encoding//src/main/resources/log4j.properties=UTF-8
encoding//src/main/resources/zfbinfo.properties=UTF-8
encoding//src/test/java=UTF-8
encoding/<project>=UTF-8
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.release=disabled
org.eclipse.jdt.core.compiler.source=1.8
activeProfiles=
eclipse.preferences.version=1
resolveWorkspaceProjects=true
version=1
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
<wb-module deploy-name="taobaostore">
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/java"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/test/java"/>
<wb-resource deploy-path="/" source-path="/src/main/webapp"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/>
<property name="context-root" value="taobaostore"/>
<property name="java-output-path" value="/taobaostore/target/classes"/>
</wb-module>
</project-modules>
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<fixed facet="wst.jsdt.web"/>
<installed facet="java" version="1.8"/>
<installed facet="wst.jsdt.web" version="1.0"/>
<installed facet="jst.web" version="3.0"/>
</faceted-project>
org.eclipse.wst.jsdt.launching.baseBrowserLibrary
\ No newline at end of file
<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</groupId>
<artifactId>taobaostore</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>taobaostore</name>
<url>http://maven.apache.org</url>
<properties>
<!-- 项目编码和依赖框架版本 -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>5.0.2.RELEASE</spring.version>
<mybatis.version>3.4.5</mybatis.version>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- logback组件配置 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.1.2</version>
<scope>compile</scope>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency> <!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency> <!-- mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency> <!-- MySQL 驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
<scope>runtime</scope>
</dependency>
<!-- druid 连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.26</version>
</dependency> <!-- aspectJ 织入 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency> <!-- JSON 处理 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.5</version>
</dependency> <!-- JUnit4 测试工具 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency> <!-- Servlet-API -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency> <!-- JSTL 标签库 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- lombok 插件 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.6</version>
<scope>compile</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<!-- 配置pagehelper插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.8</version>
</dependency>
<!-- 配置thymeleaf -->
<!-- https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf-spring4 -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<version>3.0.9.RELEASE</version>
</dependency>
<!-- 配置mybatis插件:Generator -->
<!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator</artifactId>
<version>1.3.6</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.6</version>
</dependency>
<!-- json序列化jar包 -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.12</version>
</dependency>
<!-- 配置junit测试 -->
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- Redis集成: -->
<!-- jedis依赖 -->
<!-- freemarker配置 -->
<!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>20.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/com.springsource.org.apache.commons.io -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>com.springsource.org.apache.commons.io</artifactId>
<version>1.4.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/com.springsource.org.apache.commons.fileupload -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>com.springsource.org.apache.commons.fileupload</artifactId>
<version>1.2.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-net/commons-net -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.51</version>
</dependency>
<!-- jsch 所依赖的jar包 -->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jzlib</artifactId>
<version>1.0.7</version>
</dependency>
<!-- 时间转换所依赖的jar包 -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-war-plugin -->
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.0.0</version>
</dependency>
<!-- 与支付宝对接所需要的jar包 alipay -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>1.10</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>1.3</version>
</dependency>
<!-- 2019-12-22增强版 -->
<!-- redis支持 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.6.0</version>
</dependency>
<!-- lombok依赖 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
</dependency>
</dependencies>
<build>
<plugins> <!--Tomcat7 插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<uriEncoding>UTF-8</uriEncoding>
<path>/</path>
<port>80</port>
</configuration>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.6</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
</build>
</project>
package com.alipay.demo.trade;
import com.alipay.demo.trade.model.builder.AlipayHeartbeatSynRequestBuilder;
import com.alipay.demo.trade.model.hb.*;
import com.alipay.demo.trade.service.AlipayMonitorService;
import com.alipay.demo.trade.service.impl.hb.AbsHbRunner;
import com.alipay.demo.trade.service.impl.hb.HbQueue;
import com.alipay.demo.trade.utils.Utils;
import static org.hamcrest.CoreMatchers.instanceOf;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Created by liuyangkly on 15/10/23.
执行调度,主要任务由两个线程完成,交易线程(调用当面付2.0接口)和交易保障线程(轮询),具体需要做的事情
1.当面付程序每执行完一笔交易后将交易结果保存在临时队列
2.轮询线程读取临时队列,获取基础采集信息和最多30条trade_info信息,调用支付宝monitor.heartbeat.syn接口
示例代码仅封装了如何调用该接口api,采集数据,比如采集网络信息、交易耗时、异常信息等,需要系统商开发者自行完成。
*/
public class DemoHbRunner extends AbsHbRunner {
public DemoHbRunner(AlipayMonitorService monitorService) {
super(monitorService);
}
@Override
public String getAppAuthToken() {
// 对于系统商,如果是为了商户开发监控保障接口,则需要传此值,否则如果为系统商自己做交易保障接口开发,则可不传。
return null;
}
@Override
public AlipayHeartbeatSynRequestBuilder getBuilder() {
// 系统商使用的交易信息格式,json字符串类型,从交易队列中获取
List<SysTradeInfo> sysTradeInfoList = HbQueue.poll();
// 异常信息的采集,系统商自行完成
List<ExceptionInfo> exceptionInfoList = new ArrayList<ExceptionInfo>();
// exceptionInfoList.add(ExceptionInfo.HE_SCANER);
// exceptionInfoList.add(ExceptionInfo.HE_PRINTER);
// exceptionInfoList.add(ExceptionInfo.HE_OTHER);
AlipayHeartbeatSynRequestBuilder builder = new AlipayHeartbeatSynRequestBuilder()
.setProduct(Product.FP).setType(Type.CR).setEquipmentId("cr1000001")
.setEquipmentStatus(EquipStatus.NORMAL).setTime(Utils.toDate(new Date()))
.setStoreId("store10001").setMac("0a:00:27:00:00:00").setNetworkType("LAN")
.setProviderId("2088911212323549") // 设置系统商pid
.setSysTradeInfoList(sysTradeInfoList) // 系统商同步trade_info信息
.setExceptionInfoList(exceptionInfoList) // 填写异常信息,如果有的话
;
return builder;
}
}
此差异已折叠。
package com.taobaostore;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}
package com.taobaostore.common;
import java.math.BigDecimal;
/**
* 在BigDecimal进行计算时要使用字符串构造器才能保证计算的精度
* @author xzp
*
*/
public class BigDecimalUtil {
private BigDecimalUtil() {
}
/**
* 加法
* @param v1
* @param v2
* @return
*/
public static BigDecimal add(double v1,double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.add(b2);
}
/**
* 减法
* @param v1
* @param v2
* @return
*/
public static BigDecimal sub(double v1,double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.subtract(b2);
}
/**
* 乘法
* @param v1
* @param v2
* @return
*/
public static BigDecimal mul(double v1,double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.multiply(b2);
}
/**
* 除法
* @param v1
* @param v2
* @return
*/
public static BigDecimal div(double v1,double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.divide(b2,2,BigDecimal.ROUND_HALF_UP);//四舍五入,保留两位小数
}
}
package com.taobaostore.common;
import javax.servlet.ServletContext;
import org.springframework.beans.factory.annotation.Autowired;
public class Const {
public static final String CURRENT_USER = "currentUser";
public static final String USER_NAME = "username";
public static final String EMAIL = "email";
public static final String USER_PIC = System.getProperty("catalina.home")+"/webapps/taobaouser_head/";// 用户头像存储路径
public static final String PRODUCT_ID = "product_id";
public static final String PRODUCT_MSG = "product_msg";
public static final String KEY_WORD = "keyword";
public static final String FRONT_PRODUCT_MSG = "front_product_msg";
// 使用内部接口实现权限组分离
public interface Role{
int ROLE_USER = 1;// 普通用户
int ROLE_ADMIN = 0;// 管理员用户
}
public interface Cart{
int CHECKED = 1;//购物车选中状态
int ON_CHECKED = 0;// 购物车未选中
String LIMIT_NUM_FAIL = "LIMIT_NUM_FAIL";
String LIMIT_NUM_SUCCESS = "LIMIT_NUM_SUCCESS";
}
// 支付状态常量
public enum OrderStatusEnum {
CANCELED(0,"已取消"),
NO_PAY(10,"未支付"),
PAID(20,"已付款"),
SHIPPED(40,"已发货"),
ORDER_SUCCESS(50,"订单完成"),
ORDER_CLOSE(60,"订单关闭");
private String value;
private int code;
OrderStatusEnum(int code, String value) {
this.code = code;
this.value = value;
}
public int getCode() {
return code;
}
public String getValue() {
return value;
}
}
// 支付宝回调常量
public interface AlipayCallback{
String TRADE_STATUS_WAIT_BUYER_PAY = "WAIT_BUYER_PAY";//交易创建
String TRADE_STATUS_TRADE_SUCCESS = "TRADE_SUCCESS";//交易成功
String RESPONSE_SUCCESS="success";
String RESPONSE_FAILED="faled";
}
// 支付类型常量
public enum PayPlatformEnum{
ALIPAY(1,"支付宝");
private String value;
private int code;
PayPlatformEnum(int code, String value) {
this.code = code;
this.value = value;
}
public int getCode() {
return code;
}
public String getValue() {
return value;
}
}
public enum PaymentType{
ON_LINE(1,"在线支付");
private String value;
private int code;
PaymentType(int code, String value) {
this.code = code;
this.value = value;
}
public int getCode() {
return code;
}
public String getValue() {
return value;
}
}
// 商品状态常量 1-在售,2-下架,3-删除
public enum ProductStatus{
SALL(1,"在售"),
SOLDOUT(2,"下架"),
DELETE(3,"删除");
private String value;
private int code;
ProductStatus(int code, String value) {
this.code = code;
this.value = value;
}
public int getCode() {
return code;
}
public String getValue() {
return value;
}
}
}
package com.taobaostore.common;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Configurable;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;
public class Generator {
public static void main(String[] args) throws Exception{
//MBG执行过程中的警告信息:
List<String> warnings= new ArrayList<String>();
//生成代码重复时,是否覆盖源代码
boolean override=false;
InputStream in=Thread.currentThread().getContextClassLoader().getResourceAsStream("generatorConfig.xml");
ConfigurationParser cp=new ConfigurationParser(warnings);
Configuration config=cp.parseConfiguration(in);
DefaultShellCallback callback=new DefaultShellCallback(override);
//创建MGB
MyBatisGenerator mbg=new MyBatisGenerator(config, callback, warnings);
mbg.generate(null);
for (String string : warnings) {
System.out.println(string);
}
}
}
\ No newline at end of file
package com.taobaostore.common;
import com.taobaostore.util.PropertiesUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class RedisPool {
private static JedisPool pool;// jedis连接池
private static Integer maxTotal = Integer.parseInt(PropertiesUtil.getValue("redis.max.total", "20"));//最大连接数
private static Integer maxIdle = Integer.parseInt(PropertiesUtil.getValue("redis.max.idle", "20"));//最大空闲(Idle)数
private static Integer minIdle = Integer.parseInt(PropertiesUtil.getValue("redis.min.idle", "20"));//最小空闲数
private static Boolean testOnBorrw = Boolean.parseBoolean(PropertiesUtil.getValue("redis.test.borrow", "true"));//在(获取)borrow一个jedis实例的时候,是否要进行验证操作,如果赋值为true
private static Boolean testReturn = Boolean.parseBoolean(PropertiesUtil.getValue("redis.test.return", "true"));//在(返回)ret*urn一个jedis实例的时候,是否要进行验证操作,则放回jedis的实例一定是可用的
private static String redisIp = PropertiesUtil.getValue("redis.ip");
private static Integer redisPort = Integer.valueOf(PropertiesUtil.getValue("redis.port"));
// 初始化jedis连接池
private static void initPool() {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(maxTotal);
config.setMaxIdle(maxIdle);
config.setMinIdle(minIdle);
config.setTestOnBorrow(testOnBorrw);
config.setTestOnReturn(testReturn);
config.setBlockWhenExhausted(true);// 连接耗尽的时候是否阻塞,false抛出异常,true为阻塞直到超时,默认为true
pool = new JedisPool(config, redisIp, redisPort, 1000 * 2);
}
static {
initPool();
}
/**
* 通过jedis连接池返回jedis
* @return
*/
public static Jedis getJedis() {
return pool.getResource();
}
public static void returnResource(Jedis jedis) {
pool.returnBrokenResource(jedis);
}
public static void returnBrokenResource(Jedis jedis) {
pool.returnBrokenResource(jedis);
}
public static void main(String[] args) {
Jedis jedis = pool.getResource();
jedis.set("xzpkey", "xzpvalue");
returnResource(jedis);
pool.destroy();// 临时调用,销毁连接池中所有的连接
System.out.println("program is end");
}
}
package com.taobaostore.common;
public enum ResponseCode {
SUCCESS(0,"SUCCESS"),// 响应成功
ERROR(1,"ERROR"), // 响应失败
NEED_LOGIN(10,"NEED_LOGIN"), // 登录错误
ILLEGAL_ARGUMENT(2,"ILLEGAL_ARGUMENT"); // 非法参数
private final int CODE;
private final String DESC;
ResponseCode(int code,String desc){
this.CODE = code;
this.DESC = desc;
}
public int getCODE() {
return CODE;
}
public String getDESC() {
return DESC;
}
}
package com.taobaostore.common;
import java.io.Serializable;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.map.annotate.JsonSerialize;
/**
* 响应返回
* @author xzp
*
* @param <T>
*/
// 使用@JsonSerialize注解后:比如我只传了status msg和data就不会被序列化成json,便不会出现在json中(null的属性key也会消失)
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class ServerResponse<T> implements Serializable {
private static final long serialVersionUID = 1L;
private int status;// 返回状态
private String msg;// 返回附带信息
private T data;// 返回附带对象
//使用@JsonIgnore注解之后不会被该方法不会被序列化成json
@JsonIgnore
public boolean isSuccess() {
return this.status == ResponseCode.SUCCESS.getCODE();
}
public int getStatus() {
return status;
}
public String getMsg() {
return msg;
}
public T getData() {
return data;
}
// 响应成功
public static <T> ServerResponse<T> createBySuccess(){
return new ServerResponse<T>(ResponseCode.SUCCESS.getCODE());
}
public static <T> ServerResponse<T> createBySuccess(String msg){
return new ServerResponse<T>(ResponseCode.SUCCESS.getCODE(), msg);
}
public static <T> ServerResponse<T> createBySuccess(T data){
return new ServerResponse<T>(ResponseCode.SUCCESS.getCODE(),data);
}
public static <T> ServerResponse<T> createBySuccess(String msg,T data){
return new ServerResponse<T>(ResponseCode.SUCCESS.getCODE(), msg,data);
}
// 响应失败
public static <T> ServerResponse<T> createByError(){
return new ServerResponse<T>(ResponseCode.ERROR.getCODE());
}
public static <T> ServerResponse<T> createByError(String msg){
return new ServerResponse<T>(ResponseCode.ERROR.getCODE(), msg);
}
public static <T> ServerResponse<T> createByError(T data){
return new ServerResponse<T>(ResponseCode.ERROR.getCODE(), data);
}
public static <T> ServerResponse<T> createByError(String msg,T data){
return new ServerResponse<T>(ResponseCode.ERROR.getCODE(), msg,data);
}
// 自定义错误信息(登录错误,参数错误等)
public static <T> ServerResponse<T> createByError(int errorCode,String errorMsg){
return new ServerResponse<T>(errorCode, errorMsg);
}
private ServerResponse(int status) {
this.status = status;
}
private ServerResponse(int status,String msg) {
this.status = status;
this.msg = msg;
}
private ServerResponse(int status,T data) {
this.status = status;
this.data = data;
}
private ServerResponse(int status,String msg,T data) {
this.status = status;
this.msg = msg;
this.data = data;
}
@Override
public String toString() {
return "ServerResponse [status=" + status + ", msg=" + msg + ", data=" + data + "]";
}
}
package com.taobaostore.common;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
public class TokenCache {
public static final String TOKEN_NAME = "token_";
// com.google.common.cache
private static LoadingCache<String,String> localCache = CacheBuilder.newBuilder().initialCapacity(1000).maximumSize(1000)
.build(new CacheLoader<String, String>(){
/**
* 默认的数据加载实现,如果key没有对应的值,就调用这个方法进行加载
*/
public String load(String key) throws Exception {
return "null";
};
});
public static void setKey(String key,String value) {
localCache.put(key, value);
}
public static String getKey(String key) {
String value = null;
try {
value = localCache.get(key);
if ("null".equals(value)) {
return null;
}
return value;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 调用
* TokenCache,setKey(token + username,'forgetToken随机数');
*/
}
package com.taobaostore.common;
import javax.servlet.http.HttpSession;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.taobaostore.pojo.User;
public class UserContext {
private static HttpSession getSession() {
return ((ServletRequestAttributes)(RequestContextHolder.getRequestAttributes()))
.getRequest().getSession();
}
public static User getUser() {
User user = (User)getSession().getAttribute(Const.CURRENT_USER);
return user;
}
}
\ No newline at end of file
package com.taobaostore.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.taobaostore.pojo.Cart;
public interface CartMapper {
int insert(Cart record);
int insertSelective(Cart record);
int updateByPrimaryKeySelective(Cart record);
Cart selectCartByUserIdProductId(@Param("userId")Integer userId,@Param("productId")Integer productId);
List<Cart> selectCartByUserId(Integer userId);
int selectCartProductCheckedStatusByUserId(int userId);
int deleteByUserIdProductIds(@Param("userId")Integer userId,@Param("productIds")List<String> productIds);
int deleteByCartId(Integer cartId);
int updateByCheckPitchAll(@Param("userId")Integer userId);
int updateByCheckInvertAll(@Param("userId")Integer userId);
int updateByCheckPitch(@Param("userId")Integer userId,@Param("productId")Integer productId);
int updateByCheckInvert(@Param("userId")Integer userId,@Param("productId")Integer productId);
List<Cart> listCartByUserIdAndChecked(Integer userId);
}
\ No newline at end of file
package com.taobaostore.dao;
import java.util.List;
import com.taobaostore.pojo.Category;
public interface CategoryMapper {
int insert(Category record);
int insertSelective(Category record);
int updateByPrimaryKeySelective(Category category);
List<Category> listCategory();// 查询所有商品种类
List<Category> listCategoryChildren(int categoryId);// 查询指定商品种类下属的种类
Category getCategoryById(int id);// 根据种类id查询
List<Category> listCategoryByParentId(int parent_id);// 根据父种类获取指定种类列表
}
\ No newline at end of file
package com.taobaostore.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.taobaostore.pojo.OrderItem;
public interface OrderItemMapper {
int insert(OrderItem record);
int insertSelective(OrderItem record);
List<OrderItem> listOrderItemByIdAndUserId(@Param("userId")Integer userId,@Param("orderOn")Long orderOn);
List<OrderItem> listOrderItemByOrderOn(@Param("orderOn")Long orderOn);
List<OrderItem> listOrderItemById(@Param("userId")Integer userId);
int updateByPrimaryKeySelective(OrderItem record);
int batchOrderItem(@Param("listOrderItem")List<OrderItem> listOrderItem);
}
\ No newline at end of file
package com.taobaostore.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.taobaostore.pojo.Order;
public interface OrderMapper {
int deleteByPrimaryKey(Integer id);
int insert(Order record);
int insertSelective(Order record);
Order selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(Order record);
int updateByPrimaryKey(Order record);
Order selectByUserIdAndOrderNo(@Param("userId")Integer userId,@Param("orderNo")Long orderNo);
Order selectByOrderNo(Long orderNo);
int updateOrderStatus(@Param("userId")Integer userId,@Param("orderId")long orderId);
List<Order> listOrderByUserId(@Param("userId")Integer userId);
List<Order> listOrder();
int countOrder();
}
\ No newline at end of file
package com.taobaostore.dao;
import com.taobaostore.pojo.PayInfo;
public interface PayInfoMapper {
int insert(PayInfo record);
int insertSelective(PayInfo record);
PayInfo getPayInfoByOrderOn(Long orderOn);
}
\ No newline at end of file
package com.taobaostore.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.taobaostore.pojo.Product;
public interface ProductMapper {
int insert(Product record);
int insertSelective(Product record);
List<Product> listProduct();
int updateByPrimaryKeySelective(Product record);
int CountProduct();
List<Product> listProductByName(String name);
Product getProductById(int id);
Product getProductIdStatus(int id);
List<Product> selectList();
List<Product> selectByNameAndProductId(@Param("productName")String productName,@Param("productId") Integer productId);
List<Product> selectByNameAndCategoryIds(@Param("productName")String productName,@Param("categoryIdList")List<Integer> categoryIdList);
}
\ No newline at end of file
package com.taobaostore.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.taobaostore.pojo.Receiver;
public interface ReceiverMapper {
int insert(Receiver record);
int insertSelective(Receiver record);
/**
* 查询指定用户下的所有收货地址信息
* @param userId
* @return
*/
List<Receiver> listReceiverByUserId(int userId);
int deleteReceiverById(@Param("userId")int userId,@Param("id")int id);
Receiver getReceiverById(int receiverId);
}
\ No newline at end of file
package com.taobaostore.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.taobaostore.pojo.User;
public interface UserMapper {
int insert(User record);
int insertSelective(User record);
List<User> listUser();
int updateByPrimaryKeySelective(User user);
int checkUserName(@Param("username")String username);
int checkEmail(@Param("email")String email);
User selectLogin(@Param("username")String username,@Param("password")String password);
String selectQuestion(@Param("username")String username);
int selectAnswer(@Param("username")String username,@Param("question")String question,@Param("answer")String answer);
void updatePwd(@Param("username")String username,@Param("password")String password);
int selectPassword(@Param("password")String password,@Param("id")int userid);
}
\ No newline at end of file
package com.taobaostore.pojo;
import java.util.Date;
// 购物车表
public class Cart {
private Integer id;// 购物车id
private Integer userId;// 所属用户id
private Integer productId;// 购物商品id
private Integer quantity;// 商品数量
private Integer checked;// 是否选中(1-已经选择 0-没有选中)
private Date createTime;// 创建时间
private Date updateTime;// 更新时间
public Cart(Integer id, Integer userId, Integer productId, Integer quantity, Integer checked, Date createTime,
Date updateTime) {
this.id = id;
this.userId = userId;
this.productId = productId;
this.quantity = quantity;
this.checked = checked;
this.createTime = createTime;
this.updateTime = updateTime;
}
public Cart() {
super();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Integer getProductId() {
return productId;
}
public void setProductId(Integer productId) {
this.productId = productId;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public Integer getChecked() {
return checked;
}
public void setChecked(Integer checked) {
this.checked = checked;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
@Override
public String toString() {
return "Cart [id=" + id + ", userId=" + userId + ", productId=" + productId + ", quantity=" + quantity
+ ", checked=" + checked + ", createTime=" + createTime + ", updateTime=" + updateTime + "]";
}
}
\ No newline at end of file
package com.taobaostore.pojo;
import java.util.Date;
//种类表(使用递归)
public class Category {
private Integer id;// 种类id
private Integer parentId;// 父类(父类型)id
private String name;// 类别名称
private Boolean status;// 类别状态(1-正常 2-不可用)
private Integer sortOrder;//(排序编号,同一个梯队排序)
private Date createTime;// 创建时间
private Date updateTime;// 更新时间
public Category(Integer id, Integer parentId, String name, Boolean status, Integer sortOrder, Date createTime, Date updateTime) {
this.id = id;
this.parentId = parentId;
this.name = name;
this.status = status;
this.sortOrder = sortOrder;
this.createTime = createTime;
this.updateTime = updateTime;
}
public Category() {
super();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public Integer getSortOrder() {
return sortOrder;
}
public void setSortOrder(Integer sortOrder) {
this.sortOrder = sortOrder;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Category other = (Category) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
@Override
public String toString() {
return "Category [id=" + id + ", parentId=" + parentId + ", name=" + name + ", status=" + status
+ ", sortOrder=" + sortOrder + ", createTime=" + createTime + ", updateTime=" + updateTime + "]";
}
}
\ No newline at end of file
package com.taobaostore.pojo;
import java.math.BigDecimal;
import java.util.Date;
// 订单信息表
public class Order {
private Integer id;// 订单表id
private Long orderNo;// 订单号
private Integer userId;// 用户id
private Integer receiverId;// 送货地址id
private BigDecimal payment;// 实际付款金额,单位是元,保留两位小数
private Integer paymentType;// 付款方式(在线支付)
private Integer postage;// 运费(元)
private Integer status;// 订单状态(订单状态:0-取消,10-未付款,20-已付款,40-已发货,50-交易成功,60-交易关闭)
private Date paymentTime;// 支付时间
private Date sendTime;// 发货时间
private Date endTime;// 交易结束时间
private Date closeTime;// 交易关闭时间
private Date createTime;// 订单创建时间
private Date updateTime;// 订单更新时间
public Order(Integer id, Long orderNo, Integer userId, Integer receiverId, BigDecimal payment, Integer paymentType,
Integer postage, Integer status, Date paymentTime, Date sendTime, Date endTime, Date closeTime,
Date createTime, Date updateTime) {
this.id = id;
this.orderNo = orderNo;
this.userId = userId;
this.receiverId = receiverId;
this.payment = payment;
this.paymentType = paymentType;
this.postage = postage;
this.status = status;
this.paymentTime = paymentTime;
this.sendTime = sendTime;
this.endTime = endTime;
this.closeTime = closeTime;
this.createTime = createTime;
this.updateTime = updateTime;
}
@Override
public String toString() {
return "Order [id=" + id + ", orderNo=" + orderNo + ", userId=" + userId + ", receiverId=" + receiverId
+ ", payment=" + payment + ", paymentType=" + paymentType + ", postage=" + postage + ", status="
+ status + ", paymentTime=" + paymentTime + ", sendTime=" + sendTime + ", endTime=" + endTime
+ ", closeTime=" + closeTime + ", createTime=" + createTime + ", updateTime=" + updateTime + "]";
}
public Order() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Long getOrderNo() {
return orderNo;
}
public void setOrderNo(Long orderNo) {
this.orderNo = orderNo;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Integer getReceiverId() {
return receiverId;
}
public void setReceiverId(Integer receiverId) {
this.receiverId = receiverId;
}
public BigDecimal getPayment() {
return payment;
}
public void setPayment(BigDecimal payment) {
this.payment = payment;
}
public Integer getPaymentType() {
return paymentType;
}
public void setPaymentType(Integer paymentType) {
this.paymentType = paymentType;
}
public Integer getPostage() {
return postage;
}
public void setPostage(Integer postage) {
this.postage = postage;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Date getPaymentTime() {
return paymentTime;
}
public void setPaymentTime(Date paymentTime) {
this.paymentTime = paymentTime;
}
public Date getSendTime() {
return sendTime;
}
public void setSendTime(Date sendTime) {
this.sendTime = sendTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public Date getCloseTime() {
return closeTime;
}
public void setCloseTime(Date closeTime) {
this.closeTime = closeTime;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}
\ No newline at end of file
package com.taobaostore.pojo;
import java.math.BigDecimal;
import java.util.Date;
// 订单子表(订单详细)
public class OrderItem{
private Integer id;// 订单详细表id
private Long orderOn;// 订单表id(其实父表已经有了,以此增加查询速度)
private Integer productId;// 商品id
private String productName;// 商品名称
private String productImage;// 商品图片
private BigDecimal currentUnitPrice;// 当前单价
private Integer quantity;// 商品数量
private BigDecimal totalPrice;// 商品总价
private Date createTime;// 创建时间
private Date updateTime;// 更新时间
private Integer userId;// 用户id
public OrderItem() {
}
public OrderItem(Integer id, Integer userId, Long orderOn, Integer productId, String productName, String productImage, BigDecimal currentUnitPrice, Integer quantity, BigDecimal totalPrice, Date createTime, Date updateTime) {
this.id = id;
this.userId = userId;
this.orderOn = orderOn;
this.productId = productId;
this.productName = productName;
this.productImage = productImage;
this.currentUnitPrice = currentUnitPrice;
this.quantity = quantity;
this.totalPrice = totalPrice;
this.createTime = createTime;
this.updateTime = updateTime;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Long getOrderNo() {
return orderOn;
}
public void setOrderNo(Long orderNo) {
this.orderOn = orderNo;
}
public Integer getProductId() {
return productId;
}
public void setProductId(Integer productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName == null ? null : productName.trim();
}
public String getProductImage() {
return productImage;
}
public void setProductImage(String productImage) {
this.productImage = productImage == null ? null : productImage.trim();
}
public BigDecimal getCurrentUnitPrice() {
return currentUnitPrice;
}
public void setCurrentUnitPrice(BigDecimal currentUnitPrice) {
this.currentUnitPrice = currentUnitPrice;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public BigDecimal getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(BigDecimal totalPrice) {
this.totalPrice = totalPrice;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
@Override
public String toString() {
return "OrderItem [id=" + id + ", orderOn=" + orderOn + ", productId=" + productId + ", productName="
+ productName + ", productImage=" + productImage + ", currentUnitPrice=" + currentUnitPrice
+ ", quantity=" + quantity + ", totalPrice=" + totalPrice + ", createTime=" + createTime
+ ", updateTime=" + updateTime + ", userId=" + userId + "]";
}
}
\ No newline at end of file
package com.taobaostore.pojo;
import java.util.Date;
// 支付信息表
public class PayInfo {
private Integer id;// 支付信息表id
private Integer userId;// 支付用户id
private Long orderNo;// 订单号
private Integer payPlatform;// 支付平台(支付宝,微信)
private String platformNumber;// 平台编号
private String platformStatus;// 平台状态
private Date createTime;// 创建时间
private Date updateTime;// 更新时间
public PayInfo(Integer id, Integer userId, Long orderNo, Integer payPlatform, String platformNumber, String platformStatus, Date createTime, Date updateTime) {
this.id = id;
this.userId = userId;
this.orderNo = orderNo;
this.payPlatform = payPlatform;
this.platformNumber = platformNumber;
this.platformStatus = platformStatus;
this.createTime = createTime;
this.updateTime = updateTime;
}
public PayInfo() {
super();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Long getOrderNo() {
return orderNo;
}
public void setOrderNo(Long orderNo) {
this.orderNo = orderNo;
}
public Integer getPayPlatform() {
return payPlatform;
}
public void setPayPlatform(Integer payPlatform) {
this.payPlatform = payPlatform;
}
public String getPlatformNumber() {
return platformNumber;
}
public void setPlatformNumber(String platformNumber) {
this.platformNumber = platformNumber;
}
public String getPlatformStatus() {
return platformStatus;
}
public void setPlatformStatus(String platformStatus) {
this.platformStatus = platformStatus == null ? null : platformStatus.trim();
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}
\ No newline at end of file
package com.taobaostore.pojo;
import java.math.BigDecimal;
import java.util.Date;
// 商品表
public class Product {
private Integer id;// 商品id
private Integer categoryId;// 商品种类(对应其ID)
private String name;// 商品名
private String subtitle;// 商品子标题
private String mainImage;// 商品主图(url路径)
private String subImages;// 商品子图(json格式)
private String detail;// 商品详细
private BigDecimal price;// 商品价格
private Integer stock;// 库存数量
private Integer status;// 商品状态(1-在售,2-下架,3-删除)
private Date createTime;// 创建时间
private Date updateTime;// 更新时间
@Override
public String toString() {
return "Product [id=" + id + ", categoryId=" + categoryId + ", name=" + name + ", subtitle=" + subtitle
+ ", mainImage=" + mainImage + ", subImages=" + subImages + ", detail=" + detail + ", price=" + price
+ ", stock=" + stock + ", status=" + status + ", createTime=" + createTime + ", updateTime="
+ updateTime + "]";
}
public Product(Integer id, Integer categoryId, String name, String subtitle, String mainImage, String subImages, String detail, BigDecimal price, Integer stock, Integer status, Date createTime, Date updateTime) {
this.id = id;
this.categoryId = categoryId;
this.name = name;
this.subtitle = subtitle;
this.mainImage = mainImage;
this.subImages = subImages;
this.detail = detail;
this.price = price;
this.stock = stock;
this.status = status;
this.createTime = createTime;
this.updateTime = updateTime;
}
public Product() {
super();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getCategoryId() {
return categoryId;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public String getSubtitle() {
return subtitle;
}
public void setSubtitle(String subtitle) {
this.subtitle = subtitle == null ? null : subtitle.trim();
}
public String getMainImage() {
return mainImage;
}
public void setMainImage(String mainImage) {
this.mainImage = mainImage == null ? null : mainImage.trim();
}
public String getSubImages() {
return subImages;
}
public void setSubImages(String subImages) {
this.subImages = subImages == null ? null : subImages.trim();
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail == null ? null : detail.trim();
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public Integer getStock() {
return stock;
}
public void setStock(Integer stock) {
this.stock = stock;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}
\ No newline at end of file
package com.taobaostore.pojo;
import java.util.Date;
// 送货地址表
public class Receiver {
private Integer id;// 送货表id
private Integer userId;// 用户id
private String receiverName;// 收货姓名
private String recelverPhone;// 收货人手机号码
private String receiverMobile;// 收货电话
private String receiverProvince;// 收货人省份
private String receiverCity;// 收货人城市
private String receiverDistrict;// 收货人行政区(县级)
private String receiverAddress;// 收货人地址
private String receiverZip;// 收货人邮件编码
private Date createTime;// 创建时间
private Date updateTime;// 更新时间
public Receiver(Integer id, Integer userId, String receiverName, String recelverPhone, String receiverMobile, String receiverProvince, String receiverCity, String receiverDistrict, String receiverAddress, String receiverZip, Date createTime, Date updateTime) {
this.id = id;
this.userId = userId;
this.receiverName = receiverName;
this.recelverPhone = recelverPhone;
this.receiverMobile = receiverMobile;
this.receiverProvince = receiverProvince;
this.receiverCity = receiverCity;
this.receiverDistrict = receiverDistrict;
this.receiverAddress = receiverAddress;
this.receiverZip = receiverZip;
this.createTime = createTime;
this.updateTime = updateTime;
}
public Receiver() {
super();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getReceiverName() {
return receiverName;
}
public void setReceiverName(String receiverName) {
this.receiverName = receiverName == null ? null : receiverName.trim();
}
public String getRecelverPhone() {
return recelverPhone;
}
public void setRecelverPhone(String recelverPhone) {
this.recelverPhone = recelverPhone == null ? null : recelverPhone.trim();
}
public String getReceiverMobile() {
return receiverMobile;
}
public void setReceiverMobile(String receiverMobile) {
this.receiverMobile = receiverMobile == null ? null : receiverMobile.trim();
}
public String getReceiverProvince() {
return receiverProvince;
}
public void setReceiverProvince(String receiverProvince) {
this.receiverProvince = receiverProvince == null ? null : receiverProvince.trim();
}
public String getReceiverCity() {
return receiverCity;
}
public void setReceiverCity(String receiverCity) {
this.receiverCity = receiverCity == null ? null : receiverCity.trim();
}
public String getReceiverDistrict() {
return receiverDistrict;
}
public void setReceiverDistrict(String receiverDistrict) {
this.receiverDistrict = receiverDistrict == null ? null : receiverDistrict.trim();
}
public String getReceiverAddress() {
return receiverAddress;
}
public void setReceiverAddress(String receiverAddress) {
this.receiverAddress = receiverAddress == null ? null : receiverAddress.trim();
}
public String getReceiverZip() {
return receiverZip;
}
public void setReceiverZip(String receiverZip) {
this.receiverZip = receiverZip == null ? null : receiverZip.trim();
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}
\ No newline at end of file
package com.taobaostore.pojo;
import java.util.Date;
// 用户表
public class User {
private Integer id;// 用户id
private String username;// 用户名
private String password;// 用户密码
private String email;// 用户绑定邮箱
private String phone;// 用户手机号码
private String question;// 用户所设置的密保问题
private String answer;// 用户所设置的密保答案
private Integer role;// 用户身份:1-普通用户.0-管理员用户
private String headpic;// 用户头像路径
private Date createTime;// 创建时间
private Date updateTime;// 更新时间
public User(Integer id, String username, String password, String email, String phone, String question, String answer, Integer role, Date createTime, Date updateTime) {
this.id = id;
this.username = username;
this.password = password;
this.email = email;
this.phone = phone;
this.question = question;
this.answer = answer;
this.role = role;
this.createTime = createTime;
this.updateTime = updateTime;
}
public User() {
super();
}
public String getHeadpic() {
return headpic;
}
public void setHeadpic(String headpic) {
this.headpic = headpic;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username == null ? null : username.trim();
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email == null ? null : email.trim();
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone == null ? null : phone.trim();
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question == null ? null : question.trim();
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer == null ? null : answer.trim();
}
public Integer getRole() {
return role;
}
public void setRole(Integer role) {
this.role = role;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password=" + password + ", email=" + email + ", phone="
+ phone + ", question=" + question + ", answer=" + answer + ", role=" + role + ", headpic=" + headpic
+ ", createTime=" + createTime + ", updateTime=" + updateTime + "]";
}
}
\ No newline at end of file
package com.taobaostore.service;
import com.taobaostore.common.ServerResponse;
import com.taobaostore.vo.CartVo;
public interface ICartService {
/**
* 查询当前用户的所有购物车信息
* @param userId
* @return
*/
ServerResponse<CartVo> list(Integer userId);
/**
* 新增购物车信息
* @param userId
* @param productId
* @param count
* @return
*/
ServerResponse<CartVo> add(Integer userId,Integer productId,Integer count);
/**
* 更新购物车信息
* @param userId
* @param productId
* @param count
* @return
*/
ServerResponse<CartVo> update(Integer userId,Integer productId,Integer count);
/**
* 删除购物车信息
* @param userId
* @param productIds
* @return
*/
ServerResponse<CartVo> deleteProduct(Integer userId,String productIds);
/**
* 全选当前购物车中的商品
* @param userId
* @return
*/
ServerResponse<CartVo> checkedAll(Integer userId);
/**
* 全反选当前购物车中的商品
* @param userId
* @return
*/
ServerResponse<CartVo> UncheckedAll(Integer userId);
/**
* 选中某个商品
* @param userId
* @param productId
* @return
*/
ServerResponse<CartVo> checkPitch(Integer userId,Integer productId);
/**
* 反选某个商品
* @param userId
* @param productId
* @return
*/
ServerResponse<CartVo> UncheckPitch(Integer userId,Integer productId);
}
package com.taobaostore.service;
import java.util.List;
import org.springframework.stereotype.Service;
import com.taobaostore.common.ServerResponse;
import com.taobaostore.pojo.Category;
public interface ICategoryService {
/**
* 获取指定类型品类下的所有品类信息
* @param parent_id
* @return
*/
ServerResponse<List<Category>> listCategoryByParentId(int parent_id);
/**
* 返回所有节点
* @return
*/
ServerResponse<List<Category>> listCategory();
/**
* 新增一个分类
* @param categoryName
* @param parentId
* @return
*/
ServerResponse addCategory(String categoryName,Integer parentId);
/**
* 更新一个分类信息 根据分类id修改分类Name
* @param categoryId
* @param categoryName
* @return
*/
ServerResponse updateCategory(Integer categoryId,String categoryName);
/**
* 查询指定节点下的子节点 不递归
* @param categoryId
* @return
*/
ServerResponse getChildrenParallelCategroy(Integer categoryId);
/**
* 递归输出指定节点下的所有节点的id
* @param categoryId
*/
ServerResponse selectCategoryAndDeepChildrenByrenId(Integer categoryId);
}
package com.taobaostore.service;
import org.springframework.web.multipart.MultipartFile;
import com.taobaostore.common.ServerResponse;
public interface IFileService {
ServerResponse<String> upload(MultipartFile file,String path);
}
package com.taobaostore.service;
import java.util.List;
import java.util.Map;
import com.github.pagehelper.PageInfo;
import com.taobaostore.common.ServerResponse;
import com.taobaostore.vo.CartProductVo;
import com.taobaostore.vo.CartVo;
import com.taobaostore.vo.OrderVo;
public interface IOrderService {
// 生成支付宝二维码
public ServerResponse<Map<String, String>> pay(Long orderNo,Integer userId,String path);
// 支付宝回调函数
ServerResponse aliCallback(Map<String,String> params);
ServerResponse queryOrderPayStatus(Integer userId,Long orderNo);
ServerResponse<Object> create(Integer userId,Integer receiverId);
ServerResponse<CartVo> listCartProductVo(Integer userId);
ServerResponse<List<OrderVo>> getOrderVo(Integer userId);
ServerResponse<String> cancelOrder(Integer userId,Long orderOn);
ServerResponse<PageInfo<OrderVo>> manageList(Integer pageNum,Integer pageSize);
ServerResponse<String> updateOrderStatus(Integer userId,Long orderOn,Integer statusCode);
}
package com.taobaostore.service;
import java.util.List;
import com.github.pagehelper.PageInfo;
import com.taobaostore.common.ServerResponse;
import com.taobaostore.pojo.Product;
import com.taobaostore.vo.ProductDetailVo;
import com.taobaostore.vo.ProductListVo;
public interface IProductService {
/**
* 查询全部商品信息
* @return
*/
List<Product> listProduct();
/**
* 新增商品信息
* @param product
* @return
*/
ServerResponse<String> insertProduct(Product product);
/**
* 新增或更新商品信息
* @param product
* @return
*/
ServerResponse saveOrUpdateProduct(Product product);
/**
* 更新商品的状态(1-在售 2-下架 3-删除)
* @param productId
* @param status
* @return
*/
ServerResponse<String> setProductStatus(Integer productId,Integer status);
/**
* 分页返回商品信息
* @param pageNum
* @param pageSize
* @return
*/
ServerResponse<PageInfo<ProductListVo>> listProduct(Integer pageNum,Integer pageSize);
/**
* 按照id查询出商品信息
* @param productId
* @param pageNum
* @param pageSize
* @return
*/
ServerResponse<PageInfo<ProductListVo>> getProductById(int productId,Integer pageNum,Integer pageSize);
/**
* 根据姓名模糊查询
* @param productName
* @param pageNum
* @param pageSize
* @return
*/
ServerResponse<PageInfo<ProductListVo>> listProductByName(String productName,Integer pageNum,Integer pageSize);
/**
* 按照id查询出商品详细信息
* @param productId
* @param pageNum
* @param pageSize
* @return
*/
ServerResponse<PageInfo<ProductDetailVo>> getProductByIdDetail(int productId,Integer pageNum,Integer pageSize);
/**
* 前台返回商品详细信息
* @param productId
* @return
*/
ServerResponse<ProductDetailVo> getProductDetail(Integer productId);
/**
* 按照关键词或类型搜索
* @param keyword
* @param categoryId
* @param pageNum
* @param pageSize
* @return
*/
ServerResponse<PageInfo> getProductByKeywordCategory(String keyword,Integer categoryId,int pageNum,int pageSize);
}
package com.taobaostore.service;
import com.github.pagehelper.PageInfo;
import com.taobaostore.common.ServerResponse;
import com.taobaostore.pojo.Receiver;
public interface IReceiverService {
/**
* 新增地址
* @param receiver
* @return
*/
ServerResponse<String> add(Receiver receiver);
/**
* 获取指定用户下的所有地址信息
* @param pageNum
* @param pageSize
* @param userId
* @return
*/
ServerResponse<PageInfo<Receiver>> list(int pageNum,int pageSize,Integer userId);
/**
* 删除指定地址
* @param receiverId
* @return
*/
ServerResponse<String> delete(Integer userId,Integer receiverId);
}
package com.taobaostore.service;
import org.springframework.web.multipart.MultipartFile;
import com.taobaostore.common.ServerResponse;
import com.taobaostore.pojo.User;
public interface IUserService {
/**
* 登录系统
* @param username
* @param password
* @return
*/
ServerResponse<User> login(String username,String password);
/**
* 验证用户信息
* @param type
* @param str
* @return
*/
ServerResponse<String> checkValid(String type,String str);
/**
* 用户注册系统
* @param user
* @return
*/
ServerResponse<String> register(User user);
/**
* 验证用户以及密保是否存在
* @param username
* @return
*/
ServerResponse<String> selectQuestion(String username);
/**
* 查询指定用户的密保答案
* @param username
* @param question
* @param answer
* @return
*/
ServerResponse<String> checkQuestion(String username,String question,String answer);
/**
* 执行找回密码操作
* @param username
* @param passwordNew
* @param forgetToken
* @return
*/
ServerResponse<String> forgetResetPassword(String username,String passwordNew,String forgetToken);
/**
* 保存用户信息
* @param user
* @return
*/
ServerResponse<User> updateUserMsg(User user,MultipartFile pic);
/**
* 在用户存在的情况下保存修改密码
* @param passwordOld
* @param passwordNew
* @param user
*/
ServerResponse<String> resetPassword(String passwordOld,String passwordNew,User user);
/**
* 判断用户是否为管理员且其已登录
* @param user
* @return
*/
ServerResponse checkAdminRole(User user);
}
package com.taobaostore.service.impl;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Spliterator;
import org.apache.ibatis.javassist.compiler.ast.NewExpr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.taobaostore.common.BigDecimalUtil;
import com.taobaostore.common.Const;
import com.taobaostore.common.ResponseCode;
import com.taobaostore.common.ServerResponse;
import com.taobaostore.dao.CartMapper;
import com.taobaostore.dao.ProductMapper;
import com.taobaostore.pojo.Cart;
import com.taobaostore.pojo.Product;
import com.taobaostore.service.ICartService;
import com.taobaostore.util.DateTimeUtil;
import com.taobaostore.util.PropertiesUtil;
import com.taobaostore.vo.CartProductVo;
import com.taobaostore.vo.CartVo;
@Service
@Primary
public class CartServiceImpl implements ICartService{
@Autowired
private CartMapper cartMapper;
@Autowired
private ProductMapper productMapper;
/**
* 查询该用户下所有购物车信息
* @param userId
* @return
*/
public ServerResponse<CartVo> list(Integer userId) {
CartVo cartVo = this.getCartVoLimit(userId);
return ServerResponse.createBySuccess(cartVo);
}
/**
* 新增购物车记录
*/
public ServerResponse<CartVo> add(Integer userId,Integer productId,Integer count) {
if (productId == null || count == null) {
return ServerResponse.createByError(ResponseCode.ILLEGAL_ARGUMENT.getCODE(), ResponseCode.ILLEGAL_ARGUMENT.getDESC());
}
System.out.println("测试"+cartMapper.selectCartByUserIdProductId(userId, productId));
Cart cart = cartMapper.selectCartByUserIdProductId(userId, productId);
if (cart == null) {
//这个购物车记录不存在
Cart cartItem = new Cart();
cartItem.setQuantity(count);
cartItem.setChecked(Const.Cart.ON_CHECKED);
cartItem.setProductId(productId);
cartItem.setUserId(userId);
cartMapper.insert(cartItem);
}else {
//如果已经存在这个商品的记录,就叠加他的数量
count = cart.getQuantity() + count;
cart.setQuantity(count);
cartMapper.updateByPrimaryKeySelective(cart);
}
CartVo cartVo = this.getCartVoLimit(userId);
return ServerResponse.createBySuccess("新增购物车记录成功!", cartVo);
}
/**
* 更新购物车
* @param userId
* @param productId
* @param count
* @return
*/
public ServerResponse<CartVo> update(Integer userId,Integer productId,Integer count){
if (productId == null || count == null) {
return ServerResponse.createByError(ResponseCode.ILLEGAL_ARGUMENT.getCODE(), ResponseCode.ILLEGAL_ARGUMENT.getDESC());
}
Cart cart = cartMapper.selectCartByUserIdProductId(userId, productId);
if (cart != null) {
cart.setQuantity(count);
}
cartMapper.updateByPrimaryKeySelective(cart);
CartVo cartVo = this.getCartVoLimit(userId);
return ServerResponse.createBySuccess(cartVo);
}
/***
* 删除购物车记录
* @param userId
* @param productIds
* @return
*/
public ServerResponse<CartVo> deleteProduct(Integer userId,String productIds){
List<String> list = Splitter.on(",").splitToList(productIds);
if (null == list || list.size() == 0) {
return ServerResponse.createByError(ResponseCode.ILLEGAL_ARGUMENT.getCODE(), ResponseCode.ILLEGAL_ARGUMENT.getDESC());
}
cartMapper.deleteByUserIdProductIds(userId, list);
CartVo cartVo = this.getCartVoLimit(userId);
return ServerResponse.createBySuccess(cartVo);
}
/**
* 全选购物车商品
* @return
*/
public ServerResponse<CartVo> checkedAll(Integer userId){
if (null == userId) {
return ServerResponse.createByError(ResponseCode.ILLEGAL_ARGUMENT.getCODE(), ResponseCode.ILLEGAL_ARGUMENT.getDESC());
}
cartMapper.updateByCheckPitchAll(userId);
return ServerResponse.createBySuccess(this.getCartVoLimit(userId));
}
/**
* 全反选购物车商品
* @return
*/
public ServerResponse<CartVo> UncheckedAll(Integer userId){
if (null == userId) {
return ServerResponse.createByError(ResponseCode.ILLEGAL_ARGUMENT.getCODE(), ResponseCode.ILLEGAL_ARGUMENT.getDESC());
}
cartMapper.updateByCheckInvertAll(userId);
return ServerResponse.createBySuccess(this.getCartVoLimit(userId));
}
/**
* 选中某个商品
* @param userId
* @param productId
* @return
*/
public ServerResponse<CartVo> checkPitch(Integer userId,Integer productId){
if (null == userId || null == productId) {
return ServerResponse.createByError(ResponseCode.ILLEGAL_ARGUMENT.getCODE(), ResponseCode.ILLEGAL_ARGUMENT.getDESC());
}
cartMapper.updateByCheckPitch(userId, productId);
return ServerResponse.createBySuccess(this.getCartVoLimit(userId));
}
/**
* 反选某个商品
* @param userId
* @return
*/
public ServerResponse<CartVo> UncheckPitch(Integer userId,Integer productId){
if (null == userId || null == productId) {
return ServerResponse.createByError(ResponseCode.ILLEGAL_ARGUMENT.getCODE(), ResponseCode.ILLEGAL_ARGUMENT.getDESC());
}
int resultNum = cartMapper.updateByCheckInvert(userId, productId);
return ServerResponse.createBySuccess(this.getCartVoLimit(userId));
}
/**
* 用于校验库存等问题并封装VO对象返回使用
* @param userId
* @return
*/
private CartVo getCartVoLimit(Integer userId) {
CartVo cartVo = new CartVo();
// 获取这个用户下的所有购物车商品记录
List<Cart> cartList = cartMapper.selectCartByUserId(userId);
List<CartProductVo> cartProductVoList = Lists.newArrayList();
// 初始化商品总价格
BigDecimal cartTotalPrice = new BigDecimal("0");
if (cartList != null && cartList.size() > 0) {
// 遍历cartList 用于填充cartProductVoList
for (Cart cart : cartList) {
System.out.println(cart);
CartProductVo cartProductVo = new CartProductVo();
cartProductVo.setId(cart.getId());
cartProductVo.setUserId(userId);
cartProductVo.setProductId(cart.getProductId());
System.out.println("要搜索的商品:"+cart.getProductId());
Product product = productMapper.getProductById(cart.getProductId());
if (product != null) {
cartProductVo.setProductMainImage(product.getMainImage());
cartProductVo.setProductName(product.getName());
cartProductVo.setProductSubtitle(product.getSubtitle());
cartProductVo.setProductStatus(product.getStatus());
cartProductVo.setProductPrice(product.getPrice());
//判断库存是否合法
int buyLimitCount = 0;
if (product.getStock() >= cart.getQuantity()) {
// 在库存充足的时候为我们要买的数量
buyLimitCount = cart.getQuantity();
cartProductVo.setLimitQuantity(Const.Cart.LIMIT_NUM_SUCCESS);
}else {
// 库存不充足的时候直接改为最大库存数量
buyLimitCount = product.getStock();
cartProductVo.setLimitQuantity(Const.Cart.LIMIT_NUM_FAIL);
//购物车中更新有效库存
Cart cartForQuantity = new Cart();
cartForQuantity.setId(cart.getId());
cartForQuantity.setQuantity(buyLimitCount);
cartMapper.updateByPrimaryKeySelective(cartForQuantity);
}
cartProductVo.setQuantity(buyLimitCount);
// 计算当前商品总价格
cartProductVo.setProductTotalPrice(BigDecimalUtil.mul(product.getPrice().doubleValue(), cartProductVo.getQuantity().doubleValue()));
cartProductVo.setProductChecked(cart.getChecked());
}
if (cart.getChecked() == Const.Cart.CHECKED) {
// 如果被选中就添加整个购物车总价
cartTotalPrice = BigDecimalUtil.add(cartTotalPrice.doubleValue(), cartProductVo.getProductTotalPrice().doubleValue());
}
cartProductVoList.add(cartProductVo);
}
}
System.out.println("总价格"+cartTotalPrice);
cartVo.setCartTotalPrice(cartTotalPrice);
cartVo.setCartProductVoList(cartProductVoList);
cartVo.setAllChecked(this.getAllCheckedStatus(userId));// 是否全选
cartVo.setImageHost(PropertiesUtil.getValue("FTP_IP"));
return cartVo;
}
/**
* 判断这个用户下的购物车是否全选状态
* @param userId
* @return
*/
private boolean getAllCheckedStatus(Integer userId) {
if (userId == null) {
return false;
}
return cartMapper.selectCartProductCheckedStatusByUserId(userId)==0;
}
}
package com.taobaostore.service.impl;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.google.common.collect.Sets;
import com.taobaostore.common.ServerResponse;
import com.taobaostore.dao.CategoryMapper;
import com.taobaostore.pojo.Category;
import com.taobaostore.service.ICategoryService;
@Primary
@Transactional
@Service
public class CategoryServiceImpl implements ICategoryService {
@Autowired
private CategoryMapper categorymapper;
/**
* 根据品类父id返回指定品类列表(查询同一类型的品类信息)
* @param parent_id
* @return
*/
public ServerResponse<List<Category>> listCategoryByParentId(int parent_id){
List<Category> list = categorymapper.listCategoryByParentId(parent_id);
if (null != list && list.size()!=0) {
return ServerResponse.createBySuccess(list);
}
return ServerResponse.createByError("没有找到数据");
}
/**
* 新增分类
* @param categoryName
* @param parentId
* @return
*/
@Override
public ServerResponse addCategory(String categoryName, Integer parentId) {
if (parentId == null || StringUtils.isBlank(categoryName)) {
return ServerResponse.createByError("添加类型参数错误!");
}
Category category = new Category();
category.setName(categoryName);
category.setParentId(parentId);
category.setStatus(true);
int rowCount = categorymapper.insert(category);
if (rowCount > 0) {
return ServerResponse.createBySuccess("添加分类成功");
}
return ServerResponse.createBySuccess("添加分类成功!");
}
/**
* 更新分类名称
* @param categoryId
* @param categoryName
* @return
*/
@Override
public ServerResponse updateCategory(Integer categoryId, String categoryName) {
if (null == categoryId || StringUtils.isBlank(categoryName)) {
return ServerResponse.createByError("参数为空");
}
Category category = new Category();
category.setId(categoryId);
category.setName(categoryName);
int rowCount = categorymapper.updateByPrimaryKeySelective(category);
if (rowCount > 0) {
return ServerResponse.createBySuccess("更新分类成功!");
}
return ServerResponse.createByError("更新分类失败");
}
/**
* 获取指定分类下的分类(不递归)
*/
public ServerResponse getChildrenParallelCategroy(Integer categoryId) {
if (null == categoryId) {
return ServerResponse.createByError("参数为空");
}
List<Category> list = categorymapper.listCategoryChildren(categoryId);
if (list.isEmpty()) {
return ServerResponse.createByError("没有找到分类!");
}
return ServerResponse.createBySuccess(list);
}
/**
* 获取指定分类下的所有子分类(递归算法)
*/
public ServerResponse<List<Integer>> selectCategoryAndDeepChildrenByrenId(Integer categoryId) {
if (null == categoryId) {
return ServerResponse.createByError("参数为空");
}
// 获取这个要递归的品类
Set<Category> CategorySets = Sets.newConcurrentHashSet();
findChildCategory(CategorySets, categoryId);
System.out.println("元素数量:"+CategorySets.size());
List<Integer> list =new ArrayList<Integer>();
for (Category categoryItem : CategorySets) {
list.add(categoryItem.getId());
}
return ServerResponse.createBySuccess("读取子分类成功", list);
}
/**
* 递归节点
* @param categorytSet
* @param categoryId
* @return
*/
private Set<Category> findChildCategory(Set<Category> categorytSet,Integer categoryId){
// 获取当前节点信息(判断这个节点是否还存在)
Category category = categorymapper.getCategoryById(categoryId);
// 这个节点如果不是空的我们就添加进集合
if (category != null) {
categorytSet.add(category);
}
// 查询出这个节点下的所有子节点(非递归)
List<Category> list = categorymapper.listCategoryChildren(categoryId);
for (Category categoryItem : list) {
// 将每一个子节点再递归入这个方法 判断其是否有子节点
findChildCategory(categorytSet, categoryItem.getId());
}
return categorytSet;
}
@Override
public ServerResponse<List<Category>> listCategory() {
List<Category> list = categorymapper.listCategory();
System.out.println("dao"+list);
if (null!=list&&list.size()>0) {
return ServerResponse.createBySuccess(list);
}
return ServerResponse.createByError("没有找到数据");
}
}
\ No newline at end of file
package com.taobaostore.service.impl;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.taobaostore.common.ServerResponse;
import com.taobaostore.service.IFileService;
import com.taobaostore.util.FTPUtil;
@Service
public class FileServiceImpl implements IFileService{
/**
* 上传文件
*/
public ServerResponse<String> upload(MultipartFile file,String path) {
String fileName = file.getOriginalFilename();
// 获取文件拓展名
String fileExtensionName = fileName.substring(fileName.indexOf(".")+1);
// 拼接上传文件名
String fileUploadName = UUID.randomUUID().toString()+ "." + fileExtensionName;
File fileDir = new File(path);
if (!fileDir.exists()) {
fileDir.setWritable(true);
fileDir.mkdir();
}
// 得到要上傳的目標文件
File targetFile = new File(path,fileUploadName);
try {
file.transferTo(targetFile);
//TODO 将文件上传至FTP图片服务器
FTPUtil.fileUpload(fileUploadName, file.getInputStream());
//TODO 将本机tomcat磁盘下的图片删除
fileDir.delete();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return ServerResponse.createBySuccess("上传成功",fileUploadName);
}
}
package com.taobaostore.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.taobaostore.common.ResponseCode;
import com.taobaostore.common.ServerResponse;
import com.taobaostore.dao.CategoryMapper;
import com.taobaostore.dao.ProductMapper;
import com.taobaostore.pojo.Category;
import com.taobaostore.pojo.Product;
import com.taobaostore.service.ICategoryService;
import com.taobaostore.service.IProductService;
import com.taobaostore.util.DateTimeUtil;
import com.taobaostore.util.PropertiesUtil;
import com.taobaostore.vo.ProductDetailVo;
import com.taobaostore.vo.ProductListVo;
@Service
@Primary
@Transactional
public class ProductServiceImpl implements IProductService {
@Autowired
private ProductMapper productMapper;
@Autowired
private CategoryMapper categoryMapper;
@Autowired
private ICategoryService iCategoryService;
@Override
public List<Product> listProduct() {
return productMapper.listProduct();
}
@Override
public ServerResponse<String> insertProduct(Product product) {
try {
productMapper.insertSelective(product);
} catch (Exception e) {
e.printStackTrace();
}
return ServerResponse.createBySuccess("新增商品信息成功!");
}
/**
* 新增商品
*/
public ServerResponse saveOrUpdateProduct(Product product) {
if (product != null) {
// 如果商品子图片不为空那就将第一张图片设置为主图
if (StringUtils.isNotBlank(product.getSubImages())) {
String[] subImageArray = product.getSubImages().split(",");
if (subImageArray.length > 0) {
product.setMainImage(subImageArray[0]);
}
}
if (product.getId() != null) {
System.out.println("进入更新");
int rowCount = productMapper.updateByPrimaryKeySelective(product);
if (rowCount == 1) {
return ServerResponse.createBySuccess("商品更新成功!");
}
return ServerResponse.createByError("商品更新失败!");
}else {
int rowCount = productMapper.insert(product);
if (rowCount == 1) {
return ServerResponse.createBySuccess("商品新增成功");
}
return ServerResponse.createByError("商品新增失败");
}
}
return ServerResponse.createByError("操作失败或商品参数不正确!");
}
/**
*设置商品状态(1.在售,2.下架,3.删除)
*/
public ServerResponse<String> setProductStatus(Integer productId,Integer status){
if (null == productId || null == status) {
return ServerResponse.createByError(ResponseCode.ILLEGAL_ARGUMENT.getCODE(), ResponseCode.ILLEGAL_ARGUMENT.getDESC());
}
Product product = new Product();
product.setId(productId);
product.setStatus(status);
int rowCount = productMapper.updateByPrimaryKeySelective(product);
if (rowCount == 1) {
return ServerResponse.createBySuccess("更新商品信息成功");
}else {
return ServerResponse.createByError("更新商品信息失败!");
}
}
/**
*查询指定页面以及页容量的数据
* @param pageNum
* @param pageSize
* @return
*/
public ServerResponse<PageInfo<ProductListVo>> listProduct(Integer pageNum,Integer pageSize){
PageHelper.startPage(pageNum, pageSize);
List<Product> productList = productMapper.listProduct();
List<ProductListVo> productListVos = new ArrayList<ProductListVo>();
for (Product product : productList) {
// 不显示被删除的元素
productListVos.add(ProductToVo(product));
}
PageInfo<ProductListVo> pageInfo = new PageInfo<ProductListVo>(productListVos);
int pageCount = productMapper.CountProduct();
pageInfo.setPages(pageCount % pageSize==0?pageCount/pageSize:pageCount/pageSize+1);// 手动计算总页数
System.out.println("总页数:"+pageInfo.getPages());
ServerResponse<PageInfo<ProductListVo>> response = ServerResponse.createBySuccess(pageInfo);
System.out.println("页面:"+response);
return response;
}
/**
* 按照id查询出商品信息(用于列表)
* @param productId
* @return
*/
public ServerResponse<PageInfo<ProductListVo>> getProductById(int productId,Integer pageNum,Integer pageSize){
PageHelper.startPage(pageNum, pageSize);
List<Product> productList = Lists.newArrayList();
productList.add(productMapper.getProductById(productId));
if (productMapper.getProductById(productId) == null) {
return ServerResponse.createByError("沒有找到你想要的数据");
}
List<ProductListVo> productListVos = new ArrayList<ProductListVo>();
for (Product product : productList) {
productListVos.add(ProductToVo(product));
}
PageInfo<ProductListVo> pageInfo = new PageInfo<ProductListVo>(productListVos);
int pageCount = productMapper.CountProduct();
pageInfo.setPages(pageCount % pageSize==0?pageCount/pageSize:pageCount/pageSize+1);// 手动计算总页数
System.out.println("总页数:"+pageInfo.getPages());
ServerResponse<PageInfo<ProductListVo>> response = ServerResponse.createBySuccess(pageInfo);
System.out.println("页面:"+response);
return response;
}
/**
* 按照id查询出商品信息(用于详情)
* @param productId
* @return
*/
public ServerResponse<PageInfo<ProductDetailVo>> getProductByIdDetail(int productId,Integer pageNum,Integer pageSize){
PageHelper.startPage(pageNum, pageSize);
List<Product> productList = Lists.newArrayList();
productList.add(productMapper.getProductById(productId));
if (productMapper.getProductById(productId) == null) {
return ServerResponse.createByError("沒有找到你想要的数据");
}
List<ProductDetailVo> productDetailList = new ArrayList<ProductDetailVo>();
for (Product product : productList) {
productDetailList.add(ProductToDetailVo(product));
}
PageInfo<ProductDetailVo> pageInfo = new PageInfo<ProductDetailVo>(productDetailList);
int pageCount = productMapper.CountProduct();
pageInfo.setPages(pageCount % pageSize==0?pageCount/pageSize:pageCount/pageSize+1);// 手动计算总页数
System.out.println("总页数:"+pageInfo.getPages());
ServerResponse<PageInfo<ProductDetailVo>> response = ServerResponse.createBySuccess(pageInfo);
System.out.println("页面:"+response);
return response;
}
/**
* 按照名称模糊查询商品信息
* @param productName
* @param pageNum
* @param pageSize
* @return
*/
public ServerResponse<PageInfo<ProductListVo>> listProductByName(String productName,Integer pageNum,Integer pageSize){
PageHelper.startPage(pageNum, pageSize);
List<Product> productList = productMapper.listProductByName(productName);
if (productList.size() == 0) {
return ServerResponse.createByError("沒有找到你想要的数据");
}
List<ProductListVo> productListVos = new ArrayList<ProductListVo>();
for (Product product : productList) {
// 不显示被删除的元素
productListVos.add(ProductToVo(product));
}
PageInfo<ProductListVo> pageInfo = new PageInfo<ProductListVo>(productListVos);
int pageCount = productMapper.CountProduct();
pageInfo.setPages(pageCount % pageSize==0?pageCount/pageSize:pageCount/pageSize+1);// 手动计算总页数
System.out.println("总页数:"+pageInfo.getPages());
ServerResponse<PageInfo<ProductListVo>> response = ServerResponse.createBySuccess(pageInfo);
System.out.println("页面:"+response);
return response;
}
/**
* 前台返回商品详细信息
* @param productId
* @return
*/
public ServerResponse<ProductDetailVo> getProductDetail(Integer productId){
if (productId == null) {
return ServerResponse.createByError(ResponseCode.ILLEGAL_ARGUMENT.getCODE(), ResponseCode.ILLEGAL_ARGUMENT.getDESC());
}
Product product = productMapper.getProductIdStatus(productId);
if (product == null) {
return ServerResponse.createByError("产品已被下架或者删除!");
}
ProductDetailVo productDetailVo = ProductToDetailVo(product);
return ServerResponse.createBySuccess(productDetailVo);
}
/**
* 返回用户查找的商品集合
* @param keyword
* @param categoryId
* @param pageNum
* @param pageSize
* @return
*/
public ServerResponse<PageInfo> getProductByKeywordCategory(String keyword,Integer categoryId,int pageNum,int pageSize){
if (StringUtils.isBlank(keyword) && categoryId == null) {
return ServerResponse.createByError(ResponseCode.ILLEGAL_ARGUMENT.getCODE(),ResponseCode.ILLEGAL_ARGUMENT.getDESC());
}
if (null == categoryId) {
categoryId = 0;
}
// 遍历出该节点下所有子节点分类
List<Integer> categoryIdList = new ArrayList<Integer>();
Category category = categoryMapper.getCategoryById(categoryId);
if (category == null && StringUtils.isBlank(keyword)) {
// 没有找到指定分类也没有传入关键词
PageHelper.startPage(pageNum, pageSize);
List<ProductListVo> productListVos = Lists.newArrayList();
PageInfo pageInfo = new PageInfo(productListVos);
return ServerResponse.createBySuccess(pageInfo);
}
categoryIdList = (List<Integer>) iCategoryService.selectCategoryAndDeepChildrenByrenId(categoryId).getData();
keyword = new StringBuilder().append("%").append(keyword).append("%").toString();
// 分页
PageHelper.startPage(pageNum, pageSize);
// 查出指定类型或指定关键字的商品信息
List<Product> list = productMapper.selectByNameAndCategoryIds(StringUtils.isBlank(keyword)?null:keyword,categoryIdList.size()==0?null:categoryIdList);
List<ProductListVo> productListVos = Lists.newArrayList();
for (Product product : list) {
productListVos.add(ProductToVo(product));
}
PageInfo pageInfo = new PageInfo(productListVos);
return ServerResponse.createBySuccess(pageInfo);
}
/**
* 將product對象转换为Vo对象(value Object)
* @param product
* @return
*/
private ProductListVo ProductToVo(Product product) {
ProductListVo productListVo = new ProductListVo();
productListVo.setId(product.getId());
productListVo.setName(product.getName());
productListVo.setCategoryId(product.getCategoryId());
productListVo.setStatus(product.getStatus());
productListVo.setStock(product.getStock());
productListVo.setCreateTime(DateTimeUtil.DateTostr(product.getCreateTime()));
productListVo.setImage_Main(product.getMainImage());
// 处理状态信息
if (product.getStatus()==1) {
productListVo.setStatusName("在售");
}else if (product.getStatus()==2) {
productListVo.setStatusName("下架");
}else if (product.getStatus()==3) {
productListVo.setStatusName("刪除");
}
productListVo.setCategoryName(categoryMapper.getCategoryById(product.getCategoryId()).getName());
return productListVo;
}
/**
* 将product对象转换为商品详情
* @param product
* @return
*/
private ProductDetailVo ProductToDetailVo(Product product){
ProductDetailVo productDetailVo = new ProductDetailVo();
productDetailVo.setId(product.getId());
productDetailVo.setSubtitle(product.getSubtitle());
productDetailVo.setPrice(product.getPrice());
productDetailVo.setMainImage(product.getMainImage());
String[] subImages = product.getSubImages().split(",");
productDetailVo.setSubImages(subImages);
productDetailVo.setCategoryId(product.getCategoryId());
productDetailVo.setDetail(product.getDetail());
productDetailVo.setName(product.getName());
productDetailVo.setStatus(product.getStatus());
productDetailVo.setStock(product.getStock());
Category category = categoryMapper.getCategoryById(product.getCategoryId());
if(category == null){
productDetailVo.setParentCategoryId(0);//默认根节点
}else{
productDetailVo.setParentCategoryId(category.getParentId());
}
productDetailVo.setCreateTime(DateTimeUtil.DateTostr(product.getCreateTime()));
productDetailVo.setUpdateTime(DateTimeUtil.DateTostr(product.getUpdateTime()));
return productDetailVo;
}
}
package com.taobaostore.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.taobaostore.common.ResponseCode;
import com.taobaostore.common.ServerResponse;
import com.taobaostore.dao.ReceiverMapper;
import com.taobaostore.pojo.Receiver;
import com.taobaostore.service.IReceiverService;
@Service
@Primary
public class ReceiverServiceImpl implements IReceiverService{
@Autowired
private ReceiverMapper receiverMapper;
/**
* 新增收货地址记录
*/
public ServerResponse<String> add(Receiver receiver) {
if (null == receiver) {
return ServerResponse.createByError(ResponseCode.ILLEGAL_ARGUMENT.getCODE(), ResponseCode.ILLEGAL_ARGUMENT.getDESC());
}
int resultCount = receiverMapper.insert(receiver);
if (resultCount == 1) {
return ServerResponse.createBySuccess("新增地址成功!");
}
return ServerResponse.createByError("未知的错误请联系管理员");
}
/**
* 查询全部收货地址信息
* @param pageNum
* @param pageSize
* @param userId
* @return
*/
public ServerResponse<PageInfo<Receiver>> list(int pageNum,int pageSize,Integer userId){
PageHelper.startPage(pageNum, pageSize);// 进行分页
List<Receiver> receivers = Lists.newArrayList();
if (null != userId) {
receivers = receiverMapper.listReceiverByUserId(userId);
}
PageInfo<Receiver> pageInfo = new PageInfo<Receiver>(receivers);
return ServerResponse.createBySuccess(pageInfo);
}
/**
* 删除指定收货地址
* @param receiverId
* @return
*/
public ServerResponse<String> delete(Integer userId,Integer receiverId){
if (null == receiverId) {
return ServerResponse.createByError(ResponseCode.ILLEGAL_ARGUMENT.getCODE(), ResponseCode.ILLEGAL_ARGUMENT.getDESC());
}
// 虽然我们已经有了地址表的id,但是为了防止横向越权还是要校验用户id
int resultCount = receiverMapper.deleteReceiverById(userId,receiverId);
if (resultCount == 1) {
return ServerResponse.createBySuccess("删除地址成功!");
}
return ServerResponse.createByError("遇到未知问题,请联系管理员!");
}
}
\ No newline at end of file
package com.taobaostore.service.impl;
import static org.hamcrest.CoreMatchers.nullValue;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Date;
import java.util.UUID;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.taobaostore.common.Const;
import com.taobaostore.common.ServerResponse;
import com.taobaostore.common.TokenCache;
import com.taobaostore.dao.UserMapper;
import com.taobaostore.pojo.User;
import com.taobaostore.service.IFileService;
import com.taobaostore.service.IUserService;
import com.taobaostore.util.FTPUtil;
import com.taobaostore.util.MD5Util;
import com.taobaostore.util.StringUtil;
import com.taobaostore.vo.ProductListVo;
@Service
@Primary
public class UserServiceImpl implements IUserService{
@Autowired
private UserMapper userMapper;
@Autowired
private IFileService iFileService;
/**
* 用户登录
*/
@Override
public ServerResponse<User> login(String username, String password) {
System.out.println(username);
username = StringUtil.getEncoding(username);
System.out.println(username);
// 验证用户是否存在
if (userMapper.checkUserName(username)==0) {
return ServerResponse.createByError("用户名不存在");
}
// 密码登录(MD5)
password = MD5Util.MD5Encode(password);
User user = userMapper.selectLogin(username, password);
if (user == null) {
return ServerResponse.createByError("密码错误");
}
// 将用户密码置空(保证安全)
user.setPassword(StringUtils.EMPTY);
System.out.println(user.getHeadpic());
return ServerResponse.createBySuccess("登录成功", user);
}
/**
* 用户信息注册
* @param user
* @return
*/
public ServerResponse<String> register(User user){
// 对用户的中文进行强制编码
user = StringUtil.getEncodingUser(user);
System.out.println(user);
// 对用户信息进行校验
ServerResponse<String> response = this.checkValid(Const.USER_NAME, user.getUsername());
if(!response.isSuccess()) return response;
response = this.checkValid(Const.EMAIL, user.getEmail());
if(!response.isSuccess()) return response;
// 设置用户时间轴
user.setCreateTime(new Date());
user.setUpdateTime(new Date());
// 设置用户默认权限
user.setRole(Const.Role.ROLE_USER);
// 将用户密码进行MD5加密
user.setPassword(MD5Util.MD5Encode(user.getPassword()));
user.setHeadpic("http://49.232.168.42/taobaoHead.jpg");
System.out.println("注册成功要看看");
userMapper.insert(user);
return ServerResponse.createBySuccess("用户注册成功!");
}
/**
* 校验用户信息
* @param type
* @param str
* @return
*/
public ServerResponse<String> checkValid(String type,String str){
// 判断类型不为null且不为空字符串的情况下进行校验
if (StringUtils.isNotBlank(type)) {
// 判断类型进行对应的校验
if (Const.USER_NAME.equals(type)) {
if (userMapper.checkUserName(str) > 0) {
return ServerResponse.createByError("用户已存在!");
}
}
if (Const.EMAIL.equals(type)) {
if (userMapper.checkEmail(str) > 0) {
return ServerResponse.createByError("邮箱已被使用!");
}
}
}else {
return ServerResponse.createByError("参数错误!");
}
return ServerResponse.createBySuccess("校验成功!");
}
/**
* 验证用户是否有密保问题
* 如果有就返回其密保问题
* @param username
* @return
*/
public ServerResponse<String> selectQuestion(String username){
username = StringUtil.getEncoding(username);
ServerResponse<String> response = this.checkValid(Const.USER_NAME,username);
if (response.isSuccess()) {
// 如果用户不存在
return ServerResponse.createByError("用户不存在!");
}
String question = userMapper.selectQuestion(username);
if (!StringUtils.isNotBlank(question)) {
// 如果密保问题等于空的话
return ServerResponse.createByError("没有密保问题!");
}
return ServerResponse.createBySuccess(question);
}
/**
*查询指定用户的指定密保问题是否正确
* @param username
* @param question
* @param answer
* @return
*/
public ServerResponse<String> checkQuestion(String username,String question,String answer){
username = StringUtil.getEncoding(username);
question = StringUtil.getEncoding(question);
answer = StringUtil.getEncoding(answer);
System.out.println("信息:"+username+"-"+question+"-"+answer);
int count = userMapper.selectAnswer(username, question, answer);
System.out.println("查询测试"+count);
if (count > 0) {
// 说明验证成功,将这个记录存入缓存
String token = UUID.randomUUID().toString();
TokenCache.setKey(TokenCache.TOKEN_NAME+username,token);
return ServerResponse.createBySuccess(token);
}else {
// 如果再次验证的时候失败了 那就清除token
TokenCache.setKey(TokenCache.TOKEN_NAME+username,StringUtils.EMPTY);
}
return ServerResponse.createByError("答案错误,请重新输入!");
}
/**
* 忘记密码的情况下修改密码
* @return
*/
public ServerResponse<String> forgetResetPassword(String username,String passwordNew,String forgetToken){
username = StringUtil.getEncoding(username);
if (this.checkValid(Const.USER_NAME, username).isSuccess()) {
return ServerResponse.createByError("用户不存在");
}
forgetToken = TokenCache.getKey(TokenCache.TOKEN_NAME+username);
if (StringUtils.isBlank(forgetToken)) {
// token不存在或者被销毁
return ServerResponse.createByError("token不存在!");
}
System.out.println("当前token:"+forgetToken);
// 如果token存在即说明已经通过密保验证
// 将用户的新密码转换成md5格式
String MD5Password = MD5Util.MD5Encode(passwordNew);
userMapper.updatePwd(username, MD5Password);
return ServerResponse.createBySuccess("密码找回成功!");
}
/**
* 修改用户信息
* @param user
* @return
*/
public ServerResponse<User> updateUserMsg(User user,MultipartFile pic){
try {
if (null!=pic.getOriginalFilename() && !pic.getOriginalFilename().trim().equals("")) {
// // 获取上传的图片的后缀名
// String imgSuffix = pic.getOriginalFilename().substring(pic.getOriginalFilename().lastIndexOf("."));
// System.out.println(pic.getInputStream());
// FTPUtil.fileUpload(UUID.randomUUID().toString()+imgSuffix,pic.getInputStream());
// // 生成随机字码作为图片的存储名称
// String picuuid = UUID.randomUUID().toString();
// // 拼接图片名称
// String imgname = picuuid+imgSuffix;
// // 上传图片并设置图片信息
// Files.copy(pic.getInputStream(), Paths.get(Const.USER_PIC,imgname));
// // 设置用户的图片地址
// user.setHeadpic(imgname);
// System.out.println("图片上传信息"+Const.USER_PIC+imgname);
ServerResponse<String> response = iFileService.upload(pic,Const.USER_PIC);
user.setHeadpic("http://49.232.168.42/"+response.getData());
System.out.println(user.getHeadpic());
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("图片路径:"+user.getHeadpic());
System.out.println(user);
if (null == user || null == user.getUsername()) {
return ServerResponse.createByError("没有找到要修改的用户信息!");
}
// 更新用户信息
userMapper.updateByPrimaryKeySelective(user);
// 更新完用户信息之后将更新的图片从固定目录写入动态目录用于读取
// 如果没有上传头像那就使用默认的
if (null==pic.getOriginalFilename() || pic.getOriginalFilename().trim().equals("")) {
user.setHeadpic("http://49.232.168.42/taobaoHead.jpg");
user.setUpdateTime(new Date());
}
ServerResponse<User> response = ServerResponse.createBySuccess("用户信息更新成功!", user);
return response;
}
/**
* 在登录情况下修改密码
* @param passwordOld
* @param passwordNew
* @param user
* @return
*/
public ServerResponse<String> resetPassword(String passwordOld,String passwordNew,User user){
// 防止横向越权:在修改密码的时候要校验旧密码,并且判断其id
if (userMapper.selectPassword(MD5Util.MD5Encode(passwordOld), user.getId()) == 0) {
// 旧密码错误
return ServerResponse.createByError("旧密码错误");
}
// 设置新密码
user.setPassword(MD5Util.MD5Encode(passwordNew));
int updateCount = userMapper.updateByPrimaryKeySelective(user);
if (updateCount > 0) {
// 密码更新成功
return ServerResponse.createBySuccess("密码更新成功");
}
return ServerResponse.createBySuccess("密码更新失败");
}
/**
* 判断用户是否登录且为管理员权限
* @param user
* @return
*/
public ServerResponse checkAdminRole(User user) {
if (null != user && user.getRole() == Const.Role.ROLE_ADMIN) {
return ServerResponse.createBySuccess();
}
return ServerResponse.createByError();
}
}
package com.taobaostore.util;
import java.util.Date;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
/**
* 本类使用了joda-time包做时间转换功能
* @author xzp
*
*/
public class DateTimeUtil {
private static final String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss";
/**
* 将String转化为Date(自定义时间格式)
* @param str
* @return
*/
public static Date strToDate(String str,String formatStr) {
DateTimeFormatter formatter = DateTimeFormat.forPattern(formatStr);
return formatter.parseDateTime(str).toDate();
}
/**
* 将String转化为Date(默认时间格式)
* @param str
* @return
*/
public static Date strToDate(String str) {
DateTimeFormatter formatter = DateTimeFormat.forPattern(DEFAULT_FORMAT);
return formatter.parseDateTime(str).toDate();
}
/**
* 从Date转换为String(自定义格式)
* @param date
* @param formatStr
* @return
*/
public static String DateTostr(Date date,String formatStr) {
if (date == null) {
return StringUtils.EMPTY;
}
DateTime dateTime = new DateTime(date);
return dateTime.toString(formatStr);
}
/**
* 从Date转换为String(默认时间格式)
* @param date
* @param formatStr
* @return
*/
public static String DateTostr(Date date) {
if (date == null) {
return StringUtils.EMPTY;
}
DateTime dateTime = new DateTime(date);
return dateTime.toString(DEFAULT_FORMAT);
}
public static void main(String[] args) {
System.out.println(DateTostr(new Date()));
System.out.println(strToDate("2019-10-22 20:56:19"));
}
}
此差异已折叠。
package com.taobaostore.util;
import java.security.MessageDigest;
import sun.misc.BASE64Encoder;
public class MD5Util {
public static String MD5Encode(String str) {
String result = null;
try {
str = new StringBuffer().append(str).append("").toString();
MessageDigest md5 = MessageDigest.getInstance("MD5");
BASE64Encoder encoder = new BASE64Encoder();
result = encoder.encode(md5.digest(str.getBytes("UTF-8"))).replace("==", "");
} catch (Exception e) {
e.printStackTrace();
}
return result.toUpperCase();
}
}
package com.taobaostore.util;
import java.io.IOException;
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
public class PropertiesUtil {
private static Properties properties;
static {
properties = new Properties();
try {
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("ftpDataSource.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 返回指定key的value 如果value为空则返回null
* @param key
* @return
*/
public static String getValue(String key) {
String value = properties.getProperty(key.trim());
if (StringUtils.isBlank(value)) {
return null;
}
return value.trim();
}
/**
* 设置默认值的获取value方式
* @param key
* @param defaultValue
* @return
*/
public static String getValue(String key,String defaultValue) {
String value = properties.getProperty(key.trim());
if (StringUtils.isBlank(value)) {
return defaultValue;
}
return value.trim();
}
}
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
db.driverLocation=D://mysql-connector-java-5.1.10-bin.jar
db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/taobaosys
db.username=root
db.password=1234
\ No newline at end of file
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/taobaosys
username=root
password=1234
\ No newline at end of file
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
tomcat.port=8080
\ No newline at end of file
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册