This commit is contained in:
xiangwbs
2018-06-19 22:17:03 +08:00
parent 2ddba378d7
commit 0907e01a13
31 changed files with 893 additions and 241 deletions
@@ -11,7 +11,6 @@ import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
@@ -25,7 +24,6 @@ import java.util.Map;
* 作者: xiangwb
*/
@Configuration
@EnableTransactionManagement
@PropertySource("classpath:druid.properties")
@EnableJpaRepositories(
entityManagerFactoryRef = "jpaEntityManagerFactory",
@@ -0,0 +1,22 @@
package com.xwbing.domain.entity.rest;
import com.xwbing.domain.entity.sys.JpaBaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Entity;
/**
* @author xiangwb
* @version $Id: FilesUpload.java, v 0.1 2018年06月13日 17:23 wb-xwb402636 Exp $
*/
@EqualsAndHashCode(callSuper = true)
@Data
@Entity(name = "file_upload")
public class FilesUpload extends JpaBaseEntity {
private static final long serialVersionUID = 3284231281346882055L;
public static String table = "file_upload";
private String name;
private String type;
private String data;
}
@@ -17,12 +17,9 @@ import java.util.Date;
* 作者: xiangwb
*/
@Data
@MappedSuperclass
@ApiModel
public class BaseEntity implements Serializable {
private static final long serialVersionUID = 8901948362657956187L;
@Id
@Column(length = 50)
@ApiModelProperty(value = "主键")
private String id;
@ApiModelProperty(value = "创建者",hidden = true)
@@ -30,9 +27,7 @@ public class BaseEntity implements Serializable {
@ApiModelProperty(value = "修改者",hidden = true)
private String modifier;
@ApiModelProperty(value = "创建时间",hidden = true)
@Column(name = "create_time")
private Date createTime;
@ApiModelProperty(value = "修改时间",hidden = true)
@Column(name = "modified_time")
private Date modifiedTime;
}
@@ -0,0 +1,42 @@
package com.xwbing.domain.entity.sys;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import java.io.Serializable;
import java.util.Date;
/**
* 说明: 基础类
* 项目名称: boot-module-demo
* 创建时间: 2017/5/10 16:36
* 作者: xiangwb
*/
@Data
@ApiModel
@MappedSuperclass
public class JpaBaseEntity implements Serializable {
private static final long serialVersionUID = 2657519817528673800L;
@Id
@GenericGenerator(name = "idGenerator", strategy = "uuid")
@GeneratedValue(generator = "idGenerator")
@Column(length = 50)
@ApiModelProperty(value = "主键")
private String id;
@ApiModelProperty(value = "创建者", hidden = true)
private String creator;
@ApiModelProperty(value = "修改者", hidden = true)
private String modifier;
@Column(name = "create_time")
@ApiModelProperty(value = "创建时间", hidden = true)
private Date createTime;
@Column(name = "modified_time")
@ApiModelProperty(value = "修改时间", hidden = true)
private Date modifiedTime;
}
@@ -13,9 +13,7 @@ import javax.persistence.Entity;
* 创建时间: 2017/5/10 16:36
* 作者: xiangwb
*/
@EqualsAndHashCode(callSuper = true)
@Data
@Entity(name = "sys_authority")
public class SysAuthority extends BaseEntity {
private static final long serialVersionUID = -6469518352117371987L;
public static String table = "sys_authority";
@@ -28,7 +26,6 @@ public class SysAuthority extends BaseEntity {
@ApiModelProperty(value = "url地址", required = true)
private String url;
@ApiModelProperty(value = "父ID")
@Column(name = "parent_id")
private String parentId;
@ApiModelProperty(value = "类型(菜单:1|按钮:2)", example = "1", required = true)
private Integer type;
@@ -12,9 +12,7 @@ import javax.persistence.Entity;
* 创建时间: 2017/5/10 16:36
* 作者: xiangwb
*/
@EqualsAndHashCode(callSuper = true)
@Data
@Entity(name = "sys_role")
public class SysRole extends BaseEntity {
private static final long serialVersionUID = -3048021197170624143L;
public static String table = "sys_role";
@@ -12,20 +12,16 @@ import javax.persistence.Entity;
* 创建时间: 2017/5/10 16:36
* 作者: xiangwb
*/
@EqualsAndHashCode(callSuper = true)
@Data
@Entity(name = "sys_role_authority")
public class SysRoleAuthority extends BaseEntity {
private static final long serialVersionUID = 1241064470335852429L;
public static String table = "sys_role_authority";
/**
* 角色主键
*/
@Column(name = "role_id")
private String roleId;
/**
* 权限主键
*/
@Column(name = "authority_id")
private String authorityId;
}
@@ -19,9 +19,7 @@ import java.util.List;
* 创建时间: 2017/5/10 16:36
* 作者: xiangwb
*/
@EqualsAndHashCode(callSuper = true)
@Data
@Entity(name = "sys_user_info")
@ApiModel
public class SysUser extends BaseEntity {
private static final long serialVersionUID = -2447528751353457021L;
@@ -29,7 +27,6 @@ public class SysUser extends BaseEntity {
@NotBlank(message = "用户名不能为空")
@Length(min = 1, max = 20, message = "用户名长度为1-20")
@ApiModelProperty(value = "用户名", required = true)
@Column(name = "user_name")
private String userName;
@NotBlank(message = "姓名不能为空")
@Length(min = 1, max = 20, message = "姓名长度为1-5")
@@ -48,7 +45,6 @@ public class SysUser extends BaseEntity {
@ApiModelProperty(value = "密码", hidden = true)
private String password;
@ApiModelProperty(value = "是否为管理员", hidden = true)
@Column(name = "is_admin")
private String isAdmin;
//临时字段
@ApiModelProperty(hidden = true)
@@ -12,16 +12,12 @@ import javax.persistence.Entity;
* 作者: xiangwb
* 说明: 用户登录登出信息
*/
@EqualsAndHashCode(callSuper = true)
@Data
@Entity(name = "sys_user_login_in_out")
public class SysUserLoginInOut extends BaseEntity {
private static final long serialVersionUID = -2719103095945780275L;
public static String table = "sys_user_login_in_out";
private String ip;
@Column(name = "inout_type")
private int inoutType;
@Column(name = "user_id")
private String userId;
//临时字段
private transient String userIdName;
@@ -12,20 +12,16 @@ import javax.persistence.Entity;
* 创建时间: 2017/5/10 16:36
* 作者: xiangwb
*/
@EqualsAndHashCode(callSuper = true)
@Data
@Entity(name = "sys_user_role")
public class SysUserRole extends BaseEntity {
private static final long serialVersionUID = 7340808603856635810L;
public static String table="sys_user_role";
/**
* 用户主键
*/
@Column(name = "user_id")
private String userId;
/**
* 角色主键
*/
@Column(name = "role_id")
private String roleId;
}
@@ -4,29 +4,30 @@ import java.util.List;
import java.util.Map;
/**
* 项目名称: boot-module-demo
* 创建时间: 2018/6/2 10:32
* 作者: xiangwb
* 说明: 基础mapper
* @author xiangwb
* @version $Id: BaseMapper.java, v 0.1 2018年06月04日 11:05 wb-xwb402636 Exp $
*/
public interface BaseMapper<T> {
int save(T t);
public interface BaseMapper<M> {
int insert(M model);
int saveBatch(List<T> list);
int insertBatch(List<M> models);
int deleteById(String id);
int deleteByIds(String[] ids);
int deleteByIds(List<String> ids);
int delete(Map<String, Object> map);
int delete(Map<String, Object> conditions);
int update(T t);
int update(M model);
int updateBatch(List<T> list);
int updateBatch(List<M> models);
T findById(String id);
M findById(String id);
List<T> find(Map<String, Object> map);
List<M> findByIds(List<String> ids);
List<T> findAll();
List<M> find(Map<String, Object> conditions);
List<M> findAll();
}
@@ -1,6 +1,6 @@
package com.xwbing.domain.mapper.sys;
import com.xwbing.domain.entity.sys.SysUser;
import com.xwbing.domain.entity.sys.SysRoleAuthority;
import com.xwbing.domain.mapper.BaseMapper;
import java.util.List;
@@ -11,8 +11,6 @@ import java.util.List;
* 作者: xiangwb
* 说明:
*/
public interface SysUserMapper extends BaseMapper<SysUser> {
// @Select("select * from sys_user_info")
List<SysUser> findall();
int save(SysUser sysUser);
public interface SysRoleAuthorityMapper extends BaseMapper<SysRoleAuthority> {
List<SysRoleAuthority> findByRoleId(String roleId);
}
@@ -0,0 +1,13 @@
package com.xwbing.domain.mapper.sys;
import com.xwbing.domain.entity.sys.SysRole;
import com.xwbing.domain.mapper.BaseMapper;
/**
* 项目名称: boot-module-demo
* 创建时间: 2018/6/1 21:50
* 作者: xiangwb
* 说明:
*/
public interface SysRoleMapper extends BaseMapper<SysRole> {
}
@@ -0,0 +1,16 @@
package com.xwbing.domain.mapper.sys;
import com.xwbing.domain.entity.sys.SysUserRole;
import com.xwbing.domain.mapper.BaseMapper;
import java.util.List;
/**
* 项目名称: boot-module-demo
* 创建时间: 2018/6/1 21:50
* 作者: xiangwb
* 说明:
*/
public interface SysUserRoleMapper extends BaseMapper<SysUserRole> {
List<SysUserRole> findByUserId(String userId);
}
@@ -0,0 +1,19 @@
package com.xwbing.domain.repository;
import com.xwbing.domain.entity.rest.FilesUpload;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
/**
* @author xiangwb
* @version $Id: FilesUploadRepository.java, v 0.1 2018年06月13日 17:25 wb-xwb402636 Exp $
*/
public interface FilesUploadRepository extends JpaRepository<FilesUpload, String> {
List<FilesUpload> getByName(String name, Sort sort);
List<FilesUpload> getByTypeOrderByCreateTime(String type);
List<FilesUpload> getByIdIn(List<String> ids);
}
@@ -1,10 +1,20 @@
package com.xwbing.service.rest;
import com.xwbing.domain.entity.rest.FilesUpload;
import com.xwbing.domain.repository.FilesUploadRepository;
import com.xwbing.exception.BusinessException;
import com.xwbing.util.DigestsUtil;
import com.xwbing.util.RestMessage;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
import java.util.Date;
/**
* 项目名称: boot-module-demo
@@ -14,6 +24,9 @@ import javax.servlet.http.HttpSession;
*/
@Service
public class CommonService {
@Resource
private FilesUploadRepository uploadRepository;
/**
* 保存信息表单提交时获取校验签名
*
@@ -26,4 +39,46 @@ public class CommonService {
session.setAttribute("sign", sign);
return sign;
}
/**
* 上传文件
*
* @param file
* @return
*/
public RestMessage upload(CommonsMultipartFile file) {
RestMessage result = new RestMessage();
if (file == null) {
throw new BusinessException("请选择文件");
}
FilesUpload filesUpload = new FilesUpload();
//原始名字
String originName = file.getOriginalFilename();
filesUpload.setName(originName);
//获取文件后缀名
String fileType = originName.substring(originName.lastIndexOf(".") + 1);
filesUpload.setType(fileType);
byte[] data;
try {
InputStream is = file.getInputStream();
data = new byte[is.available()];
is.read(data);
is.close();
} catch (IOException e) {
throw new BusinessException("读取数据错误");
}
//对数据字节进行base64编码
String base64 = Base64.getEncoder().encodeToString(data);
filesUpload.setData(base64);
filesUpload.setCreateTime(new Date());
FilesUpload save = uploadRepository.save(filesUpload);
if (save != null) {
result.setSuccess(true);
result.setId(save.getId());
result.setMessage("保存文件成功");
} else {
result.setMessage("保存文件失败");
}
return result;
}
}
@@ -0,0 +1,60 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.xwbing.domain.mapper.sys.SysRoleAuthorityMapper">
<resultMap id="resultMap" type="sysRoleAuthority">
<id column="id" property="id"/>
<result column="create_time" property="createTime"/>
<result column="modified_time" property="modifiedTime"/>
<result column="role_id" property="roleId"/>
<result column="authority_id" property="authorityId"/>
</resultMap>
<sql id="table">
sys_role_authority
</sql>
<sql id="columns">
id,
creator,
modifier,
create_time,
modified_time,
role_id,
authority_id
</sql>
<!-- 批量插入 -->
<insert id="insertBatch">
INSERT INTO
<include refid="table"/>(
id,
creator,
create_time,
role_id,
authority_id
)
VALUES
<foreach collection="list" item="obj" separator=",">(
(SELECT REPLACE(UUID(), '-', '') AS id),
#{obj.creator},
now(),
#{obj.roleId},
#{obj.authorityId}
)
</foreach>
</insert>
<!-- 批量删除 -->
<delete id="deleteByIds">
DELETE FROM
<include refid="table"/>
WHERE id IN
<foreach collection="list" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</delete>
<!-- 根据roleId查找 -->
<select id="findByRoleId" resultMap="resultMap">
SELECT
<include refid="columns"/>
FROM
<include refid="table"/>
where role_id=#{roleId}
</select>
</mapper>
@@ -0,0 +1,60 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.xwbing.domain.mapper.sys.SysUserRoleMapper">
<resultMap id="resultMap" type="sysUserRole">
<id column="id" property="id"/>
<result column="create_time" property="createTime"/>
<result column="modified_time" property="modifiedTime"/>
<result column="role_id" property="roleId"/>
<result column="user_id" property="userId"/>
</resultMap>
<sql id="table">
sys_role_authority
</sql>
<sql id="columns">
id,
creator,
modifier,
create_time,
modified_time,
role_id,
user_id
</sql>
<!-- 批量插入 -->
<insert id="insertBatch">
INSERT INTO
<include refid="table"/>(
id,
creator,
create_time,
role_id,
user_id
)
VALUES
<foreach collection="list" item="obj" separator=",">(
(SELECT REPLACE(UUID(), '-', '') AS id),
#{obj.creator},
now(),
#{obj.roleId},
#{obj.userId}
)
</foreach>
</insert>
<!-- 批量删除 -->
<delete id="deleteByIds">
DELETE FROM
<include refid="table"/>
WHERE id IN
<foreach collection="list" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</delete>
<!-- 根据userId查找 -->
<select id="findByUserId" resultMap="resultMap">
SELECT
<include refid="columns"/>
FROM
<include refid="table"/>
where user_id=#{userId}
</select>
</mapper>
@@ -0,0 +1,224 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.xwbing.domain.mapper.sys.SysRoleMapper">
<resultMap id="resultMap" type="sysRole">
<id column="id" property="id"/>
<result column="create_time" property="createTime"/>
<result column="modified_time" property="modifiedTime"/>
</resultMap>
<sql id="table">
sys_role
</sql>
<sql id="columns">
id,
creator,
modifier,
create_time,
modified_time,
name,
code,
enable,
remark
</sql>
<sql id="condition">
<where>
<if test="code!=null">
code=#{code}
</if>
<if test="enable!=null">
and enable=#{enable}
</if>
<if test="ids!=null">
and id in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</if>
<if test="id!=null">
and id!=#{id}
</if>
</where>
</sql>
<!-- 插入 -->
<insert id="insert">
<selectKey keyProperty="id" resultType="string" order="BEFORE">
SELECT REPLACE(UUID(), '-', '')
</selectKey>
INSERT INTO
<include refid="table"/>(
id,
creator,
create_time,
name,
code,
enable,
remark
)
VALUES(
#{id},
#{creator},
now(),
#{name},
#{code},
#{enable},
#{remark}
)
</insert>
<!-- 批量插入 -->
<insert id="insertBatch">
INSERT INTO
<include refid="table"/>(
id,
creator,
create_time,
name,
code,
enable,
remark
)
VALUES
<foreach collection="list" item="obj" separator=",">(
(SELECT REPLACE(UUID(), '-', '') AS id),
#{obj.creator},
now(),
#{obj.name},
#{obj.code},
#{obj.enable},
#{obj.remark}
)
</foreach>
</insert>
<!-- 删除 -->
<delete id="deleteById">
DELETE FROM
<include refid="table"/>
WHERE id=#{id}
</delete>
<!-- 批量删除 -->
<delete id="deleteByIds">
DELETE FROM
<include refid="table"/>
WHERE id IN
<foreach collection="list" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</delete>
<!-- 条件删除 -->
<delete id="delete">
DELETE FROM
<include refid="table"/>
<include refid="condition"/>
</delete>
<!-- 更新 -->
<update id="update">
UPDATE
<include refid="table"/>
<set>
modified_time=now(),
<if test="modifier!=null">modifier=#{modifier},</if>
<if test="name!=null">name=#{name},</if>
<if test="code!=null">code=#{code},</if>
<if test="enable!=null">enable=#{enable},</if>
<if test="remark!=null">remark=#{remark},</if>
</set>
WHERE id=#{id}
</update>
<!-- 批量更新 -->
<update id="updateBatch">
UPDATE
<include refid="table"/>
<trim prefix="set" suffixOverrides=",">
<trim prefix="modifier=case" suffix="end,">
<foreach collection="list" item="obj">
<if test="obj.modifier!=null">
when id=#{obj.id} then #{obj.modifier}
</if>
</foreach>
</trim>
<trim prefix="name=case" suffix="end,">
<foreach collection="list" item="obj">
<if test="obj.name!=null">
when id=#{obj.id} then #{obj.name}
</if>
</foreach>
</trim>
<trim prefix="code=case" suffix="end,">
<foreach collection="list" item="obj">
<if test="obj.code!=null">
when id=#{obj.id} then #{obj.code}
</if>
</foreach>
</trim>
<trim prefix="enable=case" suffix="end,">
<foreach collection="list" item="obj">
<if test="obj.enable!=null">
when id=#{obj.id} then #{obj.enable}
</if>
</foreach>
</trim>
<trim prefix="remark=case" suffix="end,">
<foreach collection="list" item="obj">
<if test="obj.remark!=null">
when id=#{obj.id} then #{obj.remark}
</if>
</foreach>
</trim>
</trim>
<where>
<foreach collection="list" separator="or" item="obj">
id=#{obj.id}
</foreach>
</where>
</update>
<!-- 查找 -->
<select id="findById" resultMap="resultMap">
SELECT
<include refid="columns"/>
FROM
<include refid="table"/>
WHERE id=#{id}
</select>
<!-- 根据ids查找 -->
<select id="findByIds" resultMap="resultMap">
SELECT
<include refid="columns"/>
FROM
<include refid="table"/>
WHERE id IN
<foreach collection="list" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</select>
<!-- 条件查询 -->
<select id="find" resultMap="resultMap">
SELECT
<include refid="columns"/>
FROM
<include refid="table"/>
<include refid="condition"/>
</select>
<!-- 查询所有 -->
<select id="findAll" resultMap="resultMap">
SELECT
<include refid="columns"/>
FROM
<include refid="table"/>
ORDER BY create_time DESC
</select>
<!--&lt;!&ndash; 统计 &ndash;&gt;-->
<!--<select id="countByPagin" parameterClass="java.util.Map" resultClass="java.lang.Integer">-->
<!--SELECT COUNT(1)-->
<!--FROM-->
<!--<include refid="table"/>-->
<!--<include refid="whereCondition"/>-->
<!--</select>-->
<!--&lt;!&ndash; 分页 &ndash;&gt;-->
<!--<select id="findByPagin" parameterClass="java.util.Map" resultMap="resultMap">-->
<!--SELECT-->
<!--<include refid="columns"/>-->
<!--FROM-->
<!--<include refid="table"/>-->
<!--<include refid="whereCondition"/>-->
<!--order by id desc LIMIT #fromRow#,#pageSize#-->
<!--</select>-->
</mapper>
@@ -1,29 +0,0 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.xwbing.domain.mapper.sys.SysUserMapper">
<resultMap id="BaseResultMap" type="sysUser">
<id column="id" property="id"/>
<result column="create_time" property="createTime"/>
<result column="modified_time" property="modifiedTime"/>
<result column="user_name" property="userName"/>
<result column="is_admin" property="isAdmin"/>
</resultMap>
<sql id="table">
sys_user_info
</sql>
<sql id="base_column">
user_id, user_name, password, phone
</sql>
<insert id="save" parameterType="com.xwbing.domain.entity.sys.SysUser" >
<selectKey keyProperty="id" resultType="string" order="BEFORE">
SELECT UUID()
</selectKey>
INSERT INTO sys_user_info(id,name,user_name,mail,is_admin,sex,create_time,modified_time) VALUES
(#{id},#{name},#{userName},#{mail},#{isAdmin},#{sex},now(),now())
</insert>
<select id="findall" resultMap="BaseResultMap">
select *
from sys_user_info
</select>
</mapper>
@@ -40,10 +40,10 @@ public class ApplicationContextConfig {
*
* @return
*/
@Bean
@Bean(name = "multipartResolver")
public CommonsMultipartResolver getCommonsMultipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(104857600);
multipartResolver.setMaxUploadSize(5 * 1024 * 1024);//5M
multipartResolver.setDefaultEncoding("UTF-8");
return multipartResolver;
}
@@ -71,3 +71,4 @@ public class ApplicationContextConfig {
return poolTaskExecutor;
}
}
@@ -5,8 +5,11 @@ import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.xwbing.handler.LoginInterceptor;
import com.xwbing.handler.UrlPermissionsInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.Ordered;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
@@ -21,18 +24,28 @@ import java.util.List;
* 创建时间: 2017/5/10 16:36
* 作者: xiangwb
*/
@Slf4j
@Configuration
@PropertySource("classpath:config.properties")
public class DispatcherServletConfig extends WebMvcConfigurerAdapter {
@Value("${loginInterceptorEnable}")
private boolean loginInterceptorEnable;
@Value("${urlPermissionsInterceptorEnable}")
private boolean urlPermissionsInterceptorEnable;
/***
* 添加拦截器
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
//登录拦截器
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**").excludePathPatterns("/user/login");
//权限拦截器
registry.addInterceptor(urlPermissionsInterceptor()).addPathPatterns("/**").excludePathPatterns("/user/login");
if(loginInterceptorEnable){
log.info("注册登录拦截器LoginInterceptor ======================= ");
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**").excludePathPatterns("/user/login");
}
if(urlPermissionsInterceptorEnable){
log.info("注册权限拦截器UrlPermissionsInterceptor ======================= ");
registry.addInterceptor(urlPermissionsInterceptor()).addPathPatterns("/**").excludePathPatterns("/user/login");
}
super.addInterceptors(registry);
}
@@ -124,6 +137,7 @@ public class DispatcherServletConfig extends WebMvcConfigurerAdapter {
List<MediaType> mediaTypes = new ArrayList<>();
mediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
mediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
mediaTypes.add(MediaType.MULTIPART_FORM_DATA);
mediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
mediaTypes.add(MediaType.TEXT_HTML);
messageConverter.setSupportedMediaTypes(mediaTypes);
@@ -139,3 +153,4 @@ public class DispatcherServletConfig extends WebMvcConfigurerAdapter {
return messageConverter;
}
}
@@ -1,10 +1,14 @@
package com.xwbing.configuration;
import com.xwbing.handler.FormRepeatFilter;
import com.xwbing.util.captcha.CaptchaServlet;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
/**
* 说明: 统一servlet/filter配置
@@ -14,24 +18,29 @@ import org.springframework.context.annotation.Configuration;
*/
@Slf4j
@Configuration
@PropertySource("classpath:config.properties")
public class ServletFilterConfig {
@Value("${formSaveFilterEnable}")
private boolean formSaveFilterEnable;
@Bean
public ServletRegistrationBean captchaServlet() {
log.info("注册登陆验证码servlet ======================= ");
log.info("注册登陆验证码CaptchaServlet ======================= ");
ServletRegistrationBean registration = new ServletRegistrationBean(new CaptchaServlet());
registration.addUrlMappings("/captcha");
return registration;
}
/*servlet*****************************************************filter*/
// @Bean
// public FilterRegistrationBean formSaveFilter() {
// log.info("注册表单重复提交过滤器formSaveFilter ======================= ");
// FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new FormRepeatFilter());
// filterRegistrationBean.addUrlPatterns("/*");
// filterRegistrationBean.addInitParameter("excludePath", "/doc,/captcha,/v2/api-docs,/swagger-resources,/configuration/ui,/configuration/security,/druid");
// filterRegistrationBean.addInitParameter("excludeType", ".js,.css,.gif,.jpg,.png,.ico,.jsp,.html,/druid/");
// return filterRegistrationBean;
// }
@Bean
public FilterRegistrationBean formSaveFilter() {
log.info("注册表单重复提交过滤器FormRepeatFilter ======================= ");
FilterRegistrationBean registration = new FilterRegistrationBean(new FormRepeatFilter());
registration.setEnabled(formSaveFilterEnable);
registration.addUrlPatterns("/*");
registration.addInitParameter("excludePath", "/doc,/captcha,/v2/api-docs,/swagger-resources,/configuration/ui,/configuration/security,/druid");
registration.addInitParameter("excludeType", ".js,.css,.gif,.jpg,.png,.ico,.jsp,.html,/druid/");
return registration;
}
}
@@ -2,31 +2,29 @@ package com.xwbing.controller.rest;
import com.alibaba.fastjson.JSONObject;
import com.xwbing.annotation.LogInfo;
import com.xwbing.domain.entity.ExpressInfo;
import com.xwbing.domain.entity.sys.SysUser;
import com.xwbing.domain.entity.vo.ExpressInfoVo;
import com.xwbing.domain.mapper.sys.SysUserMapper;
import com.xwbing.rabbit.Sender;
import com.xwbing.redis.RedisService;
import com.xwbing.domain.entity.rest.FilesUpload;
import com.xwbing.domain.repository.FilesUploadRepository;
import com.xwbing.service.rest.CookieSessionService;
import com.xwbing.service.rest.ExpressDeliveryService;
import com.xwbing.service.rest.QRCodeZipService;
import com.xwbing.util.HttpUtil;
import com.xwbing.util.EncodeUtils;
import com.xwbing.util.JsonResult;
import com.xwbing.util.RSAUtil;
import com.xwbing.util.RestMessage;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.concurrent.CompletableFuture;
/**
* 说明: 测试控制层
@@ -39,79 +37,12 @@ import java.util.concurrent.CompletableFuture;
@RestController
@RequestMapping("/test/")
public class TestControl {
@Resource
private RedisService redisService;
@Resource
private ExpressDeliveryService expressDeliveryService;
@Resource
private QRCodeZipService qrCodeZipService;
@Resource
private CookieSessionService cookieSessionService;
@Resource
private Sender sender;
@Resource
private SysUserMapper sysUserMapper;
@Transactional
@PostMapping("save")
public JSONObject save(@RequestBody SysUser sysUser) {
List<SysUser> findall = sysUserMapper.findall();
findall.forEach(sysUser1 -> sysUser1.setCreate("aaa"));
return JsonResult.toJSONObj(findall,"");
}
@GetMapping("send")
public void sendM(@RequestParam String[] msg) {
sender.sendM(msg);
}
@LogInfo("redis功能测试")
@GetMapping("redis")
public void redis() {
redisService.set("redis", "xwbing");
String s = redisService.get("redis");
log.info("redis获取的数据为:" + s);
}
@LogInfo("log功能测试")
@GetMapping("log")
public void log() {
log.info("info test");
log.error("error test");
}
@LogInfo("获取快递列表")
@GetMapping("listShipperCode")
public JSONObject listShipperCode() {
List<JSONObject> list = expressDeliveryService.listShipperCode();
return JsonResult.toJSONObj(list, "");
}
@LogInfo("快递查询")
@PostMapping("expressInfo")
public JSONObject getExpressInfo(@RequestBody ExpressInfo info) {
if (StringUtils.isEmpty(info.getLogisticCode()) || StringUtils.isEmpty(info.getShipperCode())) {
return JsonResult.toJSONObj("快递公司或物流单号不能为空");
}
ExpressInfoVo infoVo = expressDeliveryService.queryOrderTraces(info);
return JsonResult.toJSONObj(infoVo, "查询快递信息成功");
}
@LogInfo("生成二维码")
@PostMapping("createQRCode")
public JSONObject createQRCode(@RequestParam String name, @RequestParam String text) {
RestMessage qrCode = qrCodeZipService.createQRCode(name, text);
return JsonResult.toJSONObj(qrCode);
}
@LogInfo("解析二维码")
@GetMapping("decode")
public JSONObject decode(@RequestParam String path) {
if (StringUtils.isEmpty(path)) {
return JsonResult.toJSONObj("二维码图片路径不能为空");
}
File file = new File(path);
RestMessage decode = qrCodeZipService.decode(file);
return JsonResult.toJSONObj(decode);
}
private FilesUploadRepository uploadRepository;
@LogInfo("导出zip")
@GetMapping("batchGetImage")
@@ -123,21 +54,24 @@ public class TestControl {
return JsonResult.toJSONObj(restMessage);
}
@LogInfo("rsa")
@GetMapping("rsa")
public void rsa() {
String en = RSAUtil.encrypt("123456");
String de = RSAUtil.decrypt(en);
System.out.println(de);
}
@LogInfo("httpUtil")
@PostMapping("httpUtil")
public JSONObject httpUtil(@RequestBody JSONObject param) {
// String url = "http://localhost:8080/user/listAll";
// return HttpClientUtil.get(url);
String url = "http://localhost:8080/user/save";
return HttpUtil.postByJson(url, param);
@LogInfo("获取数据库图片")
@GetMapping("getDbPic")
public void getDbPic(HttpServletResponse response, @RequestParam String name) throws IOException {
if (StringUtils.isNotEmpty(name)) {
List<FilesUpload> files = uploadRepository.getByName(name, new Sort(Sort.Direction.DESC, "createTime"));
if (CollectionUtils.isNotEmpty(files)) {
String data = files.get(0).getData();
byte[] bytes = EncodeUtils.base64Decode(data);
// 设置相应类型,告诉浏览器输出的内容为图片
response.setContentType("image/jpeg");
// 禁止图像缓存。
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expire", 0);
OutputStream out = response.getOutputStream();
out.write(bytes);
}
}
}
@LogInfo("session")
@@ -151,37 +85,5 @@ public class TestControl {
public JSONObject cookie(HttpServletRequest request, HttpServletResponse response) {
return JsonResult.toJSONObj(cookieSessionService.cookie(response, request));
}
@LogInfo("completableFuture")
@GetMapping("completableFuture")
public JSONObject completableFuture() {
return JsonResult.toJSONObj(thenCombine(), "");
}
private JSONObject thenCombine() {
return CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "hello";
}).thenCombine(CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//出现异常,异常会被限制在执行任务的线程范围内
if (1 == 1) {
throw new RuntimeException("545456");
}
return "world";
}), (s1, s2) -> {
JSONObject object = new JSONObject();
object.put("s1", s1);
object.put("s2", s2);
return object;
}).join();
}
}
@@ -5,11 +5,11 @@ import com.xwbing.annotation.LogInfo;
import com.xwbing.domain.entity.vo.RestMessageVo;
import com.xwbing.service.rest.CommonService;
import com.xwbing.util.JsonResult;
import com.xwbing.util.RestMessage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
@@ -34,4 +34,12 @@ public class CommonControl {
String sign = commonService.getSign(request);
return JsonResult.toJSONObj(sign, "");
}
@LogInfo("上传文件")
@PostMapping("upload")
public JSONObject upload(@RequestParam(required = false) CommonsMultipartFile file) {
RestMessage restMessage = commonService.upload(file);
return JsonResult.toJSONObj(restMessage);
}
}
@@ -0,0 +1,6 @@
formSaveFilterEnable:false
loginInterceptorEnable:false
urlPermissionsInterceptorEnable:false
@@ -1,16 +0,0 @@
package com.xwbing;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTest {
@Test
public void contextLoads() {
}
}
@@ -0,0 +1,29 @@
package com.xwbing;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;
/**
* 说明:
* 项目名称: boot-module-demo
* 创建时间: 2018/5/10 16:36
* 作者: xiangwb
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@Transactional
@Rollback(false)
@WebAppConfiguration
public class BaseTest {
@Autowired
protected MockMvc mvc;
}
@@ -0,0 +1,68 @@
package com.xwbing.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xwbing.BaseTest;
import com.xwbing.domain.entity.sys.SysRole;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import java.text.MessageFormat;
/**
* 说明:
* 项目名称: boot-module-demo
* 创建时间: 2018/5/10 16:36
* 作者: xiangwb
*/
@Slf4j
public class SysRoleControlTest extends BaseTest {
@Test
public void all() throws Exception {
//save
SysRole sysRole = new SysRole();
sysRole.setCode("apiTest");
sysRole.setEnable("Y");
sysRole.setName("apiTest");
sysRole.setRemark("apiTest");
String saveStr = mvc.perform(MockMvcRequestBuilders
.post("/role/save")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(JSONObject.toJSONString(sysRole)))
.andReturn().getResponse().getContentAsString();
log.info(saveStr);
//getById
JSONObject response = JSONObject.parseObject(saveStr);
String getByIdStr = mvc.perform(MockMvcRequestBuilders
.get("/role/getById")
.param("id", response.getString("id")))
.andReturn().getResponse().getContentAsString();
log.info(getByIdStr);
response = JSONObject.parseObject(getByIdStr);
sysRole = JSON.toJavaObject(response.getJSONObject("data"), SysRole.class);
//listByEnable
String listByEnableString = mvc.perform(MockMvcRequestBuilders
.get("/role/listByEnable")
.param("enable", "Y"))
.andReturn().getResponse().getContentAsString();
log.info(listByEnableString);
//update
sysRole.setName("updateTest");
String updateStr = mvc.perform(MockMvcRequestBuilders
.put("/role/update")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(JSONObject.toJSONString(sysRole)))
.andReturn().getResponse().getContentAsString();
log.info(updateStr);
//removeById
String removeByIdStr = mvc.perform(MockMvcRequestBuilders
.delete(MessageFormat.format("/role/removeById/{0}", sysRole.getId())))
.andReturn().getResponse().getContentAsString();
log.info(removeByIdStr);
// mvc.perform(MockMvcRequestBuilders
// .delete(MessageFormat.format("/role/removeById/{0}", sysRole.getId())))
// .andExpect(MockMvcResultMatchers.status().isOk());
}
}
@@ -0,0 +1,128 @@
package com.xwbing.service;
import com.alibaba.fastjson.JSONObject;
import com.xwbing.BaseTest;
import com.xwbing.domain.entity.ExpressInfo;
import com.xwbing.domain.entity.sys.SysRole;
import com.xwbing.domain.entity.vo.ExpressInfoVo;
import com.xwbing.domain.mapper.sys.SysRoleMapper;
import com.xwbing.rabbit.Sender;
import com.xwbing.redis.RedisService;
import com.xwbing.service.rest.ExpressDeliveryService;
import com.xwbing.service.rest.QRCodeZipService;
import com.xwbing.service.sys.SysRoleService;
import com.xwbing.util.RSAUtil;
import com.xwbing.util.RestMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;
/**
* 项目名称: boot-module-demo
* 创建时间: 2018/6/1 13:20
* 作者: xiangwb
* 说明: 服务层功能测试
*/
@Slf4j
public class ServiceTest extends BaseTest {
@Resource
private RedisService redisService;
@Resource
private ExpressDeliveryService expressDeliveryService;
@Resource
private QRCodeZipService qrCodeZipService;
@Resource
private Sender sender;
@Resource
private SysRoleService sysRoleService;
@Resource
private SysRoleMapper sysRoleMapper;
@Transactional("jpaTransactionManager")
@Test
public void jpaTransactionTest() {
log.info("jpa数据源事务回滚");
SysRole sysRole = new SysRole();
sysRole.setName("serviceTest");
sysRole.setCode("serviceTest");
sysRole.setEnable("Y");
sysRole.setRemark("serviceTest");
Assert.assertTrue(sysRoleService.save(sysRole).isSuccess());
}
@Transactional
@Test
public void mybatisTransactionTest() {
log.info("mybatis数据源事务回滚");
SysRole sysRole = new SysRole();
sysRole.setName("serviceTest");
sysRole.setCode("serviceTest");
sysRole.setEnable("Y");
sysRole.setRemark("serviceTest");
int insert = sysRoleMapper.insert(sysRole);
Assert.assertEquals(1, insert);
}
@Test
public void listShipperCodeTest() {
log.debug("获取快递列表");
List<JSONObject> list = expressDeliveryService.listShipperCode();
Assert.assertSame(12, list.size());
}
@Test
public void expressInfoTest() {
log.debug("快递查询");
ExpressInfo info = new ExpressInfo();
info.setLogisticCode("1179751819114");
info.setShipperCode("EMS");
if (StringUtils.isEmpty(info.getLogisticCode()) || StringUtils.isEmpty(info.getShipperCode())) {
log.error("快递公司或物流单号不能为空");
}
ExpressInfoVo infoVo = expressDeliveryService.queryOrderTraces(info);
Assert.assertTrue(infoVo.isSuccess());
}
@Test
public void createQRCodeTest() {
RestMessage qrCode = qrCodeZipService.createQRCode("test", "test");
Assert.assertTrue(qrCode.isSuccess());
}
@Test
public void decodeQRCodeTest() throws IOException {
ClassPathResource pic = new ClassPathResource("pic");
String path = pic.getFile().getAbsolutePath();
File file = new File(path + File.separator + "QRCode.png");
RestMessage decode = qrCodeZipService.decode(file);
Assert.assertTrue(decode.isSuccess());
}
@Test
public void rsaTest() {
String en = RSAUtil.encrypt("123456");
String de = RSAUtil.decrypt(en);
Assert.assertEquals("123456", de);
}
@Test
public void sendTest() {
sender.sendMessage(new String[]{"mq测试"});
}
@Test
public void redisTest() {
redisService.set("redis", "xwbing");
String s = redisService.get("redis");
Assert.assertEquals("xwbing", s);
}
}
@@ -0,0 +1,49 @@
package com.xwbing.service;
import com.xwbing.BaseTest;
import com.xwbing.domain.entity.sys.SysRole;
import com.xwbing.domain.mapper.sys.SysRoleMapper;
import com.xwbing.service.sys.SysRoleService;
import com.xwbing.util.RestMessage;
import org.junit.Assert;
import org.junit.Test;
import javax.annotation.Resource;
/**
* 项目名称: boot-module-demo
* 创建时间: 2018/6/1 13:20
* 作者: xiangwb
* 说明: 权限服务层测试
*/
public class SysRoleServiceTest extends BaseTest {
@Resource
private SysRoleService sysRoleService;
@Resource
private SysRoleMapper sysRoleMapper;
@Test
public void all() {
//save
SysRole sysRole = new SysRole();
sysRole.setCode("serviceTest");
sysRole.setEnable("Y");
sysRole.setName("serviceTest");
sysRole.setRemark("serviceTest");
RestMessage rest = sysRoleService.save(sysRole);
Assert.assertTrue(rest.getMessage(), rest.isSuccess());
//getById
sysRole = sysRoleService.getById(rest.getId());
Assert.assertNotNull(sysRole);
//update
sysRole.setName("updateTest");
rest = sysRoleService.update(sysRole);
Assert.assertTrue(rest.getMessage(), rest.isSuccess());
Assert.assertNotSame("修改失败", sysRole, sysRoleService.getById(rest.getId()));
//listAllByEnable
Assert.assertNotNull(sysRoleService.listAllByEnable("Y"));
//removeById
Assert.assertTrue("删除失败", sysRoleService.removeById(rest.getId()).isSuccess());
//............................
}
}