springboot学习

----spring简介
Spring Boot 是由 Pivotal 团队提供用来简化
Spring 的搭建和开发过程的全新框架。随着近些年来微服务技术的流行,
Spring Boot 也成了时下炙手可热的热点技术。
Spring Boot 去除了大量的 xml 配置文件,简
化了复杂的依赖管理,配合各种 starter 使用,基本上可以做到自动化配
置。Spring 可以做的事情,现在用 Spring boot 都可以做。
这套 Spring Boot 框架快速入门教程以大量示例讲解了 Spring Boot 在各
类情境中的应用,让读者可以跟着笔者的思维和代码快速理解并掌握。适用于 Java
开发人员,尤其是初学 Spring Boot 的人员和需要从传统 Spring 转向 Spring Boot 开发的技术人员。

Spring Boot具有以下优点:
(1)遵循"习惯优于配置"原则,使用Spirng Boot只需很少的配置,大部分时候可以使用默认配置;
(2)项目快速搭建,另外还可以无配置整合第三方框架;
(3)可完全不使用xml配置,只使用自动配置和Java Config;
(4)内嵌入Servlet如Tomcat容器,应用可用jar包运行(java -jar);
(5)运行中应用状态的监控.

springboot的特性:
1)能够快速创建基于spring的应用程序
2)能够直接使用java.main方法启动内嵌tomcat服务器运行springboot程序,不需要部署war包文件
3)提供阅读的starter POM来简化Maven依赖配置,Spring Boot自动配置Spring,springmvc等
4)提供了程序的健康检查等功能
5)基于可以完全不用XML配置文件,采用注解配置。

spring BOOT四大核心
自动配置
起步依赖
Actuator
命令行界面
注意:
1)springboot自动吧springmvc的配置加载进来集成springmvc
2)程序必须在SpringbootApplication文件的同级或者下级目录
3)使用以后缀名yaml,yml的配置文件
4)application.properties核心配置文件
5)springboot框架的核心配置文件application.properties和
application.yaml和application.yml一起存在时只会读取application.properties
6)多环境下的核心配置文件的使用,工作中开发的环境有哪些:
开发环境,测试环境,准生产环境,生产环境。
7)多配置文件使用
主配置文件application.properties
application-dev.proertes开发环境
application-test.properties测试环境
application-ready.properties准生产环境
application-product.peoperties生产环境
采用主配置文件激活的方式激活所用的配置文件

spring.profiles.active=dev

8)多配置yml的使用

application-dev.yml等一样使用
spring.profiles.active=dev

9)springboot在核心配置文件application.properties的自定义配置
name=zhangsan
websit=http://wwww.baidu.com
在后端代码中使用@Vlue(“${name}”)
private String Name;
就可以使用其中的值

springboot遇到一个超级无语的事情,maven的骨架消失了,最终解决将springboot依赖降级,可能是maven配置的问题,下载不到高版本的

org.springframework.boot
spring-boot-starter-parent
2.1.1.RELEASE

使用yml时的格式一定要是server:
servlet:
context-path: /ss

   port: 8085
   不然无法识别

   如果有properties就先激活properties,然后再识别yaml和yml

   @Component

@ConfigurationProperties//配置属性注解
将配置文件里面的自定义属性包装为对象

注意:如果是用属性配置类name就必须要有前缀,如果没有那么就只能使用普通的@Value
在属性配置类的上面如果出现Spring Boot Configuration Annotation Processor not found in的警告
需要添加依赖

org.springframework.boot
spring-boot-configuration-processor
true

注意:如果在Springboot核心配置文件中有中文信息,会出现乱码。
一般配置文件中,不建议出现中文(注释除外)
如果有,可以先转化为ASCLL码
也可以在settin,editor,file Encodings,勾选翻译为ASCALL码

1.@ConfigurationProperties
用来加载指定的配置文件
我们前边在给bean文件注入数据的时候,使用了@ConfigurationProperties注解,不过该注
,只可以把应用主配置文件的内容读取进来,要想给Bean赋值,只能读取主配置文件,就是application.properties或者application.yml文件,若我们想自己写一个配置文件来给bean赋值,我们就可以使用该注解@PropertyResource
我们在resource里边新建一个person.properties文件,并把之前主配置文件里的内容剪贴进来
,并在bean上边加上注解@PropertySource


springboot集成jsp

1)创建存放jsp的webapp文件夹
2)打开项目结构 Project Strcture
3)选择WEB Resource Directory加号添加web文件夹为web Resource Directory
4)引入springboot内嵌Tomcat对jsp的解析包
如果仅仅解析jsp,可以添加依赖:

org.apache.tomcat.embed
tomcat-embed-jasper

