IDEA2019+-maven3.5.4+jdk8
springBoot+ mybatis + thymeleaf+Redis+mysql
完整项目源码:
https://download.csdn.net/download/qq_24892029/15073299
一、创建项目
1.File->new->project;
2.选择“Spring Initializr”,点击next;(jdk1.8默认即可)
3.完善项目信息,组名可不做修改,项目名可做修改;最终建的项目名为:test,src->main->java下包名会是:com->example->test;点击next;
4.Web下勾选Spring Web Start,(网上创建springboot项目多是勾选Web选项,而较高版本的Springboot没有此选项,勾选Spring Web Start即可,2.1.8版本是Spring Web);Template Englines勾选Thymeleaf;SQL勾选:MySQL Driver,JDBC API 和 MyBatis Framework三项;点击next;
5.选择项目路径,点击finish;打开新的窗口;
6.刚创建好的项目目录结构
7.点击右侧的Maven,点击设置(扳手图标)进行项目Maven仓库的配置;
8.(1)选择本地Maven路径;(2)勾选配置文件后边的选项,然后修改为本地Maven的配置文件,它会根据配置文件直接找到本地仓库位置;
9.配置完后,如果没有自动导包,可以点击左上角重新导包按钮,或者呢个下载按钮,选择下载所有源文件和文档
二:简单构建与配置
1.在templates文件下新建index.html页面,作为启动的初始页面;
2.在com.example.test下新建controller文件夹,在controller文件夹下建一个简单的helloController类;(Controller类要添加@Controller注解,项目启动时,SpringBoot会自动扫描加载Controller)
package com.example.test.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class helloController {
@RequestMapping("/index")
public String sayHello(){
return "index";
}
}
3.在resources文件夹下application中先配置DataSource基本信息,application文件有两种文件格式,一种是以.properties为后缀,一种是以.yml为后缀的,两种配置方式略有差别,详情可参考这个网址:https://blog.csdn.net/qq_29648651/article/details/78503853;在这我是用.yml后缀的文件格式。右键application文件选择Refact,选择Rename,将后缀改为yml;
spring:
datasource:
name: test #数据库名
url: jdbc:mysql://localhost:3306/test #url
username: root #用户名
password: 123456 #密码
driver-class-name: com.mysql.jdbc.Driver #数据库链接驱动
4.运行项目启动类TestApplication.java
5.在进行下一步编写时,我们先来链接一下数据库;点击右侧的Database,点“加号”,新建数据库链接;
6.填写数据库相关信息,点击Test Connection;
7.如果链接失败可能是驱动的问题,点击左上角的小扳手,进入数据库设置界面
8.连接成功后,显示数据库信息,user表的基本信息也显示了,下面就照这个来了;
三:SpringBoot代码展示
1.SpringBoot项目大概分为四层:
(1)DAO层:包括XxxMapper.java(数据库访问接口类),XxxMapper.xml(数据库链接实现);(这个命名,有人喜欢用Dao命名,有人喜欢用Mapper,看个人习惯了吧)
(2)Bean层:也叫model层,模型层,entity层,实体层,就是数据库表的映射实体类,存放POJO对象;
(3)Service层:也叫服务层,业务层,包括XxxService.java(业务接口类),XxxServiceImpl.java(业务实现类);(可以在service文件夹下新建impl文件放业务实现类,也可以把业务实现类单独放一个文件夹下,更清晰)
(4)Web层:就是Controller层,实现与web前端的交互。
依照上面四层,创建目录结构如下:
2.代码展示:
(1)在application配置文件中添加MyBatis配置:
mybatis:
mapper-locations: classpath:mapper/*.xml #配置映射文件
type-aliases-package: com.example.test.bean #配置实体类
(2)pom.xml文件配置信息
配置文件中未指定数据库连接的jar包的版本号,用version标签引入
<version>5.1.41</version>
(3)Bean实体类,依据数据库表,生成set和get方法;
package com.example.test.bean;
public class UserBean {
private int id;
private String name;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
(4)DAO层访问数据库接口文件:
package com.example.test.mapper;
import com.example.test.bean.UserBean;
@Repository
public interface UserMapper {
UserBean getInfo(String name,String password);
}
(5)DAO层访问数据库实现文件(需在resource包下创建mapper文件夹,然后再创建一个UserMapper.xml.在application配置文件中mybatis:mapper-locations:对应的就是该文件地址),注意<mapper>标签的namespace属性要填写 访问数据库接口类文件路径:
<?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.example.test.mapper.UserMapper">
<select id="getInfo" parameterType="String" resultType="com.example.test.bean.UserBean">
SELECT * FROM user WHERE name = #{name} AND password = #{password}
</select>
</mapper>
(6)Service层业务接口类编写:
package com.example.test.service;
import com.example.test.bean.UserBean;
@Service
public interface UserService {
UserBean loginIn(String name,String password);
}
(7)Service层业务实现类编写,注意要注解@Service,注入DAO:
package com.example.test.serviceImpl;
import com.example.test.bean.UserBean;
import com.example.test.mapper.UserMapper;
import com.example.test.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
//将DAO注入Service层
@Autowired
private UserMapper userMapper;
@Override
public UserBean loginIn(String name, String password) {
return userMapper.getInfo(name,password);
}
}
(8)项目启动类要添加注解@MapperScan项目启动时扫描mapper接口,否则会报错找不到mapper文件:
package com.example.test;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.example.test.mapper")
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
(9)编写测试类,看是否能成功 访问数据库,获取数据库信息:
package com.example.test;
import com.example.test.bean.UserBean;
import com.example.test.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestApplicationTests {
@Autowired
UserService userService;
@Test
public void contextLoads() {
UserBean userBean = userService.loginIn("a","a");
System.out.println("该用户ID为:");
System.out.println(userBean.getId());
}
}
(10) controller层,注意添加@controller注解,注入Service服务:
package com.example.test.controller;
import com.example.test.bean.UserBean;
import com.example.test.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class LoginController {
//将Service注入Web层
@Autowired
UserService userService;
@RequestMapping("/login")
public String show(){
return "login";
}
@RequestMapping(value = "/loginIn",method = RequestMethod.POST)
public String login(String name,String password){
UserBean userBean = userService.loginIn(name,password);
if(userBean!=null){
return "success";
}else {
return "error";
}
}
}
(11)html文件:
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
</head>
<body>
<form role="form" action = "/loginIn" method="post">
账号:<input type="text" id="name" name = "name"> <br>
密码:<input type="password" id = "password" name = "password"> <br>
<input type="submit" id = "login" value = "login">
</form>
</body>
</html>
success.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>success</title>
</head>
<body>
<h1>登录成功!</h1>
</body>
</html>
error.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>error</title>
</head>
<body>
<h1>登录失败!</h1>
</body>
</html>
application.yml
server:
port: 80
spring:
datasource:
name: world #数据库名
url: jdbc:mysql://:3306/world?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&characterEncoding=UTF-8 #url
username: root
password: 123
driver-class-name: com.mysql.jdbc.Driver
mybatis:
mapper-locations: classpath:mapper/*.xml #配置映射文件
type-aliases-package: com.example.test.bean #配置实体类
四:项目集成Redis
1:安装Redis
Redis中文教程:https://www.redis.net.cn/tutorial/3503.html
2:引入方式,新建common模块
新建模块common,这个模块不需要启动,因此只建成maven项目就可以,用来存放redis的配置.(在我们实战项目中,common是必不可少的一个模块,里面可以存放各种工具类,DateUtil、StringUtil、MapUtil等等,也可以存放不常修改的类,比如常量类Constant,枚举类Enum等等)
(1)
(2) groupid命名与其他项目一致
3:配置Redis
(1)pom.xml文件引入redis配置,以及key与value序列化的依赖
<?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>
<groupId>com.example</groupId>
<artifactId>common</artifactId>
<version>1.0-SNAPSHOT</version>
<!--redis配置,以及key与value序列化的依赖 开始-->
<dependencies>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.8.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.10.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.3</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>9.0.41</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
(2)编写RedisConfig配置类,主要是修改其默认的序列化方式,默认序列化方式为JdkSerializationRedisSerializer,编码格式为ISO-8859-1,值在传递过程中会出现乱码,将其修改为StringRedisSerializer,其编码方式为UTF-8,可解决乱码问题,这里写的比较简单,在实际项目中存储key,value的时候,可能存储对象的场景较多,序列化方式也会有所改变
package com.example.common.redisCfg;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
// 设置value的序列化规则和 key的序列化规则
redisTemplate.setValueSerializer(new StringRedisSerializer());
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
(3)一个常量类
package com.example.common.constants;
public class Constants {
//缓存时效-10秒
public static int CACHE_EXP_TEN_SECONDS = 10;
//缓存时效-1分钟
public static int CACHE_EXP_MINUTE = 60;
//缓存时效-永久有效
public static int CACHE_EXP_FOREVER = 0;
}
(4)编写RedisClient工具类,在这里我也就只写两个简单的设置key与value和通过key获取value的方法,在实际项目中需要许许多多,可以根据自己需求自行编写。
package com.example.common.redisCfg;
import com.example.common.constants.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@Component
public class RedisClient {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
/**
* 设置指定 key 的值
*
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean set(String key, Object value, long time) {
try {
if (time == Constants.CACHE_EXP_FOREVER) {
redisTemplate.opsForValue().set(key, value);
} else {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 获取指定 key 的值
*
* @param key 键
* @return 值
*/
@SuppressWarnings("unchecked")
public <T> T get(String key) {
return key == null ? null : (T) redisTemplate.opsForValue().get(key);
}
}
(5)在resource文件下application.properties(如果没有,自行创建)添加redis配置
# 数据库索引(默认为0)
spring.redis.database = 1
# 服务器地址
spring.redis.host = 127.0.0.1
# 服务器连接端口
spring.redis.port = 6379
# 服务器连接密码(默认为空)
spring.redis.password =
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait = -1
# 连接超时时间(毫秒)
spring.redis.timeout = 2000
# 连接池最大连接数
spring.redis.jedis.pool.max-active = 4
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle = 4
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle = 1
(6)在test项目的pom文件中添加common模块作为redis依赖
<dependency>
<groupId>com.example</groupId>
<artifactId>common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
(7)编写redis测试方法
package com.example.test.service;
public interface RedisService {
String sayHello(String s);
void setValue(String key,Object value,long time);
String getValue(String key);
}
package com.example.test.serviceImpl;
import com.example.common.redisCfg.RedisClient;
import com.example.test.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class RedisServiceImpl implements RedisService {
@Autowired
private RedisClient redisClient;
@Override
public String sayHello(String s) {
System.out.println("qk say:" + s);
return s;
}
/**
* 设置key,value存入redis
* @param key
* @param value
* @param time
*/
@Override
public void setValue(String key, Object value, long time) {
redisClient.set(key, value, time);
}
/**
* 根据key获取value
*
* @param key
* @return
*/
@Override
public String getValue(String key) {
return redisClient.get(key) == null ? "redis key time out" : redisClient.get(key);
}
}
package com.example.test.controller;
import com.example.common.constants.Constants;
import com.example.test.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/RedisTestControl")
public class RedisTestControl {
@Autowired
private RedisService redisService;
@GetMapping("/hello")
public void sayHello(){
String str = redisService.sayHello("Not hello, just hi. ");
System.out.println("consumer get str = " + str + " from provide");
}
@GetMapping("/setValue")
public String setValue(String key, String value){
//设置key有效时间为10s,便于测试
redisService.setValue(key,value, Constants.CACHE_EXP_TEN_SECONDS);
return "key: " + key +" value: " + value;
}
@GetMapping("/getValue")
public String getValue(String key){
return redisService.getValue(key);
}
}
http://127.0.0.1:8888/RedisTestControl/setValue?key=hi&value=qk
http://127.0.0.1:8888/RedisTestControl/getValue?key=hi
完整项目源码: