Springboot项目小笔记

本文主要记录我使用 idea 搭建 springboot 项目时小功能配置

连接数据库

连接 Mysql 数据库

1
2
3
4
5
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>

连接 Oracle 数据库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.oracle.ojdbc</groupId>
<artifactId>ojdbc8</artifactId>
<scope>runtime</scope>
</dependency>
<!-- java.sql.SQLException: 不支持的字符集 (在类路径中添加 orai18n.jar): ZHS16GBK -->
<dependency>
<groupId>cn.easyproject</groupId>
<artifactId>orai18n</artifactId>
<version>12.1.0.2.0</version>
</dependency>

数据源配置

1
2
3
4
5
6
<!-- druid数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.20</version>
</dependency>

yml 文件配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!-- 连接Mysql -->
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mall_vue?serverTimezone=GMT%2b8
username: root
password: 密码

<!-- 连接Oracle -->
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: oracle.jdbc.driver.OracleDriver
url: jdbc:oracle:thin:@127.0.0.1:1521:orcl
username: scott
password: 密码

pom 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<!-- 基本的 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
<!-- 热加载 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<!-- lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- 打印日志 -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.13.1</version>
<scope>test</scope>
</dependency>

启动类上 的配置

1
2
3
4
5
6
7
8
9
@SpringBootApplication
@MapperScan("cn.blue.mall.mapper")
public class MallApplication {

public static void main(String[] args) {
SpringApplication.run(MallApplication.class, args);
}

}

Controller 上的配置

1
2
3
4
5
6
@Controller
@RequestMapping("/users")
public class UserInfoController {
@Resource
private UserInfoService userInfoService;
}

Sevice 上的配置

1
2
3
4
5
6
7
8
9
10
/**
* @author Blue
* @date 2020/3/5
**/
@Service("userInfoService")
public class UserInfoServiceImpl implements UserInfoService {
@Resource
private UserInfoMapper userInfoMapper;

}

mapper 上的配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?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="cn.blue.mall.mapper.UserInfoMapper">
<resultMap id="userInfoMapper" type="cn.blue.mall.bean.UserInfo">
<id column="ID" property="id"/>
<result column="NAME" property="name"/>
<result column="EMAIL" property="email"/>
<result column="PASSWORD" property="password"/>
<result column="STATUS" property="status"/>
<result column="TELEPHONE" property="telephone"/>
<!-- roles对应了Roles类中的 roles对象 -->
<association property="roles" column="ROLE" javaType="cn.blue.mall.bean.Roles"
select="cn.blue.mall.mapper.RolesMapper.findSetRoleByRoleId"/>
</resultMap>

<sql id="Base_Column">ID ,NAME, PASSWORD, EMAIL, TELEPHONE, ROLE, STATUS</sql>

