【SpringBoot搭建我的博客】- 後臺登陸(四)

博客地址:ONESTARの客棧html

源碼領取方式一:前端

  • 掃一掃文末二維碼,關注公衆號【編程日刊】,後臺回覆【博客】,便可領取源碼

源碼領取方式二:java

歡迎給star以鼓勵(^_−)☆spring

本文將從MVC架構、MD5加密、登陸攔截器來說述我的博客系統的後臺登陸實現數據庫

MVC架構

後臺開發採用的是MVC架構,MVC 全名是 Model View Controller,是模型(model)-視圖(view)-控制器(controller)的縮寫, 是一種用於設計建立 Web 應用程序表現層的模式。MVC 中每一個部分各司其職:apache

Model(模型):編程

  • 一般指的是咱們的數據模型,通常狀況下用於封裝數據

View(視圖):

  • 一般指 jsp 或者 html,通常用於展現數據,一般視圖是依據模型數據建立的

Controller(控制器):

  • 應用程序中處理用戶交互的部分,通常用於處理程序邏輯的

1.用戶實體類

以前提到過,因爲是我的博客,就沒有作權限管理,只是簡單的區分了一下管理員(棧主)和普通用戶,因此這裏須要用戶實體類,並須要基本的用戶名和密碼,管理員登陸後能夠對後臺進行操做,而普通用戶則沒有權限,在com.star(Group組名)目錄下建立entity包,並建立User實體類,實體類以下(這裏省去了get、set、toString方法):

package com.star.entity;

import java.util.Date;

/** * @Description: 用戶實體類 * @Date: Created in 21:39 2020/5/26 * @Author: ONESTAR * @QQ羣: 530311074 * @URL: https://onestar.newstar.net.cn/ */
public class User {

    private Long id;
    private String nickname;
    private String username;
    private String password;
    private String email;
    private String avatar;
    private Integer type;
    private Date createTime;
    private Date updateTime;

}
複製代碼

2.MD5加密

因爲後面要用到MD5加密,對登陸密碼進行加密,這裏就先進行處理一下,在com.star包下建立util工具包,用來放工具類,建立MD5Utils工具類,以下:

package com.star.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/** * @Description: MD5加密工具類 * @Date: Created in 17:16 2020/5/27 * @Author: ONESTAR * @QQ羣: 530311074 * @URL: https://onestar.newstar.net.cn/ */
public class MD5Utils {

    /** * @Description: MD5加密 * @Auther: ONESTAR * @Date: 17:19 2020/5/27 * @Param: 要加密的字符串 * @Return: 加密後的字符串 */
    public static String code(String str){
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            byte[]byteDigest = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < byteDigest.length; offset++) {
                i = byteDigest[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            //32位加密
            return buf.toString();
            // 16位的加密
            //return buf.toString().substring(8, 24);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }

    }


    public static void main(String[] args) {
        System.out.println(code("111111"));
    }

}
複製代碼

分析:

  • 經過該工具類,能夠獲取密碼,在main函數中輸入本身密碼對應的明碼,而後運行,能夠在控制檯獲取對應的密碼,這個密碼是要存儲在數據庫中的password字段
  • eg:這裏是"111111"字符串,運行main後,得到密碼爲:"96e79218965eb72c92a549dd5a330112",則將該字符串存儲進數據庫中

3.持久層接口

在com.star目錄下建立dao包,建立用戶持久層接口UserDao,這裏主要查詢用戶名和密碼,經過@Param註解將參數傳遞給SQL,代碼以下:

package com.star.dao;

import com.star.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

/** * @Description: 用戶持久層接口 * @Date: Created in 0:06 2020/5/27 * @Author: ONESTAR * @QQ羣: 530311074 * @URL: https://onestar.newstar.net.cn/ */
@Mapper
@Repository
public interface UserDao {
    /** * @Description: * @Auther: ONESTAR * @Date: 10:24 2020/5/27 * @Param: username:用戶名;password:密碼 * @Return: 返回用戶對象 */
    User findByUsernameAndPassword(@Param("username") String username, @Param("password") String password);
}
複製代碼

分析:

  • @Mapper註解:讓Mybatis找到對應的mapper,在編譯的時候動態生成代理類,實現相應SQL功能
  • @Repository註解:用來聲明dao層的bean(這個註解無關緊要,能夠消去依賴注入的報錯信息)【@Mapper和@Repository註解能夠參考這篇文章:Mybatis 中的 @Repository 與 @Mapper
  • @Param註解:將參數傳遞給SQL
  • 返回一個User對象給service調用並覈對用戶名和密碼

4.mapper

Mybatis使用XMLMMapperBuilder類的實例來解析mapper配置文件並執行SQL語句,在resources目錄下建立mapper文件夾,再建立UserDao.xml文件,以下:

<?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.star.dao.UserDao">

    <!--查詢用戶名和密碼-->
    <select id="findByUsernameAndPassword" resultType="com.star.entity.User">
        select * from myblog.t_user
        where username = #{username} and password = #{password};
    </select>

</mapper>

複製代碼

5.用戶業務層

在com.star目錄下建立service包,建立用戶業務層接口UserService,這裏主要是檢驗用戶名和密碼,傳遞用戶名和密碼兩個參數,代碼以下:

package com.star.service;

import com.star.entity.User;

/** * @Description: 用戶業務層接口 * @Date: Created in 22:56 2020/5/26 * @Author: ONESTAR * @QQ羣: 530311074 * @URL: https://onestar.newstar.net.cn/ */
public interface UserService {
    //覈對用戶名和密碼
    User checkUser(String username, String password);
}
複製代碼

用戶層接口實現類:

在service包下建立Impl包,用來放接口實現類,UserServiceImpl代碼以下:

package com.star.service.Impl;

import com.star.dao.UserDao;
import com.star.entity.User;
import com.star.service.UserService;
import com.star.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/** * @Description: 用戶業務層接口實現類 * @Date: Created in 23:01 2020/5/26 * @Author: ONESTAR * @QQ羣: 530311074 * @URL: https://onestar.newstar.net.cn/ */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    /** * @Description: * @Auther: ONESTAR * @Date: 21:25 2020/5/27 * @Param: username:用戶名;password:密碼 * @Return: 返回用戶對象 */
    @Override
    public User checkUser(String username, String password) {
        User user = userDao.findByUsernameAndPassword(username, MD5Utils.code(password));
        return user;
    }
}
複製代碼