<!-- Springboot项目默认推荐使用的前段模板引擎我是thymeleaf
现在我们要使用springboot集成jsp,手动指定jsp最后编译的路径
而且springboot集成jsp编译jsp的路径是wspringboot规定好的位置
META-INF/resources
-->
src/main/webapp META-INF/resources *.*
注意!!!:如果配置了资源中哪些文件需要编译,name就不会编译resources下的文件,
为们需要给resources下的文件也给配置上
src/main/webapp META-INF/resources *.* src/main/resources true *.*
  **************************************
  将普通的maven工程转化为springboot工程:
  从别处拿到pom文件粘贴过来,按照springboot创建包
  *****************************************、

  springboot集成mybatis  --mysql驱动,mybtis依赖
   <!-- springboot集成mybatis
    mysql驱动-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>

注意:在springboot中我们不需要写版本号,springboot的父系启动依赖的父依赖为我们管理了版本号,
如果我们要更改版本号那么就在
<!--编译级别 -->
<properties>
    <java.version>1.8</java.version>
</properties>
中添加我们所需要的版本
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis-spring</artifactId>
  <version>1.3.1</version>
</dependency>

注意:我们在使用pom.xml时如果在仓库里面有这些包,我们下次使用的时候就可以自动提示,
我们需要在Build,Execution,Deployment->Build Tools->Maven->Repositories->选中右侧第一个列表->点击Update
更新仓库,对于org.mybatis.spring.boot是一定需要版本号,因为在springboot的父工程里面并没有管理这个依赖的版本号
因为这个依赖归属于org.mybatis不是spring的,他一般整理的是自己整合别人的,这个依赖是mybatis集成springboot
mybatis是主的。
  <!-- Mybatis整合Springboot框架的依赖-->
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.0.0</version>
    </dependency>

集成mybatis
1)添加mybatis依赖,mysql驱动
2)使用mtbatis提供的逆向工程生成实体bean,映射文件,Dao接口。、
逆向工程GeneratorMapper.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<classPathEntry location="D:\javaweb学习\mysql-connector-java-8.0.23\mysql-connector-java-8.0.23.jar"/>
<context id="DB2Tables" targetRuntime="MyBatis3">
	<commentGenerator>
		<property name="suppressAllComments" value="true" />
	</commentGenerator>
	<!-- 配置数据库连接 -->
	<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
		connectionURL="jdbc:mysql://localhost:3306/ssm_learn?serverTimezone=GMT%2B8"
	    userId="root"
		password="123456">
	</jdbcConnection>

	<javaTypeResolver>
		<property name="forceBigDecimals" value="false" />
	</javaTypeResolver>

	<!-- 指定javaBean生成的位置 -->
	<javaModelGenerator targetPackage="com.anyu.bean"
		targetProject="D:\SSM整合\一个SSM小项目(尚硅谷)\SSMempdeptcrud\src\main\java">
		<property name="enableSubPackages" value="true" />
		<property name="trimStrings" value="true" />
	</javaModelGenerator>

	<!--指定sql映射文件生成的位置 -->
	<!--需要使用绝对路径,不知道为什么,无法解释 -->
	<sqlMapGenerator targetPackage="mapper" targetProject="D:\SSM整合\一个SSM小项目(尚硅谷)\SSMempdeptcrud\src\main\resources">
		<property name="enableSubPackages" value="true" />
	</sqlMapGenerator>

	<!-- 指定dao接口生成的位置,mapper接口 -->
	<javaClientGenerator type="XMLMAPPER"
		targetPackage="com.anyu.dao" targetProject="D:\SSM整合\一个SSM小项目(尚硅谷)\SSMempdeptcrud\src\main\java">
		<property name="enableSubPackages" value="true" />
	</javaClientGenerator>


	<!-- table指定每个表的生成策略 -->
	<table tableName="employee" domainObjectName="Employee"></table>
	<table tableName="department" domainObjectName="Department"></table>
</context>

多种方式开启mybatis,最常见的方式一是java方式:二是maven插件的方式。
插件方式:官网:

正常方式:

org.mybatis.generator
mybatis-generator-maven-plugin
1.4.0

<GeneratorMapper.xml>
true
true

  [WARNING] Existing file D:\springboot_learn\springboot_one\src\main\java\com\anyu\dao\studentMapper.java was overwritten

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.409 s
[INFO] Finished at: 2021-06-18T18:46:42+08:00
[INFO] Final Memory: 25M/304M
[INFO] ------------------------------------------------------------------------

总结:插件的方式需要添加jdbc连接,无法使用maven的方式获取不知道为什么
“http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd”>是报红的,没关系

如果使用的java程序启动
public class MBGTest {
public static void main(String[] args) throws Exception{
List warnings = new ArrayList();
boolean overwrite = true;
String mbg=“D:\springboot_learn\springboot_one\src\main\resources\GeneratorMapper.xml”;
File configFile = new File(mbg);
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
System.out.println(“执行成功了”);
}

那么就需要添加generator依赖,以及mysql连接依赖,在GeneratorMapper.xml里面就无需使用
  <!--指定连接数据库的JDBC驱动所在位置 -->
<classPathEntry location="D:\javaweb学习\mysql-connector-java-8.0.23\mysql-connector-java-8.0.23.jar"/>
也不用使用插件了