<sql id="Base_Where">
<where>
<if test="id != null and id != ''">
AND ID=#{id}
</if>
<if test="name != null and name != ''">
AND NAME like concat(concat('%',#{name}),'%')
</if>
<if test="email != null and email != ''">
AND EMAIL=#{email}
</if>
<if test="telephone != null and telephone != ''">
AND TELEPHONE=#{telephone}
</if>
<if test="role != null">
AND ROLE=#{role}
</if>
<if test="status != null">
AND STATUS=#{status}
</if>
</where>
</sql>

<sql id="Base_Update">
<set>
<if test="name != null and name != ''">
NAME=#{name},
</if>
<if test="telephone != null and telephone != ''">
TELEPHONE=#{telephone},
</if>
<if test="email != null and email != ''">
EMAIL=#{email},
</if>
<if test="password != null and password != ''">
PASSWORD=#{password},
</if>
<if test="role != null">
ROLE=#{role},
</if>
<if test="status != null">
STATUS=#{status},
</if>
</set>
</sql>

<select id="findAll" parameterType="cn.blue.mall.bean.UserInfo"
resultMap="userInfoMapper">
SELECT
<include refid="Base_Column"/>
FROM mall_users
<include refid="Base_Where"/>
</select>

<update id="updateStatusById" parameterType="cn.blue.mall.bean.UserInfo">
UPDATE MALL_USERS
SET status = #{userInfo.status}
WHERE id=#{userInfo.id}
</update>

<insert id="addUser" parameterType="cn.blue.mall.bean.UserInfo" keyProperty="id" keyColumn="id"
useGeneratedKeys="true">
INSERT INTO MALL_USERS(ID, NAME, PASSWORD, EMAIL, TELEPHONE)
VALUES (#{id}, #{name}, #{password}, #{email}, #{telephone})
</insert>

<delete id="deleteById" parameterType="string">
DELETE FROM MALL_USERS
WHERE ID = #{id}
</delete>
</mapper>

PageHelper 分页

1
2
3
4
5
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.12</version>
</dependency>

代码示例: 前端分页,实现只需要将对应的参数传过来即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* @param pageNum 当前页码
* @param pageSize 当前每页数据量
*/
@GetMapping
@ResponseBody
public Result findAll(
@RequestParam(name = "pageNum", required = false, defaultValue = "1") Integer pageNum,
@RequestParam(name = "pageSize", required = false, defaultValue = "5") Integer pageSize,
UserInfo user) {
PageHelper.startPage(pageNum, pageSize);
List<UserInfo> list = userInfoService.findAll(null);
PageInfo<UserInfo> pageInfo = new PageInfo<>(list);
Result r = Result.success();
r.add("total", pageInfo.getTotal());
r.add("data", list);
r.setMsg("查询成功");
return r;
}

SpringBoot 的 yml 文件配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
server:
port: 80

logging:
level:
cn.blue: trace
#优先级从高至低依次为:OFF、FATAL、ERROR、WARN、INFO、DEBUG、TRACE

# layui模板里的时间格式配置
spring:
jackson:
date-format: yyyy-MM-dd HH:mm
time-zone: "GMT+8"
---
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/rbac?serverTimezone=GMT%2b8
username: root
password:

# 开发阶段关闭thymeleaf的模板缓存
thymeleaf:
cache: false

mybatis:
# 在eclipse可以这么配置
# mapper-locations: classpath:cn/blue/mapper/sqlmap/*.xml
# 在idea中mapper文件应该放在resources文件下
mapper-locations: classpath:/mapper/*.xml
configuration:
map-underscore-to-camel-case: true

# 配置别名扫描的包
type-aliases-package: com.hm.publicraise.bean

# 头像存储位置
head-img-path: classpath:/static/upload/heads

# 头像存储位置
raise-img-path: classpath:/static/upload/raises

# 富文本编辑器
ue:
server-url: /ueditor/jsp/controller

ueditor 富文本编辑器

  1. yml 文件配置
1
2
3
#  富文本编辑器
ue:
server-url: /ueditor/jsp/controller
  1. 依赖导入
1
2
3
4
5
<dependency>
<groupId>cn.jasonone.ueditor</groupId>
<artifactId>ueditor-spring-boot-starter</artifactId>
<version>1.1.4</version>
</dependency>
  1. 导入 ueditor
1
<script type="text/plain" id="editor" name="sonContent"></script>

Invalid bound statement(not found),访问不到 mapper.xml

解决方法

application 配置文件中 mybatis 配置

1
2
3
4
mybatis:
mapper-locations: classpath:/mapper/*.xml
configuration:
map-underscore-to-camel-case: true

代码正确,无法访问 controller 层方法

其他包都得放在启动类包下

拦截器

登录拦截器

1.LoginController 主要代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* 登录方法
*/
@PostMapping
public String login(UserInfo userInfo, HttpSession session) {
try {
UserInfo user = userInfoService.findOneUser(userInfo);
if (user != null) {
//存放引用常量的位置:ApplicationConst
session.setAttribute(ApplicationConst.LOGIN_SESSION_STATUS, user);
return "index";
}
} catch (Exception e) {
e.printStackTrace();
}
//重定向回去会调用controller,但是请求转发只会访问目录下的资源文件
return "redirect:/login";
}

2.LoginHandlerInterceptor 登录拦截器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Component
public class LoginHandlerInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
UserInfo user = (UserInfo) session.getAttribute(ApplicationConst.LOGIN_SESSION_STATUS);
if (user != null) {
//放行
return true;
} else {
response.sendRedirect(request.getContextPath() + "/login");
return false;
}
}
}

3.配置 WebMvcConfigurer 拦截器,将登录拦截器添加进去

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor())
//拦截所有
.addPathPatterns("/**")
//排除资源文件和登录、注销请求
.excludePathPatterns("/login", "/logout")
.excludePathPatterns("/layui/**", "/**/*.js")
.excludePathPatterns("/**/*.jpg", "/**/*.png");
}
}
打赏
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!
  1. © 2020 Liu Yang    湘ICP备20003709号

请我喝杯咖啡吧~

支付宝
微信