前后端项目(后端)

这是图片

entity文件

Article

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

package com.example.bigevent.entity;
import com.example.bigevent.anno.State;
import lombok.Data;
import org.hibernate.validator.constraints.URL;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import java.time.LocalDateTime;
@Data
public class Article {
private Integer id;//主键ID
@NotEmpty
@Pattern(regexp = "^\\S{1,10}$")
private String title;//文章标题
@NotEmpty
private String content;//文章内容
@NotEmpty
@URL
private String coverImg;//封面图像
@State
private String state;//发布状态 已发布|草稿
@NotNull
private Integer categoryId;//文章分类id
private Integer createUser;//创建人ID
private LocalDateTime createTime;//创建时间
private LocalDateTime updateTime;//更新时间
}


Category

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.example.bigevent.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
//import jakarta.validation.constraints.NotEmpty;
//import jakarta.validation.constraints.NotNull;
//import jakarta.validation.groups.Default;
import lombok.Data;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.groups.Default;
import java.time.LocalDateTime;
@Data
public class Category {
// (groups = Update.class)
@NotNull(groups = Update.class)
private Integer id;//主键ID
@NotEmpty
private String categoryName;//分类名称
@NotEmpty
private String categoryAlias;//分类别名
private Integer createUser;//创建人ID
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createTime;//创建时间
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime updateTime;//更新时间
@Override
public String toString() {
return "Category{" +
"id=" + id +
", categoryName='" + categoryName + '\'' +
", categoryAlias='" + categoryAlias + '\'' +
", createUser=" + createUser +
", createTime=" + createTime +
", updateTime=" + updateTime +
'}';
}
public interface Add extends Default {}
public interface Update extends Default{}

//如果说某个校验项没有指定分组,默认属于Default分组
//分组之间可以继承, A extends B 那么A中拥有B中所有的校验项
//
// public interface Add extends Default {
//
// }
//
// public interface Update extends Default{
//
// }
}


PageBean

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.example.bigevent.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class PageBean<T> {
private Long total;
private List<T> items;
}

Result

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.example.bigevent.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Result <T>{
private Integer code;
private String message;
private T data;

public static <E> Result<E> success(E data){
return new Result<>(0,"操作成功",data);
}

public static <E> Result<E> success(){
return new Result<>(0,"操作成功",null);
}

public static <E> Result<E> error(String message){
return new Result<>(1,message,null);
}

}

User

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.example.bigevent.entity;


import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;

import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import java.time.LocalDateTime;

@Data
public class User {
@NotNull
private Integer id;
private String username;
@JsonIgnore//springmvc把当前对象转换为json时忽略该字段
private String password;
@Pattern(regexp = "^\\S{1,10}$")
@NotEmpty
private String nickname;
@Email
@NotEmpty
private String email;
private String userPic;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}


mapper 以及 resource/mapper

ArticleMapper

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.example.bigevent.mapper;

import com.example.bigevent.entity.Article;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface ArticleMapper {
public void add(Article article);
public List<Article> list(Integer userId,String categoryId, String state);
public Article getOne(Integer id);
public void updateOne(Article article);
public void deleteOne(Integer id);
}

