Table of Contents
Getting Started with Springboot
${msg}
Home Java javaTutorial Springboot Getting Started Usage Example Analysis

Springboot Getting Started Usage Example Analysis

May 11, 2023 pm 02:22 PM
springboot

Getting Started with Springboot

Project creation can be created in IDEA.

Notes:

1. All files need to be placed in:

The same level or lower level directory of the Application file In

2, application.properties is the main core configuration file of the spring-boot project, and there can only be one core configuration file.

Springboot Getting Started Usage Example Analysis

3. When using core configuration files in multiple environments, the file name must start with application-!
application-xxx.properties

Springboot Getting Started Usage Example Analysis

(1) Development environment

# 开发环境配置文件
server.port=9000
server.servlet.context-path=/
Copy after login

(2) Test

# 测试环境配置文件
Copy after login

( 3) Production environment

# 生产环境配置文件
server.port=7000
Copy after login

Activate our customized configuration file in the main core configuration file:

#激活我们编写的application-xxx.properties配置文件
spring.profiles.active=dev
Copy after login

4, @Value annotation

spring -How to obtain the custom configuration attributes of the boot core configuration file
The following method can only obtain one attribute at a time!
For example: a configuration website=http://www.baidu.com is customized in the application.properties file
Get this customized configuration in the project:

Use annotation@ Value("${website}")

You can also write a default value. If there is no configuration item, the default value will be used@Value("${website: default value}")

package com.lxc.sprint_boot_01.web;
 
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
 
import javax.management.ValueExp;
import javax.print.DocFlavor;
 
// 声明控制层
@Controller
public class IndexController {
    @Value("${website:values}")
    private String name; // 此时website值会赋给name属性
 
    @RequestMapping(value = "/self")
    @ResponseBody
    public String self() {
        return name;
    }
}
Copy after login

5, @Component and @ConfigurationProperties(prefix="xxx") annotations

spring-boot core configuration file maps our custom configuration properties to an object (the obtained An object), the prerequisite for using this method: the attributes in the configuration file must be prefixed!

application.properties file

# 属性前边必须要有前缀,我这里前缀是user
user.name=lxc
user.password=123456
Copy after login

config -> user.java file

package com.lxc.sprint_boot_01.config;
 
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
 
@Component // 将此类交给spring容器管理
@ConfigurationProperties(prefix = "user") // 配置属性注解,参数前缀必须有值,值为我们定义的前缀
// 配置完上边的两个注解,下边把配置文件中的属性映射到下边类中去
public class User {
    private String username;
    private String password;
 
    public String getUsername() {
        return username;
    }
 
    public void setUsername(String username) {
        this.username = username;
    }
 
    public String getPassword() {
        return password;
    }
 
    public void setPassword(String password) {
        this.password = password;
    }
}
Copy after login

Calling properties

package com.lxc.sprint_boot_01.web;
 
import com.lxc.sprint_boot_01.config.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
 
import javax.management.ValueExp;
import javax.print.DocFlavor;
import java.util.HashMap;
import java.util.Map;
 
// 声明控制层
@Controller
public class IndexController {
    @Autowired // @Autowired 把User类注入进来
    private User user;
 
    @RequestMapping(value = "/many")
    @ResponseBody
    public String many() {
        return "user为:"+user.getUsername() + ",密码为:"+user.getPassword();
    }
 
}
Copy after login

Springboot Getting Started Usage Example Analysis

6. If you add the @ConfigurationProperties annotation, the red warning above will appear. To solve this problem, you need to add a dependency package:

Springboot Getting Started Usage Example Analysis

<dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-configuration-processor</artifactid>
</dependency>
Copy after login

7 . If there are Chinese characters in application.properties, garbled characters will appear. Solve the problem of Chinese garbled characters in IDEA:

Springboot Getting Started Usage Example Analysis

8. In the configuration file The key-value pair of the attribute cannot have spaces, otherwise there will be problems with parsing!

9. Spring-boo integrated JSP

First create the webapp folder under the main folder, and then click file -> ; project structure -> Modules As shown below:

Springboot Getting Started Usage Example Analysis

Then click on the file on the right in the pop-up dialog box and find us Just confirm the webapp folder you just created. The details are as follows:

Springboot Getting Started Usage Example Analysis

At this time, the webapp will become as follows.

Springboot Getting Started Usage Example Analysis

Configuring the pom.xml file

(1) First introduce the spring-boot embedded tomcat's dependency on jsp parsing, and jsp cannot be parsed without adding it

<!--引入spring-boot内嵌的tomcat对jsp的解析依赖,不添加解析不了jsp-->
<dependency>
    <groupid>org.apache.tomcat.embed</groupid>
    <artifactid>tomcat-embed-jasper</artifactid>
</dependency>
Copy after login

(2) Spring-boot uses the front-end engine thymeleaf by default. Now we want to use springboot to inherit jsp. We need to manually specify the path of the last compiled jsp, and the path for springboot to inherit jsp is the location specified by springboot: META-INF/resources

<build>
    <!--spring-boot默认使用的是前端引擎thymeleaf,现在我们要使用springboot继承jsp,需要手动指定jsp最后编译的路径,而且springboot继承jsp的路径是springboot规定好的位置:META-INF/resources-->
    <resources>
        <resource>
            <!--源文件-->
            <directory>src/main/webapp</directory>
            <!--指定编译路径:-->
            <targetpath>META-INF/resources</targetpath>
            <!--指定源文件夹中的哪些资源需要被编译-->
            <includes>
                <include>*.*</include>
            </includes>
        </resource>
    </resources>
    <plugins>
        <!-- ··· -->
    </plugins>
