Table of Contents
Getting started with Spring Boot starter
SpringBoot basic settings
1.1 SpringBoot settings port number
1.2 SpringBoot settings project name
1.3 Split of SpringBoot configuration files
1.4 SpringBoot startup log
1.5 SpringBoot implements hot deployment
1.6 SpringBoot enables paging query
springBoot Object Management
springBoot整合JSP
SpringBoot整合MyBatis
Home Java javaTutorial How does Java SpringBoot integrate JSP and MyBatis?

How does Java SpringBoot integrate JSP and MyBatis?

May 11, 2023 pm 05:46 PM
java jsp springboot

Getting started with Spring Boot starter

To run a traditional Spring project, you not only need to import various dependencies, but also configure various XML configuration files, which is very cumbersome, but after the Spring Boot project is created, , it can be run directly without writing any code or making any configuration. This is all due to Spring Boot's starter mechanism

Spring Boot extracts various scenarios in daily enterprise application development and makes it Each starter integrates various dependencies that may be used in this scenario. Users only need to introduce the starter dependencies in Maven, and SpringBoot can automatically scan the information to be loaded and start the corresponding default configuration. . The starter provides a large amount of automatic configuration, freeing users from the hassle of dealing with various dependencies and configurations. All these starters follow the conventional default configuration and allow users to adjust these configurations, that is, following the principle of "Convention is greater than configuration"

Not all starters are powered by Spring Boot is officially provided, and some starters are provided by third-party technology vendors, such as druid-spring-boot-starter and mybatis-spring-boot-starter, etc. Of course, there are also individual third-party technologies. Spring Boot officially does not provide a starter, and third-party technology vendors do not provide a starter either.

Take spring-boot-starter-web as an example, it can provide what is needed for Web development scenarios. Almost all dependencies, so when using Spring Boot to develop a Web project, you only need to introduce the Starter, without additionally importing the Web server and other Web dependencies

    <!--SpringBoot父项目依赖管理-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.13</version>
        <relativePath/>
    </parent>

    <dependencies>
        <!--导入 spring-boot-starter-web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        ...
    </dependencies>
</project>
Copy after login

You may find a problem, that is, in In the above pom.xml configuration, when the dependency spring-boot-starter-web is introduced, its version is not specified, but in the dependency tree, we see that all dependencies have version information, so these version information Where is it controlled?

In fact, these version information are uniformly controlled by spring-boot-starter-parent (version arbitration center).

spring-boot-starter-parent

spring-boot-starter-parent is the parent dependency of all Spring Boot projects, it is called the version of Spring Boot The arbitration center can uniformly manage some common dependencies within the project.

<!--SpringBoot父项目依赖管理-->
<parent>  
    <groupId>org.springframework.boot</groupId>   
    <artifactId>spring-boot-starter-parent</artifactId>    
    <version>2.4.5</version>    
</parent>
Copy after login

Spring Boot projects can obtain some reasonable default configurations by inheriting spring-boot-starter-parent, which mainly provides the following features:

  • Default JDK version (Java 8)

  • Default character set (UTF-8)

  • Dependency management function

  • Resource filtering

  • Default plug-in configuration

  • Identifies application.properties and application.yml type configuration files

SpringBoot basic settings

1.1 SpringBoot settings port number

server:
  port: 8989 #配置端口
Copy after login

1.2 SpringBoot settings project name

server:
  servlet:
    context-path: /springboot   #配置项目的虚拟路径(根路径) 项目名使用/开头
Copy after login

1.3 Split of SpringBoot configuration files

spring:
  profiles:
    active: dev  #开发环境
Copy after login

How does Java SpringBoot integrate JSP and MyBatis?

1.4 SpringBoot startup log

# 显示sql
logging:
  level:
    cn.kgc.springboot.mapper: debug  #开启日志
Copy after login

1.5 SpringBoot implements hot deployment

In the process of opening a web project, we usually need to re-open the code every time we modify it. Start the project and implement redeployment. But as projects become larger and larger, each start is a time-consuming matter. Therefore, hot deployment is a very innovative technology. With hot deployment, we can greatly improve our development efficiency

spring-boot-devtools implements hot deployment

1.Introduce dependencies

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-devtools</artifactId>
</dependency>
Copy after login

2.Configure maven plug-in

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <fork>true</fork> <!-- 如果devtools不生效  请设置该属性 -->
            </configuration>
        </plugin>
    </plugins>
</build>
Copy after login

3.Configure application.yml file

devtools:
  restart:
    enabled: true #开启热部署
Copy after login

4.Modify idea settings

File-Settings-Compiler Check Build Project automatically

5. Set Registry

ctrl shift alt /, select Registry, check Compiler autoMake allow when app running

1.6 SpringBoot enables paging query

1.Introduce dependencies:

<dependency>
     <groupId>com.github.pagehelper</groupId>
     <artifactId>pagehelper-spring-boot-starter</artifactId>
     <version>1.2.12</version>
