loginController
@RequestMapping ("/login")
@RestController
@Configuration
@EnableWebSecurity
public class LoginController {
@Resource
private UserDetailServiceImpl userDetailServiceImpl;
@Bean
AuthenticationManager authenticationManager(HttpSecurity httpSecurity) throws Exception {
return httpSecurity.getSharedObject(AuthenticationManagerBuilder.class)
.userDetailsService(userDetailServiceImpl)
.passwordEncoder(passwordEncoder())
.and()
.build();
}
/**
* 过滤器链
*
* @param authenticationManager 身份验证管理器
* @param http http
* @return {@link SecurityFilterChain}
* @throws Exception 异常
*/
@Bean
public SecurityFilterChain filterChain(AuthenticationManager authenticationManager, HttpSecurity http) throws Exception {
return http
.authorizeRequests()
.antMatchers("/add","/adduser")
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/admin/login")
.loginProcessingUrl("/admin/login")
.permitAll()
.successHandler((request, response, authentication) -> {
response.setContentType("application/json;charset=utf-8");
response.getWriter().write("{\"code\":200,\"msg\":\"登录成功\"}");
}).failureHandler((request, response, exception) -> {
response.setContentType("application/json;charset=utf-8");
response.getWriter().write("{\"code\":500,\"msg\":\"登录失败\"}");
})
.and()
.logout()
.logoutSuccessUrl("/logoutSuccess")
.permitAll()
.and()
.csrf().disable()
.headers().frameOptions().disable()
.and()
.build();
}
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring().antMatchers("/layui/**");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(); // 使用BCrypt加密
}
}
RouterController
@Controller
public class RouterController {
@RequestMapping("/")
public String index(){
return "index";
}
@RequestMapping("/admin/login")
public String login (){
return "login";
}
@RequestMapping("/logoutSuccess")
public String logoutSuccess(){
return "logout";
}
@RequestMapping("/add")
public String add(){
return "add";
}
}
addcontroller
@RestController
public class AddController {
@Resource
private AdminService adminService;
@RequestMapping("/adduser")
public Boolean addUser (Admin admin){
adminService.addUsers(admin);
return true;
}
}
TreeMenuController
@RequestMapping("/list")
@RestController
public class TreeMenuController {
@Resource
private TreeMenuService TreeMenuService;
@RequestMapping("/menu")
public List<TreeMenu>TreeMenu (){
Admin admin = (Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
List<TreeMenu> list = TreeMenuService.selectMenuByRoleId(admin.getRoleId());
return list;
}
}
adminmapper
public interface AdminMapper {
@Select("select * from admin where account = #{account}")
Admin selectById(String account) ;
@Select("insert into admin value (#{id},#{account},#{password},#{roleId})")
Boolean addUser(Admin admin);
@Select("update admin set account = #{account},password = #{password},role_id = #{roleId} where account = #{account}")
Boolean updateUser(Admin admin);
}
TreeMenuMappeer
public interface TreeMenuMapper {
@Select("select menu.* FROM treemenu menu inner join role_treemenu rm on menu.id = rm .menu_id where rm .role_id = #{roleId}")
List<TreeMenu> selectMenuByRoleId (Integer roleId);
}
AdminServiceImpl
public class AdminServiceImpl implements AdminService {
@Resource
private AdminMapper adminMapper;
@Override
public Admin selectById(String account) {
return adminMapper.selectById(account);
}
@Override
public Boolean addUsers(Admin admin) {
// 密码加密
String newPassword = new BCryptPasswordEncoder().encode(admin.getPassword());
admin.setPassword(newPassword);
return adminMapper.addUser(admin);
}
}
TreeMenuServiceImpl
@Service
public class TreeMenuServiceImpl implements TreeMenuService {
@Resource
TreeMenuMapper treeMenuMapper;
@Override
public List<TreeMenu> selectMenuByRoleId(Integer roleId) {
return treeMenuMapper.selectMenuByRoleId(roleId);
}
}
UserDetailServiceImpl
@Service
public class UserDetailServiceImpl implements UserDetailsService {
@Resource
private AdminService adminService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Admin admin= adminService.selectById(username);
return admin;
}
}
AdminService
public interface AdminService {
Admin selectById(String account);
Boolean addUsers(Admin admin);
}
TreeMenuService
public interface TreeMenuService {
List<TreeMenu> selectMenuByRoleId (Integer roleId);
}
ADD.html
html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册title>
head>
<body>
input your id:<input id="id">input>
<br>
input your username:<input id="username">input>
<br>
input your password:<input type =password id="password">input>
<br>
input your roleid:<input id="role_id">
<br>
<button onclick="add()">注册button>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js">script>
<script>
function add(){
var username = $("#username").val();
var password = $("#password").val();
var id = $("#id").val();
var role_id = $("#role_id").val();
// ajax 请求登录接口跳转首页
$.ajax({
url: '/adduser',
type: 'post',
dataType: 'json',
data: {
id:id,
account:username,
password:password,
roleId:role_id
},
success: function (data) {
if (data==true) {
window.location = "/login";
alert("注册成功,请重新登录!");
}else alert("注册失败,请重新输入信息!");
}, error: function (data) {
console.log(data);
}
});
}
script>
body>
html>
jiazai
<script>
function jiazai(){
$.ajax({
url: "/list/menu",
type: "get",
success: function (data) {
if (data){ // 如果有数据
var html = "";
for (const tr of data){
html += ""+tr.name+""+tr.url+""
}
$("#table").html(html);
}
}
})
}
script>
denglu
<script>
function denglu(){
var username = $("#username").val();
var password = $("#password").val();
// ajax 请求登录接口跳转首页
$.ajax({
url: '/admin/login',
type: 'post',
dataType: 'json',
data: {
username:username,
password:password
},
success: function (data) {
if (data.code == 200) {
window.location = "/";
} else {
alert("登录失败");
}
}, error: function (data) {
console.log(data);
}
});
}
script>
yum install java-1.8.0-openjdk-devel -y
java -jar loginDemo.jar
nohup java -jar yytest5.jar &
curl 常用的参数
curl -X POST -d "username=admin&password=123456" http://localhost:8080/login
curl -L http://localhost:8080/logout
-X/--request [GET|POST|PUT|DELETE|…] 使用指定的http method发出 http request
-H/--header 设定request里的header
-i/--include 显示response的header
-d/--data 设定 http parameters
-v/--verbose 輸出比较多的信息
-u/--user 使用者账号
-b/--cookie cookie 文件路径 使用cookie
#spring.datasource.url=jdbc:mysql://10.1.1.30:3306/manager_system
spring.datasource.url=jdbc:mysql://localhost:3306/manager_system
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=YangY657X+
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
# mybatis ????????
mybatis.configuration.map-underscore-to-camel-case=true
数据库
/*
Navicat Premium Data Transfer
Source Server : localhost_3306
Source Server Type : MySQL
Source Server Version : 80030 (8.0.30)
Source Host : localhost:3306
Source Schema : manager_system
Target Server Type : MySQL
Target Server Version : 80030 (8.0.30)
File Encoding : 65001
Date: 23/03/2023 03:16:08
*/
/**
如果需要导入的数据库不存在,需要先创建数据库
*/
CREATE DATABASE IF NOT EXISTS `manager_system` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for admin
-- ----------------------------
DROP TABLE IF EXISTS `admin`;
CREATE TABLE `admin` (
`id` int NOT NULL AUTO_INCREMENT,
`account` varchar(32) COLLATE utf8mb4_bin NOT NULL DEFAULT '' COMMENT '账号',
`password` varchar(100) COLLATE utf8mb4_bin NOT NULL COMMENT '密码',
`role_id` int DEFAULT '-1' COMMENT '角色ID',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
-- ----------------------------
-- Records of admin
-- ----------------------------
BEGIN;
INSERT INTO `admin` (`id`, `account`, `password`, `role_id`) VALUES (1, 'admin', '$2a$10$U3XImY9eYKEe9faMgVzpc..MLjYYH3Ci4..i0WNrhQYR3JkgtptL.', 1);
COMMIT;
-- ----------------------------
-- Table structure for role
-- ----------------------------
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL DEFAULT '' COMMENT '名称',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
-- ----------------------------
-- Records of role
-- ----------------------------
BEGIN;
INSERT INTO `role` (`id`, `name`) VALUES (1, 'ROLE_admin');
COMMIT;
-- ----------------------------
-- Table structure for role_treemenu
-- ----------------------------
DROP TABLE IF EXISTS `role_treemenu`;
CREATE TABLE `role_treemenu` (
`id` int NOT NULL AUTO_INCREMENT,
`role_id` int DEFAULT NULL COMMENT '角色ID',
`menu_id` int DEFAULT NULL COMMENT '菜单ID',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
-- ----------------------------
-- Records of role_treemenu
-- ----------------------------
BEGIN;
INSERT INTO `role_treemenu` (`id`, `role_id`, `menu_id`) VALUES (1, 1, 1);
INSERT INTO `role_treemenu` (`id`, `role_id`, `menu_id`) VALUES (2, 1, 2);
INSERT INTO `role_treemenu` (`id`, `role_id`, `menu_id`) VALUES (3, 1, 3);
COMMIT;
-- ----------------------------
-- Table structure for treemenu
-- ----------------------------
DROP TABLE IF EXISTS `treemenu`;
CREATE TABLE `treemenu` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL DEFAULT '' COMMENT '名称',
`url` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
-- ----------------------------
-- Records of treemenu
-- ----------------------------
BEGIN;
INSERT INTO `treemenu` (`id`, `name`, `url`) VALUES (1, '首页', '/home');
INSERT INTO `treemenu` (`id`, `name`, `url`) VALUES (2, '控制台', '/console');
COMMIT;
SET FOREIGN_KEY_CHECKS = 1;