ArticleMapper.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?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.example.bigevent.mapper.ArticleMapper">
<resultMap id="All" type="com.example.bigevent.entity.Article">
<id property="id" column="id"></id>
<result property="createUser" column="create_user"></result>
<result property="categoryId" column="category_id"></result>
<result property="content" column="content"></result>
<result property="coverImg" column="cover_img"></result>
<result property="state" column="state"></result>
<result property="title" column="title"></result>
<result property="createTime" column="create_time"></result>
<result property="updateTime" column="update_time"></result>
</resultMap>
<insert id="add" parameterType="com.example.bigevent.entity.Article">
insert into article(title,content,cover_img,state,category_id,create_user,create_time,update_time)values
(#{title},#{content},#{coverImg},#{state},#{categoryId},#{createUser},now(),now())
</insert>
<select id="list" resultMap="All">
select * from article
<where>
<if test="categoryId!=null">
category_id =#{categoryId}
</if>
<if test="state!=null">
and state=#{state}
</if>
and create_user =#{userId}
</where>
</select>
<select id="getOne" resultMap="All">
select * from article where id = #{id}
</select>
<update id="updateOne" parameterType="com.example.bigevent.entity.Article">
update article set title=#{title},content=#{content},cover_img=#{coverImg},state=#{state},category_id=#{categoryId},
update_time=now() where id =#{id}
</update>
<delete id="deleteOne" parameterType="integer">
delete from article where id = #{id}
</delete>
</mapper>


CategoryMapper

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

package com.example.bigevent.mapper;

import com.example.bigevent.entity.Category;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface CategoryMapper {
public void add(Category category);
public List<Category> getAll(Integer userId);
public Category getOne(Integer id);
public void updateOne(Category category);
public void deleteOne(Integer id);
}

CategoryMapper.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

<?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.example.bigevent.mapper.CategoryMapper">
<resultMap id="All" type="com.example.bigevent.entity.Category">
<id column="id" property="id"></id>
<result column="update_time" property="updateTime"></result>
<result column="create_time" property="createTime"></result>
<result column="category_alias" property="categoryAlias"></result>
<result column="category_name" property="categoryName"></result>
<result column="create_user" property="createUser"></result>
</resultMap>
<insert id="add" parameterType="com.example.bigevent.entity.Category">
insert into category(category_name,category_alias,create_user,create_time,update_time)values(#{categoryName},#{categoryAlias},#{createUser},now(),now())
</insert>
<select id="getAll" resultMap="All" parameterType="integer">
select * from category where create_user = #{userId}
</select>
<select id="getOne" resultMap="All">
select * from category where id = #{id}
</select>
<update id="updateOne" parameterType="com.example.bigevent.entity.Category">
update category set category_name=#{categoryName},category_alias=#{categoryAlias},update_time=now() where id =#{id}
</update>
<delete id="deleteOne">
delete from category where id =#{id}
</delete>
</mapper>

UserMapper

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.example.bigevent.mapper;

import com.example.bigevent.entity.User;
import lombok.NoArgsConstructor;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

@Mapper
@Repository
public interface UserMapper {
// @Select("select * from user where username=#{username}")
public User findByUsername(String username);

// @Insert("insert into user(username,password,create_time,update_time)values (#{username},#{password},now(),now())")
public void add(String username,String password);
public void update(User user);
public void updateAvatar(String avatarUrl,int id);
public void updatePwd(String newPwd,int id);
}


UserMapper.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?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.example.bigevent.mapper.UserMapper">
<resultMap id="All" type="com.example.bigevent.entity.User">
<id property="id" column="id"></id>
<result property="username" column="username"></result>
<result property="password" column="password"></result>
<result property="nickname" column="nickname"></result>
<result property="email" column="email"></result>
<result property="userPic" column="user_pic"></result>
<result property="createTime" column="create_time"></result>
<result property="updateTime" column="update_time"></result>
</resultMap>
<select id="findByUsername" resultMap="All" parameterType="string">
select * from user where username=#{username}
</select>
<insert id ="add" parameterType="com.example.bigevent.entity.User">
insert into user(username,password,create_time,update_time)values(#{username},#{password},now(),now())
</insert>
<update id="update" parameterType="com.example.bigevent.entity.User">
update user set nickname=#{nickname},email=#{email},update_time=#{updateTime}where id =#{id}
</update>
<update id="updateAvatar" >
update user set user_pic=#{avatarUrl},update_time=now() where id =#{id}
</update>
<update id="updatePwd">
update user set password = #{newPwd},update_time=now() where id =#{id}
</update>
</mapper>

sevice接口以及他们的实现类

ArticleService

1
2
3
4
5
6
7
8
9
10
11
12
13
14

package com.example.bigevent.service;

import com.example.bigevent.entity.Article;
import com.example.bigevent.entity.PageBean;

public interface ArticleService {
public void add(Article article);
PageBean<Article> list(Integer pageNum, Integer pageSize, String categoryId, String state);
public Article getOne(Integer id);
public void updateOne(Article article);
public void deleteOne(Integer id);
}

ArticleServiceImp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.example.bigevent.service.imp;

import com.example.bigevent.entity.Article;
import com.example.bigevent.entity.PageBean;
import com.example.bigevent.mapper.ArticleMapper;
import com.example.bigevent.service.ArticleService;
import com.example.bigevent.util.ThreadLocalUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImp implements ArticleService {
@Autowired
private ArticleMapper articleMapper;
@Override
public void add(Article article) {
Map<String,Object> map = ThreadLocalUtil.get();
Integer userId = (Integer) map.get("id");
article.setCreateUser(userId);
articleMapper.add(article);
}
@Override
public PageBean<Article> list(Integer pageNum, Integer pageSize, String categoryId, String state) {
PageBean<Article> page = new PageBean<>();
// 设置第几条记录开始,多少页记录为一页
PageHelper.startPage(pageNum,pageSize);
Map<String,Object> map = ThreadLocalUtil.get();
Integer userId =(Integer) map.get("id");
// 因为已经注册了 PageHelper插件,所以 PageHelper会在原 sql 语句上增加 limit,从而实现分页
List<Article> list = articleMapper.list(userId,categoryId,state);
Page<Article> p = (Page<Article>) list;
page.setTotal(p.getTotal());
page.setItems(p.getResult());
return page;
}
@Override
public Article getOne(Integer id) {
return articleMapper.getOne(id);
}

@Override
public void updateOne(Article article) {
articleMapper.updateOne(article);
}
@Override
public void deleteOne(Integer id) {
articleMapper.deleteOne(id);
}

}

CategoryService

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.example.bigevent.service;

import com.example.bigevent.entity.Category;

import java.util.List;

public interface CategoryService {
public void add(Category category);
public List<Category> getAll(Integer userId);
public Category getOne(Integer id);
public void updateOne(Category category);
public void deleteOne(Integer id);
}

CategoryServiceImp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.example.bigevent.service.imp;

import com.example.bigevent.entity.Category;
import com.example.bigevent.mapper.CategoryMapper;
import com.example.bigevent.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImp implements CategoryService {
@Autowired
private CategoryMapper categoryMapper;
@Override
public void add(Category category) {
categoryMapper.add(category);
}

@Override
public List<Category> getAll(Integer userId) {
return categoryMapper.getAll(userId);
}

@Override
public Category getOne(Integer id) {
return categoryMapper.getOne(id);
}

@Override
public void updateOne(Category category) {
categoryMapper.updateOne(category);
}

@Override
public void deleteOne(Integer id) {
categoryMapper.deleteOne(id);
}

}

UserService

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.example.bigevent.service;

import com.example.bigevent.entity.User;
import org.springframework.stereotype.Service;


public interface UserService {
public User findByUsername(String username);
public void add(String username,String password);
public void update(User user);
public void updateAvatar(String avatarUrl);
public void updatePwd(String newPwd);
}

UserServiceImp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.example.bigevent.service.imp;

import com.example.bigevent.entity.Result;
import com.example.bigevent.entity.User;
import com.example.bigevent.mapper.UserMapper;
import com.example.bigevent.service.UserService;
import com.example.bigevent.util.Md4Util;
import com.example.bigevent.util.ThreadLocalUtil;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.Map;

@Service
public class UserServiceImp implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User findByUsername(String username) {
User byUsername = userMapper.findByUsername(username);
return byUsername;
}

@Override
public void add(String username, String password) {
String s = Md4Util.MD5(password);
userMapper.add(username,s);

}

@Override
public void update(User user) {
user.setUpdateTime(LocalDateTime.now());
userMapper.update(user);
}

@Override
public void updateAvatar(String avatarUrl) {
Map<String,Object> map = ThreadLocalUtil.get();
int id = (int)map.get("id");
userMapper.updateAvatar(avatarUrl,id);
}

@Override
public void updatePwd(String newPwd) {
Map<String,Object> map = ThreadLocalUtil.get();
int id = (int)map.get("id");
String pwd = Md4Util.MD5(newPwd);
userMapper.updatePwd(pwd,id);
}
}

工具类

AliOssUtil

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.example.bigevent.util;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import java.io.FileInputStream;
import java.io.InputStream;
public class AliOssUtil {
private static final String BUCKET_NAME = "big-eventsfeng";
private static final String ENDPOINT = "https://oss-cn-beijing.aliyuncs.com";
private static final String ACCESS_KEY_ID = "LTAI5tRTZb2wyzYGfX3o8t1Q";
private static final String ACCESS_KEY_SECRET ="W924sKtF4wsOmP3mT38l79r31kLDsC";
public static String uploadFile(String objectName,InputStream inputStream) throws Exception {
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。

// 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。

// EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// 填写Bucket名称,例如examplebucket。

// 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
// String objectName = "exampledir/exampleobject.txt";
// 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。
// 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。
// String filePath= "D:\\localpath\\examplefile.txt";

// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(ENDPOINT,ACCESS_KEY_ID,ACCESS_KEY_SECRET);
String url = "";
try {
// InputStream inputStream = new FileInputStream(filePath);
// 创建PutObjectRequest对象。
PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, objectName, inputStream);
// 创建PutObject请求。
url = "https://"+BUCKET_NAME+"."+ENDPOINT.substring(ENDPOINT.lastIndexOf("/")+1)+"/"+objectName;
PutObjectResult result = ossClient.putObject(putObjectRequest);
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return url;
}

}

JwtUtil

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

package com.example.bigevent.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties;

import java.util.Date;
import java.util.Map;

public class JwtUtil {
private static final String KEY ="itheima";
public static String getToken(Map<String,Object> objectMap){
return JWT.create()
.withClaim("claim",objectMap).withExpiresAt(new Date(System.currentTimeMillis()+1000*60*60*12))
.sign(Algorithm.HMAC256(KEY));
}

public static Map<String,Object> parseToken(String token){
return JWT.require(Algorithm.HMAC256(KEY)).build().verify(token).getClaim("claim").asMap();
}
}


Md4Util

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

package com.example.bigevent.util;

import java.security.MessageDigest;

public class Md4Util {
public static String MD5(String s)
{
char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
try {
byte[] btInput = s.getBytes();

MessageDigest mdInst = MessageDigest.getInstance("MD5");

mdInst.update(btInput);

byte[] md = mdInst.digest();

int j = md.length;
char[] str = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[(k++)] = hexDigits[(byte0 >>> 4 & 0xF)];
str[(k++)] = hexDigits[(byte0 & 0xF)];
}
return new String(str);
}
catch (Exception e) {
e.printStackTrace();
}return null;
}
public static String convertMD5(String inStr){

char[] a = inStr.toCharArray();
for (int i = 0; i < a.length; i++){
a[i] = (char) (a[i] ^ 't');
}
String s = new String(a);
return s;

}

}


ThreadLocalUtil

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.example.bigevent.util;

import java.util.HashMap;
import java.util.Map;

/**
* ThreadLocal 工具类
*/
@SuppressWarnings("all")
public class ThreadLocalUtil {
//提供ThreadLocal对象,
private static final ThreadLocal THREAD_LOCAL = new ThreadLocal();

//根据键获取值
public static <T> T get(){
return (T) THREAD_LOCAL.get();
}

//存储键值对
public static void set(Object value){
THREAD_LOCAL.set(value);
}


//清除ThreadLocal 防止内存泄漏
public static void remove(){
THREAD_LOCAL.remove();
}
}

exception 捕获resultmapping异常

GlobalException

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.example.bigevent.exception;

import com.example.bigevent.entity.Result;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalException {
@ExceptionHandler
public Result hasException(Exception e){
e.printStackTrace();
return Result.error(StringUtils.hasLength(e.getMessage())?e.getMessage():"操作失败!");
}
}


interceptor

MyInterceptor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.example.bigevent.interceptor;

import com.example.bigevent.entity.Result;
import com.example.bigevent.util.JwtUtil;
import com.example.bigevent.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class MyInterceptor implements HandlerInterceptor {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader("Authorization");
System.out.println(token);
try {
String s = stringRedisTemplate.opsForValue().get(token);
if(s==null){
System.out.println("当前token已经被删除!");
throw new RuntimeException();
}
Map<String, Object> claim = JwtUtil.parseToken(token);
System.out.println(claim);
ThreadLocalUtil.set(claim);
return true;
} catch (Exception e) {
response.setStatus(401);
return false;
}
}


@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
ThreadLocalUtil.remove();
}
}

