1. Springboot quote

Spring Boot is a new framework from the Pivotal team designed to simplify the initial setup and development of Spring applications. The framework uses a specific way to configure so that developers no longer need to define boilerplate configurations. In this way, Spring Boot aims to be a leader in the burgeoning field of rapid Application development.

Springboot (Microframework) = SpringMVC (Controller) + Spring Core (Project Management)

SSM Spring springmvc mybatis <—- SSM Spring stauts2|struts1 mybatis <— SSH Spring Struts Hibernate


2. Characteristics of Springboot

  1. Create a stand-alone Spring application
  2. Embedded Tomcat without the need to deploy a WAR file
  3. Simplifying Maven Configuration
  4. Automatically configure Spring, no XML configuration

3. The springboot convention is greater than the configuration

Project directory structure:

  • The springboot project must add application.yml(.properties) to SRC /main/resources. The name of the core configuration file must be application
  • A Springboot project must build global entry types,xxApplication, and entry classes outside all subpackages in SRC /main/ Java. A Springboot project can only have one entry class

4. Build the Springboot environment

Environmental requirements:

# 1.System Requirements+ MAVEN3.3 or Gradle 5.x and 6.x (4.10 is also supported but in a deprecated form) Spring Framework 5.2.4.RELEASE# 2.ServletContainers: 
  Tomcat 9.0 
  Jetty 9.4 
  Undertow 2.0

# 3. Development toolsIDEA 2018 Eclipse version Later than version 17Copy the code
4.1 Introduce dependencies into the project
    <! -- Inherits springboot's parent project -->
   <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.5. RELEASE</version>
    </parent>

    <dependencies>
        <! Web support for SpringBoot -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
Copy the code
4.2 Importing a Configuration File

Project in SRC/main/resources/application. The yml

4.3 Creating packages and Creating Controllers
// Create the specified package structure in the project
/* com +| baizhi +| controller */ 
                    @Controller
                    @RequestMapping("/hello")
                    public class HelloController {
                        @RequestMapping("/hello")
                        @ResponseBody
                        public String hello(a){
                            System.out.println("======hello world=======");
                            return "hello"; }}Copy the code
4.4 Writing entry classes
Create the entry class Application in the following package structure in the project
/* com +| baizhi */
            @SpringBootApplication
            public class Application {
                public static void main(String[] args) { SpringApplication.run(Application.class,args); }}Copy the code
4.5 Running main to start the project
o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8989 (http)Com.baizhi.Application: Started Application in 2.152seconds (JVM running for 2.611)

// Note: The startup is successful if the preceding logs are displayed
Copy the code
4.6 Access Items
// Note: SpringBoot projects do not have project names by default
/ / access path: http://localhost:8080/hello/hello
Copy the code

5. The Tomcat startup port is occupied

server:
  port: 8989                 # specifies the embedded server port number
  context-path: /springboot  # to specify the access path for the project
Copy the code

6. Springboot related notes


Spring Boot usually has a class called xxxApplication with a main method in the entry class. In the main method used in SpringApplication. Run (xxxApplication. Class, args) start springboot application project.

# @restController: is a combination of @controller + @responseBody, which supports RESTful access and returns json strings.

The SpringBootApplication annotation is equivalent to:
@SpringBootConfiguration Identifies annotations that indicate that this is a SpringBoot configuration class @EnableAutoConfiguration automatically integrates with third-party technologies that are integrated in the project @ComponentScan Scan annotations in subpackages of entry classes and subpackage descendantsCopy the code

7. Split configuration files in Springboot

Note: Production and test environments may be different during actual development
Therefore, it is necessary to separate the configuration in production from the configuration in test. Springboot also provides a way to split configuration files. The following uses inconsistent item names in production as an example:
	
Project name in production: cmfz
Project name under test: springboot
Both ports are:   8080

Split as follows:
Main config file:
        application.yml	# to write the same configuration
            server:
                port: 8080 Production and test on the same port
                   
# Production profile:
        application-pord.yml
            server:
                context-path: /cmfz
# test config file:
        application-dev.yml
            server:
                context-path: /springboot
# You can use spring-profiles-active: specify the profile to use, such as spring-profiles-active=prod