</build>
Copy after login

The last step: Configure the view parser in application.properties

# 配置视图解析器
spring.mvc.view.prefix=/ # 前缀
spring.mvc.view.suffix=.jsp # 后缀
Copy after login

Create a .jsp page, test:



    <title>Title</title>


  <h2 id="msg">${msg}</h2>

Copy after login
package com.lxc.boot_02;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
 
@Controller
public class controller {
    // 写法一:
    @RequestMapping(value="/say")
    public ModelAndView say() {
        ModelAndView mv = new ModelAndView();
        // 给视图传值
        mv.addObject("msg", "hello");
        // 设置 最终视图的名称
        mv.setViewName("say");
        return mv;
    }
 
    // 写法二:把视图和模型拆分开,返回一个视图(return的是视图的名字)
    @RequestMapping(value = "/index")
    public String index(Model model) {
        model.addAttribute("msg", "lxc;");
        return "say";
    }
}
Copy after login

Writing method one:

Springboot Getting Started Usage Example Analysis

Writing method two:

Springboot Getting Started Usage Example Analysis

The above is the detailed content of Springboot Getting Started Usage Example Analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How Springboot integrates Jasypt to implement configuration file encryption How Springboot integrates Jasypt to implement configuration file encryption Jun 01, 2023 am 08:55 AM

Introduction to Jasypt Jasypt is a java library that allows a developer to add basic encryption functionality to his/her project with minimal effort and does not require a deep understanding of how encryption works. High security for one-way and two-way encryption. , standards-based encryption technology. Encrypt passwords, text, numbers, binaries... Suitable for integration into Spring-based applications, open API, for use with any JCE provider... Add the following dependency: com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt benefits protect our system security. Even if the code is leaked, the data source can be guaranteed.

How to use Redis to implement distributed locks in SpringBoot How to use Redis to implement distributed locks in SpringBoot Jun 03, 2023 am 08:16 AM

1. Redis implements distributed lock principle and why distributed locks are needed. Before talking about distributed locks, it is necessary to explain why distributed locks are needed. The opposite of distributed locks is stand-alone locks. When we write multi-threaded programs, we avoid data problems caused by operating a shared variable at the same time. We usually use a lock to mutually exclude the shared variables to ensure the correctness of the shared variables. Its scope of use is in the same process. If there are multiple processes that need to operate a shared resource at the same time, how can they be mutually exclusive? Today's business applications are usually microservice architecture, which also means that one application will deploy multiple processes. If multiple processes need to modify the same row of records in MySQL, in order to avoid dirty data caused by out-of-order operations, distribution needs to be introduced at this time. The style is locked. Want to achieve points

How SpringBoot integrates Redisson to implement delay queue How SpringBoot integrates Redisson to implement delay queue May 30, 2023 pm 02:40 PM

Usage scenario 1. The order was placed successfully but the payment was not made within 30 minutes. The payment timed out and the order was automatically canceled. 2. The order was signed and no evaluation was conducted for 7 days after signing. If the order times out and is not evaluated, the system defaults to a positive rating. 3. The order is placed successfully. If the merchant does not receive the order for 5 minutes, the order is cancelled. 4. The delivery times out, and push SMS reminder... For scenarios with long delays and low real-time performance, we can Use task scheduling to perform regular polling processing. For example: xxl-job Today we will pick

Comparison and difference analysis between SpringBoot and SpringMVC Comparison and difference analysis between SpringBoot and SpringMVC Dec 29, 2023 am 11:02 AM

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

How to solve the problem that springboot cannot access the file after reading it into a jar package How to solve the problem that springboot cannot access the file after reading it into a jar package Jun 03, 2023 pm 04:38 PM

Springboot reads the file, but cannot access the latest development after packaging it into a jar package. There is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be accessed through the stream. Read. The file is under resources publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

How SpringBoot customizes Redis to implement cache serialization How SpringBoot customizes Redis to implement cache serialization Jun 03, 2023 am 11:32 AM

1. Customize RedisTemplate1.1, RedisAPI default serialization mechanism. The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Here, open the RedisTemplate class and view the source code information of the class. publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations, BeanClassLoaderAware{//Declare key, Various serialization methods of value, the initial value is empty @NullableprivateRedisSe

How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables Jun 02, 2023 am 11:07 AM

When Springboot+Mybatis-plus does not use SQL statements to perform multi-table adding operations, the problems I encountered are decomposed by simulating thinking in the test environment: Create a BrandDTO object with parameters to simulate passing parameters to the background. We all know that it is extremely difficult to perform multi-table operations in Mybatis-plus. If you do not use tools such as Mybatis-plus-join, you can only configure the corresponding Mapper.xml file and configure The smelly and long ResultMap, and then write the corresponding sql statement. Although this method seems cumbersome, it is highly flexible and allows us to

How to get the value in application.yml in springboot How to get the value in application.yml in springboot Jun 03, 2023 pm 06:43 PM

In projects, some configuration information is often needed. This information may have different configurations in the test environment and the production environment, and may need to be modified later based on actual business conditions. We cannot hard-code these configurations in the code. It is best to write them in the configuration file. For example, you can write this information in the application.yml file. So, how to get or use this address in the code? There are 2 methods. Method 1: We can get the value corresponding to the key in the configuration file (application.yml) through the ${key} annotated with @Value. This method is suitable for situations where there are relatively few microservices. Method 2: In actual projects, When business is complicated, logic

See all articles