SpringBoot study notes (2) - power node of station B

003- springboot and web components

3.1 Using interceptors in springboot

拦截器是SpringMVC中一种对象,能拦截器对Controller的请求。

拦截器框架中有系统的拦截器, 还可以自定义拦截器。 实现对请求预先处理。

实现自定义拦截器:

1.创建实现类 实现SpringMVC框架的HandlerInterceptor接口
public interface HandlerInterceptor {
    
    
    default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
    
        return true;
    }

    default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    
    
    }

    default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    
    
    }
}

2. The interceptor needs to be declared in the configuration file of SpringMVC

<mvc:interceptors>
	<mvc:interceptor>
    	<mvc:path="url" />
        <bean class="拦截器类全限定名称"/>
    </mvc:interceptor>
</mvc:interceptors>

insert image description here


springboot中如何使用拦截器

insert image description hereinsert image description hereinsert image description here
insert image description here
insert image description here

3.2 Using servlets in springboot

在SpringBoot框架中使用Servlet对象。

使用步骤:

1.创建Servlet类。 创建类继承HttpServlet
2.注册Servlet。   让框架能找到Servlet

insert image description hereinsert image description hereinsert image description here

3.3 Use Filter in springboot

Filter是Servlet规范中的过滤器,可以处理请求, 对请求的参数, 属性进行调整。 
常常在过滤器中处理字符编码

Use filters in frames:

  1. Create a custom filter class that implements the Filter interface
  2. Register Filter object

insert image description here
insert image description hereinsert image description hereinsert image description hereinsert image description here

3.4 Character set filter

CharacterEncodingFilter: 解决post请求中乱码的问题

在SpringMVC框架, 在web.xml 注册过滤器。 配置他的属性。

在springboot中使用:

第一种方式:
	自己创建字符集过滤器,太麻烦了,直接第二种方式。
第二种方式:
	修改application.properties文件
	springboot默认有字符集过滤器CharacterEncdoingFilter 不需要自己创建
	编码方式 默认是ISO-8859-1
server.port=9001
server.servlet.context-path=/myboot

#让系统的CharacterEncdoingFilter生效  默认就是true 可以不写
server.servlet.encoding.enabled=true
#指定使用的编码方式
server.servlet.encoding.charset=utf-8
#强制request,response都使用charset属性的值
server.servlet.encoding.force=true

004- ORM operates MySQL (springboot integrates mybatis)

4.1 Basic Operation

(1) The first way: @Mapper

使用MyBatis框架操作数据, 在SpringBoot框架集成MyBatis

Steps for usage:

  1. Mybatis start-up dependency: complete the automatic configuration of mybatis objects, and put the objects in the container
  2. pom.xml specifies to include the xml file in the src/main/java directory into the classpath
  3. Create entity class Student
  4. Create a Dao interface StudentDao and create a method to query students
  5. Create the Mapper file corresponding to the Dao interface, that is, the xml file, and write the sql statement
  6. Create a Service layer object, create a StudentService interface and its implementation class. The method to go to the dao object. Complete the database operation
  7. Create a Controller object and access the Service.
  8. Write application.properties file. Configure the connection information for the database.

insert image description here
insert image description hereinsert image description hereinsert image description here


pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.4.2</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.bjpowernode</groupId>
	<artifactId>017-springboot-mapper</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<!--weby起步依赖 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<!--mybatis起步依赖-->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.1.4</version>
		</dependency>

		<!--mysql驱动-->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>

		<!--测试-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<!--resources插件-->
		<resources>
			<resource>
				<directory>src/main/java</directory>
				<includes>
					<include>**/*.xml</include>
				</includes>
			</resource>
		</resources>


		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

insert image description here


insert image description hereinsert image description hereinsert image description hereinsert image description hereinsert image description hereinsert image description here
insert image description hereinsert image description here
insert image description here
insert image description here


The first way: @Mapper (on top of the dao interface, each interface needs to use this annotation)

/**
 * @Mapper:告诉MyBatis这是dao接口,创建此接口的代理对象。
 *     位置:在类的上面
 */