Copy the code

8. Create a custom simple object in SpringBoot

8.1 Managing a Single Object

The creation of simple component objects that can be managed in SpringBoot can be created directly using annotations.

# 1. Use @repository @service @controller and @Component to manage different simple objectsFor example, to create a custom User object from a factory:Copy the code
@Component
@Data
public class User {
  private String id;
  privateString name; . }Copy the code
# 2. After being created by a factory, the object can be injected wherever it is usedFor example, using custom simple object creation in the controllerCopy the code
@Controller
@RequestMapping("hello")
public class HelloController {
    @Autowired
    privateUser user; . }Copy the code

8.2 Managing Multiple Objects

To manage complex objects in SpringBoot, you must use @Configuration + @bean annotations

# 1. Manage the creation of complex objects
Copy the code
@ the Configuration (recommended)|@Component(not recommended)
public class Beans {
    @Bean
    public Calendar getCalendar(a){
        returnCalendar.getInstance(); }}Copy the code
# 2. Use complex objects
Copy the code
@Controller
@RequestMapping("hello")
public class HelloController {
    @Autowired
    privateCalendar calendar; . }Copy the code
# note:1.@Configuration configuration annotations are mainly used to produce multiple components for factory management (in the form of registration) 2.@Component to manage individual components (in the form of packet scanning)Copy the code

9. The springboot injection

Springboot provides three injection methods: basic property injection and object injection

9.1 Basic Attribute Injection
# 1.@Value attribute injection [emphasis]
Copy the code
@Controller
@RequestMapping("hello")
public class HelloController {
  
    @Value("${name}")
    private String name;
}
Copy the code
# 2. Inject in the configuration file
Copy the code
name: xiaohei
Copy the code
9.2 Object-based Injection
ConfigurationProperties(prefix=" prefix ")
Copy the code
@Component
@Data
@ConfigurationProperties(prefix = "user")
public class User {
    private String id;
    private String name;
    private Integer age;
    privateString bir; . }Copy the code
# 2. Write configuration files
Copy the code
user:
  id: 24
  name: xiaohei
  age: 23
  bir: 2012/ 12/12
Copy the code
# 3. Import dependencies to build custom injection metadata (optional, import can add hints)
Copy the code
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-configuration-processor</artifactId>
  <optional>true</optional>
</dependency>
Copy the code

10. Configure two templates in SpringBoot

10.1 Integrating JSP templates

10.1.1 Introducing integrated JAR packages for JSP
<dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
</dependency>
Copy the code
10.1.2 Introducing JSP run plug-ins (required in the first way)
<build>
    <finalName>springboot_day1</finalName>
    <! -- Introduce JSP runtime plug-in -->
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
Copy the code
10.1.3 Configuring a View Parser
# Introduce a view resolver in the configuration file
spring:
  mvc:
    view:
      prefix: /   	# / represents access to the webApp page in the project
      suffix: .jsp 
Copy the code
10.1.4 The first way is to use plug-ins to boot

10.1.5 The second Way to start using the working Directory specified in IDEA [Recommended]

10.1.6 Enabling the ACCESS to the JSP Page
http://localhost:8989/index.jsp
Copy the code
10.1.7 No application restart is required to modify a JSP
server.servlet.jsp.init-parameters.development=true
Copy the code

10.2 Integrating the Thymelaf Template

Thymeleaf is a modern server-side Java templating engine for Web and standalone environments. — from www.thymeleaf.org/

Thymeleaf is a templating engine similar to Velocity and FreeMarker that can completely replace JSPS. Compared to other templating engines, Thymeleaf can run in both online and offline environments, i.e. it allows artists to view static pages in the browser. It also allows programmers to view dynamic pages with data on the server.

10.2.1 Importing dependencies
    <! - use thymelaf -- -- >
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
  </dependency>
Copy the code
10.2.2 Writing Configurations
spring.thymeleaf.prefix=Classpath :/templates/ # Use templates directory
spring.thymeleaf.suffix=.html # use the template suffix
spring.thymeleaf.encoding=Utf-8 # uses template encoding
spring.thymeleaf.enabled=True # Start thymelaf template
spring.thymeleaf.servlet.content-type=Text/HTML # Use the template response type
Copy the code
10.2.3 Writing Controller Tests
@Controller    // Make sure that @Controller can no longer use the @restController annotation
@RequestMapping("hello")
public class HelloController {
    @GetMapping("hello")
    public String hello(a){
        System.out.println("Test integration with Thymeleaf");
        return "index"; }}Copy the code