  <!-- 如果数据库中字段名称由多个单词组成,通过MyBatis逆向工程生成的对象属性

会按照驼峰命名法规生成属性名称
其中:数据库中字段名称中多个单词构成的时候必须使用_下划线分隔
–>




springboot不需要添加jdbc依赖

<!--<dependency>-->
        <!--<groupId>org.springframework</groupId>-->
        <!--<artifactId>spring-jdbc</artifactId>-->
        <!--<version>5.3.7</version>-->
    <!--</dependency>-->

因为 Mybatis整合Springboot框架的依赖已经集成了jdbc
我们只需添加mysql依赖
 <!-- Mybatis整合Springboot框架的依赖-->
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.0.0</version>
    </dependency>

注意:sevice that could not be found.我们的文件要保持和启动器在同级或下级位置

指定mapper文件,可以在mapper接口文件使用@mapper
也可以在程序入口类,添加@MapperScan(“文件的位置”)

mapper文件的位置
@MapperScan(basePackages = {“com.cybertron.barcode.service.dao”“})//扫描mapper.java和mapper.xml文件。

如果Mapper.xml与Mapper.class在同一个包下且同名,spring扫描Mapper.class的同时会自动扫描同名的Mapper.xml并装配到Mapper.class。

如果Mapper.xml与Mapper.class不在同一个包下或者不同名,就必须使用配置mapperLocations指定mapper.xml的位置。
application.yml中配置mybatis

注意:#配置mapper映射文件的位置
mybatis.mapper-locations=classpath:mapper/*.xml

注意一个大坑:
mybatis出现Result Maps collection already contains value for…BaseResultMap的错误,

既有可能是generatorSqlmapCustom逆向工程惹的祸。

假如使用generatorSqlmapCustom逆向工程生成代码,即生成dao文件和mapper.xml文件,

如果是再次生成代码,必须先将已经生成的代码删除,否则会在原文件中追加,仔细检查一下mapper.xml文件

看是否存在两个id为BaseResultMap的resultMap,删除多余的,只保留一个就可以解决问题。

报一个逆向工程产生的bug
UnsatisfiedDependencyException: Error creating bean with name ‘studentController’:
Unsatisfied dependency expressed through field ‘studentService’;
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'student
一直以为是student.xml位置的问题,最后发现mapper.xml文件中产生了两个id为
BaseResultMap 以及Example_Where_Clause

studentMapper.Example_Where_Clause
查看是其他数据库的同名表
(!未解决)

Malformed database URL, failed to parse the connection string near ‘;
serverTimezone=GMT%2b8’.] with root cause
数据库报错了!

jdbc:mysql://localhost:3306/springboot?useUnicode=true&serverTimezone=GMT%2b8
在springboot中不需要写分号

哭了。终于解决了,一点问题废了一个早上
*************事务
我们在spring中使用的是基于配置的
aop:config

<aop:pointcut expression=“execution(* com.anyu.service…(…))" id=“txPoint”/>

<aop:advisor advice-ref=“txAdvice” pointcut-ref=“txPoint”/>
</aop:config>

<tx:advice id=“txAdvice” transaction-manager=“TransactionManager”>
tx:attributes

<tx:method name="
”/>

<tx:method name=“get*” read-only=“true”/>
</tx:attributes>
</tx:advice>

而我们在springboot中只需要在方法上面加入注解@Transactional
@EnableTransactionManagement//在springboot2.0以前需要声明开启事务,现在可加可不加,不影响

****springmvc新注解
//@Controller 普通的控制器
@RestController//相当于控制层类上加@Controller+方法上都加@ResposeBody,意味着所有方法返回的都是json
@GetMapping(value = “/updatestudent”)//相当于
@RequestMapping(value = “/updatestudent”,method = RequestMethod.GET)
//通常在查询数据时使用
@PostMapping(value = “/update”)
//相当于@RequestMapping(value = “/update”,method = RequestMethod.POST)
//通常在新增时使用
@DeleteMapping(value = “update2”)//相当于@RequestMapping(value = “/update2”,method = RequestMethod.DELETE)
//通常在删除数据时使用
@PutMapping(value = “update3”)//相当于 @RequestMapping(value = “update3”,method = RequestMethod.PUT)
//通常在修改数据时使用
检测请求方式的工具post man


Spring Boot 实现RESTFUL
REST:Repressentation State Transfer

REST全称是Representational State Transfer,
中文意思是表述(编者注:通常译为表征)性状态转移。
它首次出现在2000年Roy Fielding的博士论文中,Roy Fielding是HTTP规范的主要编写者之一。
他在论文中提到:“我这篇文章的写作目的,就是想在符合架构原理的前提下
,理解和评估以网络为基础的应用软件的架构设计,
得到一个功能强、性能好、适宜通信的架构。REST指的是一组架构约束条件和原则。”
如果一个架构符合REST的约束条件和原则,我们就称它为RESTful架构。

REST本身并没有创造新的技术、组件或服务,而隐藏在RESTful背后的理念就是使用Web的现有特征和能力,
更好地使用现有Web标准中的一些准则和约束。虽然REST本身受Web技术的影响很深,
但是理论上REST架构风格并不是绑定在HTTP上,只不过目前HTTP是唯一与REST相关的实例。
所以我们这里描述的REST也是通过HTTP实现的REST。

@ResponseBody
@RequestMapping(value = “/emps/{ids}”,method = RequestMethod.DELETE)
public Msg delete_emp_one(@PathVariable(“ids”) String ids){}
将参数写在了路径里面
通过注解@PathVariable路径变量取得路径里面的值
如果是从ajax发送过来的Date里面取值可以使用@RequestParam获得属性值
使用RESTFUL最担心我的是路径请求冲突问题
一般采用请求方式的不同区分
如果请求方式一致那么就更改请求路径
RESTFUL请求风格路径应该使用名称,最好不要使用动词
分页,排序等操作,不需要使用斜杠传参数

springboot集成redis
a。操作redis数据类型的依赖

REmote DIctionary Server(Redis) 是一个由 Salvatore Sanfilippo 写的 key-value 存储系统,
是跨平台的非关系型数据库。
Redis 是一个开源的使用 ANSI C 语言编写、遵守 BSD 协议、支持网络、
可基于内存、分布式、可选持久性的键值对(Key-Value)存储数据库,并提供多种语言的 API。
Redis 通常被称为数据结构服务器,因为值(value)可以是字符串(String)、哈希(Hash)、
列表(list)、集合(sets)和有序集合(sorted sets)等类型。

*****springboot集成redis
测试redis的工具 redis Desktop Manager
1)添加依赖

org.springframework.boot spring-boot-starter-data-redis

2)在springboot核心配置文件中添加redis的配置

*springboot集成Dubo分布式框架
a。接口工程:存放实体bean和业务接口
b服务提供者:业务接口的实现类并将服务暴露且注册到注册中心,调用数据持久层
-添加依赖(dubbo,注册中心,接口工程)
-配置服务提供者核心配置文件
c。服务消费者:处理浏览器客户端发送的请求,从注册中心调用覅我提供者所提供的服务。
-添加依赖(dubbo,注册中心,接口工程)
-配置服务消费者核心配置文件

1.创建接口工程,springboot_dubbo_interface
提供者:springboot_dubbo_provider
消费者:springboot_dubbo_comsutor
注意在接口工程创建文件后要install不然提示找不到我文件
提供者配置文件:

#设置端口号
server.port=8081
#设置上下文根
server.servlet.context-path=/dubbo

#设置dubbo的配置
spring.application.name=springboot_dubbo_provider
#设置工程为服务提供者
spring.dubbo.server=true
#设置注册中心
spring.dubbo.registry=zookeeper://127.0.0.1:2181

在接口实现类上面添加
@Component
@Service(interfaceClass = StudnetService.class,version = “1.0.0”,timeout = 15000)
在程序入口添加
@EnableDubboConfiguration

消费者配置:
#设置端口号
server.port=8082
#设置上下文根
server.servlet.context-path=/consumtor

#设置dubbo的配置
spring.application.name=springboot_dubbo_provider
#设置注册中心
spring.dubbo.registry=zookeeper://127.0.0.1:2181

在使用提供者的类上面添加注解
@Reference(interfaceClass = StudnetService.class,version = “1.0.0”,timeout = 16000)
在程序入口处添加:@EnbleDubboConfiguration

注意关闭防火墙

    <!-- https://mvnrepository.com/artifact/org.apache.dubbo/dubbo-spring-boot-starter -->
    <dependency>
        <groupId>com.alibaba.spring.boot</groupId>
        <artifactId>dubbo-spring-boot-starter</artifactId>
        <version>2.0.0</version>

    </dependency>

    <!--&lt;!&ndash; 添加zoorkeeper,zkclient客户端&ndash;&gt;-->
    <!--<dependency>-->
        <!--<groupId>com.github.sgroschupf</groupId>-->
        <!--<artifactId>zkclient</artifactId>-->
        <!--<version>0.1</version>-->
    <!--</dependency>-->
    <!--  注册中心使用的是zookeeper,引入操作zookeeper的客户端端  -->
    <!--<dependency>-->
        <!--<groupId>org.apache.curator</groupId>-->
        <!--<artifactId>curator-framework</artifactId>-->
        <!--<version>2.12.0</version>-->
    <!--</dependency>-->
    <!-- 注册中心-->
    <!-- https://mvnrepository.com/artifact/com.101tec/zkclient -->
<!-- 使用的是以下的zoorkeeper依赖不知道为什么-->
    <dependency>
        <groupId>com.101tec</groupId>
        <artifactId>zkclient</artifactId>
        <version>0.11</version>
    </dependency>


    <!-- 引入接口工程-->
    <dependency>
        <groupId>com.anyu</groupId>
        <artifactId>dubbo_interface</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>



springboot集成dubbo,redis,Mybatis,Spring,Springmvc,JSP
a。接口工程:存放实体bean和业务接口
b。服务提供者:他是一个springboot框架web项目,集成MyBatis,Redis
-添加依赖:Mybatis依赖,Mysql驱动依赖,dubbo依赖,zookeeper依赖,Redis依赖,接口依赖
-配置spirngboot核心配置文件
-配置连接数据库
-配置连接redis
-配置dubbo
c。服务消费者:他是一个springboot项目,集成jsp,dubbo
-已添加依赖:duboo依赖
,zookeeper依赖,解析jsp页面的依赖,接口工程
     -配置Springboot核心配置文件
 -配置视图解析器
 -配置dubbo

关于找不到jsp的问题

    <resources>
        <resource>
            <directory>src/main/webapp</directory>
            <targetPath>META-INF/resources</targetPath>
            <includes>
                <include>*.*</include>
            </includes>
        </resource>
    springboot读取jsp是在META-INF/resources目录下,我们需要去指定这个文件夹!!!!


    redis:先去redis缓存中查询,如果有,直接使用,如果没有,去数据库查询并存放到redis缓存中,
    提示系统性能,用户体验提升。

     @Autowired
private RedisTemplate<Object,Object> redisTemplate;

  @Override

public Integer querystudentcount() {
/*
redis:先去redis缓存中查询,如果有,直接使用,如果没有,去数据库查询并存放到redis缓存中,
提示系统性能,用户体验提升。
*/
//先去缓存中查找有没有这个数据
Integer allstudntcount = (Integer) redisTemplate.opsForValue().get(“allstudntcount”);
//没有数据就查找并存放到redis数据库
if(null==allstudntcount){
allstudntcount= studentMapper.selectstudentcount();
redisTemplate.opsForValue().set(“allstudntcount”,allstudntcount,15, TimeUnit.HOURS);
}

return allstudntcount;

}

