• 博客系统(SSM)


    前端页面icon-default.png?t=N7T8http://t.csdnimg.cn/zwKyG以上是之前写过的博客前端页面的内容,下面是通过SSM实现的后端内容。

    目录

    一.准备工作

    1.1数据准备

    1.2修改配置版本文件

    1.3配置数据库

    二.项目公共模块

    2.1实体类

    2.2操作数据库部分

    三.功能开发

    3.1博客列表

    获取博客列表

    修改日期格式

    3.2博客详情

    3.3实现登录(使用令牌)

    账号密码登录

    强制登录

    3.4实现显示用户信息

    3.5实现用户退出

    3.6实现发博客

    3.7实现删除、编辑博客

    编辑按钮

    编辑博客

    ​编辑

    删除博客

    3.8加密(盐值)


    一.准备工作

    1.1数据准备

    建表SQL

    1. -- 建表SQL
    2. create database if not exists java_blog_spring charset utf8mb4;
    1. -- ⽤⼾表
    2. DROP TABLE IF EXISTS java_blog_spring.user;
    3. CREATE TABLE java_blog_spring.user(
    4. `id` INT NOT NULL AUTO_INCREMENT,
    5. `user_name` VARCHAR ( 128 ) NOT NULL,
    6. `password` VARCHAR ( 128 ) NOT NULL,
    7. `github_url` VARCHAR ( 128 ) NULL,
    8. `delete_flag` TINYINT ( 4 ) NULL DEFAULT 0,
    9. `create_time` DATETIME DEFAULT now(),
    10. `update_time` DATETIME DEFAULT now(),
    11. PRIMARY KEY ( id ),
    12. UNIQUE INDEX user_name_UNIQUE ( user_name ASC )) ENGINE = INNODB DEFAULT CHARACTER
    13. SET = utf8mb4 COMMENT = '⽤⼾表';
    14. -- 博客表
    15. drop table if exists java_blog_spring.blog;
    16. CREATE TABLE java_blog_spring.blog (
    17. `id` INT NOT NULL AUTO_INCREMENT,
    18. `title` VARCHAR(200) NULL,
    19. `content` TEXT NULL,
    20. `user_id` INT(11) NULL,
    21. `delete_flag` TINYINT(4) NULL DEFAULT 0,
    22. `create_time` DATETIME DEFAULT now(),
    23. `update_time` DATETIME DEFAULT now(),
    24. PRIMARY KEY (id))
    25. ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COMMENT = '博客表';
    26. -- 新增⽤⼾信息
    27. insert into java_blog_spring.user (user_name, password,github_url)values("zhangsan","123456","https://gitee.com/Roylele-java-j");
    28. insert into java_blog_spring.user (user_name, password,github_url)values("lisi","123456","https://gitee.com/Roylele-java-j");
    29. insert into java_blog_spring.blog(title,content,user_id) values("第一篇博客","111我是博客正文我是博客正文我是博客正文",1);
    30. insert into java_blog_spring.blog(title,content,user_id) values("第一篇博客","222我是博客正文我是博客正文我是博客正文",2);

    1.2创建项目

    以JDK17创建,改成JDK8的版本

    修改pom文件

    1.2修改配置版本文件

    1.3配置数据库

     配置application.yml文件

    1. #数据库连接配置
    2. spring:
    3. datasource:
    4. url: jdbc:mysql://127.0.0.1:3306/java_blog_spring?characterEncoding=utf8&useSSL=false
    5. username: root
    6. password: root
    7. driver-class-name: com.mysql.cj.jdbc.Driver
    8. mybatis:
    9. configuration:
    10. map-underscore-to-camel-case: true #配置驼峰⾃动转换
    11. log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #打印sql语句
    12. mapper-locations: classpath:mapper/**Mapper.xml
    13. # 设置⽇志⽂件的⽂件名
    14. logging:
    15. file:
    16. name: logger/spring-blog.log

    二.项目公共模块

    项目分为控制层(Controller), 服务层(Service), 持久层(Mapper). 各层之间的调用关系如下:

    2.1实体类

    1. @Data
    2. public class UserInfo {
    3. private Integer id;
    4. private String userName;
    5. private String password;
    6. private String githubUrl;
    7. private Byte deleteFlag;
    8. private Date createTime;
    9. private Date updateTime;
    10. }
    1. @Data
    2. public class BlogInfo {
    3. private Integer id;
    4. private String title;
    5. private String content;
    6. private Integer userId;
    7. private Integer deleteFlag;
    8. private Date createTime;
    9. private Date updateTime;
    10. }

    2.2操作数据库部分

    涉及到数据库的部分:

    1.用户登录,校验用户名和密码是否正确

    SQL:根据用户名,查询用户信息

    2.博客列表页

    SQL:根据ID名,查询用户信息

    SQL:获取博客列表

    3.博客详情页··

    SQL:根据博客ID,获取博客详情

    SQL:根据博客ID,编辑博客

    SQL:根据博客ID,删除博客

    4.博客添加/修改

    SQL:根据输入内容,添加博客

    对数据库的操作

    1. @Mapper
    2. public interface UserInfoMapper {
    3. // 根据用户名,查询用户信息
    4. @Select("select * from user where user_name=#{userName} and delete_flag=0")
    5. UserInfo queryByName(String userName);
    6. // 根据用户ID,查询用用户信息
    7. @Select("select * from user where id=#{id} and delete_flag=0")
    8. UserInfo queryById(Integer id);
    9. }
    1. @Mapper
    2. public interface BlogInfoMapper {
    3. // 获取博客列表
    4. @Select("select * from blog where delete_flag=0")
    5. List queryBlogList();
    6. // 根据博客ID,获取博客详情
    7. @Select("select * from blog where id=#{id} and delete_flag=0")
    8. BlogInfo queryById(Integer id);
    9. @Update("update blog set title=#{title},content=#{content} where id=#{id}")
    10. // 根据博客ID,编辑博客
    11. Integer update(BlogInfo blogInfo);
    12. @Update("update blog set delete_flag=1 where id=#{id}")
    13. // 根据博客ID,删除博客
    14. Integer deleteBlog(Integer id);
    15. // 根据输入内容,添加博客
    16. @Insert("insert into blog(title,content,user_id) values(#{title},#{content},#{userId})")
    17. Integer insertBlog(BlogInfo blogInfo);
    18. }

    测试操作数据库功能

    1. @SpringBootTest
    2. class UserInfoMapperTest {
    3. @Autowired
    4. private UserInfoMapper userInfoMapper;
    5. @Test
    6. void queryByName() {
    7. System.out.println(userInfoMapper.queryByName("zhangsan"));
    8. }
    9. @Test
    10. void queryById() {
    11. System.out.println(userInfoMapper.queryById(2));
    12. }
    13. }
    1. @SpringBootTest
    2. class BlogInfoMapperTest {
    3. @Autowired
    4. private BlogInfoMapper blogInfoMapper;
    5. @Test
    6. void queryBlogList() {
    7. System.out.println(blogInfoMapper.queryBlogList());
    8. }
    9. @Test
    10. void queryById() {
    11. System.out.println(blogInfoMapper.queryById(1));
    12. }
    13. @Test
    14. void update() {
    15. BlogInfo blogInfo=new BlogInfo();
    16. blogInfo.setTitle("test11111");
    17. blogInfo.setContent("好想躺平");
    18. blogInfo.setId(3);
    19. blogInfoMapper.update(blogInfo);
    20. }
    21. @Test
    22. void deleteBlog() {
    23. blogInfoMapper.deleteBlog(3);
    24. }
    25. @Test
    26. void insertBlog() {
    27. BlogInfo blogInfo=new BlogInfo();
    28. blogInfo.setTitle("test");
    29. blogInfo.setContent("好好学习,天天向上");
    30. blogInfo.setUserId(1);
    31. blogInfoMapper.insertBlog(blogInfo);
    32. }
    33. }

    定义返回结果的类型Result

    1. //定义统一的返回结果
    2. @Data
    3. public class Result {
    4. private int code;//200-成功 -1失败
    5. private String errorMsg;//
    6. private T data;
    7. public static Result success(T data){
    8. Result result=new Result();
    9. result.setCode(Constants.RESULT_SUCCESS);
    10. result.setData(data);
    11. return result;
    12. }
    13. public static Result fail(String errorMsg,T data){
    14. Result result=new Result();
    15. result.setCode(Constants.RESULT_FAIL);
    16. result.setErrorMsg(errorMsg);
    17. result.setData(data);
    18. return result;
    19. }
    20. }

    把常量对应放在一个类Constants中:

    1. public class Constants {
    2. public static final Integer RESULT_SUCCESS=200;
    3. public static final Integer RESULT_FAIL=-1;
    4. }

    使用AOP的方式完成统一返回结果处理:

    1. @ControllerAdvice
    2. //AOP统一返回结果
    3. public class ResponseAdvice implements ResponseBodyAdvice {
    4. @Override
    5. public boolean supports(MethodParameter returnType, Class converterType) {
    6. return true;
    7. }
    8. @SneakyThrows
    9. @Override
    10. public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
    11. if(body instanceof Result){
    12. return body;
    13. }
    14. //返回结果是String类型需要单独处理
    15. if (body instanceof String){
    16. ObjectMapper objectMapper=new ObjectMapper();
    17. return objectMapper.writeValueAsString(Result.success(body));
    18. }
    19. return Result.success(body);
    20. }
    21. }

    统一异常处理:

    1. //统一异常处理 拦截异常
    2. @ResponseBody//返回的是对象,而不是页面
    3. @ControllerAdvice
    4. public class ErrorAdvice {
    5. @ExceptionHandler//捕获到异常的注释
    6. public Result errorHandler(Exception e){
    7. Result result=new Result();
    8. // 写法一
    9. // result.setErrorMsg(e.getMessage());
    10. // 写法二
    11. result.setErrorMsg("内部发生错误,请联系管理员");
    12. result.setCode(Constants.RESULT_FAIL);
    13. return result;
    14. }
    15. }

    三.功能开发

    3.1博客列表

    获取博客列表

    约定前后端交互接口:

    请求:blog/getList

    响应:''code'':200 , ''msg'':" " data:

    1. @RequestMapping("/blog")
    2. @RestController
    3. public class BlogController {
    4. @Autowired
    5. private BlogService blogService;
    6. //获取博客列表
    7. @RequestMapping("/getList")
    8. public List getBlogList(){
    9. return blogService.getBlogList();
    10. }
    11. }
    1. @Service
    2. public class BlogService {
    3. @Autowired
    4. private BlogInfoMapper blogInfoMapper;
    5. public List getBlogList() {
    6. return blogInfoMapper.queryBlogList();
    7. }
    8. }
    1. @Mapper
    2. public interface BlogInfoMapper {
    3. // 获取博客列表
    4. @Select("select * from blog where delete_flag=0")
    5. List queryBlogList();

    前端交互部分:

    1. <script>
    2. getBlogList();
    3. function getBlogList(){
    4. $.ajax({
    5. type:"get",
    6. url:"/blog/getList",
    7. success:function(result){
    8. if(result.code==200 && result.data!=null){
    9. var blogList=result.data;
    10. //拼接字符串
    11. var finalHtml="";
    12. //对每一条博客,拼接成一个div
    13. for(var blog of blogList){
    14. finalHtml +='
      ';
    15. finalHtml +='
      '+blog.title+'
      '
      ;
    16. finalHtml +='
      '+blog.createTime+'
      '
      ;
    17. finalHtml +='
      '+blog.content+'
      '
      ;
    18. finalHtml +='查看全文>>';
    19. finalHtml +='
      ';
  • }
  • $(".right").html(finalHtml);
  • }
  • }
  • });
  • }
  • script>
  • 此时查看页面:

    修改日期格式

    对日期格式进行修改:使用SimpleDataFormat

    创建一个日期工具类

    1. //日期工具类
    2. public class DateUtils {
    3. //日期转换成2024-02-28 16;02这种格式
    4. public static String formatDate(Date date){
    5. SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm");
    6. return simpleDateFormat.format(date);
    7. }
    8. }

    对BlogInfo中的 private Date createTime;

    自己重新定义想要的get方法

    1. @Data
    2. public class BlogInfo {
    3. private Integer id;
    4. private String title;
    5. private String content;
    6. private Integer userId;
    7. private Integer deleteFlag;
    8. private Date createTime;
    9. private Date updateTime;
    10. //自定义Date的get方法
    11. public String getCreateTime() {
    12. return DateUtils.formatDate(createTime);
    13. }
    14. }

    3.2博客详情

    通过点击博客列表页的产看全文进入到详细的博客详情页。

    后端代码:

    约定前后端交互接口:

    请求:/blog/getBlogDetail?blogId=1

    BlogController类中添加BlogService类中添加

    1. //获取博客详情
    2. @RequestMapping("/getBlogDetail")
    3. public BlogInfo getBlogDetail(Integer blogId){
    4. return blogService.getBlogDetail(blogId);
    5. }
    BlogService类中添加
    
    1. public BlogInfo getBlogDetail(Integer id) {
    2. return blogInfoMapper.queryById(id);
    3. }

    测试后端代码:

    前端代码:

    blog_detail.html

    1. //获取博客详情
    2. $.ajax({
    3. type:"get",
    4. url:"/blog/getBlogDetail"+location.search,
    5. success:function(result){
    6. if(result.code==200 && result.data!=null){
    7. var blog=result.data;
    8. $(".title").text(blog.title);
    9. $(".date").text(blog.creatTime);
    10. $(".detail").text(blog.content);
    11. }
    12. }
    13. });

    3.3实现登录(使用令牌)

    账号密码登录

    以前使用的方式:

    1.根据用户名和密码,验证密码是否正确

    2.如果密码正确,存储session

    3.后续访问时,携带cookie(携带sessionId)

    现在使用token的方式:

    1.根据用户名和密码,验证密码是否正确

    2.如果密码正确,后端生成token,并返回给前端(可以放在cookie中,也可以放在本地存储中)

    3.后续访问,携带token,后端校验token的合法性(通常放在http请求的header中)

    约定前后端交互接口:

    /user/login

    参数username=xxx&&password=xxx

    创建JwtUtils工具类
    1. //JWT工具类
    2. public class JwtUtils {
    3. private static final String secretString="yvc+h4mLEjn0+7s1XQNUp8q71z5kuYgn2JnAvLXK8Hg=";
    4. private static final long expiration=30*60*1000;
    5. private static final Key key= Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));//签名的编码方式
    6. public static String genToken(Map claim){
    7. String token= Jwts.builder()
    8. .setClaims(claim)//设置载荷
    9. .setExpiration(new Date(System.currentTimeMillis()+expiration))//生成过期时间
    10. .signWith(key)//设置签名
    11. .compact();//生成token
    12. return token;
    13. }
    14. }
    UserController中添加
    1. @RequestMapping("/user")
    2. @RestController
    3. public class UserController {
    4. @Autowired
    5. private UserService userService;
    6. @RequestMapping("/login")
    7. public Result login(String username, String password){
    8. //1.参数校验
    9. //2.密码校验
    10. //3.生成token并返回
    11. if(!StringUtils.hasLength(username) || !StringUtils.hasLength(password)){
    12. return Result.fail("用户名或密码为空");
    13. }
    14. //获取数据库中的密码
    15. UserInfo userInfo=userService.queryByName(username);
    16. if(userInfo==null ||userInfo.getId()<0){
    17. return Result.fail("用户不存在");
    18. }
    19. if(!password.equals(userInfo.getPassword())){
    20. return Result.fail("密码错误");
    21. }
    22. //生成token并返回
    23. Map claim=new HashMap<>();
    24. claim.put("id",userInfo.getId());
    25. claim.put("name",userInfo.getUserName());
    26. String token= JwtUtils.genToken(claim);
    27. return Result.success(token);
    28. }
    29. }
    UserService中添加
    1. @Service
    2. public class UserService {
    3. @Autowired
    4. private UserInfoMapper userInfoMapper;
    5. public UserInfo queryByName(String username) {
    6. return userInfoMapper.queryByName(username);
    7. }
    8. }

    测试后端:

    前端:

    1. <script>
    2. function login() {
    3. // location.assign("blog_list.html");
    4. $.ajax({
    5. type:"post",
    6. url:"/user/login",
    7. data:{
    8. userName:$("#username").val(),
    9. password:$("#password").val()
    10. },
    11. success:function(result){
    12. if(result.code==200 && result.data!=null){
    13. //密码正确
    14. //本地存储token
    15. localStorage.setItem("user_token",result.data);
    16. location.href="blog_list.html";
    17. }else{
    18. alert(result.errorMsg);
    19. }
    20. }
    21. });
    22. }
    23. script>

    测试前端的登录功能,及查看存储的token:

    强制登录

    使用AOP拦截器的方式

    1. //拦截器
    2. @Slf4j
    3. @Configuration
    4. public class LoginInterceptor implements HandlerInterceptor {
    5. @Override
    6. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    7. //进行用户登录校验
    8. //1.从header中获取token
    9. //2.验证token
    10. //http发送请求
    11. String token=request.getHeader("user_token");
    12. log.info("从header中获取token,token"+token);
    13. Claims claims= JwtUtils.parseToken((token));
    14. if(claims==null){
    15. //token是不合法的
    16. response.setStatus(401);
    17. return false;
    18. }
    19. return true;
    20. }
    21. }
    1. //让拦截器生效
    2. @Configuration
    3. public class WebConfig implements WebMvcConfigurer {
    4. private static final List excludePath= Arrays.asList(
    5. "/user/login",
    6. "/**/*.html",
    7. "/pic/**",
    8. "/js/**",
    9. "/css/**",
    10. "/blog-editormd/**"
    11. );
    12. @Autowired
    13. private LoginInterceptor loginInterceptor;
    14. @Override
    15. public void addInterceptors(InterceptorRegistry registry) {
    16. //注册拦截器
    17. registry.addInterceptor(loginInterceptor)
    18. .addPathPatterns("/**")
    19. .excludePathPatterns(excludePath);
    20. }
    21. }

    JWT工具类:

    1. @Slf4j
    2. //JWT工具类
    3. public class JwtUtils {
    4. private static final String secretString="yvc+h4mLEjn0+7s1XQNUp8q71z5kuYgn2JnAvLXK8Hg=";
    5. private static final long expiration=30*60*1000;
    6. private static final Key key= Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));//签名的编码方式
    7. public static String genToken(Map claim){
    8. String token= Jwts.builder()
    9. .setClaims(claim)//设置载荷
    10. .setExpiration(new Date(System.currentTimeMillis()+expiration))//生成过期时间
    11. .signWith(key)//设置签名
    12. .compact();//生成token
    13. return token;
    14. }
    15. //解析token,返回校验token得到的值
    16. public static Claims parseToken(String token){
    17. if(token==null){
    18. return null;
    19. }
    20. //使用JWT设置签名,生成token和解析token要使用同一个签名
    21. JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
    22. Claims claims=null;
    23. try{
    24. //拿到签名后,通过签名获取信息解析
    25. claims = build.parseClaimsJws(token).getBody();
    26. }catch (Exception e){
    27. log.error("解析token失败"+token);
    28. }
    29. return claims;
    30. }
    31. }

    前端:

    这样用户登录后,即时后端服务器重启,用户也不会退出登录。

    3.4实现显示用户信息

    显示用户信息

    博客列表,显示当前登录用户信息

    /user/getUserInfo

    两种方式:

    1.如果页面需要的信息较少,且是固定不变的内容,可以把这些信息存储在token中,直接从token   中拿

    2.从token中获取用户ID,根据用户ID,获取用户信息(推荐)

    这里使用第二种方式

    UserController中
    1. /**
    2. * 获取登录用户的信息
    3. */
    4. @RequestMapping("/getUserInfo")
    5. public UserInfo getUserInfo(HttpServletRequest request){
    6. //1.从token中获取用户ID
    7. //2.根据用户ID,获取用户信息
    8. String token= request.getHeader("user_token");
    9. Integer userId=JwtUtils.getUserIdFromToken(token);
    10. if(userId==null){
    11. return null;
    12. }
    13. return userService.queryById(userId);
    14. }
     UserService中
    1. @Autowired
    2. private UserInfoMapper userInfoMapper;
    3. @Autowired
    4. private BlogInfoMapper blogInfoMapper;
    5. public UserInfo queryById(Integer userId) {
    6. return userInfoMapper.queryById(userId);
    7. }

    测试:使用postman

    博客详情页,显示当前作者的信息

    /user/getAuthorInfo?blogId=1

    UserController中

    1. /**
    2. * 获取当前作者的信息
    3. */
    4. @RequestMapping("/getAuthorInfo")
    5. public UserInfo getAuthorInfo(Integer blogId){
    6. if(blogId==null || blogId<0){
    7. return null;
    8. }
    9. return userService.getAuthorInfo(blogId);
    10. }

    UserService中

    1. public UserInfo getAuthorInfo(Integer blogId) {
    2. //1.根据博客ID获取userId
    3. //2.根据userId获取userInfo
    4. BlogInfo blogInfo = blogInfoMapper.queryById(blogId);
    5. if(blogInfo==null || blogInfo.getUserId()<0){
    6. return null;
    7. }
    8. return userInfoMapper.queryById(blogInfo.getUserId());
    9. }

    测试:

    前端:

    blog_list.html中

    1. //获取用户信息
    2. getUserInfo();
    3. function getUserInfo(){
    4. $.ajax({
    5. type:"get",
    6. url:"/user/getUserInfo",
    7. success:function(result){
    8. if(result.code==200 && result.data!=null){
    9. //页面填充
    10. var user=result.data;
    11. $(".left .card h3").text(user.userName);
    12. $(".left .card a").attr("href",user.githubUrl);
    13. }else{
    14. location.href="blog_login.html"
    15. }
    16. }
    17. });
    18. }

    同理,blog_detail.html中:

    1. //获取博客作者信息
    2. getUserInfo();
    3. function getUserInfo(){
    4. $.ajax({
    5. type:"get",
    6. url:"/user/getAuthorInfo"+location.search,
    7. success:function(result){
    8. if(result.code==200 && result.data!=null){
    9. //页面填充
    10. var user=result.data;
    11. $(".left .card h3").text(user.userName);
    12. $(".left .card a").attr("href",user.githubUrl);
    13. }else{
    14. location.href="blog_login.html"
    15. }
    16. }
    17. });
    18. }

    可以发现获取作者信息的博客列表前端代码和博客细节页代码前端代码只有url不同,则可以把这两段代码提取到common.js中去。

    common.js

    1. //把url作为参数提取出来
    2. function getUserInfo(url){
    3. $.ajax({
    4. type:"get",
    5. url:url,
    6. success:function(result){
    7. if(result.code==200 && result.data!=null){
    8. //页面填充
    9. var user=result.data;
    10. $(".left .card h3").text(user.userName);
    11. $(".left .card a").attr("href",user.githubUrl);
    12. }else{
    13. location.href="blog_login.html"
    14. }
    15. }
    16. });
    17. }

    同时对blog_list.html和blog_detail.html中进行调用修改

    3.5实现用户退出

    清除存储的token值即可完成退出

    在common.js中

    1. //用户注销
    2. function logout(){
    3. localStorage.removeItem("user_token");
    4. location.href="blog_login.html";
    5. }

    3.6实现发博客

    约定前后端交互接口

    请求:/blog/add

    参数:title=标题&content=正文

    后端BlogController中添加

    1. /**
    2. * 发布博客
    3. */
    4. @RequestMapping("/add")
    5. public Result publishBlog(String title, String content, HttpServletRequest request){
    6. //从token中获取userId
    7. String token=request.getHeader("user_token");
    8. Integer userId= JwtUtils.getUserIdFromToken(token);
    9. if(userId==null || userId<0){
    10. return Result.fail("用户未登录");
    11. }
    12. //插入博客
    13. BlogInfo blogInfo=new BlogInfo();
    14. blogInfo.setUserId(userId);
    15. blogInfo.setTitle(title);
    16. blogInfo.setContent(content);
    17. blogService.insertBlog(blogInfo);
    18. return Result.success("success");
    19. }

    BlogService中添加

    1. public Integer insertBlog(BlogInfo blogInfo) {
    2. return blogInfoMapper.insertBlog(blogInfo);
    3. }

    前端:

    blog_edit.html中:

    1. function submit() {
    2. $.ajax({
    3. type:"post",
    4. url:"/blog/add",
    5. data:{
    6. title:$("#title").val(),
    7. content:$("#content").val()
    8. },
    9. success:function(result){
    10. if(result.code==200){
    11. location.href="blog_list.html";
    12. }else{
    13. alert(result.error());
    14. }
    15. }
    16. });
    17. }

    3.7实现删除、编辑博客

    编辑按钮

    当登录用户和作者是同一个人才可以编辑、删除。

    在博客详情页判断是否显示编辑和删除按钮

    判断条件:当前 登录用户 == 作者

    1.单独写一个接口,返回true/false(登录用户 == 作者)

    2.获取博客详情使,同时返回登录用户是否为作者(当前系统使用的方式)

    在BlogInfo中添加定义,属性中布尔类型,以is开头,注意这里生成的set和get方法与之前的有所不同。

    BlogController中

    1. //获取博客详情
    2. @RequestMapping("/getBlogDetail")
    3. public BlogInfo getBlogDetail(Integer blogId,HttpServletRequest request){
    4. BlogInfo blogInfo=blogService.getBlogDetail(blogId);
    5. //判断作者是否为登录用户
    6. //从token中获取userId
    7. String token=request.getHeader("user_token");
    8. Integer userId= JwtUtils.getUserIdFromToken(token);
    9. if(userId!=null && userId==blogInfo.getUserId()){
    10. blogInfo.setLoginUser(true);
    11. }
    12. return blogInfo;
    13. }

    前端:当登录用户与文章作者为同一个人时,添加按钮。

    blog_detail.html中

    1. //判断是否显示编辑/删除按钮
    2. console.log(result);
    3. if(blog.loginUser){
    4. console.log("===true")
    5. var finalHtml="";
    6. finalHtml +='<button onclick="window.location.href=\'blog_update.html?blogId=1'+ blog.id+'\'">编辑button>';
    7. finalHtml +=' <button onclick="deleteBlog('+blog.id+')">删除button>';
    8. $(".operating").html(finalHtml);
    9. }else{
    10. console.log("===false");
    11. }

    按钮效果:

    编辑博客

    1.获取博客详情

    2.发布博客(更新文章)

    BlogController中:

    1. /**
    2. * 编辑博客
    3. */
    4. @RequestMapping("/update")
    5. public boolean updateBlog(Integer id,String title,String content){
    6. BlogInfo blogInfo=new BlogInfo();
    7. blogInfo.setTitle(title);
    8. blogInfo.setContent(content);
    9. blogInfo.setId(id);
    10. blogService.updateBlog(blogInfo);
    11. return true;
    12. }

    BlogService中:

    1. public Integer updateBlog(BlogInfo blogInfo) {
    2. return blogInfoMapper.updateBlog(blogInfo);
    3. }

    前端:

    1. function submit() {
    2. $.ajax({
    3. type:"post",
    4. url:"/blog/update",
    5. data:{
    6. id:$("#blogId").val(),
    7. title:$("#title").val(),
    8. content:$("#content").val(),
    9. },
    10. success:function(result){
    11. if(result.code==200 && result.data==true){
    12. location.href="blog_list.html";
    13. }
    14. }
    15. });

    删除博客

    1. @RequestMapping("/delete")
    2. public boolean deleteBlog(Integer blogId){
    3. blogService.delete(blogId);
    4. return true;
    5. }

    BlogService中:

    1. public Integer delete(Integer blogId) {
    2. return blogInfoMapper.deleteBlog(blogId);
    3. }

    前端:

    1. function deleteBlog(blogId) {
    2. $.ajax({
    3. type:"get",
    4. url:"/blog_delete"+location.search,
    5. success:function(result){
    6. if(result.code==200 && result.data==true){
    7. location.href="blog_list.html";
    8. }
    9. }
    10. });
    11. }

    3.8加密(盐值)

    加密思路:博采用MD5算法来进行加密。

    实现加密

    1.存储随机盐值

    2.存储加密后的密文

    3.加密算法(MD5)

    写加密/解密工具类

    1. public class SecurityUtils {
    2. /**
    3. * 加密
    4. * @param password 明文密码
    5. * @return 盐值+密文
    6. */
    7. public static String encrypt(String password){
    8. //生成随机盐值
    9. String salt = UUID.randomUUID().toString().replace("-","");
    10. System.out.println(salt);
    11. //加密 盐值+明文
    12. String securityPassword = DigestUtils.md5DigestAsHex((salt+password).getBytes());
    13. //数据库中存储 盐值+密文
    14. return salt+securityPassword;
    15. }
    16. /**
    17. * 校验
    18. * @return
    19. */
    20. public static boolean verify(String inputPassword, String sqlPassword){
    21. //取出盐值
    22. if (sqlPassword ==null || sqlPassword.length()!=64){
    23. return false;
    24. }
    25. String salt = sqlPassword.substring(0,32);
    26. //得到密文
    27. String securityPassword = DigestUtils.md5DigestAsHex((salt+inputPassword).getBytes());
    28. return (salt+securityPassword).equals(sqlPassword);
    29. }
    30. public static void main(String[] args) {
    31. String finalPassword = encrypt("123456");
    32. System.out.println(finalPassword);
    33. System.out.println(verify("123456",finalPassword));
    34. }
    35. }

    修改一下数据库密码,使用测试类给密码123456(假设我们的数据库密码为123456)生成密文:

     修改数据库明文密码为密文, 执行SQL:

    1. update user set password='';
    2. //数据库 password修改成生成的密文

    登录接口:

    1. @RequestMapping("/login")
    2. public Result login(String userName, String password){
    3. //1.参数校验
    4. //2.密码校验
    5. //3.生成token并返回
    6. if(!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)){
    7. return Result.fail("用户名或密码为空");
    8. }
    9. //获取数据库中的密码
    10. UserInfo userInfo=userService.queryByName(userName);
    11. if(userInfo==null ||userInfo.getId()<0){
    12. return Result.fail("用户不存在");
    13. }
    14. //校验密码
    15. if (!SecurityUtils.verify(password, userInfo.getPassword())){
    16. return Result.fail("密码错误!");
    17. }
    18. //生成token并返回
    19. Map<String,Object> claim=new HashMap<>();
    20. claim.put("id",userInfo.getId());
    21. claim.put("name",userInfo.getUserName());
    22. String token= JwtUtils.genToken(claim);
    23. return Result.success(token);
    24. }

    实现

  • 相关阅读:
    Ubuntu磁盘满了,导致黑屏
    FANUC机器人_通过ROBOGUIDE从零开始做一个离线仿真项目(2)
    Django框架的全面指南:从入门到高级【第128篇—Django框架】
    数据治理-数据存储和操作-数据架构类型
    【CS324】LLM(大模型的能力、数据、架构、分布式训练、微调等)
    2374. 边积分最高的节点
    MyBatis-Plus 一些记录(1)
    IPWorks EDI Translator Delphi Edition
    数字滚动组件(react)
    面试经典150题——生命游戏
  • 原文地址:https://blog.csdn.net/weixin_67793092/article/details/136165974