10.2.4 Defining templates in the Templates directory

10.2.5 Test Access
http://localhost:8989/springboot_day3/hello/hello
Copy the code
10.2.6 Viewing Results

10.2.7 Enabling Direct Access to THE HTML Page (By default, resources in the templates directory cannot be directly accessed using static resources. You can only access them using Controller Skip. After configuration, you can directly access them. The resources directory contains static resources, CSS static resources, and the templates directory contains HTML files.
spring.resources.static-locations=classpath:/templates/,classpath:/static/
Copy the code
10.2.8 Test results
http://localhost:8989/springboot_day3/index.html
Copy the code

10.3 Thymeleaf basic use

To use thymeleaf, add the following namespace to the page:

<html lang="en" xmlns:th="http://www.thymeleaf.org">
Copy the code
10.3.1 Displaying Single Data
A. Set data
model.addAttribute("name"."Zhang"); Or request. The setAttribute ("name"."Black");
Copy the code
B. Obtain data
<span th:text="${name}"/>--> Get dataCopy the code

Note: The internationalization profile must be included in the SpringBoot2.x version to display properly:

C. Obtain and parse data containing HTML tags
model.addAttribute("name".");
model.addAttribute("username"."Chen");
Copy the code
  • Get the as-is output directly
<span th:text="${name}"/>
Copy the code

  • Get and parse
 <span th:utext="${name}"/>
Copy the code

  • Assign data to form elements

    <input type="text" th:value="${username}"/>
    Copy the code

# summary
1. Use th:text="${attribute name}" to obtain the corresponding data. Use th:utext="${attribute name}" to get the corresponding data, you can parse the data in the HTML before rendering to page 3. Use th:value="${attribute name}" to get the data directly as the form element value attributeCopy the code
10.3.2 Displaying Object Data
 model.addAttribute("user".new User("21"."xiaochen".23.new Date()));
Copy the code
id:<span th:text="${user.id}"></span>
name:<span th:text="${user.name}"></span>
age:<span th:text="${user.age}"></span>
bir: <span th:text="${user.bir}"></span>= = = =<span th:text="${#dates.format(user.bir, 'yyyy-MM-dd HH:mm')}"></span>Date formattingCopy the code
10.3.3 Conditionally Displaying data
 model.addAttribute("user".new User("21"."xiaochen".23.new Date()));
Copy the code
<span th:if="${user.age} eq 23">youth</span>
Copy the code
# operator.
Gt: great than (greater than) > GE: great equal >= eq: equal (equal) == lt: less than (less than) < le: less than (less than) <= ne: not equal (not equal)! =Copy the code
10.3.4 Displaying Multiple Pieces of Data
  • Walk through the set directly
 <ul th:each="user:${users}">
   <li th:text="${user.id}"></li>
   <li th:text="${user.name}"></li>
   <li th:text="${user.age}"></li>
   <li th:text="${#dates.format(user.bir,'yyyy-MM-dd')}"></li>
</ul>
Copy the code
  • Traversal gets traversal state
 <ul th:each="user,userStat:${users}">
   <li><span th:text="${userStat.count}"/>-<span th:text="${user.id}"/></li>Get the number of iterations count starts at 1 index starts at 0<li><span th:text="${userStat.odd}"/>-<span th:text="${user.name}"/></li>Gets whether the current traversal is an odd number of rows<li><span th:text="${userStat.even}"/>-<span th:text="${user.age}"/></li>Gets whether the current traversal is an even line<li><span th:text="${userStat.size}"/>-<span th:text="${user.bir}"/></li>Gets the total number of entries in the current collection</ul>
Copy the code
10.3.5 Importing Static Resources

Static resources in the thymeleaf template project are placed by default in the small static directory of the Resources path

  • Put the corresponding static resources into the project

  • Page introduction

     <link rel="stylesheet" th:href="@{/css/index.css}">
     <script th:src="@{/js/jquery-min.js}"></script>
    Copy the code

11. Springboot integrates mybatis

11.1 Importing Dependencies
<! Mybatis - integration -- ><dependency>
< the groupId > org. Mybatis. Spring. The boot < / groupId > < artifactId > mybatis - spring - the boot - starter < / artifactId > < version > 2.1.1 < / version >  
<dependency>
< the groupId > com. Alibaba < / groupId > < artifactId > druid < / artifactId > < version > 1.1.12 < / version > < / dependency >
<dependency>
< the groupId > mysql < / groupId > < artifactId > mysql connector - Java < / artifactId > < version > 5.1.41 was < / version > < / dependency >
< p style = "max-width: 100%; clear: both; min-width: 1px
Copy the code
11.2 Configuring the Configuration File
spring:
  thymeleaf:
    mode: HTML
    encoding: UTF-8
    prefix: classpath:/templates/
    suffix: .html
    enabled: true
    cache: false
    content-type: text/html
  resources:
    static-locations: classpath:/templates/,classpath:/static/

  datasource:
    type: com.alibaba.druid.pool.DruidDataSource   # specify the connection pool type
    driver-class-name: com.mysql.jdbc.Driver        # specify driver
    url: jdbc:mysql://localhost:3306/cmfz           # specified url
    username: root									# specify a user name
    password: root								 	# specify password
Copy the code
11.3 Adding MyBatis Configuration
Add the following configuration to the configuration file:

mybatis:
  mapper-locations: classpath:com/baizhi/mapper/*.xml  Mapper configuration file location
  type-aliases-package: com.baizhi.entity              # specify the class to alias
Copy the code
// Add the following configuration to the entry class:
@SpringBootApplication
@MapperScan("com.baizhi.dao")   // This configuration must be added to the entry class
public class Application {
    public static void main(String[] args) { SpringApplication.run(Application.class,args); }}Copy the code
Table 11.4 built
CREATE TABLE `t_clazz` (
  `id` varchar(40) NOT NULL,
  `name` varchar(80) DEFAULT NULL,
  `no` varchar(90) DEFAULT NULL.PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Copy the code
11.5 Developing entity Classes
public class Clazz {
    private String id;
    private String name;
    private String no;
    // the get set method is omitted....
}
Copy the code
11.6 Developing DAO interfaces and Mapper
public interface ClazzDAO {
    List<Clazz> findAll(a);
}
Copy the code

      
<! DOCTYPEmapper PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.baizhi.dao.ClazzDAO">
    <select id="findAll" resultType="Clazz">
        select * from t_clazz 
    </select>
</mapper>
Copy the code
11.7 Service Development and Implementation
/ / interface
public interface ClazzService {
    List<Clazz> findAll(a);
}
/ / implementation
@Service
@Transactional
public class ClazzServiceImpl implements  ClazzService {
    @Autowired
    private ClazzDAO clazzDAO;
    
    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<Clazz> findAll(a) {
        returnclazzDAO.findAll(); }}Copy the code
11.8 Introducing test dependencies
 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
     <scope>test</scope>
</dependency>
Copy the code
11.9 Writing test Classes
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class TestClazzService {

    @Autowired
    private ClazzService clazzService;

    @Test
    public void test(a){
        List<Clazz> all = clazzService.findAll();
        for(Clazz clazz : all) { System.out.println(clazz); }}}Copy the code

12. Enable hot deployment of JSP pages

12.1 the introduction

In Springboot, the JSP runs in production mode by default, which does not allow modification to take effect immediately after saving. Therefore, the development process needs to debug JSP pages every time the server needs to be restarted, which greatly affects our efficiency. For this reason, Springboot provides a way to modify the default production mode to debug mode, to debug mode The configuration takes effect immediately. You need to add the following configuration to the configuration file to change the configuration to development mode.

12.2 Enabling the Test Mode
server:
  port: 8989
  jsp-servlet:
    init-parameters:
      development: true  # Enable JSP page debug mode
Copy the code

13. Hot deployment of DevTools in Springboot

13.1 the introduction

In order to further improve the development efficiency, Springboot provides us with global project hot deployment. After modifying some code and related configuration files during the development process in the future, you do not need to restart each time to make the modification take effect. After enabling Springboot global hot deployment in a project, you only need to wait a few seconds after the modification to make the modification take effect.

13.2 Enabling Hot Deployment
13.2.1 Introducing dependencies in a Project
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-devtools</artifactId>
   <optional>true</optional>
</dependency>
Copy the code
13.2.2 Configuring Automatic compilation in IDEA
# 1. Enable automatic compilation

The Preferences | Build, Execution, Deployment | Compiler - > checked Build project automatically this option
# 2. Enable file modification during runtime
CTRL + Alt + shift + / - > select 1. Registry - > check the compiler. The automake. Allow. The when. App. Running this optionCopy the code
13.2.3 Starting a Project Check whether hot deployment takes effect
# 1. The startup takes effect if the following logs are displayed
Copy the code
2019-07-17 21:23:17566.  INFO 4496 --- [  restartedMain] com.baizhi.InitApplication               : Starting InitApplication on chenyannandeMacBook-Pro.local with PID 4496 (/Users/chenyannan/IdeaProjects/ideacode/springboot_day1/target/classes started by chenyannan in /Users/chenyannan/IdeaProjects/ideacode/springboot_day1)
2019-07-17 21:23:17567.  INFO 4496 --- [  restartedMain] com.baizhi.InitApplication               : The following profiles are active: dev
2019-07-17 21:23:17612.  INFO 4496 --- [  restartedMain] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@66d799c5: startup date [Wed Jul 17 21:23:17 CST 2019]; root of context hierarchy
2019-07-17 21:23:18782.  INFO 4496 --- [  restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8989 (http)
2019-07-17 21:23:18796.  INFO 4496 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-07-17 21:23:18797.  INFO 4496 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8. 520.

Copy the code

Note: If restartedMain is displayed in the log, the log has taken effect. If the modification fails to take effect after hot deployment, restart the project and try again

14. Logback log integration

14.1 introduction of logback

Logback is another open source logging component designed by the log4J founders. Currently, logback is divided into three modules: logback-core, Logback-classic, and logback-access. Is a further improvement to log4J logging presentation

14.2 Log Levels
> DEBUG < INFO < WARN < ERROR < OFF > > Log levels from low to high: 'The higher the log level is, the less logs are generated.Copy the code
14.3 Log Classification in a Project
> Logs are divided into two types: rootLogger: listens for all run logs in a project, including logs imported from dependent JARS. Logger: listens for logs in specified packages in a projectCopy the code
14.4 Used in Java projects
14.4.1 LogBack Configuration File
The logback configuration file must be in the project root directory and must be named logback.xmlCopy the code

      
<configuration>
    <! Define log output location in project -->
    <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
        <! Define the log output format for the project -->
        <! Define the log output format for the project -->
        <layout class="ch.qos.logback.classic.PatternLayout">
            <pattern> [%p] %d{yyyy-MM-dd HH:mm:ss} %m %n</pattern>
        </layout>
    </appender>

    <! -- Project and log control -->
    <root level="INFO">
        <appender-ref ref="stdout"/>
    </root>
    <! -- Specify package log control in project -->
    <logger name="com.baizhi.dao" level="DEBUG"/>

</configuration>
Copy the code

You are not advised to use configuration XML. You can directly configure the configuration in the configuration file. This document is for introduction only and can be used when you need to customize the configuration file

14.4.2 Using Logs in Specific Classes
@Controller
@RequestMapping("/hello")
public class HelloController {
    // Declare log members
    private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(HelloController.class);
    @RequestMapping("/hello")
    @ResponseBody
    public String hello(a){
        System.out.println("======hello world=======");
        logger.debug("DEBUG");
        logger.info("INFO");
        logger.warn("WARN");
        logger.error("ERROR");
        return "hello"; }}Copy the code
14.4.3 Using Default Log Configuration

In the configuration file, set the log level to info for root and debug for com.baizhi.dao. Set the log level to DEBUG to display the corresponding SQL execution statements

logging:
  level:
    root: info
    com.baizhi.dao: debug
Copy the code

15. Faceted programming

15.1 the introduction

Springboot is a further encapsulation of the Spring framework and SpringMVC in the original project, so AOP aspect programming in the Spring framework is also supported in SpringBoot, but only annotation style aspect programming is provided in SpringBoot for fast development.

15.2 the use of
15.2.1 Importing Dependencies
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
Copy the code
15.2.2 Relevant notes
/ * *@AspectUsed on a class to indicate that the class is an aspect@BeforeUsed on a method to indicate that the method is a pre-notification method@AfterUsed on a method means that the method is a post-notification method@AroundUsed on a method means that the method is a wrap method@AroundUsed in a method to indicate that the method is a wrapped method **/
Copy the code
15.2.3 Front section
@Aspect
@Component
public class MyAspect {
    @Before("execution(* com.baizhi.service.*.*(..) )"
    public void before(JoinPoint joinPoint){
        System.out.println("Advance notice");
        joinPoint.getTarget();// Target object
        joinPoint.getSignature();// Method signature
        joinPoint.getArgs();// Method parameters}}Copy the code
15.2.4 Rear section
@Aspect
@Component
public class MyAspect {
    @After("execution(* com.baizhi.service.*.*(..) )"
    public void after(JoinPoint joinPoint){
        System.out.println("Post notification");
        joinPoint.getTarget();// Target object
        joinPoint.getSignature();// Method signature
        joinPoint.getArgs();// Method parameters}}Copy the code
> ** Note: Neither pre-notification nor post-notification returns a value. The method argument is joinPoint **Copy the code
15.2.5 Surround section

Circular notification is executed once before and once after the method is entered

@Aspect
@Component
public class MyAspect {
    @Around("execution(* com.baizhi.service.*.*(..) )"
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("Enter surround notification");
        proceedingJoinPoint.getTarget();// Target object
        proceedingJoinPoint.getSignature();// Method signature
        proceedingJoinPoint.getArgs();// Method parameters
        Object proceed = proceedingJoinPoint.proceed();// Release the target method
        System.out.println("Return to surround notification after target method executes");
        return proceed;// Return the target method return value}}Copy the code

Note: There is a return value in the surround notification, and the parameter is ProceedingJoinPoint. If a release is performed, the target method is not executed. Once a release is performed, the return value of the target method must be returned, otherwise the caller cannot accept the returned data


13. Upload and download files

13.1 File Uploading

Definition: When a user accesses the current system and uploads files from his local computer to the server where the current system resides through a browser, it is called file upload

13.1.1 Preparing to upload a Page
<form action="Path..." method="post" enctype="multipart/form-data">
        <input type="file" name="aa">
        <input type="submit" value="Upload">
</form>
<! The form submission mode must be POST. The encType attribute of the form must be multipart/form-data. The name of the background variable must be the same as the file selection name property -->
Copy the code
13.1.2 Writing controllers
@Controller
@RequestMapping("/file")
public class FileController {
  @RequestMapping("/upload")
  public String upload(MultipartFile aa, HttpServletRequest request) throws IOException {
  		String realPath = request.getServletContext().getRealPath("/files");
        File dir = new File(realPath);
        if(! dir.exists()) dir.mkdirs(); aa.transferTo(new File(realPath,aa.getOriginalFilename()));// Upload a file with the original file name
        return "index"; }}Copy the code
13.1.3 Changing the Upload Size of a File

The size of the uploaded file exceeds the default value of 10M
nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (38443713). exceeds the configured maximum (10485760).
# change the size of the uploaded file:
spring:
  http:
    multipart:
       max-request-size: 209715200  # limit file upload size to control
       max-file-size: 209715200 # specifies the maximum file size on the server

spring.servlet.multipart.max-file-size=500MB
spring.servlet.multipart.max-request-size=500MB
Copy the code
13.2 Downloading Files
13.2.1 Provides the link to download files
<a href=".. /file/download? fileName=corejava.txt">corejava.txt</a>
Copy the code
13.2.2 Developing controllers
@RequestMapping("/download")
public void download(String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String realPath = request.getServletContext().getRealPath("/upload");
        FileInputStream is = new FileInputStream(new File(realPath, fileName));
        ServletOutputStream os = response.getOutputStream();
        response.setHeader("content-disposition"."attachment; fileName="+ URLEncoder.encode(fileName,"UTF-8")); // Set attachment to download directly, do not open, inline is open inline.
        IOUtils.copy(is,os);
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }
Copy the code

14. The interceptor

14.1 Developing interceptors
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        System.out.println("= = = = = = = = = = = 1");
        return true;// Return true pass returns false block, where you can add the corresponding business code
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("2 = = = = = = = = = =");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {
        System.out.println("Three = = = = = = = = = ="); }}Copy the code
14.2 Configuring interceptors
// Interceptor configuration in 1.x
@Component
public class InterceptorConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // Add interceptor
        registry.addInterceptor(new MyInterceptor())
            .addPathPatterns("/ * *")// Define the interception path
            .excludePathPatterns("/hello/**"); // Exclude intercepting paths}}// Interceptor configuration in 2.x
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor())// Add interceptor
                .addPathPatterns("/hello/**")// Add the intercepted request path
                .excludePathPatterns("/hello/world");// Add to exclude request paths that do not pass through the interceptor}}Copy the code

Note: Static resource 404 occurs in the project after the custom interceptor in Spring Boot2.x. You need to add the following configuration to the custom interceptor:

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/file/**")
                .excludePathPatterns("/js/**"."/css/**"."/files/**");Static resources are considered a controller request
    }
// SpringBoot2.x solution for static resources that cannot be accessed after custom interceptors
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/ * *") What request path does // represent to access static resources
                .addResourceLocations("classpath:/static/")
                .addResourceLocations("classpath:/templates/"); }}Copy the code

1. First check the directory structure of your static resource, such as the following



/js/** path. The/in front of the js path is the absolute path followed by the contextPath. Therefore, it is necessary to be aware of the path.

15. Deploy the WAR package

15.1 Setting the Packaging Mode to WAR

war

15.2 Specifying an entry class in a plug-in
<build>
   <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <! Hot deployment with Chinese garble solution -->
        <configuration>
          <fork>true</fork>
          <! -- Add JVM parameters -->
          <jvmArguments>-Dfile.encoding=UTF-8</jvmArguments>
          <! -- Specify entry class -->
          <mainClass>com.baizhi.Application</mainClass>
        </configuration>
      </plugin>
    </plugins>
</build>	
Copy the code
15.3 Excluding embedded Tomcat
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-tomcat</artifactId>
  <scope>provided</scope>   <! -- Remove embedded tomcat-->
</dependency>// Exclude dependencies added when using JSP. If you use the Thmeleaf template, you do not need to do so<dependency>
  <groupId>org.apache.tomcat.embed</groupId>
  <artifactId>tomcat-embed-jasper</artifactId>
  <scope>provided</scope>  <! -- Remove the use of embedded Tomcat to parse JSP -->
</dependency>
Copy the code
15.4 Configuring an entry Class
/ / 1. SpringBootServletInitializer inheritance
//2. Override configure
public class Application extends SpringBootServletInitializer{
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        returnbuilder.sources(Application.class); }}Copy the code
15.5 Packaging Test
/* Port context-path is invalid in application. Yml. Use the war package name and external Tomcat port number to access the project */
Copy the code

SpringBoot Actuator

And rely on

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Copy the code

No notes needed

Access IP+ port /actuator to view information about navigation endpoints.

access

The health endpoint

Use the prefix /actuator plus the endpoint ID for access. For example, by default, the health endpoint maps to /actuator/ Health.

Enable all monitoring endpoints, which are disabled by default, with the following configuration;

management:
  endpoints:
    web:
      exposure:
        include: "*"
Copy the code

Do the following to display more comprehensive health information

management:
  endpoints:
    health:
      show-details: always
Copy the code

The info endpoint

Used to describe an application. For example, the configuration is as follows:

info.app.name=
info.author=
info.email=
Copy the code

Access IP + Port /actuator/info

Other endpoints

Activate the endpoint by the following configuration

management:
  endpoints:
    web:
      exposure:
        include: "*"
Copy the code

Activate the specified endpoint

management:
  endpoints:
    web:
      exposure:
        include: metircs,health
Copy the code