config

MyConfig

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.example.bigevent.config;

import com.example.bigevent.interceptor.MyInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyConfig implements WebMvcConfigurer {
@Autowired
private MyInterceptor myInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor).excludePathPatterns("/user/login","/user/register");
}
}

anno

State

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

package com.example.bigevent.anno;


import com.example.bigevent.validation.StateValidation;

import javax.validation.Constraint;
import java.lang.annotation.*;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;


@Documented
@Constraint(
validatedBy = {StateValidation.class}//指定提供校验规则的类
)
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface State {
// 提供校验失败后的提示消息
String message() default "{State属性只能是已发布或草稿}";
// 指定分组
Class<?>[] groups() default {};
// 获取state注解的附加消息
Class<? extends Payload>[] payload() default {};
}

validation

StateValidation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.example.bigevent.validation;

import com.example.bigevent.anno.State;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class StateValidation implements ConstraintValidator<State,String> {
@Override
public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
if(s==null){
return false;
}
if(s.equals("已发布")||s.equals("草稿")){
return true;
}
return false;
}
}


controller

ArticleController

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.example.bigevent.controller;

import com.example.bigevent.entity.Article;
import com.example.bigevent.entity.Category;
import com.example.bigevent.entity.PageBean;
import com.example.bigevent.entity.Result;
import com.example.bigevent.service.ArticleService;
import com.example.bigevent.util.JwtUtil;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/article")
public class ArticleController {
@Autowired
private ArticleService articleService;
@GetMapping("/list")
public Result getList(@RequestHeader(name="Authorization")String token, HttpServletResponse response){
// try{
// Map<String,Object> claim = JwtUtil.parseToken(token);
return Result.success("所有文章数据");
// }catch (Exception e){
// response.setStatus(401);
// return Result.error("未登录");
// }
}
@PostMapping
public Result<Object> add(@RequestBody @Validated Article article){
articleService.add(article);
return Result.success();
}
@GetMapping
public Result<PageBean<Article>> list(Integer pageNum,Integer pageSize,
@RequestParam(required = false)String categoryId,
@RequestParam(required = false)String state){
PageBean<Article> bean=articleService.list(pageNum,pageSize,categoryId,state);
return Result.success(bean);
}
@GetMapping("/detail")
public Result<Article> getOne(Integer id){
Article article = articleService.getOne(id);
return Result.success(article);
}
@PutMapping
public Result<Object> updateOne(@RequestBody @Validated Article article){
articleService.updateOne(article);
return Result.success();
}
@DeleteMapping
public Result<Object> deleteOne(Integer id){
articleService.deleteOne(id);
return Result.success();
}
}


