增加web,jdbc,mybatis,mysql相关组件
org.springframework.boot
spring-boot-starter-parent
2.2.2.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.1.1
mysql
mysql-connector-java
org.springframework.boot
spring-boot-maven-plugin
spring:
datasource:
username: root
password: root
url: jdbc:mysql://192.168.137.3:3306/springboot?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
driver-class-name: com.mysql.jdbc.Driver
mybatis:
config-location: classpath:/mybatis/mybatis-config.xml #指定主配置文件
mapper-locations: classpath:/mybatis/mapper/*.xml # 指定xml映射文件路径
type-aliases-package: com.atguigu.domain # 指定mybatis别名包
logging:
level:
com.atguigu.dao: debug # 配置日志
-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) DEFAULT NULL,
`password` varchar(50) DEFAULT NULL,
`name` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'zhangsan', '123', '张三');
INSERT INTO `user` VALUES ('2', 'lisi', '123', '李四');
public class User implements Serializable {
// 主键
private Integer id;
// 用户名
private String username;
// 密码
private String password;
// 姓名
private String name;
//此处省略getter和setter方法 .. ..
}
@Mapper
public interface UserDao{
public List findAll();
}
注意:
@Mapper标记该类是一个mybatis的mapper接口,可以被spring boot自动扫描到spring上下文中
在resource文件夹下面新建 /mybatis/mapper/UserDao.xml 加入配置
public interface UserService {
List findAll();
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public List findAll() {
return userDao.findAll();
}
}
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/findAll")
public List findAll(){
return userService.findAll();
}
}
/**
* @MapperScan(basePackages = "com.atguigu.dao")
* 扫描指定包下的所有Mapper接口,将动态代理的实现类对象注入Spring容器中
* basePackages属性:指定扫描的包路径地址
* 作用相当于:
*
*
*
*/
@MapperScan("com.atguigu.dao")
@SpringBootApplication
public class SpringBoot03Application {
public static void main(String[] args) {
SpringApplication.run(SpringBoot03Application.class, args);
}
}
com.alibaba
druid
1.1.12
spring:
datasource:
username: root
password: root
url: jdbc:mysql://192.168.137.3:3306/atcrowdfunding?useSSL=false&useUnicode=true&characterEncoding=UTF-8
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBoot03ApplicationTests {
@Autowired
DataSource dataSource;
/*
* HikariDataSource 默认数据源,性能很高
* DruidDataSource 使用很高,很稳定
*/
@Test
public void contextLoads() throws SQLException {
System.out.println(dataSource.getClass());
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
}
3.1扫描Dao接口,需要在主程序类中增加扫描注解@MapperScan("com.atguigu.**.dao")及事务管理@EnableTransactionManagement
3.2传统的SSM架构中采用的是声明式事务,需要在配置文件中增加AOP事务配置,Spring Boot框架中简化了这种配置,可以在Service接口中增加注解@Transactional
org.springframework.boot
spring-boot-starter-parent
2.2.2.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-starter-data-jpa
mysql
mysql-connector-java
mysql
mysql-connector-java
logging:
level:
com.atguigu.dao: debug # 配置日志
spring:
datasource:
username: root
password: root
url: jdbc:mysql://127.0.0.1:3306/springboot?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
driver-class-name: com.mysql.jdbc.Driver
jpa:
#指定数据库提供商
database: mysql
#打印SQL
show-sql: true
#是jpa层面对数据表生成策略的控制
generate-ddl: true
hibernate:
#是jpa实现hibernate层面上对数据表生成策略的控制
ddl-auto: update
#指定命名策略
naming_strategy: org.hibernate.cfg.ImprovedNamingStrategy
main:
allow-bean-definition-overriding: true
server:
port: 18081
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name = "user")
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
@Column(name = "username")
private String username;
@Column(name = "password")
private String password;
@Column(name = "name")
private String name;
//此处省略setter和getter方法... ...
}
import com.atguigu.domain.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserDao extends JpaRepository {
}
package com.atguigu.service;
import com.atguigu.domain.User;
import java.util.List;
public interface UserService {
List findUsers();
User findUserById(Integer id);
void saveUser(User user);
void updateUser(User user);
void deleteUserById(Integer id);
}
import com.atguigu.dao.UserDao;
import com.atguigu.domain.User;
import com.atguigu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
/**
* 查询所有
*/
@Override
public List findUsers() {
return userDao.findAll();
}
/**
* 根据id查询
*/
@Override
public User findUserById(Integer id) {
return userDao.findById(id).get();
}
/**
* 保存
*/
@Override
public void saveUser(User user) {
userDao.save(user);
}
/**
* 更新
*/
@Override
public void updateUser(User user) {
userDao.save(user);
}
/**
* 根据id删除
*/
@Override
public void deleteUserById(Integer id) {
userDao.deleteById(id);
}
}
import com.atguigu.domain.User;
import com.atguigu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/findUsers")
public List findUsers(){
return userService.findUsers();
}
@RequestMapping("/findUserById/{id}")
public User findUserById(@PathVariable("id") Integer id) {
return userService.findUserById(id);
}
@RequestMapping("/saveUser")
public void saveUser(User user) {
userService.saveUser(user);
}
@RequestMapping("/updateUser")
public void updateUser(User user) {
userService.updateUser(user);
}
@RequestMapping("/deleteUserById/{id}")
public void deleteUserById(@PathVariable("id") Integer id) {
userService.deleteUserById(id);
}
}
org.springframework.boot
spring-boot-starter-data-redis
在application.yml文件添加redis的配置信息
mybatis:
type-aliases-package: com.atguigu.domain # 指定mybatis别名包
mapper-locations: classpath:com/atguigu/dao/*.xml # 指定xml映射文件路径
logging:
level:
com.atguigu.dao: debug # 配置日志
spring:
datasource:
username: root
password: root
url: jdbc:mysql://127.0.0.1:3306/springboot?useUnicode=true&characterEncoding=utf8
driver-class-name: com.mysql.jdbc.Driver
redis:
port: 6379
host: 127.0.0.1
server:
port: 18081
注入redisTemplate测试redis操作
在service的试下类里面实现业务逻辑
import com.atguigu.dao.UserDao;
import com.atguigu.domain.User;
import com.atguigu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Autowired
private RedisTemplate redisTemplate;
@Override
public List findAll() {
// redis的key
String key = "alluser";
// 先查询redis中是否有数据,如果有直接返回redis的数据
List users = (List) redisTemplate.boundValueOps(key).get();
if (users!=null) {
System.out.println("从Redis中获取缓存数据="+users);
return users;
}
// 如果没有,查询数据库
users = userDao.findAll();
// 将数据库数据存入到redis中
if (users != null && users.size()>0) {
System.out.println("从数据库中获取数据存放到Redis缓存="+users);
redisTemplate.boundValueOps(key).set(users);
}
return users;
}
}
org.springframework.boot
spring-boot-starter-parent
2.2.2.RELEASE
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.springframework
spring-context-support
5.0.5.RELEASE
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class BootApplication {
public static void main(String[] args) {
SpringApplication.run(BootApplication.class, args);
}
}
import java.text.SimpleDateFormat;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
@Component
public class TaskController {
/**
* @Scheduled:定时规则
* cron:项目启动后每5秒执行一次
*
* fixedDelay:距离上一次定时任务执行完毕后N毫秒再执行,
* 执行A任务花了5秒,比如参数是3000,A任务执行完成之后,再过3秒执行
*
* fixedRate:执行周期,执行频率
* 定时任务执行开始,再过N毫秒后执行,
* 执行A任务花了2秒,比如参数是3000,A任务执行完成之后,再过1秒后执行,
* 执行A任务花了15秒,比如参数是3000,A任务执行完成之后,立即执行。
*/
@Scheduled(fixedDelay = 3000)
public void myTask() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(simpleDateFormat.format(new Date()));
}
}
上面并没有列举所有SpringBoot支持的页面模板技术。其中Thymeleaf是SpringBoot官方所推荐使用的
在应用开发中,你可以使用Thymeleaf来完全代替JSP
Thymeleaf:Thymeleaf是一个模板引擎工具,主要用于页面渲染操作(页面数据填充操作),可以取代之前的jsp操作。
创建一个独立的工程springboot-thymeleaf
pom.xml依赖
org.springframework.boot
spring-boot-starter-parent
2.2.2.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-devtools
true
org.springframework.boot
spring-boot-maven-plugin
创建html
Thymeleaf的入门
创建 application.yml ,并设置 thymeleaf 的缓存设置,设置为false
spring:
thymeleaf:
cache: false
开启自动编译
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/test")
public class TestController {
/***
* 访问/test/hello 跳转到demo1页面
*/
@RequestMapping("/hello")
public String hello(Model model){
model.addAttribute("hello","hello welcome");
return "demo1";
}
}
创建启动类ThtmeleafApplication,代码如下:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ThymeleafApplication {
public static void main(String[] args) {
SpringApplication.run(ThymeleafApplication.class,args);
}
}
定义后台控制器路径,类似
例如:修改刚刚 demo01.html 页面
import java.io.Serializable;
public class User implements Serializable {
private Integer id;
private String name;
private String address;
//省略..get..set toString
public User(Integer id, String name, String address) {
this.id = id;
this.name = name;
this.address = address;
}
public User() {
}
import com.atguigu.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.ArrayList;
import java.util.List;
@Controller
@RequestMapping("/test")
public class TestController {
/***
* 访问/test/hello 跳转到demo1页面
*/
@RequestMapping("/hello")
public String hello(Model model){
model.addAttribute("hello","hello welcome");
//集合数据
List users = new ArrayList();
users.add(new User("张三","123","张三"));
users.add(new User("李四","123","李四"));
users.add(new User("王五","123","王五"));
model.addAttribute("users",users);
return "demo1";
}
}
Thymeleaf的入门
下标
用户名
密码
姓名
import com.atguigu.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("/test")
public class TestController {
/***
* 访问/test/hello 跳转到demo1页面
*/
@RequestMapping("/hello")
public String hello(Model model){
//Map定义
Map dataMap = new HashMap();
dataMap.put("No","123");
dataMap.put("address","深圳");
model.addAttribute("dataMap",dataMap);
return "demo1";
}
}
Thymeleaf的入门
方式1
获取Key=NO的值:
获取key=address的值:
方式2
:
后台添加数组
import com.atguigu.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("/test")
public class TestController {
/***
* 访问/test/hello 跳转到demo1页面
*/
@RequestMapping("/hello")
public String hello(Model model){
//存储一个数组
String[] names = {"张三","李四","王五"};
model.addAttribute("names",names);
return "demo1";
}
}
页面输出
==============================================
后台添加日期
import com.atguigu.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.*;
@Controller
@RequestMapping("/test")
public class TestController {
/***
* 访问/test/hello 跳转到demo1页面
*/
@RequestMapping("/hello")
public String hello(Model model){
//日期
model.addAttribute("now",new Date());
return "demo1";
}
}
Thymeleaf的入门
import com.atguigu.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.*;
@Controller
@RequestMapping("/test")
public class TestController {
/***
* 访问/test/hello 跳转到demo1页面
*/
@RequestMapping("/hello")
public String hello(Model model){
//if条件
model.addAttribute("age",22);
return "demo1";
}
}
Thymeleaf的入门
终于长大了!
成年人
fragment
关于我们
Thymeleaf的入门
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class HelloListener implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("应用销毁了....HelloListener");
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("应用启动了....HelloListener");
}
}
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
@WebFilter(urlPatterns="/*")
public class HelloFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
throws IOException, ServletException {
System.out.println("HelloFilter............放行之前");
arg2.doFilter(arg0, arg1);
System.out.println("HelloFilter............放行之后");
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns="/my")
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("MyServlet do.......");
}
}
@ServletComponentScan
@MapperScan("com.atguigu.mapper")
@SpringBootApplication
public class SpringBoot03Application {
public static void main(String[] args) {
SpringApplication.run(SpringBoot03Application.class, args);
}
}