注意:无论是dubbo还是redis都需要开启各自的服务器

创建普通的springboot java程序
@SpringBootApplication
public class Application {

public static void main(String[] args) {
    /**
     * Springboot程序启动后,返回值是ConfigurableApplicationContext,它也是一个Spring容器
     * 它其实相当于原来Spring容器中启动容器ClasspathXmlApplicationContext
     */

    SpringApplication.run(Application.class, args);

    //获取Springboot容器
    ConfigurableApplicationContext applicationContext = SpringApplication.run(Application.class, args);

    //从spring容器中获取指定bean对象
    StudentService studentService = (StudentService) applicationContext.getBean("studentServiceImpl");

    //调用业务方法
    String sayHello = studentService.sayHello();

    System.out.println(sayHello);

}

}
第二种:
@SpringBootApplication //开启spring配置
public class Application implements CommandLineRunner {

@Autowired
private StudentService studentService;

public static void main(String[] args) {
    //SpringBoot启动程序,会初始化Spring容器
    SpringApplication.run(Application.class, args);
}


//重写CommandLineRunner类中的run方法
@Override
public void run(String... args) throws Exception {

    //调用业务方法
    String sayHello = studentService.sayHello("World");

    System.out.println(sayHello);
}

}

***在springboot中使用拦截器
在spring中
1)创建一个拦截器,实现HandleInterceptor接口
2)在springmvc配置文件中文件中使用mvc:interceptor
在springboot中
1)创建一个拦截器,实现HandleInterceptor接口
2)创建一个配置类代替在springmvc配置文件中文件中使用mvc:interceptor

