├── .gitignore
├── README.md
├── cppba-spring-boot-api
├── pom.xml
└── src
│ └── main
│ └── java
│ └── com.cppba.service
│ ├── ArticleClassService.java
│ └── UserService.java
├── cppba-spring-boot-core
├── pom.xml
└── src
│ └── main
│ └── java
│ └── com
│ └── cppba
│ ├── base
│ ├── annotation
│ │ └── RequiresRoles.java
│ ├── bean
│ │ ├── BaseBean.java
│ │ ├── CurrentUser.java
│ │ ├── JModelAndView.java
│ │ └── Result.java
│ ├── constant
│ │ └── Globals.java
│ ├── dao
│ │ ├── BaseRepository.java
│ │ └── impl
│ │ │ └── BaseRepositoryImpl.java
│ ├── entity
│ │ └── BaseEntity.java
│ └── util
│ │ ├── AliyunOSSUtil.java
│ │ ├── CommonUtil.java
│ │ ├── ConfigUtil.java
│ │ ├── ConfigurationUtil.java
│ │ ├── ImgCompressUtil.java
│ │ ├── JwtUtil.java
│ │ ├── MD5Util.java
│ │ ├── QRCodeUtil.java
│ │ ├── Results.java
│ │ ├── SendEmailUtil.java
│ │ ├── UploadFileUtil.java
│ │ └── VerifyCodeUtil.java
│ ├── entity
│ ├── ArticleClass.java
│ └── User.java
│ ├── form
│ └── admin
│ │ └── SettingForm.java
│ ├── repository
│ ├── ArticleClassRepository.java
│ ├── UserRepository.java
│ ├── custom
│ │ ├── ArticleClassRepositoryCustom.java
│ │ └── UserRepositoryCustom.java
│ └── impl
│ │ ├── ArticleClassRepositoryImpl.java
│ │ └── UserRepositoryImpl.java
│ └── vo
│ └── admin
│ ├── ArticleClassVO.java
│ └── SettingVO.java
├── cppba-spring-boot-service
├── pom.xml
└── src
│ └── main
│ └── java
│ └── com
│ └── cppba
│ └── service
│ └── impl
│ ├── ArticleClassServiceImpl.java
│ └── UserServiceImpl.java
├── cppba-spring-boot-web
├── pom.xml
└── src
│ └── main
│ ├── java
│ └── com
│ │ └── cppba
│ │ ├── Application.java
│ │ ├── config
│ │ └── ApplicationConfiguration.java
│ │ ├── controller
│ │ ├── admin
│ │ │ ├── ArticleClassController.java
│ │ │ └── UserController.java
│ │ ├── base
│ │ │ └── BaseController.java
│ │ └── common
│ │ │ └── CommonAction.java
│ │ └── interceptor
│ │ └── OauthInterceptor.java
│ └── resources
│ ├── config
│ ├── application-dev.properties
│ ├── application-prod.properties
│ └── application.properties
│ ├── logback.xml
│ └── templates
│ └── default
│ └── index.html
└── pom.xml
/.gitignore:
--------------------------------------------------------------------------------
1 | # Build Artifacts
2 | .gradle
3 | build
4 | target
5 | gradle
6 | classes
7 | out/
8 |
9 | # IDEA artifacts and output dirs
10 | *.iml
11 | *.ipr
12 | *.iws
13 | *.idea
14 |
15 | # Eclipse artifacts
16 | .classpath
17 | .project
18 | .settings/
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # cppba-spring-boot
2 | cppba-spring-boot教程
3 |
4 | ## 1.技术选型
5 | spring-boot、spring-data-jpa(后期会加入新技术)
6 |
7 | ## 2.项目结构
8 | cppba-spring-boot-core 通用的工具类、entity、dao
9 |
10 | cppba-spring-boot-api 提供服务接口api
11 |
12 | cppba-spring-boot-service 提供服务实现
13 |
14 | cppba-spring-boot-web web项目代码
15 |
16 | ## 3.不同环境打包
17 | application.properties 中定义当前环境(dev-开发,test-测试,prod-生产)
18 |
19 | application-dev.properties 开发环境配置
20 |
21 | application-test.properties 测试环境配置
22 |
23 | application-prod.properties 生产环境配置
24 |
25 | 其中application.properties的配置如下:
26 | ```xml
27 | ###打包时只需要修改spring.profiles.active参数,决定环境
28 |
29 | #表示当前是开发环境,读取application-dev.properties配置文件
30 | spring.profiles.active=dev
31 |
32 | #表示当前是测试环境,读取application-test.properties配置文件
33 | spring.profiles.active=test
34 |
35 | #表示当前是生产环境,读取application-prod.properties配置文件
36 | spring.profiles.active=prod
37 | ```
38 |
--------------------------------------------------------------------------------
/cppba-spring-boot-api/pom.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 | cppba-spring-boot
5 | com.cppbba
6 | 1.0.0
7 |
8 | 4.0.0
9 |
10 | cppba-spring-boot-api
11 | jar
12 |
13 | cppba-spring-boot-api
14 | http://maven.apache.org
15 |
16 |
17 | UTF-8
18 |
19 |
20 |
21 |
22 | com.cppbba
23 | cppba-spring-boot-core
24 | 1.0.0
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/cppba-spring-boot-api/src/main/java/com.cppba.service/ArticleClassService.java:
--------------------------------------------------------------------------------
1 | package com.cppba.service;
2 |
3 |
4 | import com.cppba.base.bean.Result;
5 |
6 | public interface ArticleClassService {
7 | Result page(Long userId, String name, Integer pageNumber, Integer pageSize);
8 | }
9 |
--------------------------------------------------------------------------------
/cppba-spring-boot-api/src/main/java/com.cppba.service/UserService.java:
--------------------------------------------------------------------------------
1 | package com.cppba.service;
2 |
3 |
4 | import com.cppba.base.bean.Result;
5 | import com.cppba.form.admin.SettingForm;
6 |
7 | public interface UserService {
8 |
9 | Result login(String UserName, String password) throws Exception;
10 |
11 | Result setting(Long id);
12 |
13 | Result settingUpdate(Long id,SettingForm settingFrom);
14 | }
15 |
--------------------------------------------------------------------------------
/cppba-spring-boot-core/pom.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 | cppba-spring-boot
5 | com.cppbba
6 | 1.0.0
7 |
8 | 4.0.0
9 |
10 | cppba-spring-boot-core
11 | jar
12 |
13 | cppba-spring-boot-core
14 | http://maven.apache.org
15 |
16 |
17 | UTF-8
18 |
19 |
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/cppba-spring-boot-core/src/main/java/com/cppba/base/annotation/RequiresRoles.java:
--------------------------------------------------------------------------------
1 | package com.cppba.base.annotation;
2 |
3 | import java.lang.annotation.ElementType;
4 | import java.lang.annotation.Retention;
5 | import java.lang.annotation.RetentionPolicy;
6 | import java.lang.annotation.Target;
7 |
8 | @Target(ElementType.METHOD)
9 | @Retention(RetentionPolicy.RUNTIME)
10 | public @interface RequiresRoles {
11 | String[] value();
12 | }
--------------------------------------------------------------------------------
/cppba-spring-boot-core/src/main/java/com/cppba/base/bean/BaseBean.java:
--------------------------------------------------------------------------------
1 | package com.cppba.base.bean;
2 |
3 | import com.fasterxml.jackson.core.JsonProcessingException;
4 | import com.fasterxml.jackson.databind.ObjectMapper;
5 | import org.apache.commons.lang3.builder.*;
6 |
7 | import java.io.Serializable;
8 |
9 | @SuppressWarnings("serial")
10 | public abstract class BaseBean implements Serializable {
11 |
12 | public int hashCode() {
13 | return HashCodeBuilder.reflectionHashCode(this);
14 | }
15 |
16 | public boolean equals(Object obj) {
17 | return EqualsBuilder.reflectionEquals(this, obj);
18 | }
19 |
20 | public boolean equals(Object o, String... excludeFields) {
21 | return EqualsBuilder.reflectionEquals(this, o, excludeFields);
22 | }
23 |
24 | public String toString() {
25 | return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
26 | }
27 |
28 | public int compareTo(Object o) {
29 | return CompareToBuilder.reflectionCompare(this, o);
30 | }
31 |
32 | public int compareTo(Object o, String... excludeFields) {
33 | return CompareToBuilder.reflectionCompare(this, o, excludeFields);
34 | }
35 |
36 | public String toJSONString() throws JsonProcessingException {
37 | ObjectMapper objectMapper = new ObjectMapper();
38 | return objectMapper.writeValueAsString(this);
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/cppba-spring-boot-core/src/main/java/com/cppba/base/bean/CurrentUser.java:
--------------------------------------------------------------------------------
1 | package com.cppba.base.bean;
2 |
3 | import lombok.Data;
4 |
5 | @Data
6 | public class CurrentUser{
7 |
8 | private Long id;
9 |
10 | private String userName;
11 |
12 | private String[] roles;
13 | }
14 |
--------------------------------------------------------------------------------
/cppba-spring-boot-core/src/main/java/com/cppba/base/bean/JModelAndView.java:
--------------------------------------------------------------------------------
1 | package com.cppba.base.bean;
2 |
3 | import com.cppba.base.constant.Globals;
4 | import org.springframework.web.servlet.ModelAndView;
5 |
6 | import javax.servlet.http.HttpServletRequest;
7 | import java.util.Map;
8 |
9 | public class JModelAndView extends ModelAndView {
10 |
11 | public JModelAndView(String viewName, HttpServletRequest request) {
12 | init(viewName,null,request);
13 | }
14 |
15 | public JModelAndView(String viewName, Map map, HttpServletRequest request) {
16 | //初始化
17 | init(viewName,map,request);
18 | }
19 |
20 | private void init(String viewName, Map map, HttpServletRequest request) {
21 | //模板文件夹
22 | viewName = Globals.TEMPLATE_TYPE + "/" + viewName;
23 | super.setViewName(viewName);
24 |
25 | //设置参数
26 | if(map!=null){
27 | for (String key : map.keySet()) {
28 | this.addObject(key, map.get(key));
29 | }
30 | }
31 |
32 | //模板文件夹
33 | this.addObject("template_type", Globals.TEMPLATE_TYPE);
34 |
35 | //当前项目根地址
36 | String path = request.getContextPath();
37 | String webPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
38 | this.addObject("web_path", webPath);
39 | //通用静态资源地址,如:jquery、bootstrap
40 | this.addObject("static_public_url", Globals.STATIC_PUBLIC_URL);
41 | //项目资源地址
42 | this.addObject("static_private_url", Globals.STATIC_PRIVATE_URL);
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/cppba-spring-boot-core/src/main/java/com/cppba/base/bean/Result.java:
--------------------------------------------------------------------------------
1 | package com.cppba.base.bean;
2 |
3 | import lombok.Data;
4 |
5 | import java.util.Map;
6 |
7 | @Data
8 | public class Result extends BaseBean{
9 |
10 | private static final long serialVersionUID = 1L;
11 |
12 | public boolean success; // 成功标志
13 | public Integer code; // 返回标示
14 | public String msg; // 相关消息
15 | public Object data; // 相关数据
16 | public Map errors; // 错误详细
17 |
18 | public Result() {
19 | super();
20 | }
21 |
22 | public Result(boolean success) {
23 | this.success = success;
24 | }
25 |
26 | public Result(boolean success, Integer code, Object data, String msg) {
27 | this(success);
28 | this.code = code;
29 | this.data = data;
30 | this.msg = msg;
31 | }
32 |
33 | public Result(Integer code, Map errors, String msg) {
34 | this.success = false;
35 | this.code = code;
36 | this.errors = errors;
37 | this.msg = msg;
38 | }
39 |
40 | public boolean isSuccess() {
41 | return this.success;
42 | }
43 |
44 | public boolean hasErrors() {
45 | if (this.errors != null && this.errors.size() > 0) {
46 | return true;
47 | }
48 | return false;
49 | }
50 |
51 | }
52 |
--------------------------------------------------------------------------------
/cppba-spring-boot-core/src/main/java/com/cppba/base/constant/Globals.java:
--------------------------------------------------------------------------------
1 | package com.cppba.base.constant;
2 |
3 | import com.cppba.base.util.ConfigUtil;
4 |
5 | /**
6 | * 静态变量
7 | */
8 | public class Globals {
9 |
10 | //系统应用户ID
11 | public final static int USER_ID = ConfigUtil.getInteger("USER_ID",1);
12 |
13 | //图片本地地址
14 | public final static String FILE_SYSTEM_PATH = ConfigUtil.getString("FILE_SYSTEM_PATH","../../FileSystem");
15 | //图片服务器地址
16 | public final static String FILE_SERVER_URL = ConfigUtil.getString("FILE_SERVER_URL","http://image.cppba.com");
17 |
18 | /**
19 | * email
20 | */
21 | //发送人用户名
22 | public final static String EMAIL_USERNAME = ConfigUtil.getString("EMAIL_USERNAME","Service01@51dong.cc");
23 | //发送人密码
24 | public final static String EMAIL_PASSWORD =ConfigUtil.getString("EMAIL_PASSWORD","Service.01");
25 | //邮件服务器smtp
26 | public final static String EMAIL_SMTP =ConfigUtil.getString("EMAIL_SMTP","smtp.mxhichina.com");
27 | //接收通知
28 | public final static String EMAIL_SERVER = ConfigUtil.getString("EMAIL_SERVER","Service01@51dong.cc");
29 |
30 |
31 | //aliyun-oss
32 | public final static String ENDPOINT = ConfigUtil.getString("ENDPOINT","http://oss-cn-hongkong.aliyuncs.com");
33 | public final static String ACCESSKEYID = ConfigUtil.getString("ACCESSKEYID","KCsxSw9uWTJSz90h");
34 | public final static String ACCESSKEYSECRET = ConfigUtil.getString("ACCESSKEYSECRET","JMlEEkI3nlXF1rkdBDzk9RtH1X5aD3");
35 | public final static String BUCKETNAME = ConfigUtil.getString("BUCKETNAME","hk-filesystem");
36 |
37 | //前端模板文件夹
38 | public final static String TEMPLATE_TYPE = ConfigUtil.getString("TEMPLATE_TYPE","default");
39 |
40 | //通用静态资源地址,如:jquery、bootstrap
41 | public final static String STATIC_PUBLIC_URL = ConfigUtil.getString("STATIC_PUBLIC_URL","http://127.0.0.1/public-static");
42 |
43 | //项目资源地址
44 | public final static String STATIC_PRIVATE_URL = ConfigUtil.getString("STATIC_PRIVATE_URL","http://127.0.0.1/cppba-spring-boot-static");
45 | }
46 |
--------------------------------------------------------------------------------
/cppba-spring-boot-core/src/main/java/com/cppba/base/dao/BaseRepository.java:
--------------------------------------------------------------------------------
1 | package com.cppba.base.dao;
2 |
3 | import org.springframework.data.domain.Page;
4 | import org.springframework.data.domain.Sort;
5 | import org.springframework.data.repository.NoRepositoryBean;
6 |
7 | import java.io.Serializable;
8 | import java.util.List;
9 | import java.util.Map;
10 |
11 | /**
12 | * 开发者
13 | * nickName:大黄蜂
14 | * email:245655812@qq.com
15 | * github:https://github.com/bigbeef
16 | */
17 | @NoRepositoryBean
18 | public interface BaseRepository {
19 |
20 | int executeUpdate(String hql);
21 |
22 | List findByHql(final String hql);
23 |
24 | List findByHql(final String hql, final Map params);
25 |
26 | Page pageByHql(final String hql, final Integer page, final Integer size);
27 |
28 | Page pageByHql(final String hql, final Map params, final Integer page, final Integer size);
29 |
30 | Page pageByHql(final String hql, final Map params, final Integer page, final Integer size,final Sort sort);
31 |
32 | Long count(final String hql, final Map params);
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/cppba-spring-boot-core/src/main/java/com/cppba/base/dao/impl/BaseRepositoryImpl.java:
--------------------------------------------------------------------------------
1 | package com.cppba.base.dao.impl;
2 |
3 | import com.cppba.base.dao.BaseRepository;
4 | import org.apache.commons.lang3.StringUtils;
5 | import org.springframework.data.domain.Page;
6 | import org.springframework.data.domain.PageImpl;
7 | import org.springframework.data.domain.PageRequest;
8 | import org.springframework.data.domain.Sort;
9 |
10 | import javax.persistence.EntityManager;
11 | import javax.persistence.PersistenceContext;
12 | import javax.persistence.Query;
13 | import java.io.Serializable;
14 | import java.util.List;
15 | import java.util.Map;
16 |
17 | /**
18 | * 开发者
19 | * nickName:大黄蜂
20 | * email:245655812@qq.com
21 | * github:https://github.com/bigbeef
22 | */
23 | public class BaseRepositoryImpl implements BaseRepository {
24 |
25 | @PersistenceContext
26 | private EntityManager em;
27 |
28 | public int executeUpdate(String hql){
29 | Query query = em.createQuery(hql);
30 | return query.executeUpdate();
31 | }
32 |
33 | public List findByHql(final String hql){
34 | return findByHql(hql,null);
35 | }
36 |
37 | public List findByHql(final String hql, final Map params) {
38 | return pageByHql(hql,params,0,0).getContent();
39 | }
40 |
41 | public Page pageByHql(final String hql, final Integer page, final Integer size){
42 | return pageByHql(hql,null,page,size);
43 | }
44 |
45 | public Page pageByHql(final String hql, final Map params, final Integer page, final Integer size) {
46 | return pageByHql(hql,params,page,size,null);
47 | }
48 |
49 | public Page pageByHql(final String hql, final Map params, final Integer page, final Integer size,final Sort sort){
50 | StringBuilder sqlBuilder = new StringBuilder(hql);
51 | PageRequest pageRequest;
52 | List list;
53 | Integer count;
54 |
55 | //排序
56 | if(sort != null){
57 | int i = 0;
58 | for (Sort.Order order : sort) {
59 | if(i==0){
60 | sqlBuilder.append(" order by "+order.getProperty()+" "+order.getDirection().name()+" ");
61 | }else{
62 | sqlBuilder.append(","+order.getProperty()+" "+order.getDirection().name()+" ");
63 | }
64 | i++;
65 | }
66 | }
67 |
68 | Query query = em.createQuery(sqlBuilder.toString());
69 | //参数
70 | if (params != null && params.size() > 0) {
71 | for (Object key : params.keySet()) {
72 | query.setParameter(key.toString(), params.get(key));
73 | }
74 | }
75 |
76 | if(page>0 && size>0){
77 | query.setFirstResult((page - 1) * size);
78 | query.setMaxResults(size);
79 |
80 | list= query.getResultList();
81 | count = count(hql,params).intValue();
82 | pageRequest = new PageRequest(page, size);
83 | }else{
84 | list= query.getResultList();
85 | count = list.size();
86 | pageRequest = new PageRequest(1,count);
87 | }
88 | return new PageImpl(list,pageRequest,count);
89 | }
90 |
91 | public Long count(final String hql, final Map params) {
92 | final String countHQL = prepareCountHql(hql);
93 | Query query = em.createQuery(countHQL);
94 | if (params != null && params.size() > 0) {
95 | for (Object key : params.keySet()) {
96 | query.setParameter(key.toString(), params.get(key));
97 | }
98 | }
99 | return (Long)query.getSingleResult();
100 | }
101 |
102 | //获取HQL的count(*)
103 | private String prepareCountHql(final String HQL) {
104 | String fromHql = HQL;
105 | fromHql = "from" + StringUtils.substringAfter(fromHql, "from");
106 | fromHql = StringUtils.substringBefore(fromHql, "order by");
107 | int whereIndex = fromHql.indexOf("where");
108 | int leftIndex = fromHql.indexOf("left join");
109 | if (leftIndex >= 0) {
110 | if (whereIndex >= 0) {
111 | String temp = StringUtils.substringBefore(fromHql, "left");
112 | fromHql = temp + " where "
113 | + StringUtils.substringAfter(fromHql, "where");
114 | } else {
115 | fromHql = StringUtils.substringBefore(fromHql, "left");
116 | }
117 | }
118 | return "select count(*) " + fromHql;
119 | }
120 | }
--------------------------------------------------------------------------------
/cppba-spring-boot-core/src/main/java/com/cppba/base/entity/BaseEntity.java:
--------------------------------------------------------------------------------
1 | package com.cppba.base.entity;
2 |
3 | import lombok.Data;
4 |
5 | import javax.persistence.*;
6 | import java.io.Serializable;
7 | import java.util.Date;
8 |
9 | /**
10 | * 开发者
11 | * nickName:大黄蜂
12 | * email:245655812@qq.com
13 | * github:https://github.com/bigbeef
14 | */
15 | @Data
16 | @MappedSuperclass
17 | public class BaseEntity implements Serializable {
18 | @Id
19 | @Column(name = "id")
20 | @GeneratedValue(strategy = GenerationType.IDENTITY)
21 | private Long id;
22 | @Column(name = "add_time", columnDefinition = "timestamp default current_timestamp")
23 | private Date addTime;
24 | @Column(name = "delete_status", columnDefinition = "0")
25 | private Integer deleteStatus;
26 | }
27 |
--------------------------------------------------------------------------------
/cppba-spring-boot-core/src/main/java/com/cppba/base/util/AliyunOSSUtil.java:
--------------------------------------------------------------------------------
1 | package com.cppba.base.util;
2 |
3 | import com.aliyun.oss.OSSClient;
4 | import com.cppba.base.constant.Globals;
5 | import org.slf4j.Logger;
6 | import org.slf4j.LoggerFactory;
7 |
8 | import java.io.InputStream;
9 |
10 | /**
11 | * 图片压缩处理
12 | * @author 邹文峰
13 | */
14 | public class AliyunOSSUtil {
15 | private static Logger logger = LoggerFactory.getLogger(AliyunOSSUtil.class);
16 |
17 | public static void uploadFile(InputStream inputStream, String key){
18 | // 创建OSSClient实例
19 | OSSClient ossClient = new OSSClient(Globals.ENDPOINT, Globals.ACCESSKEYID, Globals.ACCESSKEYSECRET);
20 | // 使用访问OSS
21 | ossClient.putObject(Globals.BUCKETNAME, key, inputStream);
22 | // 关闭client
23 | ossClient.shutdown();
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/cppba-spring-boot-core/src/main/java/com/cppba/base/util/CommonUtil.java:
--------------------------------------------------------------------------------
1 | package com.cppba.base.util;
2 |
3 | import com.cppba.base.bean.Result;
4 | import com.cppba.entity.User;
5 | import com.fasterxml.jackson.core.JsonProcessingException;
6 | import com.fasterxml.jackson.databind.ObjectMapper;
7 | import org.apache.commons.lang3.ObjectUtils;
8 | import org.apache.commons.lang3.StringUtils;
9 | import org.slf4j.Logger;
10 | import org.slf4j.LoggerFactory;
11 |
12 | import javax.servlet.http.Cookie;
13 | import javax.servlet.http.HttpServletRequest;
14 | import javax.servlet.http.HttpServletResponse;
15 | import javax.servlet.http.HttpSession;
16 | import java.io.IOException;
17 | import java.io.PrintWriter;
18 |
19 | /**
20 | * 开发者
21 | * nickName:大黄蜂
22 | * email:245655812@qq.com
23 | * github:https://github.com/bigbeef
24 | */
25 | public class CommonUtil {
26 |
27 | private static Logger logger = LoggerFactory.getLogger(CommonUtil.class);
28 |
29 | //判断是否是ajax请求
30 | public static boolean isAjaxRequerst(HttpServletRequest request){
31 | String requestType = request.getHeader("X-Requested-With");
32 | if(StringUtils.equals(requestType,"XMLHttpRequest")){
33 | return true;
34 | }
35 | return false;
36 | }
37 |
38 | //获取session
39 | public static HttpSession getSession(HttpServletRequest request){
40 | HttpSession session = request.getSession();
41 | //Subject currentUser = SecurityUtils.getSubject();
42 | //Session session = currentUser.getSession();
43 | return session;
44 | }
45 |
46 | //从session中获取user
47 | public static User getUserFromSession(HttpServletRequest request){
48 | HttpSession session = getSession(request);
49 | User user = (User) session.getAttribute("user");
50 | return user;
51 | }
52 |
53 | public static void responseBuildJson(Result result, HttpServletResponse response){
54 | String json = "";
55 | try {
56 | ObjectMapper objectMapper = new ObjectMapper();
57 | json = objectMapper.writeValueAsString(result);
58 | } catch (JsonProcessingException e) {
59 | e.printStackTrace();
60 | }
61 | writeToResponse(json,response);
62 | }
63 |
64 | //获取coockie
65 | public static String getCookie(String name,HttpServletRequest request){
66 | Cookie[] cookies = request.getCookies();
67 | for(Cookie c :cookies ){
68 | if(c.getName().equals(name)){
69 | return c.getValue();
70 | }
71 | }
72 | return null;
73 | }
74 |
75 | //判断Integer为空或者等于0
76 | public static boolean isIntegerNullOrZero(Integer integer){
77 | return integer==null || !ObjectUtils.notEqual(integer,0);
78 | }
79 |
80 | //判断Long为空或者等于0
81 | public static boolean isLongNullOrZero(Long l){
82 | return l==null || !ObjectUtils.notEqual(l,0L);
83 | }
84 |
85 | //获取项目根路径
86 | public static String getBasePath(HttpServletRequest request){
87 | String path = request.getContextPath();
88 | return request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
89 | }
90 |
91 | //根获取请求终端IP
92 | public static String getIpAddr(HttpServletRequest request) {
93 | String ip = request.getHeader("x-forwarded-for");
94 | if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
95 | ip = request.getHeader("Proxy-Client-IP");
96 | }
97 | if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
98 | ip = request.getHeader("WL-Proxy-Client-IP");
99 | }
100 | if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
101 | ip = request.getRemoteAddr();
102 | }
103 | if (ip.equals("0:0:0:0:0:0:0:1")) {
104 | java.net.InetAddress addr = null;
105 | try {
106 | addr = java.net.InetAddress.getLocalHost();
107 | } catch (java.net.UnknownHostException e) {
108 | e.printStackTrace();
109 | }
110 | ip = addr.getHostAddress()==null?"":addr.getHostAddress();// 获得本机IP
111 | }
112 | return ip;
113 | }
114 |
115 | protected static void writeToResponse(String json,HttpServletResponse response){
116 | response.setContentType("application/json");
117 | response.setHeader("Cache-Control", "no-cache");
118 | response.setCharacterEncoding("UTF-8");
119 | try {
120 | PrintWriter writer;
121 | writer = response.getWriter();
122 | writer.print(json);
123 | } catch (IOException e) {
124 | e.printStackTrace();
125 | }
126 | }
127 | }
128 |
--------------------------------------------------------------------------------
/cppba-spring-boot-core/src/main/java/com/cppba/base/util/ConfigUtil.java:
--------------------------------------------------------------------------------
1 | package com.cppba.base.util;
2 |
3 |
4 | import org.apache.commons.configuration2.CombinedConfiguration;
5 | import org.apache.commons.configuration2.builder.fluent.Configurations;
6 | import org.apache.commons.configuration2.ex.ConfigurationException;
7 |
8 | import java.io.File;
9 |
10 | public class ConfigUtil {
11 |
12 | private static CombinedConfiguration CONFIG = null;
13 |
14 | static {
15 | //读取config文件夹下的配置文件
16 | File configFile = new File(ConfigUtil.class.getResource("/config").getPath());
17 | File[] propertiesFiles = configFile.listFiles();
18 | Configurations configurations = new Configurations();
19 | CONFIG = new CombinedConfiguration();
20 | try {
21 | for (File propertiesFile : propertiesFiles) {
22 | if(propertiesFile.getName().contains(".properties")){
23 | CONFIG.addConfiguration(configurations.properties(propertiesFile));
24 | }
25 | }
26 | } catch (ConfigurationException e) {
27 | e.printStackTrace();
28 | }
29 | }
30 |
31 | /**
32 | * 获取 String 类型的属性值
33 | */
34 | public static String getString(String key) {
35 | return CONFIG.getString(key);
36 | }
37 |
38 | /**
39 | * 获取 String 类型的属性值(可指定默认值)
40 | */
41 | public static String getString(String key, String defaultValue) {
42 | return CONFIG.getString(key, defaultValue);
43 | }
44 |
45 | public static boolean getBoolean(String key) {
46 | return CONFIG.getBoolean(key);
47 | }
48 |
49 | public static boolean getBoolean(String key, boolean defaultValue) {
50 | return CONFIG.getBoolean(key, defaultValue);
51 | }
52 |
53 | public static Boolean getBoolean(String key, Boolean defaultValue) {
54 | return CONFIG.getBoolean(key, defaultValue);
55 | }
56 |
57 | public static Integer getInteger(String key) {
58 | return CONFIG.getInt(key);
59 | }
60 |
61 | public static Integer getInteger(String key, Integer defaultValue) {
62 | return CONFIG.getInteger(key, defaultValue);
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/cppba-spring-boot-core/src/main/java/com/cppba/base/util/ConfigurationUtil.java:
--------------------------------------------------------------------------------
1 | package com.cppba.base.util;
2 |
3 |
4 | import org.apache.commons.configuration2.CombinedConfiguration;
5 | import org.apache.commons.configuration2.builder.fluent.Configurations;
6 | import org.apache.commons.configuration2.ex.ConfigurationException;
7 |
8 | import java.io.File;
9 |
10 | public class ConfigurationUtil {
11 |
12 | private static CombinedConfiguration CONFIG = null;
13 |
14 | static {
15 | //读取config文件夹下的配置文件
16 | File configFile = new File(ConfigurationUtil.class.getResource("/config").getPath());
17 | File[] propertiesFiles = configFile.listFiles();
18 | Configurations configurations = new Configurations();
19 | CONFIG = new CombinedConfiguration();
20 | try {
21 | for (File propertiesFile : propertiesFiles) {
22 | if(propertiesFile.getName().contains(".properties")){
23 | CONFIG.addConfiguration(configurations.properties(propertiesFile));
24 | }
25 | }
26 | } catch (ConfigurationException e) {
27 | e.printStackTrace();
28 | }
29 | }
30 |
31 | /**
32 | * 获取 String 类型的属性值
33 | */
34 | public static String getString(String key) {
35 | return CONFIG.getString(key);
36 | }
37 |
38 | /**
39 | * 获取 String 类型的属性值(可指定默认值)
40 | */
41 | public static String getString(String key, String defaultValue) {
42 | return CONFIG.getString(key, defaultValue);
43 | }
44 |
45 | public static boolean getBoolean(String key) {
46 | return CONFIG.getBoolean(key);
47 | }
48 |
49 | public static boolean getBoolean(String key, boolean defaultValue) {
50 | return CONFIG.getBoolean(key, defaultValue);
51 | }
52 |
53 | public static Boolean getBoolean(String key, Boolean defaultValue) {
54 | return CONFIG.getBoolean(key, defaultValue);
55 | }
56 |
57 | public static Integer getInteger(String key) {
58 | return CONFIG.getInt(key);
59 | }
60 |
61 | public static Integer getInteger(String key, Integer defaultValue) {
62 | return CONFIG.getInteger(key, defaultValue);
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/cppba-spring-boot-core/src/main/java/com/cppba/base/util/ImgCompressUtil.java:
--------------------------------------------------------------------------------
1 | package com.cppba.base.util;
2 |
3 | import org.slf4j.Logger;
4 | import org.slf4j.LoggerFactory;
5 |
6 | import javax.imageio.ImageIO;
7 | import java.awt.image.BufferedImage;
8 | import java.io.File;
9 | import java.io.FileOutputStream;
10 | import java.io.IOException;
11 |
12 | /**
13 | * 图片压缩处理
14 | * @author 邹文峰
15 | */
16 | public class ImgCompressUtil {
17 |
18 | private static Logger logger = LoggerFactory.getLogger(ImgCompressUtil.class);
19 |
20 | /**
21 | * 生成一张缩略图
22 | * @param fileName 压缩文件("c:\\1.png")
23 | * @param type 压缩类型(1.中等缩略图:压缩为原来一半,2.小型缩略图:压缩为原来1/4)
24 | */
25 | public static void createImgCompress(String fileName,int type){
26 | if(type==1){
27 | BufferedImage img = ImgCompressUtil.resize(fileName, 0.5);
28 | ImgCompressUtil.writeToFile(fileName+"_middle.png", img);
29 | logger.info("{}小型缩略图生成成功",fileName);
30 | }else if(type==2){
31 | BufferedImage img = ImgCompressUtil.resize(fileName, 0.25);
32 | ImgCompressUtil.writeToFile(fileName+"_small.png", img);
33 | logger.info("{}中型缩略图生成成功",fileName);
34 | }else{
35 | throw new RuntimeException("没有找到此压缩类型:"+type);
36 | }
37 | }
38 |
39 | /**
40 | * 强制压缩/放大图片到固定的大小
41 | * @param fileName 压缩文件("c:\\1.png")
42 | * @param compressPercent 压缩比例(压缩为原来一半传0.5)
43 | * @return
44 | */
45 | public static BufferedImage resize(String fileName,double compressPercent){
46 | BufferedImage img = null;//原图
47 | BufferedImage compressImg = null;//压缩后图
48 | int width,height;
49 | try {
50 | File file = new File(fileName);
51 | img = ImageIO.read(file);
52 | width = (int)(img.getWidth()*compressPercent);
53 | height = (int)(img.getHeight()*compressPercent);
54 | compressImg = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB );
55 | compressImg.getGraphics().drawImage(img, 0, 0, width, height, null); // 绘制缩小后的图
56 | } catch (IOException e) {
57 | e.printStackTrace();
58 | }
59 | return compressImg;
60 | }
61 |
62 | /**
63 | *
64 | * @param file 存放位置("c:\\1.png")
65 | * @param img
66 | */
67 | public static void writeToFile(String file,BufferedImage img){
68 | try {
69 | File destFile = new File(file);
70 | FileOutputStream out = new FileOutputStream(destFile); // 输出到文件流
71 | ImageIO.write(img, "png", out);
72 | out.close();
73 | } catch (Exception e) {
74 | e.printStackTrace();
75 | }
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/cppba-spring-boot-core/src/main/java/com/cppba/base/util/JwtUtil.java:
--------------------------------------------------------------------------------
1 | package com.cppba.base.util;
2 |
3 | import com.auth0.jwt.JWT;
4 | import com.auth0.jwt.JWTCreator;
5 | import com.auth0.jwt.JWTVerifier;
6 | import com.auth0.jwt.algorithms.Algorithm;
7 | import com.auth0.jwt.interfaces.Claim;
8 | import com.cppba.base.bean.CurrentUser;
9 | import com.fasterxml.jackson.databind.ObjectMapper;
10 |
11 | public class JwtUtil {
12 |
13 | private static String secret = "com.cppba";
14 |
15 | /**
16 | * 创建一个jwt字符串
17 | * @param userJwt
18 | * @return
19 | * @throws Exception
20 | */
21 | public static String createJwt(CurrentUser currentUser) throws Exception{
22 | ObjectMapper objectMapper = new ObjectMapper();
23 | String jwtString = objectMapper.writeValueAsString(currentUser);
24 | JWTCreator.Builder builder = JWT.create();
25 | builder.withClaim("user",jwtString);
26 | return builder.sign(Algorithm.HMAC256(secret));
27 | }
28 |
29 | /**
30 | * 解码jwt token
31 | * @param token
32 | * @return
33 | * @throws Exception
34 | */
35 | public static CurrentUser decodeJwt(String token) throws Exception{
36 | JWT decode = JWT.decode(token);
37 | Claim user = decode.getClaim("user");
38 | String userString = user.as(String.class);
39 | ObjectMapper objectMapper = new ObjectMapper();
40 | CurrentUser userJwt = objectMapper.readValue(userString,CurrentUser.class);
41 | return userJwt;
42 | }
43 |
44 | /**
45 | * 验证token签名是否合法
46 | * @param token
47 | * @return
48 | * @throws Exception
49 | */
50 | public static boolean verify(String token) throws Exception {
51 | try {
52 | JWT decode = JWT.decode(token);
53 | JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret))
54 | .build();
55 | verifier.verify(token);
56 | } catch (Exception e) {
57 | return false;
58 | }
59 | return true;
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/cppba-spring-boot-core/src/main/java/com/cppba/base/util/MD5Util.java:
--------------------------------------------------------------------------------
1 | package com.cppba.base.util;
2 |
3 | import org.apache.commons.lang3.StringUtils;
4 |
5 | import java.security.MessageDigest;
6 |
7 | public class MD5Util {
8 | /**
9 | * Md5 32位小写 加密
10 | * @param source
11 | * @return
12 | * @throws Exception
13 | */
14 | public static String encode32Md5(String source) throws Exception{
15 | if(StringUtils.isEmpty(source)){
16 | return null;
17 | }
18 | MessageDigest md5 = MessageDigest.getInstance("MD5");
19 | md5.update((source).getBytes("UTF-8"));
20 | byte b[] = md5.digest();
21 |
22 | int i;
23 | StringBuffer buf = new StringBuffer("");
24 |
25 | for(int offset=0; offset hints = new Hashtable();
40 | hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
41 | hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
42 | hints.put(EncodeHintType.MARGIN, 0);
43 | try {
44 | bitMatrix = mfw.encode(content, BarcodeFormat.QR_CODE, W, H,hints);
45 | } catch (WriterException e) {
46 | e.printStackTrace();
47 | }
48 | int width = bitMatrix.getWidth();
49 | int height = bitMatrix.getHeight();
50 | BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
51 | for(int x=0; x < width; x++){
52 | for(int y=0; y < height; y++){
53 | image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
54 | }
55 | }
56 | return image;
57 | }
58 |
59 | /**
60 | *
61 | * QRCodeCreate(生成二维码)
62 | * @param content 二维码内容
63 | * @param path 保存相对路径("/usr/tomcat/webapps/FileSystem"+path)
64 | * @param W 宽度
65 | * @param H 高度
66 | * @return
67 | *//*
68 | public static String QRCodeCreate(String content,String path,Integer W,Integer H){
69 | String name=UUID.randomUUID().toString()+".png";
70 | String root = Globals.getFileSystemPath()+path;
71 | //创建文件夹
72 | File dirFile = new File(root);
73 | if (!dirFile.exists()) {
74 | dirFile.mkdirs();
75 | }
76 | //生成二维码
77 | MultiFormatWriter mfw = new MultiFormatWriter();
78 | BitMatrix bitMatrix = null;
79 | Hashtable hints = new Hashtable();
80 | hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
81 | hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
82 | hints.put(EncodeHintType.MARGIN, 0);
83 | try {
84 | bitMatrix = mfw.encode(content, BarcodeFormat.QR_CODE, W, H,hints);
85 | } catch (WriterException e) {
86 | e.printStackTrace();
87 | }
88 | int width = bitMatrix.getWidth();
89 | int height = bitMatrix.getHeight();
90 | BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
91 | for(int x=0; x < width; x++){
92 | for(int y=0; y < height; y++){
93 | image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
94 | }
95 | }
96 | try {
97 | ImageIO.write(image, "png", new File(root+"/"+name));
98 | } catch (IOException e) {
99 | e.printStackTrace();
100 | }
101 | return name;
102 | }*/
103 | }
104 |
--------------------------------------------------------------------------------
/cppba-spring-boot-core/src/main/java/com/cppba/base/util/Results.java:
--------------------------------------------------------------------------------
1 | package com.cppba.base.util;
2 |
3 | import com.cppba.base.bean.Result;
4 | import com.google.common.collect.Maps;
5 |
6 | import java.util.Map;
7 |
8 | public class Results {
9 |
10 | protected Results() {
11 | }
12 |
13 | public static Result newResult() {
14 | return new Result();
15 | }
16 |
17 | //
18 | // 业务调用成功
19 | // --------------------------------------------------------------------------------------------------------------------------------
20 | public static Result success() {
21 | return success(null, null);
22 | }
23 |
24 | public static Result success(Integer code) {
25 | return success(code, null);
26 | }
27 |
28 | public static Result success(String msg) {
29 | return success(null, msg);
30 | }
31 |
32 | public static Result success(Integer code, String msg) {
33 | return successWithData(code, null, msg);
34 | }
35 |
36 | public static Result successWithData(Object data) {
37 | return successWithData(null, data, null);
38 | }
39 |
40 | public static Result successWithData(Object data, String msg) {
41 | return successWithData(null, data, msg);
42 | }
43 |
44 | public static Result successWithData(Integer code, Object data) {
45 | return successWithData(code, data, null);
46 | }
47 |
48 | public static Result successWithData(Integer code, Object data, String msg) {
49 | return new Result(true, code, data, msg);
50 | }
51 |
52 | //
53 | // 业务调用失败
54 | // --------------------------------------------------------------------------------------------------------------------------------
55 | public static Result failure() {
56 | return failure(null, null);
57 | }
58 |
59 | public static Result failure(Integer code) {
60 | return failure(code, null);
61 | }
62 |
63 | public static Result failure(String msg) {
64 | return failure(null, msg);
65 | }
66 |
67 | public static Result failure(Integer code, String msg) {
68 | return failureWithData(code, null, msg);
69 | }
70 |
71 | public static Result failureWithData(Object data) {
72 | return failureWithData(null, data, null);
73 | }
74 |
75 | public static Result failureWithData(Object data, String msg) {
76 | return failureWithData(null, data, msg);
77 | }
78 |
79 | public static Result failureWithData(Integer code, Object data) {
80 | return failureWithData(code, data, null);
81 | }
82 |
83 | public static Result failureWithData(Integer code, Object data, String msg) {
84 | return new Result(false, code, data, msg);
85 | }
86 |
87 | //
88 | // 代码执行失败:返回包含错误提示
89 | // --------------------------------------------------------------------------------------------------------------------------------
90 | public static Result failureWithError(Throwable ex) {
91 | return failureWithError(null, null, ex.getMessage());
92 | }
93 |
94 | public static Result failureWithError(String field, String msg) {
95 | Map errors = Maps.newHashMap();
96 | errors.put(field, msg);
97 | return failureWithError(null, errors, msg);
98 | }
99 |
100 | public static Result failureWithError(Map errors, String msg) {
101 | return failureWithError(null, errors, msg);
102 | }
103 |
104 | public static Result failureWithError(Integer code, Map errors, String msg) {
105 | return new Result(code, errors, msg);
106 | }
107 |
108 | }
109 |
--------------------------------------------------------------------------------
/cppba-spring-boot-core/src/main/java/com/cppba/base/util/SendEmailUtil.java:
--------------------------------------------------------------------------------
1 | package com.cppba.base.util;
2 |
3 | import com.cppba.base.constant.Globals;
4 | import org.apache.commons.lang3.StringUtils;
5 |
6 | import javax.activation.DataHandler;
7 | import javax.activation.FileDataSource;
8 | import javax.mail.*;
9 | import javax.mail.internet.*;
10 | import java.util.Properties;
11 |
12 | /**
13 | *
14 | *
15 | * SendEmail
16 | * 邮件发送工具类
17 | *
18 | * 2015-12-4 下午04:22:03
19 | *
20 | * @version 1.0.0
21 | *
22 | */
23 | public class SendEmailUtil {
24 |
25 | //发送邮件
26 | public static boolean sendEmail(String toUserEmail/*收件人*/,String subject/*标题*/,String content/*正文*/,String file/*发送附件*/,String fileName/*附件名*/){
27 | try {
28 | final Properties mailProps = new Properties();
29 | mailProps.put("mail.smtp.auth", "true");
30 | mailProps.put("username", Globals.EMAIL_USERNAME);
31 | mailProps.put("password", Globals.EMAIL_PASSWORD);
32 | mailProps.put("mail.smtp.host", Globals.EMAIL_SMTP);
33 |
34 | // 构建授权信息,用于进行SMTP进行身份验证
35 | Authenticator auth = new Authenticator() {
36 | @Override
37 | protected PasswordAuthentication getPasswordAuthentication() {
38 | // 用户名、密码
39 | String userName = mailProps.getProperty("username");
40 | String password = mailProps.getProperty("password");
41 | return new PasswordAuthentication(userName, password);
42 | }
43 | };
44 | Session mailSession = Session.getInstance(mailProps, auth);
45 | MimeMessage message = new MimeMessage(mailSession);
46 | message.setFrom(new InternetAddress(Globals.EMAIL_USERNAME));
47 | message.setRecipient(Message.RecipientType.TO, new InternetAddress(toUserEmail));
48 | message.setSubject(subject);
49 | MimeMultipart multi = new MimeMultipart("related");
50 |
51 | MimeBodyPart attach = new MimeBodyPart(); //表示附件
52 | //附件不为空
53 | if(StringUtils.isNotBlank(file)){
54 | attach.setDataHandler(new DataHandler(new FileDataSource(file)));
55 | attach.setFileName( MimeUtility.encodeText(fileName));
56 | multi.addBodyPart(attach);
57 | }
58 | //添加邮件内容
59 | MimeBodyPart bodyPart = new MimeBodyPart();
60 | bodyPart.setDataHandler(new DataHandler(content, "text/html;charset=UTF-8"));// 网页格式
61 | multi.addBodyPart(bodyPart);
62 |
63 | message.setContent(multi);
64 | message.saveChanges();
65 | Transport.send(message);
66 | } catch (Exception e) {
67 | e.printStackTrace();
68 | return false;
69 | }
70 | return true;
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/cppba-spring-boot-core/src/main/java/com/cppba/base/util/UploadFileUtil.java:
--------------------------------------------------------------------------------
1 | package com.cppba.base.util;
2 |
3 | import com.cppba.base.constant.Globals;
4 | import org.slf4j.Logger;
5 | import org.slf4j.LoggerFactory;
6 | import org.springframework.web.multipart.MultipartFile;
7 | import sun.misc.BASE64Decoder;
8 |
9 | import java.io.File;
10 | import java.io.FileOutputStream;
11 | import java.io.InputStream;
12 | import java.io.OutputStream;
13 | import java.util.UUID;
14 |
15 | /**
16 | * @author Administrator
17 | *
18 | */
19 | public class UploadFileUtil {
20 | private static Logger logger = LoggerFactory.getLogger(UploadFileUtil.class);
21 | /**
22 | * base64 -- 文件base64编码 "iVBORw0KGgoAAAAN......"
23 | * path -- 上传路径 "/Image/article"
24 | * ext -- 拓展名 "png"
25 | * @throws Exception
26 | */
27 | public static String base64ToFile(String base64,String path,String ext) throws Exception{
28 | String root = Globals.FILE_SYSTEM_PATH+path;
29 | //创建文件夹
30 | File dirFile = new File(root);
31 | if (!dirFile.exists()) {
32 | dirFile.mkdirs();
33 | }
34 | String name=UUID.randomUUID().toString()+"."+ext;
35 | BASE64Decoder decoder = new BASE64Decoder();
36 | FileOutputStream write = new FileOutputStream(new File(root+"/"+name));
37 | byte[] decoderBytes = decoder.decodeBuffer(base64);
38 | write.write(decoderBytes);
39 | write.close();
40 | //生成中等缩略图
41 | ImgCompressUtil.createImgCompress(root+"/"+name,1);
42 | //生成小等缩略图
43 | ImgCompressUtil.createImgCompress(root+"/"+name,2);
44 | return name;
45 | }
46 |
47 | // 图片上传
48 | public static String uploadFile(MultipartFile file, String path,boolean isImage) {
49 | String root = Globals.FILE_SYSTEM_PATH + path;
50 | // 创建文件夹
51 | File dirFile = new File(root);
52 | if (!dirFile.exists()) {
53 | dirFile.mkdirs();
54 | }
55 | // 获得图片后缀名
56 | String fileName = file.getOriginalFilename();
57 | String fileExt = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
58 |
59 | InputStream is;
60 | String name = UUID.randomUUID().toString()+fileExt;
61 | try {
62 | is = file.getInputStream();
63 | File descfile = new File(root, name);
64 | OutputStream os = new FileOutputStream(descfile);
65 | byte[] buffer = new byte[400];
66 | int count = 0;
67 | while ((count = is.read(buffer)) > 0) {
68 | os.write(buffer, 0, count);
69 | }
70 | os.close();
71 | is.close();
72 | //如果是图片则压缩
73 | if(isImage){
74 | // 生成中等缩略图
75 | ImgCompressUtil.createImgCompress(root + "/" + name, 1);
76 | // 生成小等缩略图
77 | ImgCompressUtil.createImgCompress(root + "/" + name, 2);
78 | }
79 | logger.info("{} 文件上传成功为 {}",fileName,name);
80 | } catch (Exception e) {
81 | logger.error(e.getMessage(), e);
82 | }
83 |
84 | return name;
85 | }
86 |
87 | //阿里云图片上传
88 | public static String uploadFileAliyun(MultipartFile file, String path) {
89 | String root = path;
90 | // 获得图片后缀名
91 | String fileName = file.getOriginalFilename();
92 | String fileExt = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
93 |
94 | String name = UUID.randomUUID().toString()+fileExt;
95 | InputStream is;
96 | try {
97 | is = file.getInputStream();
98 | AliyunOSSUtil.uploadFile(is,path+"/"+name);
99 | logger.info("{} 文件上传成功为 {}",fileName,path+"/"+name);
100 | } catch (Exception e) {
101 | logger.error(e.getMessage(), e);
102 | }
103 | return name;
104 | }
105 | }
--------------------------------------------------------------------------------
/cppba-spring-boot-core/src/main/java/com/cppba/base/util/VerifyCodeUtil.java:
--------------------------------------------------------------------------------
1 | package com.cppba.base.util;
2 |
3 | import javax.imageio.ImageIO;
4 | import java.awt.*;
5 | import java.awt.geom.AffineTransform;
6 | import java.awt.image.BufferedImage;
7 | import java.io.File;
8 | import java.io.FileOutputStream;
9 | import java.io.IOException;
10 | import java.io.OutputStream;
11 | import java.util.Arrays;
12 | import java.util.Random;
13 |
14 | public class VerifyCodeUtil {
15 |
16 | //使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符
17 | public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
18 | private static Random random = new Random();
19 |
20 |
21 | /**
22 | * 使用系统默认字符源生成验证码
23 | * @param verifySize 验证码长度
24 | * @return
25 | */
26 | public static String generateVerifyCode(int verifySize){
27 | return generateVerifyCode(verifySize, VERIFY_CODES);
28 | }
29 | /**
30 | * 使用指定源生成验证码
31 | * @param verifySize 验证码长度
32 | * @param sources 验证码字符源
33 | * @return
34 | */
35 | public static String generateVerifyCode(int verifySize, String sources){
36 | if(sources == null || sources.length() == 0){
37 | sources = VERIFY_CODES;
38 | }
39 | int codesLen = sources.length();
40 | Random rand = new Random(System.currentTimeMillis());
41 | StringBuilder verifyCode = new StringBuilder(verifySize);
42 | for(int i = 0; i < verifySize; i++){
43 | verifyCode.append(sources.charAt(rand.nextInt(codesLen-1)));
44 | }
45 | return verifyCode.toString();
46 | }
47 |
48 | /**
49 | * 生成随机验证码文件,并返回验证码值
50 | * @param w
51 | * @param h
52 | * @param outputFile
53 | * @param verifySize
54 | * @return
55 | * @throws IOException
56 | */
57 | public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException{
58 | String verifyCode = generateVerifyCode(verifySize);
59 | outputImage(w, h, outputFile, verifyCode);
60 | return verifyCode;
61 | }
62 |
63 | /**
64 | * 输出随机验证码图片流,并返回验证码值
65 | * @param w
66 | * @param h
67 | * @param os
68 | * @param verifySize
69 | * @return
70 | * @throws IOException
71 | */
72 | public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException{
73 | String verifyCode = generateVerifyCode(verifySize);
74 | outputImage(w, h, os, verifyCode);
75 | return verifyCode;
76 | }
77 |
78 | /**
79 | * 生成指定验证码图像文件
80 | * @param w
81 | * @param h
82 | * @param outputFile
83 | * @param code
84 | * @throws IOException
85 | */
86 | public static void outputImage(int w, int h, File outputFile, String code) throws IOException{
87 | if(outputFile == null){
88 | return;
89 | }
90 | File dir = outputFile.getParentFile();
91 | if(!dir.exists()){
92 | dir.mkdirs();
93 | }
94 | try{
95 | outputFile.createNewFile();
96 | FileOutputStream fos = new FileOutputStream(outputFile);
97 | outputImage(w, h, fos, code);
98 | fos.close();
99 | } catch(IOException e){
100 | throw e;
101 | }
102 | }
103 |
104 | /**
105 | * 输出指定验证码图片流
106 | * @param w
107 | * @param h
108 | * @param os
109 | * @param code
110 | * @throws IOException
111 | */
112 | public static void outputImage(int w, int h, OutputStream os, String code) throws IOException{
113 | int verifySize = code.length();
114 | BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
115 | Random rand = new Random();
116 | Graphics2D g2 = image.createGraphics();
117 | g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
118 | Color[] colors = new Color[5];
119 | Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN,
120 | Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
121 | Color.PINK, Color.YELLOW };
122 | float[] fractions = new float[colors.length];
123 | for(int i = 0; i < colors.length; i++){
124 | colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
125 | fractions[i] = rand.nextFloat();
126 | }
127 | Arrays.sort(fractions);
128 |
129 | g2.setColor(Color.GRAY);// 设置边框色
130 | g2.fillRect(0, 0, w, h);
131 |
132 | Color c = getRandColor(200, 250);
133 | g2.setColor(c);// 设置背景色
134 | g2.fillRect(0, 2, w, h-4);
135 |
136 | //绘制干扰线
137 | Random random = new Random();
138 | g2.setColor(getRandColor(160, 200));// 设置线条的颜色
139 | for (int i = 0; i < 20; i++) {
140 | int x = random.nextInt(w - 1);
141 | int y = random.nextInt(h - 1);
142 | int xl = random.nextInt(6) + 1;
143 | int yl = random.nextInt(12) + 1;
144 | g2.drawLine(x, y, x + xl + 40, y + yl + 20);
145 | }
146 |
147 | // 添加噪点
148 | float yawpRate = 0.05f;// 噪声率
149 | int area = (int) (yawpRate * w * h);
150 | for (int i = 0; i < area; i++) {
151 | int x = random.nextInt(w);
152 | int y = random.nextInt(h);
153 | int rgb = getRandomIntColor();
154 | image.setRGB(x, y, rgb);
155 | }
156 |
157 | shear(g2, w, h, c);// 使图片扭曲
158 |
159 | g2.setColor(getRandColor(100, 160));
160 | int fontSize = h-4;
161 | Font font = new Font("Algerian", Font.ITALIC, fontSize);
162 | g2.setFont(font);
163 | char[] chars = code.toCharArray();
164 | for(int i = 0; i < verifySize; i++){
165 | AffineTransform affine = new AffineTransform();
166 | affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize/2, h/2);
167 | g2.setTransform(affine);
168 | g2.drawChars(chars, i, 1, ((w-10) / verifySize) * i + 5, h/2 + fontSize/2 - 10);
169 | }
170 |
171 | g2.dispose();
172 | ImageIO.write(image, "jpg", os);
173 | }
174 |
175 | private static Color getRandColor(int fc, int bc) {
176 | if (fc > 255)
177 | fc = 255;
178 | if (bc > 255)
179 | bc = 255;
180 | int r = fc + random.nextInt(bc - fc);
181 | int g = fc + random.nextInt(bc - fc);
182 | int b = fc + random.nextInt(bc - fc);
183 | return new Color(r, g, b);
184 | }
185 |
186 | private static int getRandomIntColor() {
187 | int[] rgb = getRandomRgb();
188 | int color = 0;
189 | for (int c : rgb) {
190 | color = color << 8;
191 | color = color | c;
192 | }
193 | return color;
194 | }
195 |
196 | private static int[] getRandomRgb() {
197 | int[] rgb = new int[3];
198 | for (int i = 0; i < 3; i++) {
199 | rgb[i] = random.nextInt(255);
200 | }
201 | return rgb;
202 | }
203 |
204 | private static void shear(Graphics g, int w1, int h1, Color color) {
205 | shearX(g, w1, h1, color);
206 | shearY(g, w1, h1, color);
207 | }
208 |
209 | private static void shearX(Graphics g, int w1, int h1, Color color) {
210 |
211 | int period = random.nextInt(2);
212 |
213 | boolean borderGap = true;
214 | int frames = 1;
215 | int phase = random.nextInt(2);
216 |
217 | for (int i = 0; i < h1; i++) {
218 | double d = (double) (period >> 1)
219 | * Math.sin((double) i / (double) period
220 | + (6.2831853071795862D * (double) phase)
221 | / (double) frames);
222 | g.copyArea(0, i, w1, 1, (int) d, 0);
223 | if (borderGap) {
224 | g.setColor(color);
225 | g.drawLine((int) d, i, 0, i);
226 | g.drawLine((int) d + w1, i, w1, i);
227 | }
228 | }
229 |
230 | }
231 |
232 | private static void shearY(Graphics g, int w1, int h1, Color color) {
233 |
234 | int period = random.nextInt(40) + 10; // 50;
235 |
236 | boolean borderGap = true;
237 | int frames = 20;
238 | int phase = 7;
239 | for (int i = 0; i < w1; i++) {
240 | double d = (double) (period >> 1)
241 | * Math.sin((double) i / (double) period
242 | + (6.2831853071795862D * (double) phase)
243 | / (double) frames);
244 | g.copyArea(i, 0, 1, h1, 0, (int) d);
245 | if (borderGap) {
246 | g.setColor(color);
247 | g.drawLine(i, (int) d, i, 0);
248 | g.drawLine(i, (int) d + h1, i, h1);
249 | }
250 |
251 | }
252 |
253 | }
254 | public static void main(String[] args) throws IOException{
255 | File dir = new File("F:/verifies");
256 | int w = 200, h = 80;
257 | for(int i = 0; i < 50; i++){
258 | String verifyCode = generateVerifyCode(4);
259 | File file = new File(dir, verifyCode + ".jpg");
260 | outputImage(w, h, file, verifyCode);
261 | }
262 | }
263 | }
--------------------------------------------------------------------------------
/cppba-spring-boot-core/src/main/java/com/cppba/entity/ArticleClass.java:
--------------------------------------------------------------------------------
1 | package com.cppba.entity;
2 |
3 | import com.cppba.base.entity.BaseEntity;
4 | import com.fasterxml.jackson.annotation.JsonIgnore;
5 | import lombok.Data;
6 |
7 | import javax.persistence.*;
8 |
9 | /**
10 | * 开发者
11 | * nickName:大黄蜂
12 | * email:245655812@qq.com
13 | * github:https://github.com/bigbeef
14 | */
15 | @Data
16 | @Entity
17 | @Table(name = "article_class")
18 | public class ArticleClass extends BaseEntity {
19 | @Column(name = "user_id")
20 | private Long userId;
21 |
22 | @Column(name = "name")
23 | private String name;
24 |
25 | @Column(name = "sort")
26 | private String sort;
27 |
28 | @JsonIgnore
29 | @ManyToOne(fetch = FetchType.LAZY)
30 | @JoinColumn(name = "user_id", updatable = false, insertable = false)
31 | private User user;
32 | }
33 |
--------------------------------------------------------------------------------
/cppba-spring-boot-core/src/main/java/com/cppba/entity/User.java:
--------------------------------------------------------------------------------
1 | package com.cppba.entity;
2 |
3 | import com.cppba.base.entity.BaseEntity;
4 | import lombok.Data;
5 |
6 | import javax.persistence.Column;
7 | import javax.persistence.Entity;
8 | import javax.persistence.Table;
9 |
10 | /**
11 | * 开发者
12 | * nickName:大黄蜂
13 | * email:245655812@qq.com
14 | * github:https://github.com/bigbeef
15 | */
16 | @Data
17 | @Entity
18 | @Table(name = "user")
19 | public class User extends BaseEntity {
20 | @Column(name = "user_name")
21 | private String userName;
22 | @Column(name = "password")
23 | private String password;
24 | @Column(name = "nick_name")
25 | private String nickName;
26 | @Column(name = "remark")
27 | private String remark;
28 | @Column(name = "title")
29 | private String title;
30 | @Column(name = "keyword")
31 | private String keyword;
32 | @Column(name = "description")
33 | private String description;
34 | }
35 |
--------------------------------------------------------------------------------
/cppba-spring-boot-core/src/main/java/com/cppba/form/admin/SettingForm.java:
--------------------------------------------------------------------------------
1 | package com.cppba.form.admin;
2 |
3 | import lombok.Data;
4 |
5 | @Data
6 | public class SettingForm {
7 |
8 | private String nickName;
9 |
10 | private String remark;
11 |
12 | private String title;
13 |
14 | private String keyword;
15 |
16 | private String description;
17 | }
18 |
--------------------------------------------------------------------------------
/cppba-spring-boot-core/src/main/java/com/cppba/repository/ArticleClassRepository.java:
--------------------------------------------------------------------------------
1 | package com.cppba.repository;
2 |
3 |
4 | import com.cppba.entity.ArticleClass;
5 | import com.cppba.repository.custom.ArticleClassRepositoryCustom;
6 | import org.springframework.data.jpa.repository.JpaRepository;
7 |
8 | /**
9 | * 开发者
10 | * nickName:大黄蜂
11 | * email:245655812@qq.com
12 | * github:https://github.com/bigbeef
13 | */
14 | //同时继承base和自定义repository,自定义接口实现命名必须以此接口名加后缀
15 | public interface ArticleClassRepository extends ArticleClassRepositoryCustom,JpaRepository {
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/cppba-spring-boot-core/src/main/java/com/cppba/repository/UserRepository.java:
--------------------------------------------------------------------------------
1 | package com.cppba.repository;
2 |
3 |
4 | import com.cppba.entity.User;
5 | import com.cppba.repository.custom.UserRepositoryCustom;
6 | import org.springframework.data.jpa.repository.JpaRepository;
7 |
8 | /**
9 | * 开发者
10 | * nickName:大黄蜂
11 | * email:245655812@qq.com
12 | * github:https://github.com/bigbeef
13 | */
14 | //同时继承base和自定义repository,自定义接口实现命名必须以此接口名加后缀
15 | public interface UserRepository extends JpaRepository, UserRepositoryCustom {
16 |
17 | User getByUserName(String userName);
18 |
19 | User getById(Long id);
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/cppba-spring-boot-core/src/main/java/com/cppba/repository/custom/ArticleClassRepositoryCustom.java:
--------------------------------------------------------------------------------
1 | package com.cppba.repository.custom;
2 |
3 | import com.cppba.base.dao.BaseRepository;
4 | import com.cppba.entity.ArticleClass;
5 | import org.springframework.data.domain.Page;
6 |
7 | /**
8 | * 开发者
9 | * nickName:大黄蜂
10 | * email:245655812@qq.com
11 | * github:https://github.com/bigbeef
12 | */
13 | //用户自定义repository接口
14 | public interface ArticleClassRepositoryCustom extends BaseRepository {
15 |
16 | Page page(Long userId, String name, Integer pageNumber, Integer pageSize);
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/cppba-spring-boot-core/src/main/java/com/cppba/repository/custom/UserRepositoryCustom.java:
--------------------------------------------------------------------------------
1 | package com.cppba.repository.custom;
2 |
3 | import com.cppba.base.dao.BaseRepository;
4 | import com.cppba.entity.User;
5 |
6 | /**
7 | * 开发者
8 | * nickName:大黄蜂
9 | * email:245655812@qq.com
10 | * github:https://github.com/bigbeef
11 | */
12 | //用户自定义repository接口
13 | public interface UserRepositoryCustom extends BaseRepository {
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/cppba-spring-boot-core/src/main/java/com/cppba/repository/impl/ArticleClassRepositoryImpl.java:
--------------------------------------------------------------------------------
1 | package com.cppba.repository.impl;
2 |
3 |
4 | import com.cppba.base.dao.impl.BaseRepositoryImpl;
5 | import com.cppba.entity.ArticleClass;
6 | import com.cppba.repository.custom.ArticleClassRepositoryCustom;
7 | import com.google.common.collect.Maps;
8 | import org.apache.commons.lang3.StringUtils;
9 | import org.springframework.data.domain.Page;
10 | import org.springframework.stereotype.Repository;
11 |
12 | import java.util.HashMap;
13 |
14 | /**
15 | * 开发者
16 | * nickName:大黄蜂
17 | * email:245655812@qq.com
18 | * github:https://github.com/bigbeef
19 | */
20 | //用户自定义repository实现(命名必须以最顶层repository加后缀(默认Impl)规则,这里是UserRepository+Impl)
21 | @Repository
22 | public class ArticleClassRepositoryImpl extends BaseRepositoryImpl implements ArticleClassRepositoryCustom {
23 |
24 | public Page page(Long userId, String name, Integer pageNumber, Integer pageSize){
25 | String HQL = "select ac from ArticleClass ac where 1=1 and ac.deleteStatus=0 ";
26 | HashMap params = Maps.newHashMap();
27 | if(userId != null){
28 | HQL += " and ac.user.id = :userId ";
29 | params.put("userId",userId);
30 | }
31 | if(StringUtils.isNotBlank(name)){
32 | HQL += " and ac.name like :name ";
33 | params.put("name","%"+name+"%");
34 | }
35 | HQL += " order by ac.sort";
36 | return this.pageByHql(HQL,params,pageNumber,pageSize);
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/cppba-spring-boot-core/src/main/java/com/cppba/repository/impl/UserRepositoryImpl.java:
--------------------------------------------------------------------------------
1 | package com.cppba.repository.impl;
2 |
3 |
4 | import com.cppba.base.dao.impl.BaseRepositoryImpl;
5 | import com.cppba.entity.User;
6 | import com.cppba.repository.custom.UserRepositoryCustom;
7 | import org.springframework.stereotype.Repository;
8 |
9 | /**
10 | * 开发者
11 | * nickName:大黄蜂
12 | * email:245655812@qq.com
13 | * github:https://github.com/bigbeef
14 | */
15 | //用户自定义repository实现(命名必须以最顶层repository加后缀(默认Impl)规则,这里是UserRepository+Impl)
16 | @Repository
17 | public class UserRepositoryImpl extends BaseRepositoryImpl implements UserRepositoryCustom {
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/cppba-spring-boot-core/src/main/java/com/cppba/vo/admin/ArticleClassVO.java:
--------------------------------------------------------------------------------
1 | package com.cppba.vo.admin;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Data;
5 |
6 | @Data
7 | @AllArgsConstructor
8 | public class ArticleClassVO {
9 |
10 | private Long userId;
11 |
12 | private String name;
13 |
14 | private String sort;
15 | }
16 |
--------------------------------------------------------------------------------
/cppba-spring-boot-core/src/main/java/com/cppba/vo/admin/SettingVO.java:
--------------------------------------------------------------------------------
1 | package com.cppba.vo.admin;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Data;
5 |
6 | @Data
7 | @AllArgsConstructor
8 | public class SettingVO {
9 |
10 | private String nickName;
11 |
12 | private String remark;
13 |
14 | private String title;
15 |
16 | private String keyword;
17 |
18 | private String description;
19 | }
20 |
--------------------------------------------------------------------------------
/cppba-spring-boot-service/pom.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 | cppba-spring-boot
5 | com.cppbba
6 | 1.0.0
7 |
8 | 4.0.0
9 |
10 | cppba-spring-boot-service
11 | jar
12 |
13 | cppba-spring-boot-service
14 | http://maven.apache.org
15 |
16 |
17 | UTF-8
18 |
19 |
20 |
21 |
22 | com.cppbba
23 | cppba-spring-boot-api
24 | 1.0.0
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/cppba-spring-boot-service/src/main/java/com/cppba/service/impl/ArticleClassServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.cppba.service.impl;
2 |
3 | import com.cppba.base.bean.Result;
4 | import com.cppba.base.util.Results;
5 | import com.cppba.repository.ArticleClassRepository;
6 | import com.cppba.service.ArticleClassService;
7 | import org.springframework.stereotype.Service;
8 | import org.springframework.transaction.annotation.Transactional;
9 |
10 | import javax.annotation.Resource;
11 |
12 |
13 | /**
14 | * 开发者
15 | * nickName:大黄蜂
16 | * email:245655812@qq.com
17 | * github:https://github.com/bigbeef
18 | */
19 | @Service
20 | @Transactional
21 | public class ArticleClassServiceImpl implements ArticleClassService {
22 |
23 | @Resource
24 | private ArticleClassRepository articleClassRepository;
25 | //private ArticleClassRepositoryCustom articleClassRepositoryCustom;
26 |
27 | public Result page(Long userId, String name, Integer pageNumber, Integer pageSize){
28 | return Results.successWithData(articleClassRepository.page(userId,name,pageNumber,pageSize));
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/cppba-spring-boot-service/src/main/java/com/cppba/service/impl/UserServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.cppba.service.impl;
2 |
3 | import com.cppba.base.bean.CurrentUser;
4 | import com.cppba.base.bean.Result;
5 | import com.cppba.base.util.JwtUtil;
6 | import com.cppba.base.util.MD5Util;
7 | import com.cppba.base.util.Results;
8 | import com.cppba.entity.User;
9 | import com.cppba.form.admin.SettingForm;
10 | import com.cppba.repository.UserRepository;
11 | import com.cppba.service.UserService;
12 | import com.cppba.vo.admin.SettingVO;
13 | import com.google.common.collect.Maps;
14 | import org.apache.commons.lang3.StringUtils;
15 | import org.springframework.stereotype.Service;
16 | import org.springframework.transaction.annotation.Transactional;
17 |
18 | import javax.annotation.Resource;
19 | import java.util.Map;
20 |
21 |
22 | /**
23 | * 开发者
24 | * nickName:大黄蜂
25 | * email:245655812@qq.com
26 | * github:https://github.com/bigbeef
27 | */
28 | @Service
29 | @Transactional
30 | public class UserServiceImpl implements UserService {
31 |
32 | @Resource
33 | private UserRepository userRepository;
34 |
35 | @Override
36 | public Result login(String UserName, String password) throws Exception {
37 | User user = userRepository.getByUserName(UserName);
38 | if (user == null) {
39 | return Results.failure("用户不存在!");
40 | }
41 | String Md5Password= MD5Util.encode32Md5(password);
42 | if (!StringUtils.equals(user.getPassword(), Md5Password)) {
43 | return Results.failure("密码不正确!");
44 | }
45 | CurrentUser currentUser = new CurrentUser();
46 | currentUser.setId(user.getId());
47 | currentUser.setUserName(user.getUserName());
48 | currentUser.setRoles(new String[]{"login"});
49 | String token = JwtUtil.createJwt(currentUser);
50 | Map map = Maps.newHashMap();
51 | map.put("token",token);
52 | map.put("user",user);
53 | return Results.successWithData(map,"登录成功!");
54 | }
55 |
56 | @Override
57 | public Result setting(Long id) {
58 | User user = userRepository.getById(id);
59 | if(user == null){
60 | return Results.failure("用户不存在");
61 | }
62 | SettingVO settingVO = new SettingVO(user.getNickName(),user.getRemark(),user.getTitle(),user.getKeyword(),user.getDescription());
63 | return Results.successWithData(settingVO);
64 | }
65 |
66 | @Override
67 | public Result settingUpdate(Long id, SettingForm settingFrom) {
68 | User user = userRepository.getById(id);
69 | if(user == null){
70 | return Results.failure("用户不存在");
71 | }
72 | user.setNickName(settingFrom.getNickName());
73 | user.setTitle(settingFrom.getTitle());
74 | user.setKeyword(settingFrom.getKeyword());
75 | user.setDescription(settingFrom.getDescription());
76 | user.setRemark(settingFrom.getRemark());
77 | userRepository.save(user);
78 | return Results.success("修改成功");
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/cppba-spring-boot-web/pom.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 | cppba-spring-boot
5 | com.cppbba
6 | 1.0.0
7 |
8 |
9 | 4.0.0
10 | cppba-spring-boot-web
11 | jar
12 | cppba-spring-boot-web
13 | http://maven.apache.org
14 |
15 |
16 |
17 | com.cppbba
18 | cppba-spring-boot-service
19 | 1.0.0
20 |
21 |
22 |
23 |
24 | cppba-spring-boot-web
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/cppba-spring-boot-web/src/main/java/com/cppba/Application.java:
--------------------------------------------------------------------------------
1 | package com.cppba;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 | import org.springframework.boot.web.servlet.ServletComponentScan;
6 | import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
7 |
8 | @EnableJpaRepositories
9 | // same as @Configuration @EnableAutoConfiguration @ComponentScan
10 | @SpringBootApplication
11 | //WebFilter,WebServlet,WebListener
12 | @ServletComponentScan
13 | public class Application {
14 | public static void main(String[] args) {
15 | SpringApplication.run(Application.class, args);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/cppba-spring-boot-web/src/main/java/com/cppba/config/ApplicationConfiguration.java:
--------------------------------------------------------------------------------
1 | package com.cppba.config;
2 |
3 | import com.cppba.interceptor.OauthInterceptor;
4 | import org.springframework.context.annotation.Bean;
5 | import org.springframework.context.annotation.Configuration;
6 | import org.springframework.web.cors.CorsConfiguration;
7 | import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
8 | import org.springframework.web.filter.CorsFilter;
9 | import org.springframework.web.multipart.commons.CommonsMultipartResolver;
10 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
11 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
12 |
13 | @Configuration
14 | public class ApplicationConfiguration extends WebMvcConfigurerAdapter {
15 |
16 | /**
17 | * 拦截器
18 | * @param registry
19 | */
20 | @Override
21 | public void addInterceptors(InterceptorRegistry registry){
22 | //权限拦截器
23 | registry.addInterceptor(new OauthInterceptor()).addPathPatterns("/**");
24 | }
25 |
26 | /**
27 | * 跨域配置
28 | * @return
29 | */
30 | @Bean
31 | public CorsFilter corsFilter() {
32 | CorsConfiguration corsConfiguration = new CorsConfiguration();
33 | corsConfiguration.addAllowedOrigin("*");
34 | corsConfiguration.addAllowedHeader("*");
35 | corsConfiguration.addAllowedMethod("*");
36 | UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
37 | source.registerCorsConfiguration("/**", corsConfiguration);
38 | return new CorsFilter(source);
39 | }
40 |
41 | /**
42 | * 文件上传
43 | * @return
44 | */
45 | @Bean
46 | public CommonsMultipartResolver multipartResolver(){
47 | CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
48 | commonsMultipartResolver.setDefaultEncoding("UTF-8");
49 | commonsMultipartResolver.setMaxUploadSize(104857600);
50 | commonsMultipartResolver.setMaxInMemorySize(4096);
51 | return commonsMultipartResolver;
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/cppba-spring-boot-web/src/main/java/com/cppba/controller/admin/ArticleClassController.java:
--------------------------------------------------------------------------------
1 | package com.cppba.controller.admin;
2 |
3 | import com.cppba.base.annotation.RequiresRoles;
4 | import com.cppba.base.bean.CurrentUser;
5 | import com.cppba.base.bean.Result;
6 | import com.cppba.controller.base.BaseController;
7 | import com.cppba.service.ArticleClassService;
8 | import org.springframework.web.bind.annotation.RequestMapping;
9 | import org.springframework.web.bind.annotation.RequestParam;
10 | import org.springframework.web.bind.annotation.ResponseBody;
11 | import org.springframework.web.bind.annotation.RestController;
12 |
13 | import javax.annotation.Resource;
14 | import javax.servlet.http.HttpServletRequest;
15 |
16 | /**
17 | * 开发者
18 | * nickName:大黄蜂
19 | * email:245655812@qq.com
20 | * github:https://github.com/bigbeef
21 | */
22 | @RestController
23 | @RequestMapping("/admin/articleClass")
24 | public class ArticleClassController extends BaseController {
25 |
26 | @Resource
27 | private ArticleClassService articleClassService;
28 |
29 | @ResponseBody
30 | @RequiresRoles({"login"})
31 | @RequestMapping("/page")
32 | public Result page(
33 | HttpServletRequest request,
34 | @RequestParam(name = "pageNumber",defaultValue = "0") Integer pageNumber,
35 | @RequestParam(name = "pageSize",defaultValue = "0")Integer pageSize,
36 | @RequestParam(name = "name",defaultValue = "")String name) {
37 | CurrentUser currentUser = getCurrentUser(request);
38 | return articleClassService.page(currentUser.getId(),name,pageNumber,pageSize);
39 | }
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/cppba-spring-boot-web/src/main/java/com/cppba/controller/admin/UserController.java:
--------------------------------------------------------------------------------
1 | package com.cppba.controller.admin;
2 |
3 | import com.cppba.base.annotation.RequiresRoles;
4 | import com.cppba.base.bean.CurrentUser;
5 | import com.cppba.base.bean.Result;
6 | import com.cppba.base.util.Results;
7 | import com.cppba.controller.base.BaseController;
8 | import com.cppba.form.admin.SettingForm;
9 | import com.cppba.service.UserService;
10 | import org.springframework.web.bind.annotation.RequestMapping;
11 | import org.springframework.web.bind.annotation.RequestMethod;
12 | import org.springframework.web.bind.annotation.ResponseBody;
13 | import org.springframework.web.bind.annotation.RestController;
14 |
15 | import javax.annotation.Resource;
16 | import javax.servlet.http.HttpServletRequest;
17 |
18 | /**
19 | * 开发者
20 | * nickName:大黄蜂
21 | * email:245655812@qq.com
22 | * github:https://github.com/bigbeef
23 | */
24 | @RestController
25 | @RequestMapping("/admin/user")
26 | public class UserController extends BaseController {
27 |
28 | @Resource
29 | private UserService userService;
30 |
31 |
32 | @ResponseBody
33 | @RequestMapping("/login")
34 | public Result login(String userName, String password) {
35 | try {
36 | return userService.login(userName,password);
37 | } catch (Exception e) {
38 | e.printStackTrace();
39 | return Results.failure("请检查输入密码!");
40 | }
41 | }
42 |
43 |
44 | @ResponseBody
45 | @RequiresRoles({"login"})
46 | @RequestMapping("/setting")
47 | public Result setting(HttpServletRequest request) {
48 | CurrentUser currentUser = getCurrentUser(request);
49 | return userService.setting(currentUser.getId());
50 | }
51 |
52 |
53 | @ResponseBody
54 | @RequiresRoles({"login"})
55 | @RequestMapping(value="/setting/update",method = RequestMethod.POST)
56 | public Result settingUpdate(HttpServletRequest request, SettingForm settingFrom) {
57 | CurrentUser currentUser = getCurrentUser(request);
58 | return userService.settingUpdate(currentUser.getId(),settingFrom);
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/cppba-spring-boot-web/src/main/java/com/cppba/controller/base/BaseController.java:
--------------------------------------------------------------------------------
1 | package com.cppba.controller.base;
2 |
3 | import com.cppba.base.bean.CurrentUser;
4 |
5 | import javax.servlet.http.HttpServletRequest;
6 |
7 | public class BaseController {
8 | public CurrentUser getCurrentUser(HttpServletRequest request){
9 | return (CurrentUser) request.getAttribute("user");
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/cppba-spring-boot-web/src/main/java/com/cppba/controller/common/CommonAction.java:
--------------------------------------------------------------------------------
1 | package com.cppba.controller.common;
2 |
3 | import com.cppba.base.util.CommonUtil;
4 | import com.cppba.base.util.QRCodeUtil;
5 | import com.cppba.base.util.VerifyCodeUtil;
6 | import com.cppba.controller.base.BaseController;
7 | import org.slf4j.Logger;
8 | import org.slf4j.LoggerFactory;
9 | import org.springframework.stereotype.Controller;
10 | import org.springframework.web.bind.annotation.RequestMapping;
11 | import org.springframework.web.bind.annotation.RequestParam;
12 |
13 | import javax.imageio.ImageIO;
14 | import javax.servlet.http.HttpServletRequest;
15 | import javax.servlet.http.HttpServletResponse;
16 | import javax.servlet.http.HttpSession;
17 | import java.awt.image.BufferedImage;
18 | import java.io.IOException;
19 |
20 | /**
21 | * 开发者
22 | * nickName:大黄蜂
23 | * email:245655812@qq.com
24 | * github:https://github.com/bigbeef
25 | */
26 | @Controller
27 | public class CommonAction extends BaseController {
28 | private static Logger logger = LoggerFactory.getLogger(CommonAction.class);
29 |
30 | //返回403错误
31 | /*@RequestMapping("/403")
32 | public void login(
33 | HttpServletRequest request, HttpServletResponse response){
34 | Map map = new HashMap();
35 | CommonUtil.responseBuildJson("403","你无权访问该资源!",null,response);
36 | }*/
37 |
38 | /**
39 | * 获取二维码
40 | * text 必须用UTF8编码格式,x内容出现 & 符号时,请用 %26 代替,换行符使用 %0A
41 | */
42 | @RequestMapping("/qrcode_image")
43 | public void qrcode_image(
44 | HttpServletRequest request,HttpServletResponse response,
45 | @RequestParam(value="text", defaultValue="")String text){
46 | try{
47 | response.setHeader("Pragma", "No-cache");
48 | response.setHeader("Cache-Control", "no-cache");
49 | response.setDateHeader("Expires", 0);
50 | response.setContentType("image/jpeg");
51 |
52 | BufferedImage image = QRCodeUtil.QRCodeCreate(text, 250, 250);
53 |
54 | ImageIO.write(image, "png",response.getOutputStream());
55 | }catch (Exception e){
56 | logger.error(e.getMessage(),e);
57 | }
58 |
59 | }
60 |
61 | //下载二维码
62 | @RequestMapping("/download_qrcode_image")
63 | public void download_qrcode_image(
64 | HttpServletRequest request,HttpServletResponse response,
65 | @RequestParam(value="text", defaultValue="")String text) throws IOException {
66 | response.setHeader("Content-Disposition", "attachment; filename=qingcheng.png");
67 | response.setContentType("application/octet-stream; charset=utf-8");
68 |
69 | BufferedImage image = QRCodeUtil.QRCodeCreate(text, 250, 250);
70 | ImageIO.write(image, "png",response.getOutputStream());
71 | }
72 |
73 | // 生成图片验证码
74 | @RequestMapping("/auth_image")
75 | public void auth_Image(
76 | HttpServletRequest request, HttpServletResponse response){
77 | try{
78 | response.setHeader("Pragma", "No-cache");
79 | response.setHeader("Cache-Control", "no-cache");
80 | response.setDateHeader("Expires", 0);
81 | response.setContentType("image/jpeg");
82 |
83 | // 生成随机字串
84 | String verifyCode = VerifyCodeUtil.generateVerifyCode(4);
85 | // 存入会话session
86 | HttpSession session = CommonUtil.getSession(request);
87 | session.setAttribute("code", verifyCode.toLowerCase());
88 | // 生成图片
89 | int w = 200, h = 80;
90 | VerifyCodeUtil.outputImage(w, h, response.getOutputStream(),
91 | verifyCode);
92 | }catch (Exception e){
93 | logger.error(e.getMessage(),e);
94 | }
95 | }
96 |
97 | //图片上传
98 | //path 例如:"/Image/article"
99 | /*@RequestMapping("/upload_file")
100 | public void upload_file(
101 | HttpServletRequest request, HttpServletResponse response,
102 | @RequestParam(value="path", defaultValue="Image/article")String path,
103 | @RequestParam(value="fileName", defaultValue="imgFile")String fileName,
104 | @RequestParam(value="isImage", defaultValue="true")boolean isImage
105 | ) throws IOException {
106 | Map map = new HashMap();
107 | MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
108 | CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile(fileName);
109 | String name = UploadFileUtil.uploadFileAliyun(file, path);
110 | map.put("error", 0);
111 | map.put("success", 1);
112 | map.put("url", Globals.FILE_SERVER_URL +"/"+path+ "/" + name);
113 | // 构建返回
114 | CommonUtil.responseBuildJson(map,response);
115 | }*/
116 | }
117 |
--------------------------------------------------------------------------------
/cppba-spring-boot-web/src/main/java/com/cppba/interceptor/OauthInterceptor.java:
--------------------------------------------------------------------------------
1 | package com.cppba.interceptor;
2 |
3 | import com.cppba.base.annotation.RequiresRoles;
4 | import com.cppba.base.bean.CurrentUser;
5 | import com.cppba.base.bean.Result;
6 | import com.cppba.base.util.CommonUtil;
7 | import com.cppba.base.util.JwtUtil;
8 | import org.apache.commons.lang3.StringUtils;
9 | import org.springframework.web.method.HandlerMethod;
10 | import org.springframework.web.servlet.HandlerInterceptor;
11 | import org.springframework.web.servlet.ModelAndView;
12 |
13 | import javax.servlet.http.HttpServletRequest;
14 | import javax.servlet.http.HttpServletResponse;
15 | import java.lang.reflect.Method;
16 | import java.util.Arrays;
17 | import java.util.List;
18 |
19 | public class OauthInterceptor implements HandlerInterceptor {
20 | public boolean preHandle(HttpServletRequest request,
21 | HttpServletResponse response, Object handler) throws Exception {
22 |
23 | //如果不是映射到方法直接通过
24 | if (!(handler instanceof HandlerMethod)) {
25 | return true;
26 | }
27 |
28 | HandlerMethod handlerMethod = (HandlerMethod) handler;
29 | Method method = handlerMethod.getMethod();
30 |
31 | //该controller的角色权限注解
32 | RequiresRoles annotation = method.getAnnotation(RequiresRoles.class);
33 | //如果不需要权限验证的controller
34 | if(annotation == null){
35 | return true;
36 | }
37 |
38 | //获取客户的传来的token,此处可以根据前后端约定自定义怎么获取token
39 | //String token = CommonUtil.getCookie("token", request);
40 | String token = request.getHeader("Authorization");
41 | //System.out.println("token:"+token);
42 |
43 | //没有token
44 | if(StringUtils.isBlank(token)){
45 | toUnauthorized(response);
46 | return false;
47 | }
48 |
49 | //验证token签名是否合法
50 | boolean verify = JwtUtil.verify(token);
51 | //System.out.println("verify:"+verify);
52 | if(!verify){
53 | toUnauthorized(response);
54 | return false;
55 | }
56 |
57 | //解码用户信息
58 | CurrentUser currentUser = JwtUtil.decodeJwt(token);
59 | //System.out.println("userJwt:"+userJwt.toString());
60 | String[] roles = currentUser.getRoles();
61 | List rolesList = Arrays.asList(roles);
62 |
63 | //是否包含角色权限注解
64 | if(annotation!=null){
65 | String[] needRoles = annotation.value();
66 | List needRoleList = Arrays.asList(needRoles);
67 | //System.out.println("needRoles:"+ needRoleList.toString());
68 | //需要的权限该用户是否都包含
69 | for(String needRole : needRoleList){
70 | if(StringUtils.isBlank(needRole)){
71 | continue;
72 | }
73 | if(!rolesList.contains(needRole)){
74 | toUnauthorized(response);
75 | return false;
76 | }
77 | }
78 | }
79 | request.setAttribute("user",currentUser);
80 | return true;
81 | }
82 |
83 | public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
84 |
85 | }
86 |
87 | public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
88 |
89 | }
90 |
91 | //返回未授权结果
92 | private void toUnauthorized(HttpServletResponse response){
93 | CommonUtil.responseBuildJson(new Result(false,null,null,"无访问权限"),response);
94 | //response.setStatus(HttpStatus.UNAUTHORIZED.value());
95 | }
96 | }
--------------------------------------------------------------------------------
/cppba-spring-boot-web/src/main/resources/config/application-dev.properties:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bigbeef/cppba-spring-boot/b3259cb3b77a21926f0a4ba1d9be22f2714389f6/cppba-spring-boot-web/src/main/resources/config/application-dev.properties
--------------------------------------------------------------------------------
/cppba-spring-boot-web/src/main/resources/config/application-prod.properties:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bigbeef/cppba-spring-boot/b3259cb3b77a21926f0a4ba1d9be22f2714389f6/cppba-spring-boot-web/src/main/resources/config/application-prod.properties
--------------------------------------------------------------------------------
/cppba-spring-boot-web/src/main/resources/config/application.properties:
--------------------------------------------------------------------------------
1 | spring.profiles.active=dev
2 |
--------------------------------------------------------------------------------
/cppba-spring-boot-web/src/main/resources/logback.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/cppba-spring-boot-web/src/main/resources/templates/default/index.html:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 | Hello World!
6 |
7 |
15 |
16 |
17 | Hello.v.2
18 |
19 | STATIC_PRIVATE_URL:
20 |
21 |
24 |
25 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 |
5 | com.cppbba
6 | cppba-spring-boot
7 | pom
8 | 1.0.0
9 |
10 | cppba-spring-boot-web
11 | cppba-spring-boot-core
12 | cppba-spring-boot-api
13 | cppba-spring-boot-service
14 |
15 |
16 | cppba-spring-boot
17 | http://maven.apache.org
18 |
19 |
20 | org.springframework.boot
21 | spring-boot-starter-parent
22 | 1.5.3.RELEASE
23 |
24 |
25 |
26 | UTF-8
27 |
28 |
29 |
30 |
31 |
32 | org.springframework.boot
33 | spring-boot-starter-web
34 |
35 |
36 | org.springframework.boot
37 | spring-boot-starter-test
38 |
39 |
40 | org.springframework.boot
41 | spring-boot-starter-data-jpa
42 |
43 |
44 | org.springframework.boot
45 | spring-boot-starter-thymeleaf
46 |
47 |
48 |
49 | mysql
50 | mysql-connector-java
51 |
52 |
53 |
54 | com.alibaba
55 | druid
56 | 1.0.27
57 |
58 |
59 |
60 | com.aliyun.oss
61 | aliyun-sdk-oss
62 | 2.2.3
63 |
64 |
65 |
66 | org.apache.commons
67 | commons-configuration2
68 | 2.1.1
69 |
70 |
71 |
72 | commons-beanutils
73 | commons-beanutils
74 | 1.9.3
75 |
76 |
77 |
78 | org.apache.commons
79 | commons-lang3
80 | 3.5
81 |
82 |
83 |
84 | commons-fileupload
85 | commons-fileupload
86 | 1.3.2
87 |
88 |
89 |
90 | org.projectlombok
91 | lombok
92 | 1.16.14
93 |
94 |
95 |
96 | com.google.guava
97 | guava
98 | 19.0
99 |
100 |
101 |
102 | org.lazyluke
103 | log4jdbc-remix
104 | 0.2.7
105 |
106 |
107 |
108 | com.sun.mail
109 | javax.mail
110 |
111 |
112 |
113 | com.google.zxing
114 | core
115 | 3.2.1
116 |
117 |
118 |
119 | com.auth0
120 | java-jwt
121 | 3.1.0
122 |
123 |
124 |
125 |
126 |
127 |
128 | org.springframework.boot
129 | spring-boot-maven-plugin
130 |
131 |
132 |
133 |
134 |
135 |
--------------------------------------------------------------------------------