SpringBoot研究ノート-03SpringMVCからSpringBootへ

1.MyBatisを統合する

A.依存関係を追加する

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <!--继承父项目-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.zzt</groupId>
    <artifactId>demo</artifactId>
    <version>SpringBoot-01</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <!--web开发-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--SpringBoot集成MyBatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>
        <!--Mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!--SpringBoot测试-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!--SpringBoot打包-->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
        <!--配置资源过滤-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>

</project>

B.SpringBoot構成ファイル

#数据库连接配置
spring.datasource.url = jdbc:mysql://localhost:3306/study_mybatis?serverTimezone=GMT%2B8
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
spring.datasource.username = ****
spring.datasource.password = ****
#引入mybatis主配置文件
mybatis.config-location=classpath:mybatis-config.xml
#引入mapper.xml文件(如果与dao接口处于同一包下可以不指定,用@MapperScan指定包路径)
#mybatis.mapper-locations=com/zzt/dao/*.xml

MyBatisのメイン設定ファイル

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--实体类别名-->
    <typeAliases>
        <package name="com.zzt.vo"/>
    </typeAliases>
</configuration>

C.daoレイヤー(Mapper.xmlはdaoインターフェースと同じ名前である必要があることに注意してください。@ Mapperインターフェースはこれがコンポーネントであることを宣言します)

package com.zzt.mapper;

import com.zzt.vo.Student;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

@Mapper
public interface StudentMapper {
    public Student queryStudentById(@Param("id") int id);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zzt.mapper.StudentMapper">
    <select id="queryStudentById" resultType="Student">
        select id,name,age from t_stu where id=#{id}
    </select>
</mapper>

D.サービス層(インターフェース+実装クラスを使用)

package com.zzt.service;

import com.zzt.vo.Student;

public interface StudentService {
    public Student queryStudentById(Integer id);
}
package com.zzt.service.Impl;

import com.zzt.mapper.StudentMapper;
import com.zzt.service.StudentService;
import com.zzt.vo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    public Student queryStudentById(Integer id) {
        return studentMapper.queryStudentById(id);
    }
}

E. daoのインジェクションをテストします(@MapperScanは、Mapper.xmlおよびインターフェイスと同じパッケージに適用可能なMapper.xmlファイルをスキャンするために使用されます)

package com.zzt;

import com.zzt.service.Impl.StudentServiceImpl;
import com.zzt.service.StudentService;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;


@SpringBootApplication()
@MapperScan("com.zzt.mapper") // 当mapper接口和xml文件处于同一包下,使用这种方式
public class DemoApplication {

    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(DemoApplication.class, args);
        System.out.println("容器创建成功");
        StudentService studentService = ctx.getBean(StudentServiceImpl.class);
        System.out.println(studentService.queryStudentById(1));
    }

}

6.実行結果

2.JSPを使用してデータを表示します

A.コントローラー

package com.zzt.controller;

import com.zzt.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @RequestMapping("/queryStudentById")
    public ModelAndView queryStudentById(@RequestParam("id") Integer id) {
        System.out.println("进入方法");
        ModelAndView mv = new ModelAndView();
        mv.addObject("student",studentService.queryStudentById(id));
        mv.setViewName("showStudent");
        return mv;
    }
}

B.JSP解決の依存関係

以前にプロジェクトに取り組んでいたとき、JSPを解析するために外部Tomcat(Tomcatソフトウェアに統合された一部の解析パッケージ)を使用しました。SpringBootはTomcatに組み込まれており、デフォルトでJSPを解析するためのパッケージが含まれていないため、追加する必要があります。分析の依存関係:

        <!--内嵌Tomcat对JSP的解析包-->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        <!--jstl循环的依赖,按需要加入-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

C.リゾルバー構成を表示する

#配置视图解析器 /表示webapp根目录
spring.mvc.view.prefix=/ 
spring.mvc.view.suffix=.jsp

D.新しいWebアプリケーションを作成し、構成のコンパイル中にWebアプリケーションリソースを含めます

            <resource>
                <directory>src/main/webapp</directory>
                <targetPath>META-INF/resources</targetPath>
                <includes>
                    <include>**/*.*</include>
                </includes>
            </resource>

E.JSPページ/showStudent.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String basePath = request.getScheme()+ "://" +
            request.getServerName() + ":" + request.getServerPort() +
            request.getContextPath() + "/";
%>
<html>
<head>
    <title>标题</title>
    <base href="<%=basePath%>" />
</head>
<body>
    ${student.id}--${student.name}--${student.age}
</body>
</html>

F.プロジェクトを開始し、次のアドレスにアクセスします:http:// localhost:8080 / student / queryStudentById?id = 1

3.ホットデプロイメントプラグインJRebel-プロジェクトが変更されたときに再起動する問題を解決します

方法1:自動インストールを検索します(遅くなります。試すにはしごがあります)

方法2:圧縮されたパッケージをダウンロードし、理想のプラグインディレクトリに解凍します

アクティベートする必要があります。http//www.cicoding.cn/other/jrebel-activation/を参照してください(まだラダーが必要な場合があります)

次に、Rebelを使用してプロジェクトを開始します。

コードが変更された場合は、再構築するだけで済みます。

[注]:ポップアップウィンドウをアクティブ化するためのXRebel(JRebelにバンドルおよびダウンロード)が面倒だと思われる場合は、アクティブ化することもできます〜

おすすめ

転載: blog.csdn.net/qq_39304630/article/details/113079474