在配置类上面添加注解:
@Configuration//定义此类为配置文件(即之间的springmvc的xml配置文件)
让这个类实现webmvcConfigurer
实现一个方法addIntercerptor 注入一个拦截器(相当于mvc:interceptors)
{

registry.addInterceptor(new UserInterceptor().addPathPatterns(拦截的路径).excludePathPatterns(排查的路径);
}

*springboot使用servlet
在spring中
1)创建一个servlet它要集成httpservlet
2)在web.xml文件定义个一个servlet和一个sevletmapping
在springboot中
springboot pom文件已经集成了servlet
第一种方式:
1)创建一个servlet它要集成httpservlet
2)在类上面添加一个注解@WebServlet(urlpatterns=“/myservlet”)
3)在springboot启动入口类上添加注解
@ServletComponentScan(basepackages=“com.anyu.springboot.Servlet”)
第二种方式:
1)创建一个servlet它要集成HttpServlet
2)创建一个配置类servletconfig
方法的返回值ServletRegistrationBean
@Configuration//该注解将此类定义为配置类(相当于一个xml配置文件)
public class ServletConfig {
//@Bean是一个方法级别上的注解,主要用于配置类

/*
   相当于一个
   <beans>
   <bean id=" " class=" ">
   <beans>
 */
@Bean
public ServletRegistrationBean TwoServletConfig(){
    ServletRegistrationBean servletRegistrationBean=new ServletRegistrationBean(new TwoServlet(),"/twoServlet");
    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);
}

}