分析:

  • 這裏主要是獲取數據庫中的用戶名和密碼,經過控制器傳遞過來的密碼進行解析匹配,匹配成功則登陸

6.登陸控制器

在controller控制器包下建立admin包,用來放用戶管理的控制器,建立LoginController用戶登陸控制器,在這裏進行登陸跳轉、登陸校驗、註銷功能,代碼以下:

package com.star.controller.admin;

import com.star.entity.User;
import com.star.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

/** * @Description: 用戶登陸控制器 * @Date: Created in 21:40 2020/5/27 * @Author: ONESTAR * @QQ羣: 530311074 * @URL: https://onestar.newstar.net.cn/ */
@Controller
@RequestMapping("/admin")
public class LoginController {

    @Autowired
    private UserService userService;

    /** * @Description: 跳轉登陸頁面 * @Auther: ONESTAR * @Date: 21:57 2020/5/27 * @Param: * @Return: 返回登陸頁面 */
    @GetMapping
    public String loginPage(){
        return "admin/login";
    }

    /** * @Description: 登陸校驗 * @Auther: ONESTAR * @Date: 10:04 2020/5/27 * @Param: username:用戶名 * @Param: password:密碼 * @Param: session:session域 * @Param: attributes:返回頁面消息 * @Return: 登陸成功跳轉登陸成功頁面,登陸失敗返回登陸頁面 */
    @PostMapping("/login")
    public String login(@RequestParam String username, @RequestParam String password, HttpSession session, RedirectAttributes attributes) {
        User user = userService.checkUser(username, password);
        if (user != null) {
            user.setPassword(null);
            session.setAttribute("user",user);
            return "admin/index";
        } else {
            attributes.addFlashAttribute("message", "用戶名和密碼錯誤");
            return "redirect:/admin";
        }
    }

    /** * @Description: 註銷 * @Auther: ONESTAR * @Date: 10:15 2020/5/27 * @Param: session:session域 * @Return: 返回登陸頁面 */
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/admin";
    }
}
複製代碼

分析:

  • @RequestMapping註解:映射請求路徑
  • 登陸校驗:將前端傳遞過來的用戶名和密碼給service進行檢驗覈對,並放入session域中(session是全局的,登陸後訪問其餘頁面或者重開頁面也是登陸狀態)
  • 登陸成功跳轉後臺管理頁面,失敗則跳轉登陸頁面
  • 登陸成功後能夠進行註銷,註銷後返回登陸頁面

運行代碼,訪問:http://localhost:8080/admin/ ,輸入用戶名和密碼,這裏要注意先將密碼進行MD5加密,將加密後的字符串存儲進數據庫。以下,登陸成功,跳轉到了後臺管理頁面

image

前端直接用thymeleaf模板處理,不作解說

7.登陸攔截器

在沒有登陸的狀況下,不能讓遊客訪問到後臺管理頁面,在這裏就須要加一個登陸攔截器,將訪問路徑給過濾掉,這裏就用SpringBoot裏面內置的interceptor,在com.star包下新建interceptor包,建立LoginInterceptor登陸過濾攔截器,繼承HandlerInterceptorAdapter適配器,重寫預處理方法,進行攔截,以下:

攔截器:

package com.star.interceptor;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** * @Description: 登陸過濾攔截 * @Author: ONESTAR * @Date: Created in 13:55 2020/3/27 * @QQ羣: 530311074 * @URL: https://onestar.newstar.net.cn/ */
public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 判斷session裏面是否有用戶,沒有的話重定向到登陸頁面,給攔截掉
        if (request.getSession().getAttribute("user") == null) {
            response.sendRedirect("/admin");
            return false;
        }
        return true;
    }
}
複製代碼

分析:

  • 繼承HandlerInterceptorAdapter適配器,重寫預處理方法preHandle
  • 對session進行判斷,看是否有用戶,沒有的話重定向到登陸頁面,給攔截掉
  • 還須要指定攔截的內容

指定攔截內容:

同級包下新建WebConfig配置類,繼承WebMvcConfigurerAdapter配置,重寫addInterceptors過濾設置,以下:

package com.star.interceptor;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/** * @Description: 指定攔截內容的配置類 * @Author: ONESTAR * @Date: Created in 13:57 2020/3/27 * @QQ羣: 530311074 * @URL: https://onestar.newstar.net.cn/ */
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                //過濾的路徑
                .addPathPatterns("/admin/**")
                .excludePathPatterns("/admin")
                .excludePathPatterns("/admin/login");
    }
}
複製代碼

分析:

  • @Configuration註解:代表是一個有效的配置類
  • 重寫addInterceptors方法
  • 指定要攔截的路徑,這裏攔截"admin"訪問路徑

攔截器完成

按照MVC架構開發,後端MVC架構目錄結構以下

image


至此,我的博客系統的後臺登陸功能實現完成,下一篇將講述博客的分類管理

【點關注,不迷路,歡迎持續關注本站】

image
相關文章
相關標籤/搜索