2021-6-22:开发小而美的博客(后台登录)
文章目录
后台管理
登录
1. 构建登录页面和后台管理首页
2. UserService和UserRepositiory
3. LoginController实现登录
4. MD5加密
5. 登录拦截器
1、构建登录页面
参考官网: http//sesmantic-ui.com
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head th:replace="admin/_fragments :: head(~{::title})">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>博客管理登录</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/semantic-ui/2.2.4/semantic.min.css">
<link rel="stylesheet" href="../../static/css/me.css">
</head>
<body>
<br>
<br>
<br>
<div class="m-container-small m-padded-tb-massive" style="max-width: 30em !important;">
<div class="ur container">
<div class="ui middle aligned center aligned grid">
<div class="column">
<h2 class="ui teal image header">
<div class="content">
管理后台登录
</div>
</h2>
<form class="ui large form" method="post" action="#" th:action="@{/admin/login}">
<div class="ui segment">
<div class="field">
<div class="ui left icon input">
<i class="user icon"></i>
<input type="text" name="username" placeholder="用户名">
</div>
</div>
<div class="field">
<div class="ui left icon input">
<i class="lock icon"></i>
<input type="password" name="password" placeholder="密码">
</div>
</div>
<button class="ui fluid large teal submit button">登 录</button>
</div>
<div class="ui error mini message"></div>
<div class="ui mini negative message" th:unless="${#strings.isEmpty(message)}" th:text="${message}">用户名和密码错误</div>
</form>
</div>
</div>
</div>
</div>
<!--/*/<th:block th:replace="_fragments :: script">/*/-->
<script src="https://cdn.jsdelivr.net/npm/jquery@3.2/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/semantic-ui/2.2.4/semantic.min.js"></script>
<!--/*/</th:block>/*/-->
<script>
$('.ui.form').form({
fields : {
username : {
identifier: 'username',
rules: [{
type : 'empty',
prompt: '请输入用户名'
}]
},
password : {
identifier: 'password',
rules: [{
type : 'empty',
prompt: '请输入密码'
}]
}
}
});
</script>
</body>
</html>
效果展示
2、博客管理页面
登录进去后就进入的页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head th:replace="admin/_fragments :: head(~{::title})">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>博客管理</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/semantic-ui/2.2.4/semantic.min.css">
<link rel="stylesheet" href="../../static/css/me.css">
</head>
<body>
<!--导航-->
<nav th:replace="admin/_fragments :: menu(0)" class="ui inverted attached segment m-padded-tb-mini m-shadow-small" >
<div class="ui container">
<div class="ui inverted secondary stackable menu">
<h2 class="ui teal header item">管理后台</h2>
<a href="#" class="active m-item item m-mobile-hide"><i class="mini home icon"></i>博客</a>
<a href="#" class=" m-item item m-mobile-hide"><i class="mini idea icon"></i>分类</a>
<a href="#" class="m-item item m-mobile-hide"><i class="mini tags icon"></i>标签</a>
<div class="right m-item m-mobile-hide menu">
<div class="ui dropdown item">
<div class="text">
<img class="ui avatar image" src="https://unsplash.it/100/100?image=1005">
奈一
</div>
<i class="dropdown icon"></i>
<div class="menu">
<a href="#" th:href="@{/admin/logout}" class="item">注销</a>
</div>
</div>
</div>
</div>
</div>
<a href="#" class="ui menu toggle black icon button m-right-top m-mobile-show">
<i class="sidebar icon"></i>
</a>
</nav>
<!--中间内容-->
<div class="m-container-small m-padded-tb-big">
<div class="ui container">
<div class="ui success large message">
<h3>Hi,</h3>
<p>奈一,欢迎登录!</p>
</div>
<img src="https://unsplash.it/1000/400?image=1005" alt="" class="ui rounded bordered fluid image">
</div>
</div>
<br>
<br>
<!--底部footer-->
<footer th:replace="admin/_fragments :: footer" class="ui inverted vertical segment m-padded-tb-massive">
<div class="ui center aligned container">
<div class="ui inverted divided stackable grid">
<div class="three wide column">
<div class="ui inverted link list">
<div class="item">
<img src="../../static/images/wechat.jpg" class="ui rounded image" alt="" style="width: 110px">
</div>
</div>
</div>
<div class="three wide column">
<h4 class="ui inverted header m-text-thin m-text-spaced " >最新博客</h4>
<div class="ui inverted link list">
<a href="#" class="item m-text-thin">用户故事(User Story)</a>
<a href="#" class="item m-text-thin">用户故事(User Story)</a>
<a href="#" class="item m-text-thin">用户故事(User Story)</a>
</div>
</div>
<div class="three wide column">
<h4 class="ui inverted header m-text-thin m-text-spaced ">联系我</h4>
<div class="ui inverted link list">
<a href="#" class="item m-text-thin">Email:lirenmi@163.com</a>
<a href="#" class="item m-text-thin">QQ:2448923662</a>
</div>
</div>
<div class="seven wide column">
<h4 class="ui inverted header m-text-thin m-text-spaced ">Blog</h4>
<p class="m-text-thin m-text-spaced m-opacity-mini">这是我的个人博客、会分享关于编程、写作、思考相关的任何内容,希望可以给来到这儿的人有所帮助...</p>
</div>
</div>
<div class="ui inverted section divider"></div>
<p class="m-text-thin m-text-spaced m-opacity-tiny">Copyright © 2016 - 2017 Lirenmi Designed by Lirenmi</p>
</div>
</footer>
<!--/*/<th:block th:replace="_fragments :: script">/*/-->
<script src="https://cdn.jsdelivr.net/npm/jquery@3.2/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/semantic-ui/2.2.4/semantic.min.js"></script>
<!--/*/</th:block>/*/-->
<script>
$('.menu.toggle').click(function () {
$('.m-item').toggleClass('m-mobile-hide');
});
$('.ui.dropdown').dropdown({
on : 'hover'
});
</script>
</body>
</html>
效果展示
3、新建service包
3.1、新建UserService接口
检查用户名和密码
3.2、新建UserServiceImpl接口实现
package net.lhf.service;
import net.lhf.dao.UserRepository;
import net.lhf.po.User;
import net.lhf.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* 功能:
* 作者:李红芙
* 日期:2021年6月23日
*/
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Override
public User checkUser(String username, String password) {
User user = userRepository.findByUsernameAndPassword(username, MD5Utils.code(password));
return user;
}
}
4、新建dao包
4.1、新建UserRepository类
5、新建admin包
存放关于后台管理的web
5.1、新建LoginController类
package net.lhf.web.admin;
import net.lhf.po.User;
import net.lhf.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;
/**
* 功能:
* 作者:李红芙
* 日期:2021年6月23日
*/
@Controller
@RequestMapping("/admin")
public class LoginController {
@Autowired
private UserService userService;
@GetMapping
public String loginPage() {
return "admin/login";
}
@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";
}
}
@GetMapping("/logout")
public String logout(HttpSession session) {
session.removeAttribute("user");
return "redirect:/admin";
}
}
6、在数据库中写入数据
7、运行测试
点击登录时没有反应,把登录改成button
就可以进行登录了
9、MD5加密
9.1、新建util包
9.2、新建MD5Utils类
package net.lhf.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* 功能:
* 作者:李红芙
* 日期:2021年6月23日
*/
public class MD5Utils {
/**
* MD5加密类
* @param str 要加密的字符串
* @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("123"));
}
}
9.3、运行加密方法
9.4、复制加密密码到数据库
10、登录拦截器
10.1、新建BlogController类
package net.lhf.web.admin;
import net.lhf.po.Blog;
import net.lhf.po.User;
import net.lhf.service.BlogService;
import net.lhf.service.TagService;
import net.lhf.service.TypeService;
import net.lhf.vo.BlogQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.servlet.http.HttpSession;
/**
* 功能:
* 作者:李红芙
* 日期:2021年6月23日
*/
@Controller
@RequestMapping("/admin")
public class BlogController {
private static final String INPUT = "admin/blogs-input";
private static final String LIST = "admin/blogs";
private static final String REDIRECT_LIST = "redirect:/admin/blogs";
@Autowired
private BlogService blogService;
@Autowired
private TypeService typeService;
@Autowired
private TagService tagService;
@GetMapping("/blogs")
public String blogs(@PageableDefault(size = 8, sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable,
BlogQuery blog, Model model) {
model.addAttribute("types", typeService.listType());
model.addAttribute("page", blogService.listBlog(pageable, blog));
return LIST;
}
@PostMapping("/blogs/search")
public String search(@PageableDefault(size = 8, sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable,
BlogQuery blog, Model model) {
model.addAttribute("page", blogService.listBlog(pageable, blog));
return "admin/blogs :: blogList";
}
@GetMapping("/blogs/input")
public String input(Model model) {
setTypeAndTag(model);
model.addAttribute("blog", new Blog());
return INPUT;
}
private void setTypeAndTag(Model model) {
model.addAttribute("types", typeService.listType());
model.addAttribute("tags", tagService.listTag());
}
@GetMapping("/blogs/{id}/input")
public String editInput(@PathVariable Long id, Model model) {
setTypeAndTag(model);
Blog blog = blogService.getBlog(id);
blog.init();
model.addAttribute("blog",blog);
return INPUT;
}
@PostMapping("/blogs")
public String post(Blog blog, RedirectAttributes attributes, HttpSession session) {
blog.setUser((User) session.getAttribute("user"));
blog.setType(typeService.getType(blog.getType().getId()));
blog.setTags(tagService.listTag(blog.getTagIds()));
Blog b;
if (blog.getId() == null) {
b = blogService.saveBlog(blog);
} else {
b = blogService.updateBlog(blog.getId(), blog);
}
if (b == null ) {
attributes.addFlashAttribute("message", "操作失败");
} else {
attributes.addFlashAttribute("message", "操作成功");
}
return REDIRECT_LIST;
}
@GetMapping("/blogs/{id}/delete")
public String delete(@PathVariable Long id,RedirectAttributes attributes) {
blogService.deleteBlog(id);
attributes.addFlashAttribute("message", "删除成功");
return REDIRECT_LIST;
}
}
11、运行查看
12、新建interceptor包
12.1、新建LoginInterceptor类
package net.lhf.interceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 功能:
* 作者:李红芙
* 日期:2021年6月23日
*/
public class LoginInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
if (request.getSession().getAttribute("user") == null) {
response.sendRedirect("/admin");
return false;
}
return true;
}
}
12.1、新建LoginInterceptor类
配置类
package net.lhf.interceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* 功能:
* 作者:李红芙
* 日期:2021年6月23日
*/
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new net.lhf.interceptor.LoginInterceptor())
.addPathPatterns("/admin/**")
.excludePathPatterns("/admin")
.excludePathPatterns("/admin/login");
}
}