完善评论以及多个组件的使用

This commit is contained in:
xbx 2024-05-17 19:07:41 +08:00
parent aec28947fe
commit 75282d20cd
39 changed files with 428 additions and 25 deletions

8
.idea/modules.xml Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/Springboot_01Demo.iml" filepath="$PROJECT_DIR$/Springboot_01Demo.iml" />
</modules>
</component>
</project>

8
Springboot_01Demo.iml Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<module version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/test" isTestSource="true" />
</content>
</component>
</module>

44
pom.xml
View File

@ -74,6 +74,50 @@
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- 缓存框架springcache -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- httpclient-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<!-- Json-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
<!-- Poi-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.0.0</version>
</dependency>
<!-- websocket-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,66 @@
package com.xubx.springboot_01demo.Poi;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class PoiTest {
//写入
public static void write() throws Exception{
//在内存中创建一个Excel文件
XSSFWorkbook workbook = new XSSFWorkbook();
//在Excel文件中创建一个sheet
XSSFSheet sheet = workbook.createSheet("info");
//在sheet中创建行对象rownum编号从0开始
XSSFRow row = sheet.createRow(0);
//创建单元格并写入文件内容
row.createCell(0).setCellValue("姓名");
row.createCell(1).setCellValue("城市");
//创建一个新的行
XSSFRow row1 = sheet.createRow(1);
row1.createCell(0).setCellValue("张三");
row1.createCell(1).setCellValue("北京");
//创建一个新的行
XSSFRow row2 = sheet.createRow(2);
row2.createCell(0).setCellValue("李四");
row2.createCell(1).setCellValue("上海");
//通过输出流将workbook对象输出到磁盘
FileOutputStream out = new FileOutputStream(new File("C:\\info.xlsx"));
//关闭资源
workbook.write(out);
out.close();
}
//读取
public static void read() throws Exception{
FileInputStream fileInputStream = new FileInputStream(new File("C:\\Users\\Xubx\\info.xlsx"));
//读取Excel文件
XSSFWorkbook excel = new XSSFWorkbook(fileInputStream);
//读取第一个sheet
XSSFSheet sheet = excel.getSheetAt(0);
//获取sheet中的最后一行行号
int lastRowNum = sheet.getLastRowNum();
for (int i = 0; i <= lastRowNum; i++) {
//获取行对象
XSSFRow row = sheet.getRow(i);
//获取单元格对象
String name = row.getCell(0).getStringCellValue();
String city = row.getCell(1).getStringCellValue();
System.out.println(name + " " + city);
}
//关闭资源
excel.close();
fileInputStream.close();
}
public static void main(String[] args) throws Exception {
// write();
read();
}
}

View File