CategoryController

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.example.bigevent.controller;

import com.example.bigevent.entity.Category;
import com.example.bigevent.entity.Result;
import com.example.bigevent.service.CategoryService;
import com.example.bigevent.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/category")
public class CategoryController {
@Autowired
private CategoryService categoryService;
@PostMapping
public Result<Object> add(@RequestBody @Validated(Category.Add.class) Category category){
Map<String,Object> map = ThreadLocalUtil.get();
Integer id = (Integer) map.get("id");
category.setCreateUser(id);
categoryService.add(category);
System.out.println(category);
return Result.success();
}
@GetMapping
public Result<List<Category>> getAll(){
Map<String,Object> map = ThreadLocalUtil.get();
Integer userId = (Integer) map.get("id");
List<Category> all = categoryService.getAll(userId);
return Result.success(all);
}
@GetMapping("/detail")
public Result<Category> getOne(Integer id){
Category one = categoryService.getOne(id);
return Result.success(one);
}
@PutMapping
public Result<Object> updateOne(@RequestBody @Validated(Category.Update.class) Category category){
categoryService.updateOne(category);
return Result.success();
}
@DeleteMapping()
public Result<Object> deleteOne(Integer id){
categoryService.deleteOne(id);
return Result.success();
}

}

FileUploadController

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.example.bigevent.controller;