</dependency>

----------------------------------------------
 <dependency>
     <groupId>com.github.pagehelper</groupId>
     <artifactId>pagehelper-spring-boot-starter</artifactId>
     <version>1.2.10</version>
</dependency>
Copy after login

2.Configure the application.yml file (you can use the default without configuring)

# pageHelper分页配置
pagehelper:
  helper-dialect: mysql  #数据库类型
  reasonable: true   #分页合理化 page<1 查询第一页 page >pageNumber 查询最后一页
  support-methods-arguments: true  # 支持mapper接口传递参数开启分页
  params: count=countSql  #用于从对象中根据属性名取值
Copy after login

3. Write the controller, business layer, and persistence layer for testing

@Override
public PageInfo<User> getPage(int pageNum, int pageSize) {

    PageHelper.startPage(pageNum, pageSize);

    List<User> userList = userMapper.selectList();

    PageInfo<User> pageInfo = new PageInfo<>(userList);

    return pageInfo;
}
Copy after login

springBoot Object Management

  • Management Object

    How to manage objects in spring:

    1. Use xml configuration files and use bean tags in the files to set object management

<bean id="" class="xxx.xxx.xxx"></bean>
Copy after login

2. Use the annotation @Component @Controller @Service @Repository

How springboot manages objects:

1. Use configuration mode to create objects

Springboot supports using the @Configuration annotation to be added to the configuration class. As a configuration class, this class is equivalent to the spring configuration file. This annotation can only be used on the class. Use the @Bean annotation on the method in the configuration class, which is equivalent to the bean tag

@Configuration
public class MyConfiguration{
    @Bean
    public User getUser(){
        return new User();
    }
    @Bean
    public Student getStudent(){
        return new Student();
    }
}
Copy after login

in the spring configuration file. 2. Use the original spring annotation @Component @Controller @Service @ Repository

  • Attribute injection

    spring original injection method

    1.set method

    2.constructor

    3.Automatic injection

name: tom
age: 30
price: 23.5
sex: true
birth: 2021/11/28 12:12:12
array: 12,13,15,17
list: 李四,lisi,tom
map: "{&#39;aa&#39;:30,&#39;bb&#39;:&#39;lisi&#39;}" # 注入map使用json格式  取值的个数#{${map}}
Copy after login

对象的注入

object:
  name: lisi
  age: 20
  birth: 2021/11/24
Copy after login
@Controller
@RequestMapping("/inject2")
@ConfigurationProperties("object")
public class InjectController2 {

    private String name;
    private Integer age;
    private Date birth;

   	public void setName(String name) {
        this.name = name;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public void setBirth(Date birth) {
        this.birth = birth;
    }
    @RequestMapping("/inject")
    @ResponseBody
    public String inject(){
        System.out.println(name);
        System.out.println(age);
        System.out.println(birth);
        return  "ok";
    }
}
Copy after login

注意:添加一下依赖,可以再写yaml文件时提示,消除红色的警告提示。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>
Copy after login

springBoot整合JSP

引入依赖

<!--        标准标签库-->
<dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>
<!--        让springboot内置的tomcat具有解析jsp的能力-->
<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
</dependency>
Copy after login

配置视图解析器

spring:
  mvc:
    view:
      prefix: /
      suffix: .jsp
Copy after login

设置不重启项目 刷新jsp页面

server:
  servlet:
    jsp:
      init-parameters:
        development: true  # 修改jsp页面无需重新启动项目
Copy after login

集成后无法访问jsp页面解决方案

1.添加插件

<build>
    <resources>
        <!--注册webapp目录为资源目录-->
        <resource>
            <directory>src/main/webapp</directory>
            <targetPath>META-INF/resources</targetPath>
            <includes>
                <include>**/*.*</include>
            </includes>
        </resource>
    </resources>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
Copy after login

2.设置工作目录

How does Java SpringBoot integrate JSP and MyBatis?

3.插件启动

How does Java SpringBoot integrate JSP and MyBatis?

SpringBoot整合MyBatis

引入依赖

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
</dependency>
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.3</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.12</version>
</dependency>
Copy after login

编写配置文件

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&characterEncoding=utf-8
Copy after login

mybatis配置

mybatis:
  mapper-locations: classpath:mapper/*.xml  #设置mapper文件的位置
  type-aliases-package: cn.kgc.springboot.entity # 起别名
  configuration:
    map-underscore-to-camel-case: true #开启驼峰命名
Copy after login

设置dao接口的扫描

1.在入口类上使用注解,完成扫描

@SpringBootApplication
@MapperScan("cn.kgc.springboot.dao") //扫描dao接口所在的包 同时生成代理对象 注入spring容器
public class Springday02Application {
    public static void main(String[] args) {
        SpringApplication.run(Springday02Application.class, args);
    }
}
Copy after login

The above is the detailed content of How does Java SpringBoot integrate JSP and MyBatis?. 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

See all articles