@Mapper
public interface StudentDao {
    
    

    Student selectById(@Param("stuId") Integer id);
}
弊端:如果有50个接口 就要写50次@Mapper

(2) The second way: @MapperScan

不在dao接口上写@Mapper
在主类上写 @MapperScan(basePackages = "com.bjpowernode.dao")
	basePackages:指定 dao 接口所在的包名。
/**
* @MapperScan: 扫描所有的 mybatis 的 dao 接口
* 位置:在主类的上面
* 属性:basePackages:指定 dao 接口的所在的包名。
* dao 接口和 mapper 文件依然在同一目录
 */
//dao包和mapper包下都有dao接口
@SpringBootApplication
@MapperScan(basePackages = {
    
    "com.bjpowernode.dao","com.bjpowernode.mapper"})
public class Application {
    
    
}

(3) The third method: the Mapper file and the Dao interface are managed separately

It is recommended to use the third method

Steps: Now put the Mapper file in the resources directory

1) Create a subdirectory (custom) such as mapper in the resources directory

2) Put the mapper file in the mapper directory

3) In the application.properties file, specify the directory of the mapper file

#指定mapper文件的位置
mybatis.mapper-locations=classpath:mapper/*.xml
#指定mybatis的日志
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

4) Specify in pom.xml to compile the files in the resources directory into the target directory

<!--resources插件-->
<resources>
   <resource>
      <directory>src/main/resources</directory>
      <includes>
         <include>**/*.*</include>
      </includes>
   </resource>
</resources>

Others are consistent with the second method
Note that @MapperScan=(basePackages=dao interface package) should be added to the main class


insert image description hereinsert image description hereinsert image description here
insert image description here

4.2 Transactions

Transactions in the Spring framework:

1) Objects that manage transactions: transaction managers (interfaces, interfaces have many implementation classes)

​ For example: use Jdbc or mybatis to access the database, the transaction manager used: DataSourceTransactionManager

2) Declarative transaction: In the xml configuration file or use annotations to describe the content of transaction control

​ Control transactions: isolation level, propagation behavior, timeout

3) Transaction processing method:

1) @Transactional in the Spring framework

2) The aspectj framework can declare the content of transaction control in the xml configuration file


Using transactions in SpringBoot: Both of the above methods are fine.

1) Add @Transactional above the business method. After adding the annotation, the method has a transaction function.

2) Clearly above the main startup class, add @EnableTransactionManager


insert image description hereinsert image description hereinsert image description here