springboot使用filter*
1.使用注解的方式
1)创建一个过滤器类继承 javax.servlet.Filter;(Filter)
2)实现doFilter方法
3)在类的上面添加注解@WebFilter @WebFilter(urlPatterns = “/filter”)
4)在入口启动类上面添加注解@ServletComponentScan(basepackages=“/com.anyu.Filter”)
@WebFilter(urlPatterns = “/myfilter”)
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);
}

}

2.使用配置类的方式
1)创建一个过滤器类继承 javax.servlet.Filter;(Filter)
2)创建配置类
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean TwoFilterConfig(){
FilterRegistrationBean filterRegistrationBean=new FilterRegistrationBean(new TwoFilter());
filterRegistrationBean.addUrlPatterns("/user/");
//一定要使用
不能使用**不然过滤不到

    return filterRegistrationBean;
}

}


springboot设置字符编码
1.直接在servlet里面更改
resp.setContentType(“text/html;character=utf-8”);
resp.setCharacterEncoding(“utf-8”);
2.使用配置类
1)@Configuration//将此定义为配置文件
public class EncodingConfig {
@Bean
public FilterRegistrationBean encodingbean(){
//创建字符编码过滤器
CharacterEncodingFilter characterEncodingFilter=new CharacterEncodingFilter();
//设置强制使用指定字符编码
characterEncodingFilter.setForceEncoding(true);
//设置指定字符编码
characterEncodingFilter.setEncoding(“utf-8”);
FilterRegistrationBean filterRegistrationBean=new FilterRegistrationBean();
filterRegistrationBean.setFilter(characterEncodingFilter);
//设置编码过滤的请求路径
filterRegistrationBean.addUrlPatterns(“/*”);
return filterRegistrationBean;
}
}
2)在servlet中使用
resp.setContentType(“text/html;character=utf-8”);
设置浏览器的字符编码
3)关闭springboot默认的字符编码格式
在application.properties中设置
#关闭springboot默认的字符编码
spring.http.encoding.enabled=false

3)第三种方式,修改springboot默认的配置
#第三种实现方式,直接在配置文件中配置
spring.http.encoding.enabled=true
spring.http.encoding.force=true
spring.http.encoding.charset=utf-8

***springboot项目的打包方式
默认是jar
1)修改打包方式war
2)在插件中添加

springbootwar
3)


src/main/webapp
META-INF/resources

.




src/main/resources

**/.



4)

org.apache.tomcat.embed
tomcat-embed-jasper

5)#配置视图解析器
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp
6)在程序入口继承SpringBootServletInitializer并重写configure方法
@SpringBootApplication
public class SpringbootWarApplication extends SpringBootServletInitializer {

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

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
    //参数为当前springboot启动类
    //构建新资源
    return builder.sources(SpringbootWarApplication.class);
}

}
7)给test添加public
8)打包并将war文件移动到tomcat webapp目录下
9)以管理的身份启动

遇到的问题:
打包失败,显示test启动入口不是公共的,添加public
tomcat布置失败,必须以管理员的身份启动

c盘权限不够 无法解压
放到其他地方 或者修改权限
就能成功解压 并加载项目

另外 在conf文件夹下server.xml中

unpackWARs=“true” 设置自动解压war

最后 如果还是不能自动解压
将war后缀改成zip 然后自己手动解压
然后启动tomcat

注意:之前在application.properties设置的上下文根和端口号无效,以本地tomcat为准

springboot打包成分jar包**
在 pom.xml 文件中添加 Tomcat 解析 jsp 依赖

org.apache.tomcat.embed
tomcat-embed-jasper

如果设置了
那么原先的资源指定目录就失效了,需要把resources目录也指定上,不然文件就消失了
在 pom.xml 文件中添加 resources 配置,以后为了保险起见,
大家在打包的时候,建议把下面的配置都加上
build>
springboot


src/main/webapp
META-INF/resources

.



src/main/resources

**/.





org.springframework.boot
spring-boot-maven-plugin
1.4.2.RELEASE



修改 application.properties 配置文件
#设置内嵌 Tomcat 端口号
server.port=9090
#设置项目上下文根
server.servlet.context-path=/ #配置 jsp 的前/后缀
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp
设置程序:
@Controller
public class IndexController {
@RequestMapping(value = “/abc”)
public String abc(Model model) {
model.addAttribute(“data”,“SpringBoot 框架打 jar 运行”);
return “abc”;
}
@RequestMapping(value = “/abc/json”)
public @ResponseBody Object json() {
Map<String,Object> paramMap = new HashMap<String, Object>();
paramMap.put(“code”,“10000”);
return paramMap;
} }
创建 webapp 并指定为 web 资源目录
通过 maven package 打包
1)将程序打包成jar
2)执行java-jar XXXX.jar
注意:如果部署后jsp无法使用,可能是springboot的版本问题,需要修改版本重新打包。
linux下执行jar

