博客地址:ONESTARの客棧
源碼領取方式一:
- 掃一掃文末二維碼,關注公眾號【編程日刊】,后台回復【博客】,即可領取源碼
源碼領取方式二:
以jpa為持久層源碼地址:https://github.com/oneStarLR/myblog-jpa
以mybatis為持久層源碼地址:https://github.com/oneStarLR/myblog-mybaits
歡迎給star以鼓勵(^_−)☆
本文將從MVC架構、MD5加密、登錄攔截器來講述個人博客系統的后台登錄實現
MVC架構
后台開發采用的是MVC架構,MVC 全名是 Model View Controller,是模型(model)-視圖(view)-控制器(controller)的縮寫, 是一種用於設計創建 Web 應用程序表現層的模式。MVC 中每個部分各司其職:
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加密,將加密后的字符串存儲進數據庫。如下,登錄成功,跳轉到了后台管理頁面
前端直接用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架構目錄結構如下
至此,個人博客系統的后台登錄功能實現完成,下一篇將講述博客的分類管理
【點關注,不迷路,歡迎持續關注本站】