insert image description here

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.4.2</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.bjpowernode</groupId>
	<artifactId>019-springboot-transactional</artifactId>
	<version>0.0.1-SNAPSHOT</version>


	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<!--MyBatis起步依赖-->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.1.4</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>

		<!--处理资源目录-->
		<resources>
			<resource>
				<directory>src/main/resources</directory>
				<includes>
					<include>**/*.*</include>
				</includes>
			</resource>
		</resources>
		<plugins>
			<!--mybatis代码自动生成插件-->
			<plugin>
				<groupId>org.mybatis.generator</groupId>
				<artifactId>mybatis-generator-maven-plugin</artifactId>
				<version>1.3.6</version>
				<configuration>
					<!--配置文件的位置: 在项目的根目录下,和src平级的-->
					<configurationFile>GeneratorMapper.xml</configurationFile>
					<verbose>true</verbose>
					<overwrite>true</overwrite>
				</configuration>
			</plugin>

			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>


insert image description hereinsert image description here

<?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>

    <!-- 指定连接数据库的JDBC驱动包所在位置,指定到你本机的完整路径 -->
    <classPathEntry location="D:\tools\mysql-connector-java-8.0.22.jar"/>

    <!-- 配置table表信息内容体,targetRuntime指定采用MyBatis3的版本 -->
    <context id="tables" targetRuntime="MyBatis3">

        <!-- 抑制生成注释,由于生成的注释都是英文的,可以不让它生成 -->
        <commentGenerator>
            <property name="suppressAllComments" value="true" />
        </commentGenerator>

        <!-- 配置数据库连接信息 -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/springdb?useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=Asia/Shanghai"
                        userId="root"
                        password="123">
        </jdbcConnection>

        <!-- 生成model类,targetPackage指定model类的包名, targetProject指定生成的model放在eclipse的哪个工程下面-->
        <javaModelGenerator targetPackage="com.bjpowernode.model"
                            targetProject="D:\course\25-SpringBoot\springboot-prj\019-springboot-transactional\src\main\java">
            <property name="enableSubPackages" value="false" />
            <property name="trimStrings" value="false" />
        </javaModelGenerator>

        <!-- 生成MyBatis的Mapper.xml文件,targetPackage指定mapper.xml文件的包名, targetProject指定生成的mapper.xml放在eclipse的哪个工程下面 -->
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>

        <!-- 生成MyBatis的Mapper接口类文件,targetPackage指定Mapper接口类的包名, targetProject指定生成的Mapper接口放在eclipse的哪个工程下面 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.bjpowernode.dao" targetProject="src/main/java">
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>

        <!-- 数据库表名及对应的Java模型类名 -->
        <table tableName="student" domainObjectName="Student"
               enableCountByExample="false"
               enableUpdateByExample="false"
               enableDeleteByExample="false"
               enableSelectByExample="false"
               selectByExampleQueryId="false"/>


    </context>

</generatorConfiguration>

insert image description here
insert image description here


insert image description here


insert image description here
insert image description here
insert image description here
insert image description hereinsert image description here

005- Interface architecture style - RESTful

5.1 Understanding RESTful

接口: API(Application Programming Interface,应用程序接口)
是一些预先定义的接口(如函数、HTTP接口)或指软件系统不同组成部分衔接的约定。 
用来提供应用程序与开发人员基于某软件或硬件得以访问的一组例程,而又无需访问源码,或理解内部工作机制的细节。

接口(API):
	广义上来说,可以指访问servlet,controller的url,或者调用其他程序的 函数

架构风格: api组织方式(样子)(接口怎么写 格式)
	这是一个传统的写法: http://localhost:9002/mytrans/addStudent?name=lisi&age=26
	在地址上提供了 访问的资源名称addStudent, 在其后使用了get方式传递参数。

insert image description here


RESTful架构风格

1)REST:
	(英文:Representational State Transfer,中文:表现层状态转移)。

REST:是一种接口的架构风格和设计的理念,不是标准。

优点: 更简洁,更有层次

表现层状态转移:
​	表现层就是视图层,显示资源的,通过视图页面,jsp等等显示操作资源的结果。
​ 	状态:资源变化
​ 	转移:资源可以变化的。资源能创建,new状态,资源创建后可以查询资源,能看到资源的内容。
		 这个资源内容,可以被修改,修改后资源 和之前的不一样。

2)REST中的要素:
	用REST表示资源和对资源的操作。 在互联网中,表示一个资源或者一个操作。
	资源使用url表示的,在互联网,使用的图片,视频,文本,网页等等都是资源。
	资源是用名词表示。
	
	对资源的操作:
		查询资源: 看,通过url找到资源。
		创建资源: 添加资源
		更新资源: 更新资源,编辑
	    删除资源: 去除

insert image description here


insert image description hereinsert image description here


insert image description here


insert image description here

Explain REST in one sentence: use url to represent resources, and use http actions to operate resources.

5.2 RESTful annotations

(1) Basic operation

Spring Boot 开发 RESTful 
主要是由几个注解实现

insert image description here


insert image description hereinsert image description hereinsert image description here

insert image description here


insert image description hereinsert image description hereinsert image description hereinsert image description here


insert image description here

使用postman

insert image description hereinsert image description here

insert image description here


insert image description hereinsert image description hereinsert image description hereinsert image description hereinsert image description here


(2) Support put/delete requests in page/ajax

insert image description here

insert image description hereinsert image description hereinsert image description hereinsert image description hereinsert image description hereinsert image description here
insert image description here
insert image description here
insert image description here
insert image description here

(3) Note

要保证:请求方式+url 唯一

insert image description here

Guess you like

Origin blog.csdn.net/m0_52041525/article/details/125873385
Recommended