目录
一、数据库表准备
二、创建项目
三、整合SpringMVC
四、整合连接池
五、整合mybatis
六、启动测试
七、整合Thymeleaf
创建一个"demo"数据库,并在其中创建一张user表。我们接下来将整合项目并取出数据库user表中所有数据。
/*
Navicat MySQL Data Transfer
Source Server : dong
Source Server Version : 50642
Source Host : localhost:3306
Source Database : demo
Target Server Type : MYSQL
Target Server Version : 50642
File Encoding : 65001
Date: 2020-06-09 21:28:14
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for user_tb
-- ----------------------------
DROP TABLE IF EXISTS `user_tb`;
CREATE TABLE `user_tb` (
`userid` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) DEFAULT NULL,
`department` varchar(255) DEFAULT NULL,
`class` int(11) DEFAULT NULL,
PRIMARY KEY (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user_tb
-- ----------------------------
INSERT INTO `user_tb` VALUES ('1', '周杰伦', '音乐系', '5');
INSERT INTO `user_tb` VALUES ('2', '张无忌', '武当派', '1');
INSERT INTO `user_tb` VALUES ('3', '赵敏', '蒙古族', '3');
1、创建项目 | |
2、编写基本项目结构以及代码 | |
pom.xml
4.0.0
com.hedong
hedong
1.0.0-SNAPSHOT
org.springframework.boot
spring-boot-starter-parent
2.0.6.RELEASE
org.springframework.boot
spring-boot-starter-web
user.java
package com.hedong.pojo;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Table(name = "user_tb")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer userid;
private String username;
private String department;
private Integer classroom;
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public Integer getClassroom() {
return classroom;
}
public void setClassroom(Integer classroom) {
this.classroom = classroom;
}
}
引导类UserApplication.java
package com.hedong;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class UserApplication {
public static void main(String[] args) {
SpringApplication.run(UserApplication.class);
}
}
其实现在默认配置已经可以使用SpringMVC了,下面介绍如和访问静态资源和添加拦截器。
1、访问静态资源
我们习惯会把静态资源放在classpath:/static/
目录下。我们创建目录,并且添加一些静态资源:
启动引导类后,在浏览器中访问静态资源如下:
2、添加拦截器
在SpringBoot中,我们是通过java配置来配置拦截器,而不使用xml方式。
MyInterceptor.java
package com.hedong.interceptors;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle method is running!");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle method is running!");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion method is running!");
}
}
MyConfiguration.java
package com.hedong.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyConfiguration implements WebMvcConfigurer {
@Autowired
private HandlerInterceptor myInterceptor;
/**
* 重写接口中的addInterceptors方法,添加自定义拦截器
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor).addPathPatterns("/**");
}
}
这样自定义拦截器就配置成功了。
在pom.xml中引入jdbc的启动器:
org.springframework.boot
spring-boot-starter-jdbc
mysql
mysql-connector-java
在application.properties中指定连接池参数
# 连接四大参数
spring.datasource.url=jdbc:mysql://localhost:3306/demo
spring.datasource.username=root
spring.datasource.password=hd2503652646.
# 可省略,SpringBoot自动推断
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.hikari.idle-timeout=60000
spring.datasource.hikari.maximum-pool-size=30
spring.datasource.hikari.minimum-idle=10
在pom.xml中添加mybatis启动器
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.2
需要注意,这里没有配置mapper接口扫描包,因此我们需要给每一个Mapper接口添加@Mapper
注解,才能被识别。
在pom.xml中添加mapper启动器
tk.mybatis
mapper-spring-boot-starter
2.0.2
package com.hedong.mapper;
import com.hedong.pojo.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper extends tk.mybatis.mapper.common.Mapper {
}
UserService.java
package com.hedong.service;
import com.hedong.mapper.UserMapper;
import com.hedong.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User queryById(int id){
return this.userMapper.selectByPrimaryKey(id);
}
@Transactional
public void deleteById(int id){
this.userMapper.deleteByPrimaryKey(id);
}
}
UserController.java
package com.hedong.controller;
import com.hedong.pojo.User;
import com.hedong.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Controller
@RequestMapping("user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("{id}")
@ResponseBody
public User queryUserById(@PathVariable("id")int id){
return this.userService.queryById(id);
}
@GetMapping("/all")
public String all(ModelMap model) {
// 查询用户
List users = this.userService.queryAll();
// 放入模型
model.addAttribute("users", users);
// 返回模板名称(就是classpath:/templates/目录下的html文件名)
return "users";
}
}
启动引导类,在浏览器中输入地址
可以看到获取user成功。
在UserService.java中添加方法
public List queryAll() {
return this.userMapper.selectAll();
}
在UserController.java中添加对应方法,获取全体用户信息。
@GetMapping("/all")
public String all(ModelMap model) {
// 查询用户
List users = this.userService.queryAll();
// 放入模型
model.addAttribute("users", users);
// 返回模板名称(就是classpath:/templates/目录下的html文件名)
return "users";
}
在pom.xml中引入thymeleaf启动器
org.springframework.boot
spring-boot-starter-thymeleaf
模板默认放在classpath下的templates文件夹,我们新建一个html文件放入其中,把html 的名称空间,改成:xmlns:th="http://www.thymeleaf.org"
会有语法提示 。
users.html
首页
用户列表!
id
姓名
部门
班级
启动引导类并输入地址访问。
至此,所有内容整合结束!