@ -3,10 +3,13 @@ package com.xubx.springboot_01demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableCaching //开启缓存功能
@MapperScan("com.xubx.springboot_01demo.mapper")
@EnableScheduling //开启定时任务
public class Springboot01DemoApplication {
public static void main(String[] args) {

View File

@ -0,0 +1,17 @@
package com.xubx.springboot_01demo.Task;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
@Slf4j
public class Test {
// @Scheduled(cron = "0/5 * * * * ?")
public void test() {
log.info("定时任务执行:{}", new Date());
}
}

View File

@ -0,0 +1,18 @@
package com.xubx.springboot_01demo.WebSocket;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* WebSocket配置类用于注册WebSocket的Bean
*/
@Configuration
public class WebSocketConfiguration {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}

View File

@ -0,0 +1,71 @@
package com.xubx.springboot_01demo.WebSocket;
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* WebSocket服务
*/
@Component
@ServerEndpoint("/ws/{sid}")
public class WebSocketServer {
//存放会话对象
private static Map<String, Session> sessionMap = new HashMap();
/**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(Session session, @PathParam("sid") String sid) {
System.out.println("客户端:" + sid + "建立连接");
sessionMap.put(sid, session);
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
*/
@OnMessage
public void onMessage(String message, @PathParam("sid") String sid) {
System.out.println("收到来自客户端:" + sid + "的信息:" + message);
}
/**
* 连接关闭调用的方法
*
* @param sid
*/
@OnClose
public void onClose(@PathParam("sid") String sid) {
System.out.println("连接断开:" + sid);
sessionMap.remove(sid);
}
/**
* 群发
*
* @param message
*/
public void sendToAllClient(String message) {
Collection<Session> sessions = sessionMap.values();
for (Session session : sessions) {
try {
//服务器向客户端发送消息
session.getBasicRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

View File

@ -0,0 +1,21 @@
package com.xubx.springboot_01demo.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Component
public class WebSocketTask {
@Autowired
private WebSocketServer webSocketServer;
/**
* 通过WebSocket每隔5秒向客户端发送消息
*/
@Scheduled(cron = "0/5 * * * * ?")
public void sendMessageToClient() {
webSocketServer.sendToAllClient("这是来自服务端的消息:" + DateTimeFormatter.ofPattern("HH:mm:ss").format(LocalDateTime.now()));
}
}

View File

@ -0,0 +1,38 @@
package com.xubx.springboot_01demo.configuration;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
@Slf4j
public class SwaggerConfiguration {
@Bean
public Docket createRestApi() {
log.info("准备生成接口文档");
ApiInfo apiInfo = new ApiInfoBuilder()
.title("个人博客接口文档")
.description("博客相关接口的文档")
.version("1.0")
.build();
//指定生成接口文档的类型
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo)
.select()
//指定生成接口需要扫描的包
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
.paths(PathSelectors.any())
.build();
}
}

View File

@ -2,42 +2,57 @@ package com.xubx.springboot_01demo.controller;
import com.xubx.springboot_01demo.pojo.Blogs;
import com.xubx.springboot_01demo.service.BlogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;
@RestController //注解标识这是一个控制器类
@CrossOrigin //加上CrossOrigin可解决跨域问题
@Slf4j
@Api(tags = "博客接口")
public class BlogsController {
@Resource
BlogService blogService;
//博客展示
@GetMapping("/getBlogs")
@Cacheable(value = "blogs")
@ApiOperation("获取所有博客")
public List<Blogs> getBlogs (){
log.info("博客展示");
return blogService.findAllBlogs();
}
//博客详情
@GetMapping("/getBlogDetail")
@Cacheable(value = "blogDetail")
@ApiOperation("获取博客详情")
public Blogs getBlogDetail(@RequestParam("blogId") int id){
return blogService.findByIdBlogs(id);
}
//新增博客
@PostMapping("/addBlog")
@CacheEvict(value = "blogs",allEntries = true)
@ApiOperation("新增博客")
public void addBlog(@RequestBody Blogs blogs){
blogService.addBlogs(blogs);
}
//修改博客
@PostMapping("/updateBlog")
@CacheEvict(value = "blogs",allEntries = true)
@ApiOperation("修改博客")
public void updateBlog(@RequestBody Blogs blogs){
blogService.updateBlogs(blogs);
}
//删除博客
@GetMapping("/deleteBlog")
@CacheEvict(value = "blogs",allEntries = true)
@ApiOperation("删除博客")
public void deleteBlog(@RequestParam("blogId") int id){
blogService.deleteBlogs(id);
}

View File

@ -4,6 +4,8 @@ import com.xubx.springboot_01demo.pojo.Comment;
import com.xubx.springboot_01demo.pojo.Value;
import com.xubx.springboot_01demo.service.CommentService;
import com.xubx.springboot_01demo.utils.api.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
@ -12,18 +14,19 @@ import java.util.List;
@RestController //注解标识这是一个控制器类
@CrossOrigin //加上CrossOrigin可解决跨域问题
@Api(tags = "评论接口")
public class CommentController {
@Resource
CommentService commentService;
//获取所有评论
@GetMapping("/getComment")
@ApiOperation("获取所有评论")
public List<Comment> getComment(@RequestParam("blogId") int article_id){
System.out.println("article"+article_id);
System.out.println("all:"+commentService.findAllComment(article_id));
return commentService.findAllComment(article_id);
}
//新增评论
@PostMapping("/addComment")
@ApiOperation("新增评论")
public void addComment(@RequestBody Comment comment){
commentService.addComment(comment);
}

View File

@ -6,6 +6,10 @@ import com.xubx.springboot_01demo.service.UserService;
import com.xubx.springboot_01demo.utils.token.RedisUtil;
import com.xubx.springboot_01demo.utils.token.RequestHolder;
import com.xubx.springboot_01demo.utils.token.TokenGenerate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@ -16,6 +20,8 @@ import java.io.IOException;
@RestController //注解标识这是一个控制器类
@CrossOrigin //加上CrossOrigin可解决跨域问题
@Slf4j
@Api(tags = "用户接口")
public class UserController {
@Resource
UserService userService;
@ -23,6 +29,7 @@ public class UserController {
RedisUtil redisUtil;
@PostMapping("/register")
@ApiOperation("用户注册")
public ResponseEntity<String> register(@RequestBody User user) {
//注册
if (userService.insertUser(user)) {
@ -32,7 +39,9 @@ public class UserController {
}
@PostMapping("/login")
@ApiOperation("用户登录")
public String login(@RequestBody User user) {
log.info("用户登录:{}", user.getUsername());
//登陆
if (userService.findUserByUsername(user)) {
String token = new TokenGenerate().generateToken(user.getUsername());
@ -43,11 +52,13 @@ public class UserController {
}
@GetMapping("/getUsername")
@ApiOperation("获取用户名")
public String getUserName() {
return RequestHolder.getuserId();
}
@RequestMapping("/uploadAvatar")
@ApiOperation("上传头像")
public void uploadAvatar(MultipartFile file) throws IOException {
String pType = file.getContentType();
pType = pType.substring(pType.indexOf("/") + 1);
@ -64,6 +75,7 @@ public class UserController {
}
@GetMapping("/getAvatar")
@ApiOperation("获取头像")
public ResponseEntity<String> getAvatar() {
String path = userService.getAvatar(RequestHolder.getuserId());
System.out.println("发给前端的路径:" + path);
@ -71,6 +83,7 @@ public class UserController {
}
@GetMapping("usernameChange")
@ApiOperation("修改用户名")
public ResponseEntity<String> usernameChange(@RequestParam("username") String username){
if(userService.usernameChange(RequestHolder.getuserId(),username)){
RequestHolder.add(username);
@ -80,6 +93,7 @@ public class UserController {
}
@GetMapping("passwordChange")
@ApiOperation("修改密码")
public ResponseEntity<String> passwordChange(@RequestParam("oldPassword") String oldPassword,@RequestParam("newPassword") String newPassword){
if(userService.passwordChange(RequestHolder.getuserId(),oldPassword,newPassword)){
return ResponseEntity.ok("修改成功!");

View File

@ -1,8 +1,9 @@
package com.xubx.springboot_01demo.pojo;
import java.io.Serializable;
import java.sql.Timestamp;
public class Blogs {
public class Blogs implements Serializable {
private int id;
private String title;
private String description;

View File

@ -1,10 +1,11 @@
package com.xubx.springboot_01demo.pojo;
import java.io.Serializable;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
public class Comment {
public class Comment implements Serializable {
private int comment_id;
private int article_id;
private String username;
@ -13,6 +14,15 @@ public class Comment {
private String parent_name;
private String created;
private String avatar;
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
@Override
public String toString() {

View File

@ -3,7 +3,9 @@ package com.xubx.springboot_01demo.pojo;
import com.baomidou.mybatisplus.annotation.TableField;
public class User {
import java.io.Serializable;
public class User implements Serializable {
private String username;
private String password;
private String avatar;

View File

@ -1,6 +1,8 @@
package com.xubx.springboot_01demo.pojo;
public class Value {
import java.io.Serializable;
public class Value implements Serializable {
private String value;
public Value() {

View File

@ -1,10 +1,13 @@
package com.xubx.springboot_01demo.service.impl;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.xubx.springboot_01demo.controller.UserController;
import com.xubx.springboot_01demo.mapper.CommentMapper;
import com.xubx.springboot_01demo.pojo.Comment;
import com.xubx.springboot_01demo.service.CommentService;
import com.xubx.springboot_01demo.service.UserService;
import com.xubx.springboot_01demo.utils.token.RequestHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@ -14,6 +17,8 @@ import java.util.List;
public class CommentServiceImpl implements CommentService {
@Resource
CommentMapper commentMapper;
@Resource
UserService userService;
@Override
public List<Comment> findAllComment(int article_id) {
return commentMapper.findAllComment(article_id);
@ -22,12 +27,13 @@ public class CommentServiceImpl implements CommentService {
@Override
public void addComment(Comment comment) {
Comment comment1 = new Comment();
comment1.setArticle_id(comment.getArticle_id());
//对象属性拷贝
BeanUtils.copyProperties(comment,comment1);
comment1.setUsername(RequestHolder.getuserId());
comment1.setContent(comment.getContent());
comment1.setParent_id(comment.getParent_id());
comment1.setParent_name(comment.getParent_name());
comment1.setCreated(comment.getCreated());
comment1.setAvatar(userService.getAvatar(RequestHolder.getuserId()));
System.out.println(comment1);
commentMapper.addComment(comment1);
}

View File

@ -1,4 +0,0 @@
package com.xubx.springboot_01demo.utils;
public class test {
}

View File

@ -0,0 +1,17 @@
package com.xubx.springboot_01demo.utils.token;
public class RequestHolder {
private static final ThreadLocal<String> userHolder = new ThreadLocal<>();
public static void add(String userId) {
userHolder.set(userId);
}
public static String getuserId() {
return userHolder.get();
}
public static void remove() {
userHolder.remove();
}
}

View File

@ -2,14 +2,16 @@ spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://124.71.135.249:3306/vue
spring.datasource.username=root
spring.datasource.password=xbx123
server.port=8081
#spring.web.resources.static-locations=classpath:/static/
spring.web.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.xubx.springboot_01demo.pojo
spring.redis.host=124.71.135.249
spring.redis.port=6379
spring.redis.password=123456
logging.level.com.xubx.springboot_01demo.mapper= debug
#Path???????ant_path_matcher
spring.mvc.pathmatch.matching-strategy=ant_path_matcher

View File

@ -21,8 +21,8 @@
</select>
<!--新增评论-->
<insert id="addComment" parameterType="com.xubx.springboot_01demo.pojo.Comment">
insert into comment (article_id, username, content, parent_id, parent_name, created)
values (#{article_id}, #{username}, #{content}, #{parent_id}, #{parent_name}, #{created})
insert into comment (article_id, username, content, parent_id, parent_name, created, avatar)
values (#{article_id}, #{username}, #{content}, #{parent_id}, #{parent_name}, #{created}, #{avatar})
</insert>
</mapper>

View File

@ -0,0 +1,39 @@
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
@SpringBootTest(classes = httpClient.class)
public class httpClient {
@Test
public void get() {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
URIBuilder builder = new URIBuilder("http://localhost:8081/getBlogs");
HttpGet httpGet = new HttpGet(builder.build());
response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

View File

@ -2,14 +2,16 @@ spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://124.71.135.249:3306/vue
spring.datasource.username=root
spring.datasource.password=xbx123
server.port=8081
#spring.web.resources.static-locations=classpath:/static/
spring.web.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.xubx.springboot_01demo.pojo
spring.redis.host=124.71.135.249
spring.redis.port=6379
spring.redis.password=123456
logging.level.com.xubx.springboot_01demo.mapper= debug
#Path???????ant_path_matcher
spring.mvc.pathmatch.matching-strategy=ant_path_matcher

Binary file not shown.