**springboot日志文件
在spring中使用的是在mybatis.xml文件中配置



只能打印到控制台
开发的时候使用
实际工作中使用的是logback
springboot推荐使用以-spring结尾的文件
例如logback-spring.xml
1)添加依赖

org.mybatis.spring.boot mybatis-spring-boot-starter 2.0.0 mysql mysql-connector-java org.apache.tomcat.embed tomcat-embed-jasper 2)设置properties文件 #设置内嵌 Tomcat 端口号 server.port=9090 #设置项目上下文根 server.servlet.context-path=/ #配置 jsp 的前/后缀 spring.mvc.view.prefix=/ spring.mvc.view.suffix=.jsp #配置连接 MySQL 数据库信息 spring.datasource.url=jdbc:mysql://192.168.92.134:3306/springboot?useUnicode =true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDa tetimeCode=false&serverTimezone=UTC spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.username=root spring.datasource.password=123456 3)逆向工程生成dao <?xml version="1.0" encoding="UTF-8"?>

connectionURL=“jdbc:mysql://localhost:3306/springboot”
userId=“root”
password=“123456”>








4)添加插件 在 pom.xml 文件 -> build -> plugins 中添加插件 org.mybatis.generator mybatis-generator-maven-plugin 1.3.6 GeneratorMapper.xml true true 5)指定资源文件夹 src/main/java **/*.xml src/main/resources **/*.* src/main/webapp META-INF/resources **/*.* 6)编写程序: 编写 StudentController @Slf4j @Controller public class StudentController { @Autowired private StudentService studentService; @RequestMapping(value = "/student/count") public @ResponseBody Object allStudentCount() { log.info("-----------查询开始------------"); Long allStudentCount = studentService.queryAllStudentCount(); log.info("-----------查询结束------------"); return "学生总人数为:" + allStudentCount; } } 7)编写service 编写 StudentService 接口及实现类 public interface StudentService { /** * 获取学生总人数 * @return */ Long queryAllStudentCount(); } @Service public class StudentServiceImpl implements StudentService { @Autowired private StudentMapper studentMapper; @Override public Long queryAllStudentCount() { return studentMapper.selectAllStudentCount(); } } 8)dao StudentMapper.java /** * 获取学生总人数 * @return */ Long selectAllStudentCount(); StudentMapper.xml select count(*) from t_student 9)写日志配置文件 Spring Boot 官方推荐优先使用带有 -spring 的文件名作为你的日志配置(如使用 logback-spring.xml ,而不是 logback.xml),命名为 logback-spring.xml 的日志配置文件。 默认的命名规则,并且放在 src/main/resources 下如果你即想完全掌控日志配置,但又不想 用 logback.xml 作为 Logback 配置的名字,application.yml 可以通过 logging.config 属性指定自 定义的名字: logging.config=classpath:logging-config.xml (1) 我们一般针对 DAO 的包进行 DEBUG 日志设置: 这样的话,只打印 SQL 语句: (2) 代码里打印日志 之前我们大多数时候自己在每个类创建日志对象去打印信息,比较麻烦: private static final Logger logger = LoggerFactory.getLogger(StudentServiceImpl.class); logger.error("xxx"); 现在可以直接在类上通过 @Slf4j 标签去声明式注解日志对象

A、 在 pom.xml 中添加依赖

org.projectlombok lombok 1.18.2 logback-spring.xml <?xml version="1.0" encoding="UTF-8"?> debug %date [%-5p] [%thread] %logger{60} [%file : %line] %msg%n UTF-8 D:/log/stdout.log %date [%-5p] %thread %logger{60} [%file : %line] %msg%n

D:/log/stdout.log.%d{yyyy-MM-dd}.log</fileNamePatter
n>
30








10)启动类:
@SpringBootApplication
@MapperScan(basePackages = “com.abc.springboot.mapper”)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
} }

thymeleaf*
jsp需要先编译才能渲染被淘汰,出现模板引擎
thymeleaf为了实现前后端分离 基于html,java写的
在xml文件中引入命名空间
xmlns:th=“http://www.thymeleaf.org”
让用户体验更好
使用的时候让页面实时更新:关闭缓存,在run config中更新资源
spring.thymeleaf.cache=false
idea配置更新资源

命名空间后面的地址是一个约束文件,约束你使用thymeleaf表达式
的一个规则文件,就好比我们之前在xml文件中的dtd
pom。xml

org.springframework.boot
spring-boot-starter-parent
2.1.1.RELEASE

视图解析器默认
#spring.thymeleaf.prefix=classpath:/templates/

#spring.thymeleaf.suffix=.html
可不写。默认

表达式*****
xmlns:th="http://www.thymeleaf.org"必须加,不然识别不到th表达式

Title

用户的姓名:

标准变量表达式:(推荐)

${}必须依托于html标签,在标签里面