import com.example.bigevent.entity.Result;
import com.example.bigevent.util.AliOssUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class FileUploadController {
@PostMapping("/upload")
public Result<String> upload(MultipartFile multipartFile) throws Exception {
String originalFilename = multipartFile.getOriginalFilename();
String filename = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
// multipartFile.transferTo(new File("C:\\Users\\23224\\Desktop\\txt文档\\"+filename));
String url = AliOssUtil.uploadFile(filename, multipartFile.getInputStream());
return Result.success(url);
}
}


UserController

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package com.example.bigevent.controller;

import com.example.bigevent.entity.Result;
import com.example.bigevent.entity.User;
import com.example.bigevent.service.UserService;
import com.example.bigevent.util.JwtUtil;
import com.example.bigevent.util.Md4Util;
import com.example.bigevent.util.ThreadLocalUtil;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Pattern;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {
@Autowired
private UserService userService;
@Autowired
private StringRedisTemplate stringRedisTemplate;
@RequestMapping("/register")
public Result register(@Pattern(regexp = "^\\S{5,16}$") String username,@Pattern(regexp = "^\\S{5,16}$") String password){
User byUsername = userService.findByUsername(username);
if (byUsername == null){
userService.add(username,password);
return Result.success();
}else{
return Result.error("用户名重复");
}
}

@RequestMapping("/login")
public Result login(@Pattern(regexp="^\\S{5,16}$")String username,@Pattern(regexp = "^\\S{5,16}$")String password){
User byUsername = userService.findByUsername(username);
if(byUsername==null){
return Result.error("用户不存在");
}else{
String ps = Md4Util.MD5(password);
System.out.println(ps);
System.out.println(byUsername.getPassword());
if (ps.equals(byUsername.getPassword())){
Map<String,Object> token = new HashMap<>();
token.put("username",byUsername.getUsername());
token.put("id",byUsername.getId());
String token1 = JwtUtil.getToken(token);
stringRedisTemplate.opsForValue().set(token1,token1,1, TimeUnit.HOURS);
return Result.success(token1);
}else{
return Result.error("密码错误");
}
}
}
@GetMapping("/userInfo")
public Result<User> getInfo(){
// @RequestHeader(name="Authorization") String token
Map<String, Object> map = ThreadLocalUtil.get();
String username = (String)map.get("username");
User user =userService.findByUsername(username);
return Result.success(user);
}

@PutMapping("/update")
public Result updateUser(@RequestBody @Validated User user){
userService.update(user);
return Result.success();
}
@PatchMapping("/updateAvatar")
public Result updateAvatar(@RequestParam @URL String avatarUrl){
userService.updateAvatar(avatarUrl);
return Result.success();
}

@PatchMapping("/updatePwd")
public Result updatePwd(@RequestBody Map<String,String>psw,@RequestHeader("Authorization")String token){
String oldPwd = psw.get("old_pwd");
String newPwd = psw.get("new_pwd");
String rePwd = psw.get("re_pwd");
if(oldPwd==null||newPwd==null||rePwd==null){
return Result.error("缺少重要参数!");
}
Map<String,Object> map = ThreadLocalUtil.get();
String username = (String)map.get("username");
User byUsername = userService.findByUsername(username);
String oldPwd1 = byUsername.getPassword();
if (!oldPwd1.equals(Md4Util.MD5(oldPwd))){
System.out.println("米:"+Md4Util.MD5(oldPwd));
return Result.error("与原密码不一致!");
}
if(!newPwd.equals(rePwd)){
return Result.error("两次输入的密码不一致!");
}
userService.updatePwd(newPwd);
stringRedisTemplate.opsForValue().getOperations().delete(token);
return Result.success();

}
}


配置信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/big_event?serverTimezone=Asia/Shanghai&characterEncoding=utf-8&useSSL=false&useUnicode=true
password: 123456
username: root
redis:
lettuce:
pool:
max-active: 8
max-idle: 8
min-idle: 0
max-wait: 100
host: 192.168.235.128
port: 6379
password: 123456
mybatis:
mapper-locations: classpath:mapper/*.xml
# configuration:
# map-underscore-to-camel-case: true

依赖导入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.12</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>big-event</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>big-event</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.6</version>
</dependency>

<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.6</version>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.15.1</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<!-- no more than 2.3.3-->
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.3</version>
</dependency>

</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>

</project>


启动类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

package com.example.bigevent;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class BigEventApplication {

public static void main(String[] args) {
SpringApplication.run(BigEventApplication.class, args);
}

}