目录
主要功能:实现登陆拦截,然后进入主页面进行增删改查工作,开启Druid数据源,进行durid日志监控
页面展示:
代码编写:
目录结构:
导入依赖:
配置application.yml
配置登陆拦截器以及开启durid监控
配置开启拦截功能: 创建MyMvConfig类
编写登陆拦截:创建LoginHandlerInterceptor类
配置开启durid数据源监控功能:创建DruidConfig类
编写实体类:
创建Message类: (使用了lombok插件,没有需要安装该插件或者手动生成getter和setter)
创建 User类
编写mapper类
创建MesageMapper类
创建UserMapper类
编写mapper映射文件
创建MessageMapper.xml
创建UserMapper.xml
编写实现类:
创建MessageService接口
创建MessageServiceImpl类
创建 UserService接口
创建UserServiceImpl类
编写控制类
创建UserController类
编写前端页面
创建登陆页面:login.html
创建主页面:index.html
创建添加页面:add.hhtml
创建更新页面:update.html
哈哈哈,终于到最后了,累呀
创建数据库:mybatis
然后创建数据表
到这里就大公告成了,哈哈哈
开启服务,浏览器访问:http://localhost:8080/
代码下载:https://download.csdn.net/download/qq_44716544/19697167
或者看下边教程代码(已全部贴出)
进入duird监控页面
org.springframework.boot
spring-boot-starter-jdbc
org.springframework.boot
spring-boot-starter-web
mysql
mysql-connector-java
5.1.47
runtime
org.springframework.boot
spring-boot-starter-test
test
com.alibaba
druid
1.2.5
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.1.4
org.thymeleaf
thymeleaf-spring5
org.projectlombok
lombok
1.18.20
log4j
log4j
1.2.17
org.springframework.boot
spring-boot-devtools
true
true
spring:
datasource:
username: root
password: 123
url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.jdbc.Driver
#springBoot数据库驱动默认为mysql8.0版本,使用8.0以下版本的数据库需要在pom.xml手动更改数据库驱动版本
#切换为阿里巴巴druid源
type: com.alibaba.druid.pool.DruidDataSource
# 自定义数据源
#Spring Boot 默认是不注入这些属性值的,需要自己绑定
#druid 数据源专有配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
#如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority
#则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
#关闭thymeleaf的缓存
thymeleaf:
cache: false #关闭缓存
devtools:
restart:
enabled: true #设置开启热部署
additional-paths: src/main/java #重启目录
exclude: WEB-INF/**
freemarker:
cache: false #页面不加载缓存,修改即时生效
#yml整合mybatis
mybatis:
type-aliases-package : com.chen.springbootcruddemo
mapperLocations: classpath:mapper/*.xml
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #开启mybatis日志控制台SQL打印
package com.chen.springbootcruddemo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyMvConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// registry.addViewController("/").setViewName("login");
registry.addViewController("/login.html").setViewName("login");
// registry.addViewController("/main.html").setViewName("dashboard");
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor()).
//进行拦截资源 addPathPatterns("/**").excludePathPatterns("/login.html","/","/login","/css/**","/js/**","/img/**");
}
}
package com.chen.springbootcruddemo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//登陆成功之后,应该有用户的session
Object loginUser= request.getSession().getAttribute("loginUser");
if(loginUser==null){
System.out.println("=================");
request.setAttribute("msg","没有权限,请先登录");
request.getRequestDispatcher("/login.html").forward(request,response);
return false;
}
else {
return true;
}
}
}
开启后:在浏览器打开查看监控:http://localhost:8080/druid/index.html
登陆 :admin 密码:123456
package com.chen.springbootcruddemo.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource(){
return new DruidDataSource();
}
//后台监控:web.xml,ServletRegistrationBean
//因为SpringBoot 内置了servlet容器,所以没有web.xml,替代方法
//访问:http://localhost:8080/druid
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean= new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");
//后台需要有人登录,账号密码配置
HashMap
package com.chen.springbootcruddemo.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Message {
private int id;
private String content;
private String title;
}
package com.chen.springbootcruddemo.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
}
package com.chen.springbootcruddemo.mapper;
import com.chen.springbootcruddemo.pojo.Message;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface MessageMapper {
List queryMessage();
int addMessage(Message message);
int deleteMessage(String id);
Message queryMessageById(String id);
int updateMessage(Message message);
List queryByMessage(String content);
}
package com.chen.springbootcruddemo.mapper;
import com.chen.springbootcruddemo.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
@Repository
@Mapper
public interface UserMapper {
User login(String name);
}
insert into mybatis.show (title,content) values (#{title},#{content});
delete from mybatis.show where id=#{id};
update mybatis.show set title =#{title},content=#{content} where id=#{id};
package com.chen.springbootcruddemo.service;
import com.chen.springbootcruddemo.pojo.Message;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Service;
import java.util.List;
public interface MessageService {
List queryMessage();
int addMessage(Message message);
int deleteMessage(String id);
Message queryMessageById(String id);
int updateMessage(Message message);
List queryByMessage(String content);
}
package com.chen.springbootcruddemo.service;
import com.chen.springbootcruddemo.mapper.MessageMapper;
import com.chen.springbootcruddemo.pojo.Message;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class MessageServiceImpl implements MessageService{
@Resource
MessageMapper messageMapper;
@Override
public List queryMessage() {
return messageMapper.queryMessage();
}
@Override
public int addMessage(Message message) {
return messageMapper.addMessage(message);
}
@Override
public int deleteMessage(String id) {
return messageMapper.deleteMessage(id);
}
@Override
public Message queryMessageById(String id) {
return messageMapper.queryMessageById(id);
}
@Override
public int updateMessage(Message message) {
return messageMapper.updateMessage(message);
}
@Override
public List queryByMessage(String content) {
return messageMapper.queryByMessage(content);
}
}
package com.chen.springbootcruddemo.service;
import com.chen.springbootcruddemo.pojo.User;
public interface UserService {
User login(String name);
}
package com.chen.springbootcruddemo.service;
import com.chen.springbootcruddemo.mapper.UserMapper;
import com.chen.springbootcruddemo.pojo.User;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service
public class UserServiceImpl implements UserService{
@Resource
UserMapper userMapper;
@Override
public User login(String name) {
return userMapper.login(name);
}
}
package com.chen.springbootcruddemo.controller;
import com.chen.springbootcruddemo.pojo.Message;
import com.chen.springbootcruddemo.pojo.User;
import com.chen.springbootcruddemo.service.MessageService;
import com.chen.springbootcruddemo.service.MessageServiceImpl;
import com.chen.springbootcruddemo.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.swing.text.Style;
import java.util.List;
@Controller
public class UserController {
@Resource
UserServiceImpl userService;
@Resource
MessageServiceImpl messageService;
/*
*
*
* 登陆
*
* */
@RequestMapping("/login")
//@ResponseBody
public String loginCheck(String username,String password,Model model, HttpSession session){
if(username!=null&&password!=null) {
User user = userService.login(username);
if(user!=null) {
if(user.getPwd().equals(password)) {
session.setAttribute("loginUser", username);
List messages=messageService.queryMessage();
model.addAttribute("messages",messages);
System.out.println("messsage:========"+messages);
return "redirect:/index";
}
else{
model.addAttribute("msg","密码错误");
return "login";
}
}
else{
model.addAttribute("msg","账号错误");
return "login";
}
}
else{
model.addAttribute("msg","账号或密码不能为空");
return "login";
}
}
@RequestMapping("/")
public String login(){
return "login";
}
/*
*
*
* 首页
*
* */
@RequestMapping("/index")
public String index(Model model){
List messages=messageService.queryMessage();
model.addAttribute("messages",messages);
System.out.println("messsage:========"+messages);
return "/index";
}
/*
*
* 添加页面
*
* */
@RequestMapping("/add")
public String add(){
return "/add";
}
/*
*
*
* 添加信息
*
* */
@RequestMapping("/addmessage")
public String addMessage(Message message){
int n= messageService.addMessage(message);
return "redirect:/index";
}
/*
*
* 删除信息
* */
@RequestMapping("/delete/{id}")
public String delete(@PathVariable("id") String id){
int n=messageService.deleteMessage(id);
return "redirect:/index";
}
/*
*
* 更改信息
* */
@RequestMapping("/update/{id}")
public String update(@PathVariable("id") String id,Model model){
Message message=messageService.queryMessageById(id);
model.addAttribute("message",message);
return "update";
}
/*
*
* 更改信息
* */
@RequestMapping("/update")
public String updateMessage(Message message,Model model){
int n=messageService.updateMessage(message);
return "redirect:/index";
}
/*
*
* 搜索信息
* */
@RequestMapping("/search")
public String searchMessage(String content,Model model){
List messages=messageService.queryByMessage(content);
model.addAttribute("messages",messages);
System.out.println("=========ddd"+messages);
return "index";
}
/*
*
* 搜索信息
* */
@RequestMapping("/quit")
public String quit(HttpSession session){
session.invalidate();
return "login";
}
}
登陆
首页
首页
.
id
内容
标题
操作
更改 | 删除
添加信息
添加信息
更改信息
更改信息
DROP TABLE IF EXISTS `show`;
CREATE TABLE `show` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`content` varchar(255) CHARACTER SET gbk COLLATE gbk_chinese_ci NOT NULL,
`title` varchar(255) CHARACTER SET gbk COLLATE gbk_chinese_ci NOT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 7 CHARACTER SET = gbk COLLATE = gbk_chinese_ci ROW_FORMAT = Compact;
INSERT INTO `show` VALUES (1, '测试测试', '测试');
INSERT INTO `show` VALUES (5, '123456', 'www2222222222');
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(25) CHARACTER SET gbk COLLATE gbk_chinese_ci NULL DEFAULT NULL,
`pwd` varchar(25) CHARACTER SET gbk COLLATE gbk_chinese_ci NULL DEFAULT NULL,
`perms` varchar(255) CHARACTER SET gbk COLLATE gbk_chinese_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 20 CHARACTER SET = gbk COLLATE = gbk_chinese_ci ROW_FORMAT = Compact;
INSERT INTO `user` VALUES (18, 'root', '123456', 'user:update');
INSERT INTO `user` VALUES (19, '123', '123', NULL);