一、工程创建
1.1、需求分析
通过Spring Boot+MyBatis整合实现一个对user表的CRUD。
1.2、pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.4</version>
<relativePath/>
</parent>
<groupId>com.by</groupId>
<artifactId>Springboot_MyBatis</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.0</version>
</dependency>
</dependencies>
<build>
<!-- 如果不添加此节点src/main/java目录下的所有配置文件都会被漏掉。 -->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
</build>
</project>
1.3、application.properties
数据源配置文件
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
1.4、启动类
package com.by;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan("com.by.mapper")
@SpringBootApplication
public class SpringBootMyBatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootMyBatisApplication.class);
}
}
二、登录
PageController
package com.by.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class PageController {
@RequestMapping("/")//启动默认至登录页
public String showLogin(){
return "login";
}
}
UserController
package com.by.controller;
import com.by.pojo.User;
import com.by.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpSession;
import java.util.List;
@Controller
@RequestMapping("user")
public class UserController {
@Autowired
UserService userService;
/**
* 登录
* @param nam
* @param pwd
* @return
*/
@RequestMapping("login")
public String login(String nam, String pwd, HttpSession session){
User user = userService.login(nam, pwd);
if (user==null){
return "login";
}else {
session.setAttribute("user",user);
return "redirect:selectUser";
}
}
}
Service
package com.by.service;
import com.by.pojo.User;
import java.util.List;
public interface UserService {
User login(String nam,String pwd);
}
package com.by.service;
import com.by.mapper.UserMapper;
import com.by.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserMapper userMapper;
@Override
public User login(String nam, String pwd) {
return userMapper.login(nam,pwd);
}
}
Mapper
package com.by.mapper;
import com.by.pojo.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface UserMapper {
User login(@Param("nam") String nam, @Param("pwd") String pwd);
}
<?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.by.mapper.UserMapper">
<select id="login" resultType="com.by.pojo.User">
select * from user where nam=#{nam} and pwd=#{pwd}
</select>
</mapper>
三、Spring Boot整合拦截器
3.1、添加拦截器
package com.by.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Object user = request.getSession().getAttribute("user");
if (user!=null){
return true;
}
response.sendRedirect("/");
return false;
}
}
3.2、配置拦截器
package com.by.config;
import com.by.converter.DateConverter;
import com.by.interceptor.LoginInterceptor;
import org.springframework.format.FormatterRegistry;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Component
public class MyConfig implements WebMvcConfigurer {
//重写addInterceptors 添加需要拦截的路径addPathPatterns和不需要拦截的.excludePathPatterns
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/user/*").excludePathPatterns("/user/login");
}
}
四、新增用户
Controller
package com.by.controller;
import com.by.pojo.User;
import com.by.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpSession;
import java.util.List;
@Controller
@RequestMapping("user")
public class UserController {
@Autowired
UserService userService;
/**
* 新增用户
* @param user
* @return
*/
@RequestMapping("addUser")
public String addUser(User user){
userService.addUser(user);
return "redirect:selectUser";
}
/**
* 跳转新增
* @return
*/
@RequestMapping("toAddUser")
public String toAddUser(){
return "add";
}
Service
package com.by.service;
import com.by.pojo.User;
import java.util.List;
public interface UserService {
void addUser(User user);
}
package com.by.service;
import com.by.mapper.UserMapper;
import com.by.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserMapper userMapper;
@Override
public void addUser(User user) {
userMapper.InsertUser(user);
}
}
Mapper
package com.by.mapper;
import com.by.pojo.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface UserMapper {
void InsertUser(User user);
}
<?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.by.mapper.UserMapper">
<insert id="InsertUser" parameterType="com.by.pojo.User">
insert into user(nam,pwd,sex,birth) values(#{nam},#{pwd},#{sex},#{birth})
</insert>
</mapper>
五、Spring Boot整合日期转换器
引入pom依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.0</version>
</dependency>
创建日期转换器
package com.by.converter;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.core.convert.converter.Converter;
import java.util.Date;
public class DateConverter implements Converter<String, Date> {
@Override
public Date convert(String s) {
String[] patterns=new String[]{
"yyyy-MM-dd"
};
try {
//通过org.apache.commons.lang3.time.DateUtils工具类进行转换
Date date= DateUtils.parseDate(s,patterns);
return date;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
配置日期转换器
package com.by.config;
import com.by.converter.DateConverter;
import com.by.interceptor.LoginInterceptor;
import org.springframework.format.FormatterRegistry;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Component
public class MyConfig implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new DateConverter());
}
}
六、页面HTML
引入thymeleaf启动器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
在resources下建templates包写html
add.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>添加用户</title>
</head>
<body>
<h3>新增用户</h3>
<hr/>
<form th:action="@{/user/addUser}" method="post">
姓名:<input type="text" name="nam"/><br/>
密码:<input type="text" name="pwd"/><br/>
性别:<input type="radio" name="sex" value="1"/>女
<input type="radio" name="sex" value="0"/>男<br/>
生日:<input type="text" name="birth"/><br/>
<input type="submit" value="确定"/><br/>
</form>
</body>
</html>
login.html
<html>
<head>
<meta charset="UTF-8">
<title>注册</title>
</head>
<body>
<center>
<h3>登录</h3>
<hr/>
<form th:action="@{/user/login}" method="post">
账号:<input type="text" name="nam"/><br/>
密码:<input type="text" name="pwd"/><br/>
<input type="submit" value="确定"/><br/>
</form>
</center>
</body>
</html>