SpringBoot时候Spring全新框架,用来简化Spring的创建与开发,它简化了SSM框架。
完全抛弃了xml配置,使用大量默认配置简化开发过程。
SpringBoot创建项目,让编码、部署、配置、监控变得简单。
快速创建Spring应用程序
用java main 方法启动内嵌的tomcat运行SpringBoot程序,不需要部署war文件
提供start pom 简化maven配置
自动化配置,根据maven依赖,自动配置Spring、SpringMVC等。
提供健康检查功能
基本不使用xml配置文件,用注解配置
自动配置、起步依赖、Actuator(健康检查)、命令行界面
创建空项目:
new - Project - Empty Project - next - 文件名及项目位置 - finish
创建module:
new - module - Spring initializr - next -添加项目的信息 - next
添加依赖 - next - finish
选择依赖Spring web
父工程、我的项目:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.5.RELEASE</version>
<relativePath/>
</parent>
<groupId>com.spring</groupId>
<artifactId>001-springboot-first</artifactId>
<version>1.0.0</version>
依赖:
spring web、test、插件
<!--SpringBoot框架web项目起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--SpringBoot框架web项目测试起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<!--SpringBoot项目打包编译的创建-->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
001-springboot-first
new - module - Spring initializr - next -添加项目的信息 - next - 添加依赖 - next -finish
<!--SpringBoot框架web项目起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
默认端口号为8080
启动SpringBoot
进入启动类,点击启动按钮
重启成功
创建module后,
@Controller
public class IndexController {
@RequestMapping("/say")
public @ResponseBody String say(){
return "hello,SpringBoot";
}
}
启动启动类后,直接访问
http://localhost:8080/say
003-springboot-contextpath项目
#设置内嵌tomcat端口
server.port=8081
#设置上下文根(包名)
server.servlet.context-path=/springboot
004-springboot-properties-yml项目
application.properties,application.yaml与application.yml,都是SpringBoot配置文件,配置格式不一样而已
application.yaml与application.yml一样。
#yml、yaml
server:
port: 8081
servlet:
context-path: /
pom还是
SpringBoot启动依赖、test、插件
启动类启动,访问
http://localhost:8081/say?message=123
SpringBoot配置文件properties与yaml都存在,以properties优先
005-springboot-both-properties-yml项目
006-springboot-multi-environment项目
工作环境:开发环境、测试环境、准生产环境、生产环境
dev、test、ready、pro
配置不同端口号,不同的context-path
主配置文件中application.properties 选择要激活哪一个
如 spring.profiles.active=dev
application-dev.properties、application-product.properties、application-ready-product.properties、application-test.properties
#开发环境的配置文件
server.port=8081
server.servlet.context-path=/dev
#生产环境的开发环境
server.port=8084
server.servlet.context-path=/product
#准生产开发环境的配置文件
server.port=8083
server.servlet.context-path=/ready
#测试环境的配置文件
server.port=8082
server.servlet.context-path=/test
application.properties
#springboot主核心配置文件
#激活使用的配置文件(值等于谁,端口号、上下文根就是谁)
#spring.profiles.active=test
spring.profiles.active=dev
# spring.profiles.active=ready
# spring.profiles.active=product
spring.profiles.active不同值,表示不同开发环境
007-springboot-multi-environment-yml
#主配置文件的配置文件
#激活配置文件
spring:
profiles:
active: dev
#开发环境的配置文件
server:
port: 8081
servlet:
context-path: /dev
#生产环境的配置文件
server:
port: 8084
servlet:
context-path: /product
#准备生产环境的配置文件
server:
port: 8083
servlet:
context-path: /ready
#测试环境的配置文件
server:
port: 8082
servlet:
context-path: /test
008-springboot-custom-configuration项目
application.properties
#设置内嵌tomcat的端口号
server.port=8081
#上下文的根
server.servlet.context-path=/
school.name=浙江大学
website=http://www.zhejiang.com
MyController
@Controller
public class MyController {
@Value("${school.name}")
private String schoolName;
@Value("${website}")
private String website;
@RequestMapping("/say")
@ResponseBody
public String say(){
return "hello,springboot,008"+schoolName+","+website;
}
}
009-springboot-configuration2项目
server.port=8081
server.servlet.context-path=/
school.name=Peking collage
school.website=http://beijing.com
/**
* @功能描述:@Component:把类创建对象交给spring容器
* @ConfigurationProperties(prefix = "school"),把类设为配置类,指定配置文件的前缀(school)
*/
@Component
@ConfigurationProperties(prefix = "school")
public class School {
private String name;
private String website;
public School() {
}
set、get方法
}
MyController
/**
* @功能描述:@Controller:把控制器对象交给spring容器创建
* @Autowired:注入引用类型
*/
@Controller
public class MyController {
@Autowired
private School school;
@RequestMapping(value = "/say")
@ResponseBody
public String say(){
return "hello,springboot,009"+school.getName()+","+school.getWebsite();
}
}
<!--添加@ConfigurationProperties,警告提示-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
010-springboot-jsp项目
引入springboot内部tomcat对jsp解析依赖
<!--引入springboot内部tomcat对jsp解析依赖,必须添加-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
配置src/main/webapp到META-INF/resources
<resources>
<!--springboot前端引擎默认thymeleaf-->
<!--配置springboot集成jsp、编译jsp的路径-->
<resource>
<!--源文件、指定编译的位置、指定源文件夹中要编译的文件-->
<directory>src/main/webapp</directory>
<targetPath>META-INF/resources</targetPath>
<includes>
<include>*.*</include>
</includes>
</resource>
</resources>
#视图解析器
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp
@Controller
public class MyController {
// @RequestMapping(value = "some")
@RequestMapping(value = "/some")
public ModelAndView say(){
System.out.println("some请求");
ModelAndView mv = new ModelAndView();
mv.addObject("message","springboot");
mv.setViewName("show");//视图解析器可以用
System.out.println("some1请求");
return mv;
}
}
添加springboot起步依赖、test、mysql驱动、mybatis整合springboot的起步依赖、
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--mybatis整合springboot的起步依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<resources>
<!--手动指定文件夹为resources-->
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml
<!--mybatis代码自动生成插件-->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.6</version>
<configuration>
<!-- mybatis用于生成代码的配置文件 -->
<configurationFile>src/main/resources/mybatis-generator/GeneratorMapper.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
<!--添加配置跳过测试-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
model,即实体类
mapper:dao(使用逆行工程)
MyBatis逆向工程生成实体类、映射文件、dao接口
ResultMap作用:当表与实体类属性不一致,进行转换;级联查询
逆向工程文件GeneratorMapper.xml
resources/mybatis-generator/GeneratorMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- 1.指定连接数据库的JDBC驱动包所在位置,指定到你本机的完整路径,需确保本地路径下存在该jar -->
<classPathEntry location="E:\jar\mysql-connector-java-5.1.4.jar"/>
<!-- 配置table表信息内容体,targetRuntime指定采用MyBatis3的版本 -->
<context id="tables" targetRuntime="MyBatis3">
<!--序列化-->
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
<!--以下需要插件 -->
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--2. 配置数据库连接信息 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/springboot"
userId="root"
password="root">
</jdbcConnection>
<!-- 3.生成model类,targetPackage指定model类的包名, targetProject指定生成的model放在eclipse的哪个工程下面-->
<!-- <javaModelGenerator targetPackage="com.bj.springboot.model" targetProject="src/main/java">-->
<javaModelGenerator targetPackage="com.springboot.model" targetProject="src/main/java">
<property name="enableSubPackages" value="false" />
<property name="trimStrings" value="false" />
</javaModelGenerator>
<!-- 4.生成MyBatis的Mapper.xml文件,targetPackage指定mapper.xml文件的包名, targetProject指定生成的mapper.xml放在eclipse的哪个工程下面 -->
<!-- <sqlMapGenerator targetPackage="com.bj.springboot.mapper" targetProject="src/main/java">-->
<sqlMapGenerator targetPackage="com.springboot.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- 5.生成MyBatis的Mapper接口类文件,targetPackage指定Mapper接口类的包名, targetProject指定生成的Mapper接口放在eclipse的哪个工程下面 -->
<!-- <javaClientGenerator type="XMLMAPPER" targetPackage="com.bj.springboot.mapper" targetProject="src/main/java">-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.springboot.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 6.数据库表名及对应的Java模型类名 -->
<table tableName="t_student" domainObjectName="Student"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="false"/>
</context>
</generatorConfiguration>
<!--1.注意E:盘必须有jar包,目前版本号是mysql驱动版本,其他版本号不知道是否可以。
2.驱动、地址不能改。
改的是地址中localhost为192.168...
数据库名可以修改。
3.3、4、5中的targetPackage,根据实际情况添加package路径(项目包名)
4.6中有多少个表就有多少个配置
-->
我的mysql版本是mysql-connector-java-5.1.4,
如果是高版本:mysql-connector-java-8.0.22.jar
<classPathEntry location="E:\jar\mysql-connector-java-8.0.22.jar"/>
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/springboot?userUnicode=true;characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true"
userId="root"
password="123456">
</jdbcConnection>
@Service
public class StudentServiceImpl implements StudentService {
@Resource
private StudentMapper studentMapper;
@Override
public Student queryStudent(Integer id) {
Student student = studentMapper.selectByPrimaryKey(id);
System.out.println("service的查询id方法");
return student;
}
}
@Controller
public class MyController {
@Resource
private StudentService studentService;
@RequestMapping("/query")
@ResponseBody
public Object queryStudentById(Integer id) {
Student student = studentService.queryStudent(id);
System.out.println("student= "+student);
return student;
}
}
@SpringBootTest
class ApplicationTests {
@Autowired
private StudentMapper studentMapper;
@Test
void contextLoads() {
Student student = studentMapper.selectByPrimaryKey(1);
System.out.println(student);
}
}
application.properties
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?userUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
## spring.datasource.url=jdbc:mysql://localhost:3306/springboot 如果失败使用上面的spring.datasource.url
spring.datasource.username=root
spring.datasource.password=root
mysql高版本
#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#spring.datasource.url=jdbc:mysql://localhost:3306/springboot?
userUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
014-springboot-mybatis-2项目
把mapper放入resources下的mapper下
application.properties
#配置扫描dao的mapper文件(xxxMapper.xml)
mybatis.mapper-locations=classpath:mapper/*.xml
有了此配置后,mapper.xml不用添加@Mapper注解,pom不用手动指定resources
启动类添加
扫描dao的包
@MapperScan(basePackages = "com.springboot.dao")
1、两个注解:@Mapper,@MapperScan
@Mapper在每个dao接口上,扫描Dao接口
@MapperScan启动类上,扫描dao包
2、mapper映射文件存放位置,2个
1)、dao接口、mapper.xml放在src/main/java/dao下
需要手动pom文件配置resources,目的就是指定src/main/java也是resources资源路径
<resources>
<!--手动指定文件夹为resources-->
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml
2)、将mapper映射文件放到resources的mapper下(dao接口与mapper文件分开发)
将mapper映射文件放到resources的mapper下,需要在properties配置文件指明mapper的位置、启动类扫描dao接口
mybatis.mapper-locations=classpath:mapper/*.xml
@MapperScan(basePackages = "com.springboot.dao")
015-springboot-transaction项目
事务是一个完整的功能、业务
事务与DML的SQL语句有关系。即增删改
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentMapper studentMapper;
@Override
@Transactional
public int updateStudentById(Student student) {
int num = studentMapper.updateByPrimaryKeySelective(student);
int i=10/0;
return num;
}
}
通过int i=10/0;异常,查看事务是否有效
@SpringBootApplication
@MapperScan(basePackages = "com.springboot.dao")
@EnableTransactionManagement //开启事务(加不加都可以)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
System.out.println("015springboot事务的启动类");
}
}
写controller等
测试:
http://localhost:8080/update?id=2&name=ww
@RestController注解
用在controller类上,是@RequestBody+@Controller
作用:控制器所有方法的返回值为JSON对象
@GetMapping(value="/some")
控制器方法的get提交,
类似于
@RequestMapping(value = “/select”,method = RequestMethod.GET )
@PostMapping(value = “/insert”)类似于@RequestMapping(value = “/insert”,method = RequestMethod.POST )
@DeleteMapping(value = “/delete”)类似于 @RequestMapping(value = “/delete”,method = RequestMethod.DELETE )
@PutMapping(value = “/update”)类似于@RequestMapping(value = “/update”,method = RequestMethod.PUT )
017-springboot-RESTful
RESTful风格表示一种请求的风格,它携带参数。它让访问更简单
如正常的访问
http://localhost:8080/boot/order?id=1&name=2
使用RESTful风格后,http://localhost:8080/boot/order/02/1
查看代码,使用 @RequestMapping
@RequestMapping(value="/student/detail/{id}/{name}")
public Object student0(@PathVariable("id") Integer id,@PathVariable("name") String name){
Map<String, Object> map = new HashMap<>();
map.put("id",id);
map.put("name",name);
System.out.println("方法1");
return map;
}
问题:直接使用 @RequestMapping会分不清参数类型,会产生问题
解决:
使用增删改查
@GetMapping、@PostMapping、@DeleteMapping、@PutMapping
请求参数的位置
如 @PostMapping(value="/student/detail/{id}/{name}")与 @PostMapping(value="/student/{id}/detail/{name}")不一样
注意:
请求路径用名词
分页、排序等不能 / 传参
传的参数不是数据库的字段,不能用 /
@GetMapping(value="/student/detail/{id}/{name}")
public Object student2(@PathVariable("id") Integer id,@PathVariable("name") String name){
Map<String, Object> map = new HashMap<>();
map.put("id",id);
map.put("name",name);
System.out.println("方法2");
return map;
}
@PostMapping(value="/student/detail/{id}/{name}")
public Object student3(@PathVariable("id") Integer id,@PathVariable("name") String name){
Map<String, Object> map = new HashMap<>();
map.put("id",id);
map.put("name",name);
System.out.println("方法3");
return map;
}
@PostMapping(value="/student/{id}/detail/{name}")
public Object student4(@PathVariable("id") Integer id,@PathVariable("name") String name){
Map<String, Object> map = new HashMap<>();
map.put("id",id);
map.put("name",name);
System.out.println("方法4");
return map;
}
启动启动类、访问
@GetMapping(value="/student/detail/{id}/{name}")
使用:http://localhost:8080/student/detail/1/www
@PostMapping、@DeleteMapping、@PutMapping需要使用postMan进行访问。因为浏览器仅仅支持get请求
018-springboot-redis
redis有四种数据,String、hash、list、zset
org.springframework.boot
spring-boot-starter-data-redis
在这里插入代码片
#redis配置信息
spring.redis.host=
spring.redis.port=
spring.redis.password=
@RestController
public class MyController {
@Autowired
private StudentService studentService;
@RequestMapping("/put")
public Object put(String key, String value) {
studentService.put(key, value);
return "值已经放入Redis";
}
@RequestMapping("/get")
public Object get() {
String count= studentService.get("count");
return "数据count为: "+count;
}
}
//redis有四种数据,String、hash、list、zset
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private RedisTemplate<String,String> redisTemplate;
@Override
public void put(String key, String value) {
// redisTemplate.opsForValue(); String
// redisTemplate.opsForHash(); hash
// redisTemplate.opsForList(); list
// redisTemplate.opsForZSet(); zset
redisTemplate.opsForValue().set(key,value);
}
@Override
public String get(String key) {
String count = redisTemplate.opsForValue().get(key);
return count;
}
}
接口工程:存放实体类、业务方法
服务提供者:业务接口的实现类,把服务暴露且注册到注册中心。调用dao数据持久层
服务消费者:处理浏览器客户端的请求,从注册中心调用提供者的服务
019-springboot-dubbo-interface:注册中心
020-springboot-dubbo-provider:服务提供者
021-springboot-dubbo-consumer:消费者
这三个项目是一起的,即dubbo集成springboot
实现原理:消费者为处理器,注册中心为业务接口、服务提供者为业务层实现类
三者通过@service、@Reference连接,
启动类开启dubbo、 @EnableDubboConfiguration
除了接口工程是maven项目,其他都是Springboot项目
接口工程:019-springboot-dubbo-interface
new - module - maven -(不选webapp,啥也不选) - next -next - finish
服务提供者:020-springboot-dubbo-provider
new - module - Spring Initializr - next -next - finish
服务消费者:021-springboot-dubbo-consumer
new - module - Spring Initializr - next -next - finish
仅仅提供service接口,即业务方法接口
public interface StudentService {
Integer queryAllStudentsCount();
}
pom啥也没有
仅仅有实现类 ServiceImpl,即业务接口的实现类
<!--Dubbo集成springboot框架起步依赖-->
<dependency>
<groupId>com.alibaba.spring.boot</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<!--注册中心-->
<dependency>
<groupId>com.101tec</groupId>
<artifactId>zkclient</artifactId>
<version>0.10</version>
</dependency>
<!-- 接口工程-->
<dependency>
<groupId>com.springboot</groupId>
<artifactId>019-springboot-dubbo-interface</artifactId>
<version>1.0.0</version>
</dependency>
#设置内嵌tomcat端口、设置上下文的根
server.port=8081
server.servlet.context-path=/
#设置dubbo配置、声明当前工程为一个服务提供者、设置注册中心zookeeper
spring.application.name=020-springboot-dubbo-provider
spring.dubbo.server=true
spring.dubbo.registry=zookeeper://192.168.56.10:2181
import com.alibaba.dubbo.config.annotation.Service;
import com.springboot.service.StudentService;
import org.springframework.stereotype.Component;
//@Service:是Alibaba的注解。com.alibaba.dubbo.config.annotation.Service;
@Component
@Service(interfaceClass = StudentService.class,version = "1.0.0",timeout = 15000)
public class StudentServiceImpl implements StudentService {
@Override
public Integer queryAllStudentsCount() {
//用dao
return 1000;
}
}
mapper的映射文件放到resources的mapper下
#mapper配置文件的路径
mybatis.mapper-locations=classpath:mapper/*.xml
#设置内嵌tomcat端口
server.port=8080
#设置上下文的根
server.servlet.context-path=/
#设置dubbo配置
spring.application.name=021-springboot-dubbo-consumer
#设置注册中心
spring.dubbo.registry=zookeeper://192.168.56.10:2181
import com.alibaba.dubbo.config.annotation.Reference;
import com.springboot.service.StudentService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/*
@Reference:alibaba的。com.alibaba.dubbo.config.annotation.Reference;
*/
@RestController
public class MyController {
@Reference(interfaceClass =StudentService.class,version = "1.0.0",check = false)
private StudentService studentService;
@RequestMapping("/student")
public Object studentCount(){
Integer num= studentService.queryAllStudentsCount();
return num;
}
}
提供者:
Service实现类中,类上加@Component、@Service
@Service是阿里巴巴的
消费者:
controller上,
@Reference是阿里巴巴的,注入远程的Service实现类
提供者、消费者 开启dubbo功能
Springboot集成dubbo、Spring、SpringMVC、MyBatis、Redis、jsp
接口工程: 023-springboot-dubbo-ssm-interface
服务提供者:024-springboot-dubbo-ssm-provider
服务消费者:025-sringboot-dubbo-ssm-consumer
接口工程:是maven项目,不选择webapp,其他啥也不选
服务提供者、服务消费者为Springboot项目
逆向工程之后
接口工程:把实体类、service接口 放入接口工程。实体类需要序列化
服务提供者:把dao、mapper文件、service实现类放入provider,mapper文件放入resources的mapper下
服务消费者:pom添加接口工程的jar包。
依赖:
springboot起步依赖、mysql驱动、mybatis集成springboot起步依赖、dubbo集成springboot的起步依赖、注册中心zkclient、接口工程、springboot集成Redis、mybatis代码自动生成插件
<!-- springboot起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--逆向工程需要mysql驱动、mybatis集成springboot起步依赖-->
<!--1.mybatis集成springboot起步依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<!--2.mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- dubbo集成springboot的起步依赖-->
<dependency>
<groupId>com.alibaba.spring.boot</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<!--注册中心-->
<dependency>
<groupId>com.101tec</groupId>
<artifactId>zkclient</artifactId>
<version>0.10</version>
</dependency>
<!--接口工程-->
<dependency>
<groupId>com.springboot</groupId>
<artifactId>023-springboot-dubbo-ssm-interface</artifactId>
<version>1.0.0</version>
</dependency>
<!--springboot集成Redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--mybatis代码自动生成插件-->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.6</version>
<configuration>
<!-- mybatis用于生成代码的配置文件 -->
<configurationFile>generator/GeneratorMapper.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
<!--添加配置跳过测试-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
#配置内嵌tomcat的端口号、上下文的根
server.port=8081
server.servlet.context-path=/
#配置扫描dao的mapper文件(xxxMapper.xml)
mybatis.mapper-locations=classpath:mapper/*.xml
#连接数据库
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root
#设置dubbo、声明当前工程为服务提供者、设置注册中心
spring.application.name=024-springboot-dubbo-ssm-provider
spring.dubbo.server= true
#spring.dubbo.registry=zookeeper://localhost:2181
spring.dubbo.registry=zookeeper://192.168.56.10:2181
#dubbo.registry.check=false
dubbo.protocol.name=dubbo
dubbo.protocol.port=20880
#设置Redis的host、port、密码
spring.redis.host=192.168.56.10
spring.redis.port=6379
#spring.redis.password=football
import com.alibaba.dubbo.config.annotation.Service;
import com.springboot.dao.StudentMapper;
import com.springboot.entity.Student;
import com.springboot.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
//@Service:是Alibaba的注解。com.alibaba.dubbo.config.annotation.Service;
//@Service(interfaceClass = StudentService.class,version = "1.0.0",timeout = 15000)
@Component
@Service(interfaceName = "com.springboot.service.StudentService",version = "1.0.0",timeout = 15000)
public class StudentServiceImpl implements StudentService {
@Autowired
StudentMapper studentMapper;
@Autowired
private RedisTemplate<Object,Object> redisTemplate;
@Override
public Student queryStudentById(Integer id) {
Student student = studentMapper.selectByPrimaryKey(id);
return student;
}
@Override
public Integer queryAllStudentCount() {
//从redis获取值
Integer studentCount = (Integer) redisTemplate.opsForValue().get("allStudentCount");
if(studentCount==null){
//如果Redis值为空,去数据库查询,再放到Redis,设置Redis数据有效时间
studentCount = studentMapper.selectAllStudentCount();
redisTemplate.opsForValue().set("allStudentCount",studentCount,30, TimeUnit.MINUTES);
}
return studentCount;
}
}
@SpringBootApplication
@EnableDubboConfiguration //开启dubbo
@MapperScan("com.springboot.dao")
@EnableDubbo
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
pom
springboot的起步依赖、dubbo集成springboot的起步依赖、注册中心zkclient、接口工程
springboot集成jsp、springboot前端引擎默认thymeleaf插件
<!--springboot集成jsp-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<resources>
<!--springboot前端引擎默认thymeleaf-->
<!--配置springboot集成jsp、编译jsp的路径-->
<resource>
<!--源文件、指定编译的位置、指定源文件夹中要编译的文件-->
<directory>src/main/webapp</directory>
<targetPath>META-INF/resources</targetPath>
<includes>
<include>*.*</include>
</includes>
</resource>
</resources>
Springbootp配置文件application.properties
#配置内嵌tomcat的端口号、上下文的根
server.port=8080
server.servlet.context-path=/
#设置dubbo设置注册中心
spring.application.name=025-sringboot-dubbo-ssm-consumer
spring.dubbo.registry=zookeeper://192.168.56.10:2181
#jsp的视图解析器
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp
controller
@RestController
public class MyController {
// @Reference(interfaceClass =StudentService.class,version = "1.0.0",check = false)
@Reference(interfaceName = "com.springboot.service.StudentService",version = "1.0.0",timeout = 15000)
private StudentService studentService;
@RequestMapping("/student/detail/{id}")
public String studentDetail(Model model, @PathVariable("id") Integer id){ //RESTful风格
Student student= studentService.queryStudentById(id);
model.addAttribute("student",student);
return "studentDetail";
}
@RequestMapping("/student/all/count")
public Object studentCount(){
Integer num= studentService.queryAllStudentCount();
return num;
}
}
启动类 开启dubbo
@SpringBootApplication
@EnableDubboConfiguration //开启dubbo
@EnableDubbo
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
jsp
添加webapp,创建jsp文件 studentDetail.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>学生详情</title>
</head>
<body>
studentDetail.jsp
<h2>学生详情</h2>
<h3>学生id:${student.id}</h3>
<h3>学生姓名:${student.name}</h3>
<h3>学生年龄:${student.age}</h3>
</body>
</html>
026-springboot-java-1
Springboot创建非Web工程,即Springboot的java工程
实际项目创建非Web工程,就创建maven项目就好了。非Web工程(了解)即可
创建springboot项目,不用勾选spring web
@Service
public class StudentServiceImpl implements StudentService {
@Override
public String sayHello() {
return "hello";
}
}
026-springboot-java-1的第一个启动类,
在启动类中,调用service实现类
@SpringBootApplication
public class Application {
public static void main(String[] args) {
//启动类启动后,返回值ConfigurableApplicationContext,它是一个spring的容器。它相当于ClasspathXmlApplicationContext
//获取springboot容器
ConfigurableApplicationContext ac = SpringApplication.run(Application.class, args);
//从spring容器获取对象
StudentServiceImpl service = (StudentServiceImpl) ac.getBean("studentServiceImpl");
String result = service.sayHello();
System.out.println(result);
}
}
026-springboot-java-1的第二个启动类,
@SpringBootApplication
public class Application1 implements CommandLineRunner {
//注入service接口
@Autowired
private StudentService studentService;
public static void main(String[] args) {
// 启动启动类,初始化spring容器
SpringApplication.run(Application1.class, args);
}
// 重写CommandLineRunner的run方法,调用业务方法
@Override
public void run(String... args) throws Exception {
String result = studentService.sayHello();
System.out.println("调用业务方法的结果: "+result);
}
}
026-springboot-java-1,第三个启动类
//关闭启动的logo
@SpringBootApplication
public class Application2 {
public static void main(String[] args) {
// SpringApplication.run(Application2.class, args);
SpringApplication springApplication = new SpringApplication(Application2.class);
//关闭启动的logo
springApplication.setBannerMode(Banner.Mode.OFF);
springApplication.run(args);
}
}
创建log的网站
resources下创建banner.txt
_
(_)
___ _ __ _ __ _ _ __ __ _
/ __| '_ \| '__| | '_ \ / _` |
\__ \ |_) | | | | | | | (_| |
|___/ .__/|_| |_|_| |_|\__, |
| | __/ |
|_| |___/
//修改SpringBoot启动的logo
@SpringBootApplication
public class Application3 {
public static void main(String[] args) {
SpringApplication.run(Application3.class, args);
}
}
030-springboot-interceptor项目
SpringBoot使用拦截器
定义一个拦截器,实现HandlerInterceptor接口
创建一个配置类,(即:功能与springmvc配置文件使用mvc:interceptors标签一样)
创建SpringBoot 的web项目
new - module - Spring initializr - spring web - next - next - finish
写拦截器类,实现HandlerInterceptor接口
拦截登录验证:session获取user,判断user是否存在。
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("进入拦截器--------");
User user = (User) request.getSession().getAttribute("user");
System.out.println(user.getClass());
//判断是否登录
if (user==null){
response.sendRedirect(request.getContextPath()+ "/user/error");
return false;
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
}
@Configuration //声明此类为配置类,就是SpringMVC的xml文件
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//拦截user下所有请求,必须用户登录后才能访问
String[] addPathPatterns = {
"/user/**"
};
//把以下请求排除,不要登录也可访问
String[] excludePathPatterns = {
"/user/out","/user/error" ,"/user/login"
};
registry.addInterceptor(new MyInterceptor()).addPathPatterns(addPathPatterns).excludePathPatterns(excludePathPatterns);
}
}
@Controller
@RequestMapping("/user")
public class UserController {
// 把login、out、error请求排除拦截
@RequestMapping("/login")
@ResponseBody
public Object login(HttpServletRequest request) {
User user = new User();
user.setId(1);
user.setName("Tom");
request.getSession().setAttribute("user", user);
return "login success";
}
//用户登录后才能访问的请求
@RequestMapping("/center")
@ResponseBody
public Object center() {
return "go to see center page!";
}
//改请求 用户不登录也能访问
@RequestMapping("/out")
@ResponseBody
public Object out() {
return "login out";
}
//用户未登录,访问了需要登录才能访问的请求,会跳转到该路径,
@RequestMapping("/error")
@ResponseBody
public Object error() {
return "error,用户未登录,不能访问";
}
}
031-springboot-servlet-1
步骤:
创建Servlet,继承HttpServlet。
web.xml使用Servlet、Servlet-mapping标签
第一种:注解
Servlet上加@WebServlet
启动上加 @ServletComponentScan
创建springboot项目
创建Servlet,继承HttpServlet
重写doGet、doPost
类上加@WebServlet(urlPatterns = “/myServlet”),设置请求路径
//@WebServlet: 设置请求路径
@WebServlet(urlPatterns = "/myServlet")
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().println("My springboot Servlet");
resp.getWriter().flush();
resp.getWriter().close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
032-springboot-servlet-2
第二种: 配置类
配置类添加@Configuration,相对于xml配置文件
@Configuration //声明为配置类
public class ServletConfig {
// @Bean:是一个方法上的注解,用在配置类中。相当于 标签
@Bean
public ServletRegistrationBean myServletRegistrationBean() {
// 创建对象ServletRegistrationBean时,添加我们的Servlet与请求路径
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new MyServlet(), "/myServlet");
return servletRegistrationBean;
}
}
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().println("My springboot Servlet-2");
resp.getWriter().flush();
resp.getWriter().close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
启动启动类,测试访问
http://localhost:8080/myServlet
033-springboot-filter-1
第一种:注解
第二种:配置类
创建springboot 的web项目
处理器类
实现Filter接口、重写doFilter方法,
方法内调用doFilter方法
类上加@WebFilter,添加路径
@WebFilter(urlPatterns = "/myFilter")
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("--------we are in filter now!-----------");
filterChain.doFilter(servletRequest,servletResponse);
}
}
@SpringBootApplication //开启spring容器
@ServletComponentScan(basePackages = "com.springboot.filter") //开启扫描过滤器类
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
启动启动类,测试访问
http://localhost:8080/myFilter
控制台有输出
034-springboot-filter-2
配置类,相对于xml配置文件
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("欢迎您进入过滤器");
filterChain.doFilter(servletRequest,servletResponse);
}
}
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean myFilterRegistrationBean() {
//注册过滤器
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new MyFilter());
//添加过滤路径
filterRegistrationBean.addUrlPatterns("/user/*");
return filterRegistrationBean;
}
}
@Controller
@ResponseBody
public class MyController {
@RequestMapping("/user/detail")
public String userDetail(){
return "/user/detail";
}
@RequestMapping("/center")
public String center(){
return "/center";
}
}
启动启动类,测试访问
http://localhost:8080/user/detail
http://localhost:8080/center
拦截器:只有配置类。拦截请求。
过滤器:两种,注解、配置类。过滤数据。
Servlet:两种,注解、配置类。
中文乱码,设置字符串编码解决
035-springboot-character-encoding-1
创建springboot web项目
Servlet
继承HttpServlet
重写doGet、doPost方法
类上加@WebServlet,表示请求路径
统一设置浏览器的响应类型
@WebServlet(urlPatterns = "/myServlet")
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().println("欢迎使用springboot");
//统一设置浏览器的响应类型
resp.setContentType("text/html;character=utf-8");
resp.getWriter().flush();
resp.getWriter().close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
@Configuration //声明为配置类
public class SystemConfig {
@Bean
public FilterRegistrationBean characterFilterRegistrationBean() {
//创建字符编码过滤器
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
//设置强制使用指定的字符编码
characterEncodingFilter.setForceEncoding(true);
//设置指定字符编码
characterEncodingFilter.setEncoding("utf-8");
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
//设置字符编码过滤器
filterRegistrationBean.setFilter(characterEncodingFilter);
// 设置字符编码过滤器路径
filterRegistrationBean.addUrlPatterns("/*");
return filterRegistrationBean;
}
}
#关闭springboot的http字符编码支持,这样我们设置的spring字符编码过滤器才生效
#spring.http.encoding.enabled=false
server.servlet.encoding.enabled=false
启动启动类,测试访问
http://localhost:8080/myServlet
036-springboot-character-encoding-2
@WebServlet(urlPatterns = "/myServlet")
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().println("欢迎使用springboot-2");
//统一设置浏览器的响应类型
resp.setContentType("text/html;character=utf-8");
resp.getWriter().flush();
resp.getWriter().close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
#设置spring响应类型
#spring.http.encoding.enabled=true
#spring.http.encoding.force=true
#spring.http.encoding.charset=utf-8
server.servlet.encoding.enabled=true
server.servlet.encoding.force=true
server.servlet.encoding.charset=utf-8
启动启动类,测试
http://localhost:8080/myServlet
037-springboot-war
<!--修改打包方式-->
<packaging>war</packaging>
<!--tomcat内嵌的jsp-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!-- 指定打war包的字符。打包后war包名称-->
<finalName>SpringBootWar</finalName>
<resources>
<!--springboot前端引擎默认thymeleaf-->
<!--配置springboot集成jsp、编译jsp的路径-->
<resource>
<!--源文件、指定编译的位置、指定源文件夹中要编译的文件-->
<directory>src/main/webapp</directory>
<targetPath>META-INF/resources</targetPath>
<includes>
<include>*.*</include>
</includes>
</resource>
<resource>
<!--源文件、指定编译的位置、指定源文件夹中要编译的文件-->
<directory>src/main/resources</directory>
<includes>
<include>**/*.*
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>用户信息</h1>
${id}
${name}
</body>
</html>
@Controller
public class UserController {
@RequestMapping("/user/detail")
@ResponseBody
public Object userSetail(){
Map<String, Object> map = new HashMap<>();
map.put("id",1001);
map.put("name","lisi");
return map;
}
@RequestMapping("/user/page/detail")
public String userPageSetail(Model model){
model.addAttribute("id",1001);
model.addAttribute("name","lisi");
return "userDetail";
}
}
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
//参数为当前springboot启动类,构建新资源
return builder.sources(Application.class);
}
}
测试访问:
http://localhost:8080/springboot/user/page/detail
http://localhost:8080/springboot/user/page/detail
如果不是不是本机的tomcat的呢?
配置本机tomcat环境变量为tomcat路径即可,
再启动startup.bat,访问路径
本地部署war后,项目配置文件的上下文根与端口号就失效了,以本地的tomcat为准
038-springboot-jar
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.4.2.RELEASE</version>
</plugin>
server.port=9090
server.servlet.context-path=/
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp
@Controller
public class UserController {
@RequestMapping(value = "/user/json/detail")
@ResponseBody
public Object userDetail(){
Map<String, Object> map = new HashMap<String, Object>();
map.put("id",1001);
map.put("name","lisi");
return map;
}
@RequestMapping(value = "/user/page/detail")
public String userPageDetail(Model model){
model.addAttribute("id",1001);
model.addAttribute("name","lisi");
return "userDetail";
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>用户信息</h1>
${id}
${name}
</body>
</html>
启动启动类,测试
http://localhost:9090/user/page/detail
http://localhost:9090/user/json/detail
此处不用tomcat,因为SpringBoot有内嵌的tomcat
测试
http://localhost:9090/user/page/detail
http://localhost:9090/user/json/detail
或者写一个bat文件,文件中有
java -jar springboot.jar
点击运行,即可
jar包以项目的端口号为准,使用内嵌的tomcat
war包是web项目,必须放到tomcat才能执行。
jar包通过内嵌的tomcat执行。
war包 项目的端口号、上下文根失效,以运行war包的tomcat为准。tomcat即本地。
jar包以项目的端口号、上下文根为准,使用内嵌的tomcat。
jar包,如果是虚拟机,
创建run-jar.sh
修改run-jar.sh文件权限
chmod 777 run-jar.sh
把jar包上传到与run-jar.sh同一目录下
执行run-jar.sh,执行jar包
./run-jar.sh
使用linux的地址进行访问
如
http://linux的ip:9090/user/page/detail
<!-- mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--mybatis集成springboot-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
<build>
<resources>
<!--手动指定文件夹为resources,扫描xxMapper.xml文件-->
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml
org.mybatis.generator
mybatis-generator-maven-plugin
1.3.6
generator/GeneratorMapper.xml
true
true
org.springframework.boot
spring-boot-maven-plugin
代码生成器GeneratorMapper.xml
逆向工程生成dao、mapper映射文件、实体类
配置文件application.properties配置数据库
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?userUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
spring.datasource.username=root
spring.datasource.password=root
<?xml version="1.0" encoding="UTF-8" ?>
<!--日志级别从低到高,TRACE、DEBUG、INFO、WARN、ERROR、FATAL-->
<configuration scan="true" scanPeriod="10 seconds">
<!-- 1.输出到控制台。部分日志-->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>debug</level>
</filter>
<encoder>
<Pattern>%date [%5p] [%thread] %logger{60} [%file : %line] %msg%n</Pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<!-- 2.文件追加器,输出到文件。全部日志-->
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<File>D:/log/springboot-logback.log</File>
<encoder>
<Pattern>%date %-5p %thread %logger{60} [%file : %line] %msg%n</Pattern>
<!-- <Pattern>%date %5p %thread %logger{60} [%file : %line] %msg%n</Pattern>-->
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>D:/log/springboot-logback.log.%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>30</maxHistory>
</rollingPolicy>
</appender>
<!--logger单个定义-->
<logger name="com.springboot.dao" level="DEBUG"/>
<!--root全部定义-->
<!-- root为根,如果根有日志级别,以root为主;否则以自己追加器日志级别为准-->
<root level="INFO">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="FILE"/>
</root>
</configuration>
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentMapper studentMapper;
@Override
public Integer queryStudentCount() {
Integer count = studentMapper.queryStudentCount();
return count;
}
}
@Controller
@Slf4j
public class StudentController {
@Autowired
private StudentService studentService;
@RequestMapping(value = "/student/count")
@ResponseBody
public String studentCount() {
log.info("查询当前学生总人数");
// log.warn("查询当前学生");
Integer count = studentService.queryStudentCount();
return "学生人数" + count;
}
}
@SpringBootApplication
@MapperScan(basePackages = "com.springboot.dao")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
SpringBoot集成Thymeleaf模板引擎技术,SpringBoot官方推荐Thymeleaf代替jsp技术,Thymeleaf以HTML为载体。
Thymeleaf官方地址:
thymeleaf模板引擎的页面必须通过中央调度器
040-springboot-thymeleaf-1项目
<!--pringboot起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--pringboot集成Themeleaf起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
@Controller
public class UserController {
@RequestMapping(value = "/user/detail")
public String message(Model model) {
model.addAttribute("data","使用Themeleaf模板引擎");
return "message";
}
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--thymeleaf模板引擎的页面必须通过中央调度器,与放在WEB-INF一样-->
message.html
<h2 th:text="${data}">用户信息</h2>
</body>
</html>
启动启动类,测试
http://localhost:8080/user/detail
见项目041-springboot-thymeleaf-2
html文件变化时,无法及时更新,怎么办?
解决:关闭页面缓存
#关闭thymeleaf的缓存,默认开启
spring.thymeleaf.cache=false
#设置Thymeleaf的前后缀(可选)
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
重启启动类
访问http://localhost:8080/message
修改message.html,
不用重启启动类,再次访问http://localhost:8080/message
结果:页面数据发生变化。
这就是Thymeleaf的页面数据自动刷新 的功能
042-springboot-thymeleaf-expression
语法:${…}
与El表达式相同
获取controller的module的数据
如
<h1>标准变量表达式:${}h1>
用户编号:<span th:text="${user.id}">对象的情况span>br>
用户姓名:<span th:text="${user.username}">span>br>
用户年龄:<span th:text="${user.age}">span>
语法:*{…}
标准变量表达式必须使用th:object来绑定对象
如绑定User对象
<h1>标准变量表达式:*{}h1>
<div th:object="${user}">
用户编号:<span th:text="*{id}">span>br>
用户姓名:<span th:text="*{username}">span>br>
用户年龄:<span th:text="*{age}">span>
div>
<h1>混合使用h1>
用户编号:<span th:text="*{user.id}">span>br>
用户姓名:<span th:text="*{user.username}">span>
用户年龄:<span th:text="*{user.age}">span>br>
pom
thymeleaf、spring web
实体类
User,必须序列化Serializable
UserController
添加@RequestBody就是返回JSON数据,不添加就是转发页面
@Controller
public class UserController {
@RequestMapping(value = "/user/detail")
public ModelAndView message() {
ModelAndView mv = new ModelAndView();
User user = new User();
user.setId(1001);user.setUsername("lisi");user.setAge(25);
mv.setViewName("userDetail");
mv.addObject("user",user);
return mv;
}
@RequestMapping(value = "/url")
public String urlExpression(Model model) {
model.addAttribute("id",1001);
model.addAttribute("username","wangwu");
model.addAttribute("age",26);
return "url";
}
@RequestMapping(value = "/test")
@ResponseBody
public String test(String username) {
return "请求路径/test, 参数username= " + username;
}
@RequestMapping(value = "/test1")
@ResponseBody
public String test1(Integer id,String username,Integer age) {
return "请求路径/test1, id="+id+",username= "+username+",age="+age;
}
@RequestMapping(value = "/test2/{id}")
@ResponseBody
public String test2(@PathVariable("id") Integer id) {
return "test2请求路径, id= "+id;
}
@RequestMapping(value = "/test3/{id}/{username}")
@ResponseBody
public String test3(@PathVariable("id") Integer id, @PathVariable("username") String username) {
return "test3请求路径, id= "+id+",username= "+username;
}
#关闭thymeleaf的缓存,默认开启为true,false为关闭
spring.thymeleaf.cache=false
#设置Thymeleaf的前后缀(可选)
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<title>标准变量、标准变量表达式title>
head>
<body>
<h1>标准变量表达式:${}h1>
用户编号:<span th:text="${user.id}">对象的情况span>br>
用户姓名:<span th:text="${user.username}">span>br>
用户年龄:<span th:text="${user.age}">span>
<h1>标准变量表达式:*{}h1>
<div th:object="${user}">
用户编号:<span th:text="*{id}">span>br>
用户姓名:<span th:text="*{username}">span>br>
用户年龄:<span th:text="*{age}">span>
div>
<h1>混合使用h1>
用户编号:<span th:text="*{user.id}">span>br>
用户姓名:<span th:text="*{user.username}">span>
用户年龄:<span th:text="*{user.age}">span>br>
body>
html>
url.html
DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>URL路径表达式title>
head>
<body>
<h2>URL 路径表达式:@{...}h2>
<h2>a标签的绝对路径(没有参数)h2>
<a href="http://www.baidu.com">跳转到百度:传统写法a>br>
<a th:href="@{http://www.baidu.com}">路径表达式:跳转到百度a>br>
<a th:href="@{http://localhost:8080/user/detail}">跳转至:/user/detaila>br>
<h2>URL路径表达式,相对路径(不带参数)h2>
<a th:href="@{/user/detail}">跳转至相对路径:user/detaila>br>
<h2>绝对路径(带参数),不推荐h2>
<a href="http://localhost:8080/test?username=lisi">绝对路径,带参数/test?usernamea>br>
<a href="http://localhost:8080/test?username='lisi'">绝对路径,带参数/test?usernamea>br>
<a th:href="@{http://localhost:8080/test?username=张三}">路径表达式写法,绝对路径,带参/test?usernamea>
<h2>URL路径表达式,相对路径(带参数)h2>
<a th:href="@{/test?username=lisi}">相对路径,带参数a>br>
<h2>URL路径表达式,相对路径(带后台参数)h2>
<a th:href="@{'/test?username='+ ${username} }">相对路径+后台的参数a>br>
<a th:href="@{'/test1?id=' + ${id} + '&username=' + ${username}+'&age='+${age}}">相对路径+后台的多参a>br>
<a th:href="@{/test1(id=${id},username=${username},age=${age})}">强烈推荐: 相对路径+后台的参数a>br>
<a th:href="@{'/test2/'+${id}}">restful相对路径+后台的参数a>br>
<a th:href="@{'/test3/'+${id}+'/'+${username} }">restful相对路径+后台的多参a>
body>
html>
js、图片
url2.html
DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<script type="text/javascript" th:src="@{/js/jquery-1.10.1.js}">script>
<script>
$(function () {
alert($("#username").val())
})
script>
<input type="text" id="username" value="hello">br>
<img th:src="@{/image/003.jpg}">
body>
html>
需要后台的数据使用 th:
不是后台的数据,不用th:
property.html
DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<form action="/test1">
用户编号:<input type="text" name="id">br>
用户名称:<input type="text" name="username">br>
用户年龄:<input type="text" name="age">br>
<input type="submit">
form>
<form th:action="@{/test1}">
用户编号:<input type="text" id="id" name="id">br>
用户名称:<input type="text" id="name" name="username">br>
用户年龄:<input type="text" id="age" name="age">br>
<input type="submit">
form>
body>
html>
th:action---->action
th:src-------->src
th:href-------->href
th:text--------->text
th:id------->id
th:name----->name
th:onclick----->onclick
th:each
th:if
th:inline
043-springboot-thymeleaf项目
th:each 循环
th:if 判断
th:inline 内联表达式
eachList.html
<body>
<div th:each="user, userStat:${userList}">
<span th:text="${userStat.index}"/>
<span th:text="${userStat.count}"/>
<span th:text="${user.id}"/>
<span th:text="${user.nick}"/>
<span th:text="${user.phone}"/>
<span th:text="${user.address}"/>
div>
<br/>
<div th:each="user:${userList}">
<span th:text="${userStat.index}"/>
<span th:text="${userStat.count}"/>
<span th:text="${user.id}"/>
<span th:text="${user.nick}"/>
<span th:text="${user.phone}"/>
<span th:text="${user.address}"/>
div>
body>
测试:
http://localhost:8080/each/each
eachMap.html
<body>
<div th:each="userMap,userMapStat:${userMaps}">
<span th:text="${userMapStat.count}"/>
<span th:text="${userMapStat.index}"/>
<span th:text="${userMap.key}"/>
<span th:text="${userMap.value}"/>
<span th:text="${userMap.value.id}"/>
<span th:text="${userMap.value.nick}"/>
<span th:text="${userMap.value.phone}"/>
<span th:text="${userMap.value.address}"/>
div>
<br/>
userMapStat可以不使用,默认名称为对象名+Stat
<div th:each="userMap:${userMaps}">
<span th:text="${userMapStat.count}"/>
<span th:text="${userMapStat.index}"/>
<span th:text="${userMap.key}"/>
<span th:text="${userMap.value}"/>
<span th:text="${userMap.value.id}"/>
<span th:text="${userMap.value.nick}"/>
<span th:text="${userMap.value.phone}"/>
<span th:text="${userMap.value.address}"/>
div>
body>
测试:
http://localhost:8080/each/map
eachArray.html
<body>
<div th:each="user, userStat:${userArray}">
<span th:text="${userStat.index}"/>
<span th:text="${userStat.count}"/>
<span th:text="${user.id}"/>
<span th:text="${user.nick}"/>
<span th:text="${user.phone}"/>
<span th:text="${user.address}"/>
div>
<br/>
userStat可以不写,默认名称为对象名+Stat
<div th:each="user:${userArray}">
<span th:text="${userStat.index}"/>
<span th:text="${userStat.count}"/>
<span th:text="${user.id}"/>
<span th:text="${user.nick}"/>
<span th:text="${user.phone}"/>
<span th:text="${user.address}"/>
div>
测试:
http://localhost:8080/each/array
三层循环:list中有map、map中有list、list中为User对象
eachComplex.html
<body>
<span>list-->map-->list-->userspan>
<div th:each="listMap:${userList}">
<div th:each="listMapList:${listMap}">
map的key:<span th:text="${listMapList.key}"/>
<div th:each="user:${listMapList.value}">
<span th:text="${user.id}"/>
<span th:text="${user.nick}"/>
<span th:text="${user.phone}"/>
<span th:text="${user.address}"/>
div>
div>
div>
body>
测试:
http://localhost:8080/each/all
th:if、th:unless、th:switch
condition.html
<div th:if="${sex==1}">
男
div>
<div th:if="${sex==0}">
女
div>
<div th:if="${sex eq 1}">
男
div>
<div th:unless="${sex ne 1}">
女
div>
<div th:unless="${sex != 1}">
女
div>
<div th:switch="${productType}">
<span th:case="0"> 产品0span>
<span th:case="1"> 产品1span>
<span th:case="*"> 无此产品span>
div>
测试
http://localhost:8080/condition
th:inline内联表达式
th:inline有三个取值,即text、javascript、none。其中none没效果
不依赖与html,直接使用 [[]] 可以获取动态数据,但是必须在父级标签上添加th:inline=“text”
inline.html
内联文本th:inline="text"
<div th:text="${data}">xxxdiv>
<div th:inline="text">
数据:[[${data}]]
div>
<div th:inline="text">
数据:[[${user.id}]]
div>
<br/>
内联脚本th:inline="javascript"
<script type="text/javascript" th:inline="javascript">
function showData() {
alert([[${data}]])
}
script>
<button onclick="showData()">展示数据button>
@Controller
public class UserController {
@RequestMapping("/each/list")
public String eachList(Model model){
ArrayList<User> userList = new ArrayList<>();
for (int i=0;i<10;i++){
User user = new User();
user.setId(i);user.setNick("张"+i);user.setPhone("1380000000"+i);user.setAddress("杭州萧山区"+i);
userList.add(user);
}
model.addAttribute("userList",userList);
return "eachList";
}
@RequestMapping("/each/map")
public String eachMap(Model model){
HashMap<Integer, Object> userMaps = new HashMap<>();
for (int i=0;i<10;i++){
User user = new User();
user.setId(i);user.setNick("张"+i);user.setPhone("1390000000"+i);user.setAddress("杭州萧山区"+i);
userMaps.put(i,user);
}
model.addAttribute("userMaps",userMaps);
return "eachMap";
}
@RequestMapping("/each/array")
public String eachArray(Model model){
User[] userArray = new User[10];
for (int i=0;i<10;i++){
User user = new User();
user.setId(i);user.setNick("张"+i);user.setPhone("1370000000"+i);user.setAddress("杭州萧山区"+i);
userArray[i]=user;
}
model.addAttribute("userArray",userArray);
return "eachArray";
}
@RequestMapping("/each/all")
public String eachComplex(Model model){
ArrayList<Map<Integer, List<User>>> userList = new ArrayList<>();
for (int i=0;i<2;i++){
HashMap<Integer, List<User>> map = new HashMap<>();
for (int j=0;j<2;j++){
ArrayList<User> list = new ArrayList<>();
for (int k=0;k<3;k++){
User user = new User();
user.setId(k);user.setNick("张"+k);user.setPhone("1360000000"+k);user.setAddress("杭州萧山区"+k);
list.add(user);
}
map.put(j,list);
}
userList.add(map);
}
model.addAttribute("userList",userList);
return "eachComplex";
}
@RequestMapping("/condition")
public String condition(Model model){
model.addAttribute("sex",1);
model.addAttribute("flag",true);
model.addAttribute("productType",0);
return "condition";
}
@RequestMapping("/inline")
public String inline(Model model){
User user = new User();
user.setId(1002);user.setNick("张三");user.setPhone("13700000001");user.setAddress("杭州萧山区");
model.addAttribute("user",user);
model.addAttribute("data","springboot");
return "inline";
}
044-springboot-thymeleaf-literal
literal.html
<body>
<h2>文本字面量:用单引号''包含的字符串就是 字面量h2>
<a th:href="@{'/user/detail?sex='+${sex}}">查看性别a>
<span th:text="hello">span>
<h2>数字字面量h2>
今年是<span th:text="2020">1949span>年<br/>
20年后是<span th:text="2020+20">1969span>年<br/>
<h2>boolean字面量h2>
<div th:if="${flag}">
执行成功
div>
<div th:if="${!flag}">
执行不成功
div>
<h2>null字面量h2>
<span th:text="${user.id}" /><br/>
<span th:unless="${userDetail eq null}" >
对象已创建,地址不为空
span>
<span th:if="${userDetail.id eq null}" ><br/>
空
span>
body>
@RequestMapping("/literal")
public String literal(Model model) {
model.addAttribute("sex", 1);
model.addAttribute("data", "springboot data");
model.addAttribute("flag", true);
User user = new User();
user.setId(1001);user.setUsername("lisi");
model.addAttribute("user",user);
User userDetail = new User();
model.addAttribute("userDetail",userDetail);
return "literal";
}
http://localhost:8080/literal
<body>
<h2>共120条12页,当前第一页, 首页,上一页,下一页,尾页h2>
<span th:text="'共'+${totalRows}+'条'+${totalPage}+'页,当前第'+${currentPage}+'页, 首页,上一页,下一页,尾页'">span>
<h2>使用更优雅的字符串拼接:|要拼接的字符串|,把数据进行替换h2>
<span th:text="|共${totalRows}条${totalPage}页,当前第${currentPage}页, 首页,上页,下一页,尾页|">span>
body>
@RequestMapping("/splice")
public String splice(Model model) {
model.addAttribute("totalRows", 123);
model.addAttribute("totalPage", 13 );
model.addAttribute("currentPage", 2);
return "splice";
}
测试:http://localhost:8080/splice
三元运算符
算数运算符:+ - * / %
关系运算符:> >= < <= (gt ge lt le )
相等判断:== != (eq ne)
@RequestMapping("/operator")
public String operator(Model model) {
model.addAttribute("sex", 1);
model.addAttribute("flag", true );
return "operator";
}
operator.html
<h2>运算符h2>
<span th:text="${sex eq 1 ? '男' :'女'}">三元运算符span><br/>
<span th:text="${sex == 1 ? '男' :'女'}">三元运算符span><br/>
<h2>算数运算h2>
20+5=<span th:text="20+5">span><br/>
20-5=<span th:text="20-5">span><br/>
20*5=<span th:text="20*5">span><br/>
20/5=<span th:text="20/5">span><br/>
20%3=<span th:text="20%3">span><br/>
<h2>关系比较h2>
5>2为<span th:if="5>2">真span><br/>
5>2为<span th:if="5 gt 2">真span><br/>
2<5为<span th:if="2 lt 5">真span><br/>
<span th:if="${sex == 1 }">男span><br/>
<span th:if="${sex eq 1 }">男span><br/>
模板引擎提供的内置对象,用#开始使用。
#request、#session
request:把数据放入request作用域
session:把数据放session
index.html
<h2>从Sesion取值h2>
<span th:text="${#session.getAttribute('data')}">span><br/>
<span th:text="${#httpSession.getAttribute('data')}">span><br/>
<span th:text="${session.data}">span>
<script type="text/javascript" th:inline="javascript">
//获取协议名称
var scheme=[[${#request.getScheme()}]];
//获取服务器名称
var serverName=[[${#request.getServerName()}]];
//获取服务器端口号
var serverPort=[[${#request.getServerPort()}]];
//获取上下文根
var contextPath=[[${#request.getContextPath()}]];
var all =scheme+"://"+serverName+":"+serverPort+"/"+contextPath+'?id='+queryString;
// alert(all)
var requestURL=[[${#httpServletRequest.requestURL}]];
var queryString=[[${#httpServletRequest.queryString}]];
var all2 = requestURL+'?'+queryString;
alert(all2)
// alert(queryString)
script>
//基本表达式
@RequestMapping("/index")
public String index(HttpServletRequest request, Model model,Integer id) {
model.addAttribute("username", "lisi");
request.getSession().setAttribute("data", "sessionData");
return "index";
}
测试:
http://localhost:8080/springboot/index?id=1
模板引擎提供一组功能性内置对象,可以在模板中直接使用对象的方法。
采用的数据类型:集合、时间、数值。
内置对象前都需要加#,内置对象一般以s结尾。
<body>
<span th:text="${time}">span><br/>
<span th:text="${#dates.format(time,'yyyy-MM-dd HH:mm:ss')}">span><br/>
<span th:text="${data}">span><br/>
<div th:text="${#strings.substring(data,0,6)}">div><br/>
body>
//功能表达式
@RequestMapping("/function")
public String function(Model model) {
model.addAttribute("time", new Date());
model.addAttribute("data", "springboot");
return "function";
}
maven的空项目
new module - maven - next -045-springboot-parent
下一步,finish
<packaging>pompackaging>
删除src
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
把047提供者、048消费者的父工程替换为045-springboot-parent
<parent>
<artifactId>045-springboot-parent</artifactId>
<groupId>com.springboot</groupId>
<version>1.0.0</version>
<relativePath>../045-springboot-parent/pom.xml</relativePath>
</parent>
<properties>
<java.version>1.8java.version>
<dubbo-spring-boot-starter-version>2.0.0dubbo-spring-boot-starter-version>
<zkclient-version>0.10zkclient-version>
<mybatis-spring-boot-starter-version>2.0.0mybatis-spring-boot-starter-version>
properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.spring.bootgroupId>
<artifactId>dubbo-spring-boot-starterartifactId>
<version>${dubbo-spring-boot-starter-version}version>
dependency>
<dependency>
<groupId>com.101tecgroupId>
<artifactId>zkclientartifactId>
<version>${zkclient-version}version>
dependency>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>${mybatis-spring-boot-starter-version}version>
dependency>
dependencies>
dependencyManagement>
maven - 046-springboot-dubbo-ssm-interface
next - finish
springboot web项目
047-springboot-dubbo-ssm-provider
选中spring web依赖
把父工程改为
<parent>
<artifactId>045-springboot-parentartifactId>
<groupId>com.springbootgroupId>
<version>1.0.0version>
<relativePath>../045-springboot-parent/pom.xmlrelativePath>
parent>
添加依赖
dubbo、zookeeper、MyBatis、mysql、redis 、接口工程
<!-- springboot起步依赖、 dubbo、zookeeper、MyBatis、mysql、redis 、接口工程 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- dubbo集成springboot起步依赖 -->
<dependency>
<groupId>com.alibaba.spring.boot</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
</dependency>
<!-- zookeeper注册中心 -->
<dependency>
<groupId>com.101tec</groupId>
<artifactId>zkclient</artifactId>
</dependency>
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- MyBatis集成SpringBoot起步依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<!-- SpringBoot集成redis起步依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 接口工程,自己创建的java工程的依赖版本号不需要父工程管理-->
<dependency>
<groupId>com.springboot</groupId>
<artifactId>046-springboot-dubbo-ssm-interface</artifactId>
<version>1.0.0</version>
</dependency>
springboot web项目
048-springboot-dubbo-ssm-consumer
把父工程改为
<parent>
<artifactId>045-springboot-parentartifactId>
<groupId>com.springbootgroupId>
<version>1.0.0version>
<relativePath>../045-springboot-parent/pom.xmlrelativePath>
parent>
添加依赖
springboot起步依赖、 dubbo、zookeeper、thymeleaf、接口工程
<!-- springboot起步依赖、 dubbo、zookeeper、thymeleaf、接口工程 -->
<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>
<!-- dubbo集成springboot起步依赖 -->
<dependency>
<groupId>com.alibaba.spring.boot</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
</dependency>
<!-- zookeeper注册中心 -->
<dependency>
<groupId>com.101tec</groupId>
<artifactId>zkclient</artifactId>
</dependency>
<!-- 接口工程,自己创建的java工程的依赖版本号不需要父工程管理-->
<dependency>
<groupId>com.springboot</groupId>
<artifactId>046-springboot-dubbo-ssm-interface</artifactId>
<version>1.0.0</version>
</dependency>
把逆行工程添加到提供者的项目
点击执行,生成实体类、dao接口、mapper文件
出现问题:找不到接口工程
解决:找到接口工程,install。把接口工程发布到本地仓库
还需要把父工程页发布到本地仓库
重新执行逆向工程,成功
把实体类放入接口工程,dao、mapper文件放入provider
application-dev.properties、application-prod.properties
server.port=8081
server.servlet.context-path=/
#设置数据库
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?userUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
spring.datasource.username=root
spring.datasource.password=root
#dubbo的配置
spring.application.name=047-springboot-dubbo-ssm-provider
#设置当前服务为服务提供者
spring.dubbo.server=true
#指定注册中心
spring.dubbo.registry=zookeeper://192.168.56.10:2181
# redis配置
spring.redis.host=192.168.56.10
spring.redis.port=6379
#spring.redis.password=111111
主配置文件application.properties,激活dev
spring.profiles.active=dev
application-dev.properties、application-prod.properties
server.port=8080
server.servlet.context-path=/
# 设置dubbo
spring.application.name=048-springboot-dubbo-ssm-consumer
#指定注册中心
spring.dubbo.registry=zookeeper://192.168.56.10:2181
# thymeleaf配置
spring.thymeleaf.cache=false
# 配置视图解析器
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp
# 设置字符编码
#设置spring响应类型
#spring.http.encoding.enabled=true
#spring.http.encoding.force=true
#spring.http.encoding.charset=utf-8
server.servlet.encoding.enabled=true
server.servlet.encoding.force=true
server.servlet.encoding.charset=utf-8
主配置文件application.properties
spring.profiles.active=dev
pom
<resources>
<!--手动指定文件夹为resources-->
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml
src/main/resources
**/ *.*</include>
</includes>
</resource>
</resources>
@Service是alibaba.dubbo的
@Service(interfaceClass = StudentService.class,version = “1.0.0”,timeout = 15000)可以使用interfaceName
import com.alibaba.dubbo.config.annotation.Service;
import com.springboot.dao.StudentMapper;
import com.springboot.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
@Service(interfaceClass = StudentService.class,version = "1.0.0",timeout = 15000)
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentMapper studentMapper;
@Override
public Student queryStudentById(Integer id) {
Student student= studentMapper.queryStudentById(id);
return student;
}
}
Reference是alibaba.dubbo的
@Reference(interfaceClass = StudentService.class,version = “1.0.0”,timeout = 15000)可以使用interfaceName,必须与实现类一致
@Controller
public class StudentController {
@Reference(interfaceClass = StudentService.class, version = "1.0.0", check = false)
private StudentService studentService;
@RequestMapping("/student/detail/{id}")
public String studentDetail(Model model, @PathVariable("id") Integer id) {
Student student = studentService.queryStudentById(id);
model.addAttribute("student", student);
return "studentDetail";
}
}
provider:
添加@MapperScan扫描dao包
@MapperScan(basePackages = “com.spring.dao”)
开启dubbo
@EnableDubboConfiguration //开启dubbo
consumer:
@EnableDubboConfiguration //开启dubbo
DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>studentDetailtitle>
head>
<body>
编号:<span th:text="${student.id}">span><br/>
名称:<span th:text="${student.name}">span><br/>
年龄:<span th:text="${student.age}">span>
body>
html>