Catalogue of series articles
Tip: you can add the directories of all articles in the series here. You need to add the directories manually
For example, the first chapter is the use of pandas, an introduction to Python machine learning
Tip: after writing the article, the directory can be generated automatically. For how to generate it, please refer to the help document on the right
preface
Tip: Here you can add the general contents to be recorded in this article:
For example, with the continuous development of artificial intelligence, machine learning technology is becoming more and more important. Many people have started learning machine learning. This paper introduces the basic content of machine learning.
Tip: the following is the main content of this article. The following cases can be used for reference
1, What is pandas?
Example: pandas is a NumPy based tool created to solve data analysis tasks.
2, Use steps
1. Import and storage
The code is as follows (example):
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import warnings warnings.filterwarnings('ignore') import ssl ssl._create_default_https_context = ssl._create_unverified_context
2. Read in data
The code is as follows (example):
data = pd.read_csv( 'https://labfile.oss.aliyuncs.com/courses/1283/adult.data.csv') print(data.head())
The url used here is the data requested by the network.
summary
Tip: here is a summary of the article:
For example, the above is what we want to talk about today. This paper only briefly introduces the use of pandas, which provides a large number of functions and methods that enable us to process data quickly and conveniently.
SpringBoot learn one
Spring boot is designed based on spring 4.0. It not only inherits the original excellent features of spring framework, but also further simplifies the whole construction and development process of spring application by simplifying configuration. In addition, SpringBoot integrates a large number of frameworks to solve the version conflict of dependent packages and the instability of references.
Advantages of SpringBoot:
- You can create independent Spring applications, and based on its Maven or Gradle plug-ins, you can create executable JARs and WARs;
- Embedded Servlet containers such as Tomcat or Jetty;
- Provide automatically configured starter project object model (POMS) to simplify Maven configuration;
- Configure the Spring container automatically as much as possible;
- Provide prepared features, such as indicators, health checks and externalized configurations;
- Absolutely no code generation, no XML configuration required.
1. Learning objectives & mind map
2. Development history of spring framework
2.1.Spring1.x Era
In the spring 1. X era, bean s are configured through xml files. With the continuous expansion of the project, xml configuration needs to be divided into different configuration files, and frequent switching between java classes and xml configuration files is required.
2.2. Spring 2. X Era
With the annotation support brought by JDK1.5, spring 2. X can use annotations to declare and inject beans, greatly reducing xml configuration files and greatly simplifying project development.
So, the question is, should we use xml or annotations?
Best practices:
-
xml is used for the basic configuration of the application, such as data source, resource file, etc;
-
Annotations for business development, such as injecting bean s into Service;
2.3.Spring3.x to Spring4.x to Spring5.x
Since spring 3. X, Java configuration mode has been provided. Using java configuration mode can better understand the beans you configure. Now we are in this era, and spring 4. X, spring 5. X and Spring Boot all recommend using java configuration mode.
3. Spring 5.X application zero configuration development
From version 5.x, the Spring framework recommends the use of annotations to develop and configure java applications, and can completely replace the original development in the form of XML + annotations
During project development and environment configuration in the form of solution, the Spring framework provides annotations related to environment configuration and business bean development.
3.1 notes
3.1.1 💖 Declare Bean annotations
@component:The role of the component is not clearly defined, and the current class is declared as a business component at the class level Spring Ioc Vessel maintenance @service:At the business logic layer(Service layer)Class level declaration @Repository:In the data access layer(dao layer)Class level declaration @contro1ler:In the presentation layer(MVC)Use annotation to label the current class as a controller
3.1.2 inject Bean annotation
@Autowired: spring Official comments @Inject: ]SR-330 Provide notes (standard setter)) @Resource: JSR-250 Provide comments
The above three annotations are declared on the Set method or attribute. Generally, they are more used to declaring on the attribute in general development, and the code is concise and clear. The 5.x annotation configuration method simplifies the xml configuration, and the application development and xml environment configuration are realized through corresponding annotations.
3.1.3 configuring and obtaining Bean annotations in spring 5. X
@configuration:On the function and class, declare the current class as a configuration class, which is equivalent to a configuration class xml configuration file @comporentscan:Automatically scan the specified package marked with@Repository ,@service,@controller @component:Annotated class and by Ioc Instantiate and maintain containers @Bean:Act on method,amount to xml In the file<bean>Declare the return value of the current method as a bean @value:obtain properties File assignment key value value
3.2 instantiation and acquisition of beans in chestnut 1-IOC
3.2.1 creating a common Spring project
Add Spring coordinate related configuration in pom.xml
<!--add to Spring Dependent coordinates of--> <!-- https://mvnrepository.com/artifact/org.springframework/spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.9</version> </dependency>
Add a compilation environment plug-in in pom.xml
<plugins> <!-- Compilation environment plug-in --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <!--Source code used JDK edition--> <source>1.8</source> <!--Target to be generated class The compiled version of the file--> <target>1.8</target> <!--Set character set encoding--> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins>
3.2.2 create Bean object
@Repository public class UserDao { public void test(){ System.out.println("UserDao Test..."); } } @Service public class UserService { //Injection object @Resource private UserDao userDao; public void test(){ System.out.println("UserService Test..."); userDao.test(); } }
3.2.3 create IocConfig configuration class
//Declare the current class as a configuration class @Configuration //Set the scope of the scan package @ComponentScan("com.fx.springboot") public class IocConfig { }
3.2.4 create startup class to execute test
public class Test01 { public static void main(String[] args) { //The Java based configuration class loads the context environment of Spring applications AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(IocConfig.class); //Gets the specified bean object UserService userService = ac.getBean(UserService.class); //Call method userService.test(); } }
At this time, start the Spring lOC container, instantiate the AnnotationConfigApplicationContext class, receive the configuration parameter class locConfig, and obtain the UserService Bean implementation method call. At this time, there is no xml configuration file in the application environment, which simplifies the xml configuration of the application
3.3 use of chestnut 2-@Bean annotation
Use the @ Bean annotation declaration to return the instantiated Bean object at the method (Note: the method name is generally the Bean object name) level.
3.3.1 create Bean object
//Bean object public class AccountDao { public void test(){ System.out.println("AccountDao Test..."); } }
3.3.2 declaring configuration classes
//Declare the current class as a configuration class @Configuration //Set the scope of the scan package @ComponentScan("com.fx.springboot") public class IocConfig02 { //@Bean annotation: it is usually used to integrate third-party bean objects, such as data sources, third-party components, etc. (only instantiated bean objects are required) @Bean //Give the return value of the method to the IOC container for maintenance public AccountDao accountDao(){ return new AccountDao(); } }
3.3.3 testing
//The Java based configuration class loads the context environment of Spring applications AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(IocConfig02.class); //Get configuration class object IocConfig02 iocConfig02 = ac.getBean(IocConfig02.class); //Returns a Boolean type. true indicates that it is a singleton, and false indicates that it is not a singleton System.out.println(ac.isSingleton("iocConfig02")); AccountDao accountDao = iocConfig02.accountDao(); accountDao.test();
3.4 chestnut 3 - read external configuration file
When developing Java web applications, configuration files are common, such as xml, properties, yml and other files. In Spring applications, the reading of configuration files is also supported. For configuration file reading, we can specify the reading of relevant configurations by declaring @ PropertySource annotation to class level.
Spring EI expression language supports the use of expressions in Xml and annotations, similar to EL expressions in JSP. The spring framework uses this expression to realize resource injection. It mainly uses the * * @ Value * * annotation to use expressions. Through the @ Value annotation, it can realize parameter injection such as ordinary string, expression operation results, Bean property file content and property file. The specific use is as follows:
3.4.1 preparation of configuration files
Add user.properties and jdbc.properties files in src/main/resources directory
# user.properties user.userName=admin user.password=admin #jdbc.properties jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://127.0.0.1:3306/hr?useUnicode=true&characterEncoding=utf8 jdbc.username=root jdbc.password=123456
3.4.2 @PropertySource loading configuration resources
Load the Property configuration file through @ PropertySource
//Declare the current class as a configuration class @Configuration //Set the scope of the scan package @ComponentScan("com.fx.springboot") @PropertySource(value = {"classpath:jdbc.properties","classpath:jdbc.properties"}) public class IocConfig03 { //Gets the value of the property in the jdbc.properties file @Value("${jdbc.driver}") private String driver; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; }
Profile:
//Load context AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(IocConfig03.class); //Get configuration class object IocConfig03 iocConfig03 = ac.getBean(IocConfig03.class); System.out.println(iocConfig03.toString());
3.4.3 other Bean objects obtain the contents of the Properties file
Load once, and then get it in other classes through the @ Value property
@Service public class UserService { //Injection object @Resource private UserDao userDao; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; public void test(){ System.out.println("UserService Test..."); userDao.test(); //Gets the properties in the configuration file System.out.println("full name:"+username+",password"+password); } }
3.5 combined annotation and meta annotation
Spring has introduced annotation support since version 2.x (the purpose is to introduce the annotation function in jdk1.5) to eliminate a large number of xml configurations by introducing annotations. The annotations introduced by spring are mainly used to inject bean and aop aspect related configurations. However, due to the extensive use of annotations, a large number of duplicate annotation codes will appear, and the codes will be repeated. In order to eliminate duplicate annotations, The introduction of composite annotation in meta annotation can be understood as code reconstruction, which is equivalent to annotation annotation. It has the original function of meta annotation. For example, the @ Configuration annotation used in defining the Configuration class is composite annotation, and has the @ Component annotation function, that is, the Configuration class itself is also a single bean maintained by IOC.
3.5.1 user defined combined annotation
Define MyCompScan annotation and have the annotation function of @ ComponentScan scanner
Custom annotation is a refactoring of annotations to simplify annotations
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @ComponentScan public @interface MyCompScan { String[] value() default {}; }
4. Spring MVC zero configuration creation & Deployment
Based on Spring Mvc 5.X, use Maven to build a Spring MVC web project, and create and deploy the project through the annotations and related configurations provided by Spring.
4.1 create spring MVC web project
Create Maven's web project
4.2 add coordinate related configuration to pom.xml
<!--Spring web Coordinate dependence--> <!-- https://mvnrepository.com/artifact/org.springframework/spring-web --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.3.9</version> </dependency> <!--Spring-webmvc Coordinate dependence--> <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.9</version> </dependency> <!--web servlet--> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency>
plug-in unit:
<build> <finalName>SpringBoot1002</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> </pluginManagement> </build>
4.3 adding source code
@Controller public class HelloController { @RequestMapping("/index") public String index(){ return "index"; } }
4.4 adding views
Create index.jsp in the WEB-INF/views directory (JSP is used as the template here)
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h2>hello MVC</h2> </body> </html>
4.5 spring MVC configuration class addition
The Spring Mvc configuration information MvcConfig file is added as the MVC framework environment. Originally, it is configured through xml (view parser, Json converter, file upload parser, etc.). Here, based on the annotation, it is configured by inheriting the WebMvcConfigurerAdapter class and rewriting relevant methods (note that the MVC environment is started through the @ EnableWebMvc annotation).
/** * Configure JSP view parser * @return */ @Bean//Give the method return value to the IOC container for maintenance public InternalResourceViewResolver viewResolver(){ //Get view parser InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); //Set prefix viewResolver.setPrefix("/WEB-INF/views/"); //Set suffix viewResolver.setPrefix(".jsp"); //Return to the view parser (handed over to the IOC container for maintenance) return viewResolver; }
After the MvcConfig class is defined, the problem arises. How to load the MvcConfig class? Originally, when building the Mvc application, the configuration file is loaded by loading the web.xml file when the application is started by the container. The current environment web.xml file does not exist. At this time, the Mvc application built based on annotation defines WebInitializer to implement the WebApplicationInitializer interface (this interface is used to configure the interface of Servlet3.0 + configuration to replace the web.xml configuration). When the servlet container starts the Mvc application, it will load the Mvc application information configuration through the springservletcontainerstarter interface. Implement the onStartup method of this interface to load the application information configuration.
4.6 adding entry file code
public class WebInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { //Get the context of Spring application AnnotationConfigWebApplicationContext ac = new AnnotationConfigWebApplicationContext(); //Register MVC configuration class ac.register(MvcConfig.class); //Set the context information of ServletContext ac.setServletContext(servletContext); //Configure forwarder ServletRegistration.Dynamic servlet=servletContext.addServlet("dispatcher",new DispatcherServlet(ac)); //Set mapping path servlet.addMapping("/"); //De instantiate Bean at startup servlet.setLoadOnStartup(1); } }
4.7 deployment and testing
Deploying tests on Tomcat
5. SpringBoot concepts and features
5.1 framework concept
With the popularity of dynamic languages (Ruby, Scala, NodeJs, etc.), Java development has become relatively cumbersome, cumbersome configuration, low development efficiency, complex deployment process, and relatively difficult third-party integration. For this environment, Spring Boot has been developed, and its usage * * habit is greater than the configuration goal **, with the help of Spring Boot, the project can run quickly. At the same time, with the help of Spring Boot, the web application can be quickly created and deployed independently (jar package, war package, embedded servlet container). At the same time, with the help of Spring Boot, the relevant xml environment configuration can be done without or rarely when developing the application, which simplifies the development and greatly improves the project development efficiency.
Spring Boot is a new framework provided by pivot team. Its design purpose is to simplify the initial construction and development process of spring applications. The framework uses a specific way to configure, so that developers no longer need to define template configuration. In this way, Spring Boot can be used in the booming field of rapid application development (rapid application development) become a leader.
5.2 frame features
Create independent Spring applications, embedded Tomcat, Jetty containers, no need to deploy WAR packages, simplify Maven and Gradle configuration, and configure Spring as automatically as possible. Directly implant practical functions in the product environment, such as metrics, health check and extension configuration, no code generation and XML configuration. At the same time, Spring Boot not only simplifies web applications, but also provides a Series rely on packages to make other work out of the box.
5.3 Spring Boot quick start
5.3.1 environmental preparation
Idea,Maven,Jdk1.8,Spring Boot2.0x
5.3.2 create project
Create a normal Maven project
5.3.3 add dependent coordinates
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.2</version> <relativePath/> <!-- lookup parent from repository --> </parent> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
The Spring Boot project must set the parent to the Spring Boot parent, which contains a large number of default configurations to simplify program development
5.3.4 import web coordinates and related plug-ins of Spring Boot
<plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins>
5.3.5 add source code
@Controller public class HelloController { @RequestMapping("/hello") @ResponseBody public String hello(){ return "hello SpringBoot"; } }
5.3.6 create startup program
@SpringBootApplication public class Test01Application { public static void main(String[] args) { SpringApplication.run(Test01Application.class); } }
5.3.7 start Spring Boot application and test
6.Spring Boot core configuration
6.1 setting the Banner Icon
When building the Spring Boot project environment, after the program is started, a striking SpringBoot icon will be printed on the console. The icon describes the SpringBoot version information. This is a big difference between Spring Boot project and spring project startup. Spring Boot displays the application startup icon when the program is started through the default Banner. Of course, the icon can also be customized.
6.1.1 Banner icon customization
When the Spring Boot project starts, the banner.txt icon file under the src/main/resources daily record is loaded by default. If the directory file is not provided, the Spring Boot default is used. Create a new resources resource directory under the main directory and a new banner.txt text file under the directory. You can set custom icons.
Generate banner icon online website: banner Icon
Create your own Banner.txt icon in the resources directory
6.1.2 Banner Icon
If you don't want to see the startup icon during startup, you can also close it through code. Modify the StarterApplication, set the BannerMode value Banner.Mode.OFF, start the Spring Boot application, and close the icon output function
SpringApplication springApplication = new SpringApplication(Test01Application.class); //Set Banner icon off springApplication.setBannerMode(Banner.Mode.OFF); //Start SpringBoot springApplication.run();
6.2 Spring Boot configuration file
Spring Boot will read the global configuration file by default. The configuration file name is fixed as application.properties or application.yml. It is placed in the src/main/resources resource directory. Use the configuration file to modify the default value of Spring Boot automatic configuration.
Add the application.properties file in the resources resource directory. The configuration information is as follows:
application.properties:
#Set the port number on which the project starts server.port=8899 #Set the access path of the project (context / site name) server.servlet.context-path=/mvc/ ##Data source configuration spring.datasource.driver-class-name=com. mysq1.cj.jdbc.Driver spring.datasource.ur1=jdbc:mysql://127.0.0.1:3306/hr? useUnicode=true&characterEncodi ng=utf8 spring.datasource.username=root spring.datasource.password=root
application.yml:
#Set the port number of the project server: port: 8866 #Set the access path of the project servlet: context-path: /mvc02
6.3 Starter coordinates & Automation configuration
6.3.1 Starter coordinate configuration
Spring Boot introduces a new Starter coordinate system to simplify the Starter pom of most scenarios of enterprise project development. The application can eliminate the related configuration of the Start pom of the specified scenario, and the automatically configured Bean can be obtained through Spring Boot.
6.3.1.1 web Starter
Use Spring MVC to construct RESTful Web applications, and use Tomcat as the default embedded container
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
6.3.1.2 freemarker&thymeleaf Starter
Rendering views using Trymeleaf in MVC applications
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
6.3.1.3 appendix, common Starter
name | describe |
---|---|
spring-boot-starter-thymeleaf | Enabling MVC Web applications to support Thymeleaf |
spring-boot-starter-mail | Sending support using Java Mail and Spring email |
spring-boot-starter-data-redis | The Redis key value is used to store the database through Spring Data Redis and Jedis client |
spring-boot-starter-web | Build the Web, including the RESTful style framework spring MVC and the default embedded container Tomcat |
spring-boot-starter-activemq | Using Apache ActiveMQ for JMS |
spring-boot-starter-data-elasticsearch | Use Elasticsearch, analytics engine, Spring Data Elasticsearch |
spring-boot-starter-aop | Aspect oriented programming through Spring AOP and AspectJ |
spring-boot-starter-security | Using Spring Security |
spring-boot-starter-data-jpa | Using Spring Data JPA through Hibernate |
spring-boot-starter | Core starter, including auto configuration support, logging and YAML |
spring-boot-starter-freemarker | Enable MVC Web applications to support FreeMarker |
spring-boot-starter-batch | Using Spring Batch |
spring-boot-starter-data-solr | Using Apache Solr through Spring Data Solr |
spring-boot-starter-data-mongodb | Use MongoDB files to store databases, spring data, and MongoDB |
6.3.2 SpringBoot automation configuration
6.3.2.1 view springboot starter coordinate version
Previously, the SpringBoot Starter coordinates were introduced to simplify the configuration of the application environment. Here, spring boot Starter web coordinates are built in the environment to briefly analyze the automatic configuration process of spring boot.
6.3.2.2 automation configuration
Spring Boot projects generally have an entry class of * Application. The main method is provided in the entry class, which is the entry method of a standard Java Application@ SpringBootApplication annotation is the core annotation of Spring Boot. It is actually a composite annotation:
-
@SpringBootApplication
It can be seen that this annotation is also a combined annotation, which combines the @ Configuration annotation. For Spring Boot applications,
@The Spring Boot configuration annotation belongs to the configuration annotation of the Boot project and is also a composite annotation, which is recommended in the Spring Boot project
@The SpringBootConfiguration annotation because it combines the @ Configuration annotation.
-
@EnableAutoConfiguration
@The EnableAutoConfiguration annotation combines @ AutoConfigurationPackage
@Import(AutoConfigurationlmportSelector.class) annotation.
@The bottom layer of AutoConfigurationPackage is also a @ lmport(AutoConfigurationPackages.Registrar.class), which will
Scan the components under the package of the startup class into the Spring container.
6.4 Profile configuration
Profile is a global profile used by Spring to support different configurations for different environments. application-{profile}.yml is used for configuration,
For example, application-dev.yml and application-test.yml.
Set spring.profiles.active=test |dev| prod in application.yml to dynamically switch different environments. The specific configuration is as follows:
6.5 log configuration
When developing enterprise projects, the output of logs is undoubtedly a more effective way to locate system bug s. It is also an effective means to quickly find and solve errors after the project enters the production environment. Therefore, the use of logs is also an important function for the project.
Spring Boot uses the LogBack logging system by default. If you do not need to change to other logging systems, such as Log4j2, there is no need for redundant configuration. LogBack prints logs to the console by default. If you want to use LogBack, you need to add dependency dependency in principle.
Because new Spring Boot projects generally refer to Spring Boot starter or Spring Boot starter web, and these two start dependencies already contain dependencies on Spring Boot starter logging, there is no need to add additional dependencies.
6.5.1 log output
These two bags are used. Don't lead to the wrong bag
import org.slf4j.Logger; import org.slf4j.LoggerFactory;
6.5.2 log output format configuration
Modify the application.yml file to add the log output format information configuration. You can modify the application.yml file to control the console log output format, and set the log information output to external files.
#Log output logging: pattern: console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger- %msg%n" level: debug file: path: "." name: "springboot.log"
7. FreeMarker & thymeleaf view technology collection
7.1 Freemarker view set
SpringBoot internally supports the integration of Freemarker view technology and provides an automatic configuration class FreeMarkerAutoConfiguration. With the help of automatic configuration, Freemarker foundation can be easily integrated into SpringBoot environment. The Freemarker environment configuration is introduced here with the help of the getting started] project.
-
Starter coordinate introduction
<!--freemarker Coordinate dependence--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>
-
Add configuration information for freemaker
Freemarker default view path document resources/templates directory (determined by the automation configuration class FreemarkerProperties), which can be modified in application.yml.
#Dynamic environment switching spring: profiles: active: dev #Freemaker configuration freemarker: suffix: .ftl content-type: text/html charset: utf-8 template-loader-path: classpath:/views/
7.2 Thymeleaf view set
SpringBoot supports multiple view technology integration, and the SpringBoot official website recommends using Thymeleaf as the front-end view page. Here, Thymeleaf view integration is realized, and Thymeleaf environment configuration is introduced with the help of the entry project.
-
Starter coordinate introduction
<!--thymeleaf Coordinate dependence--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
-
Add Thymeleaf configuration information
The default view path of Thymeleaf is the resources/templates directory (determined by the automation configuration class Thymeleaf Properties class), which can be modified in application.yml.
#Thymeleaf configuration thymeleaf: prefix: classpath:/html/ #Close cache cache: false
-
Prepare controller forwarding view
//Thymeleaf view @RequestMapping("/index") public String index(Model model){ //Set the data for the request domain model.addAttribute("msg","Thymeleaf view Test..."); //Forwarding view return "index"; }
-
Modify settings for HTML pages
<html lang="en" xmlns:th="http://www.thymeleaf.org">
-
Write the index.html file
Modify the default access directory and create an html directory under the resources directory
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Thymeleaf view</title> </head> <body> <h2 th:text="${msg}"></h2> </body> </html>
8. SpringBoot static resource access
From the entry project, we can see that the Spring Mvc request interception rule is' / ', and the default static resource path of Spring Boot is as follows:
That is, we can store the static resource files of web applications in the resources resource directory.
8.1 default static resource path
Create a static or public directory in the resources directory to store static resource files such as images, js and css
8.2 custom static resource path
Add a configuration classpath:/os after spring.resources.static-locations/
#Set the default access path of static resources. Multiple paths are separated by commas web: resources: #Set multiple access paths static-locations: classpath:/static/,classpath:/public/,classpath:/os/
9. Spring boot project packaging and deployment
When the project is developed, deployed and launched, the project needs to be packaged. The project built in the introduction belongs to a common application. Because the Tomcat container is embedded in SpringBoot, all packaged jar packages can run by default.
9.1 jar package deployment
9.1.1 configure packaging commands
Configure the packaging command in the corresponding Maven window
clean compile package -Dmaven.test.skip=true
9.2 deployment of war package
Deploying web projects in the form of War package is a common deployment method in the production environment, and it is also the deployment scheme of most web applications at present. Here, the steps of packaging and deploying Spring Boot Web projects are as follows
Owe first
SpringBoot learning II
1. Learning objectives
2. Mybatis Integration & data access
When using SpringBoot to develop enterprise projects, persistent layer data access is the basis for front-end page data display. SpringBoot supports the relevant persistent layer frameworks corresponding to common relational database products on the market (Oracle, Mysql, SqlServer, DB2, etc.). Of course, in addition to supporting relational database access, it also supports many current data access operations of non relational databases (Redis, Solr, MongoDB, etc.), This paper mainly introduces the integration of spring boot with Mybatis and the basic addition, deletion, modification and query of persistent layer data.
2.1 spring boot integrates Mybatis
2.1.1 environment integration and configuration
Dependent coordinates:
<!-- mybatis integrate--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.1</version> </dependency> <!-- springboot Paging plug-in--> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.13</version> </dependency> <!-- mysql drive--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- c3p0 data source--> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.5</version> </dependency>
Set configuration item (application.yml):
server: #Set port number port: 8080 #Set access address servlet: context-path: / spring: #Database configuration datasource: username: root password: 123456 url: jdbc:mysql://localhost:3306/iot?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai type: com.mchange.v2.c3p0.ComboPooledDataSource ## Mybatis configuration mybatis: mapper-locations: classpath:/mappers/*.xml type-aliases-package: com.fx.pojo configuration: #Shunting hump configuration map-underscore-to-camel-case: true ## pageHelper pagehelper: helper-dialect: mysql ##Display dao and execute SQL statement logging: level: com: fx: dao: debug
m.github.pagehelper
pagehelper-spring-boot-starter
1.2.13
Set configuration item(application.yml): ```yml server: #Set port number port: 8080 #Set access address servlet: context-path: / spring: #Database configuration datasource: username: root password: 123456 url: jdbc:mysql://localhost:3306/iot?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai type: com.mchange.v2.c3p0.ComboPooledDataSource ## Mybatis configuration mybatis: mapper-locations: classpath:/mappers/*.xml type-aliases-package: com.fx.pojo configuration: #Shunting hump configuration map-underscore-to-camel-case: true ## pageHelper pagehelper: helper-dialect: mysql ##Display dao and execute SQL statement logging: level: com: fx: dao: debug