选择变量表达式(星号表达式)*{}(不推荐)

*{}必须使用th:object属性来绑定这个对象 在div子标签中使用*来代替绑定的对象${username}

user的id:
user的username:
user的password:
我写入的user的id属性

标准变量表达式与选择变量表达式的混合使用(不推荐)

用户id: 用户姓名: 用户密码:

URL路径表达式

Title

url路径表达式:@{...}

a标签中的绝对路径(没有参数)

html中的传统写法
thymeleaf的路径写法
html中的传统写法到index页面
thymeleaf的路径写法到index页面

url路径表达式,相对路径{没有参数}(实际开发中推荐使用)

传统相对路径到index页面
thymeleaf相对路径到index页面

绝对路径路径带参数(不推荐)

传统写法带参数
thymeleaf写法带参数

相对路径带参数

thymeleaf相对写法带参数
thymeleaf相对写法带多个参数
thymeleaf相对写法带多个参数省略写法

一般来说我们使用thymeleaf是从后台取值的时候才使用,不取值时还是使用html
thymeleaf循环
th:each=“user,userstat: u s e r L i s t " 其中 u s e r s t a t 是状态可写可不写不写是 t h : e a c h = " u s e r : {userList}" 其中userstat是状态可写可不写 不写是 th:each="user: userList"其中userstat是状态可写可不写不写是th:each="user:{userList}”

th:*属性。 说明
th:id id声明,类似html标签中的id属性
th:each 元素遍历(类似JSP中的c:forEach标签)
th:if 条件判断,如果为真
th:unless 条件判断,如果为假
th:value 属性值修改,指定标签属性值
th:href 用于设定链接地址
th:src 用于设定链接地址
th:text 用于指定标签显示的文本内容
th:action 定义后台控制器路径,类似标签的action属性
th:field 常用于表单字段绑定,通常与th:object一起使用, 属性绑定、集合绑定
th:object 用于表单数据对象绑定

种类 表达式语法 说明
变量表达式 ${…} 主要用于获取域对象中的变量值,类似EL表达式
链接URL表达式 @{…} 用于 th:src 和 th:href,th:action属性中
片段表达式 ~{…} 使用th:insert或th:replace属性插入片段
消息表达式 #{…} 通常与th:text属性一起使用,指明声明了th:text的标签的文本是#{}中的key所对应的value,而标签内的文本将不会显示。
选择表达式 *{} 只要是没有选择的对象,选择表达式与变量表达式的语法是完全一样的
如果选择了对象,选择表达式计算的是选定的对象,而不是整个环境变量映射
工具对象表达式 #maps 常用于日期、集合、数组对象的访问

内敛文本:th:inline

数据:[[${data}]]
这个数据可以写在div里面,但是在外面也有结果,官方不推荐

内敛脚本 th:inline=“JavaScript"

字符串拼接:
正常
th:text=“‘共’+ x x x + ′ 页 ′ " 更优雅的方式使用 ∣ ∣ t h : t e x t = " ∣ 共 {xxx}+'页' " 更优雅的方式使用| | th:text="|共 xxx+"更优雅的方式使用∣∣th:text="∣{xxx}页|”

运算符:

三元运算符 表达式?正确:错误

算术运算

20+5=
20-5=
20*5=
20/5=
20%3=

关系比较

5>2为 真
5>2为 真
5<2 真
5<2 真
1>=1 真
1>=1 真
1<=1 真
1<=1 真

相等判断

男 男 女

基本表达式对象
request session
从session中取值
th:text=“${#session.getAttribute(‘data’)}}”

th:text=“${#Httpsession.getAttribute(‘data’)}}”

th:text=“${#session.data}”

使用request解析路径
http://localhost:8080/springboot/user
http:协议getSchema
localhost:服务器名称 getServerName
8080:端口号 getServerPort
springboot:上下文根 getContextPath
user :URL
请求参数:HttpServletRequest.queryString
获取全路径 HttpServletRequest.requestURL
使用内敛javascript

功能性表达式对象
模板引擎提供的一组功能性内置对象,可以在模板中直接使用这些对象提供的功能方法
工作中常使用的数据类型,如集合,时间,数值,可以使用 Thymeleaf 的提供的功能性对象
来处理它们

内置功能对象前都需要加#号,内置对象一般都以 s 结尾
官方手册:http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html
#dates: java.util.Date 对象的实用方法:

#calendars: 和 dates 类似, 但是 java.util.Calendar 对象;
#numbers: 格式化数字对象的实用方法;
#strings: 字符串对象的实用方法: contains, startsWith, prepending/appending 等;
#objects: 对 objects 操作的实用方法;
#bools: 对布尔值求值的实用方法;
#arrays: 数组的实用方法;
#lists: list 的实用方法,比如
#sets: set 的实用方法;
#maps: map 的实用方法;
#aggregates: 对数组或集合创建聚合的实用方法;

setx VAGRANT_HOME “D:\VirtualBox\HOME/.vagrant.d” /M

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值