Java Xiaobai Practice Manual-Phase 5-SpringBoot Framework (day01)

 


SpringBoot

1. The role of the SpringBoot framework

The SpringBoot framework can be directly understood as a better SpringMVC framework!

The SpringBoot framework follows the idea of ​​"convention is greater than configuration". It completes most of the common configurations by default (no matter which project is created, the configuration method or even the configuration values ​​are unchanged), and it integrates most of them by default Commonly used dependencies.

2. Create a SpringBoot project

The ways to create a SpringBoot project are:

  • In any development tool, set SpringBoot as the parent project of the current project;

  • Open the https://start.spring.iowebsite, fill in the information of the new project on the website, download the project compression package, and import the downloaded project through the development tool;

  • Directly in the development tool, create a SpringBoot project through the creation wizard. If you are using Eclipse, you need to install the SpringTools plug-in.

This time we will use IntelliJ IDEA to create the SpringBoot project. Select Create New Project on the main interface of IntelliJ IDEA to start creating a new project. In the project type interface, select Spring Initializr on the left , and then continue to create the project, and set up the Group during the creation process. And Artifact , select Packaging as war, by default, you can temporarily not add other dependencies. After the creation is successful, the project will automatically download a large number of dependencies. During the whole process, you must ensure that the current computer can connect to the Maven server.

3. Start the SpringBoot project

In the created SpringBoot project, the package exists by default in src/main/javacn.tedu.demo (the package name is related to the Group and Artifact filled in when the project is created ), and the DemoApplication class exists by default in this package (the class name is used when creating the project The filled-in Artifact isApplication formed by splicing words). There are main()methods in this class . When the main()method is executed , the entire project will start, so this is also called the project startup class .

After startup, the Run panel will automatically open , and you can see Tomcat related words in the startup log! In fact, the SpringBoot project comes with Tomcat. When the project is started (when the main()method of the startup class is executed ), the current project will be automatically deployed to the built-in Tomcat!

Note: Since the built-in Tomcat will be started when the SpringBoot project is started, make sure that the port is not occupied, otherwise conflicts will occur and the project cannot be started!

If the project can be started normally, the core jar file should not be damaged!

There is also a package by default under the project's src/test/javacn.tedu.demo . In this package DemoApplicationTests, there is a class by default , which is a unit test class, and in this class, there is an empty test method by default, which can be used in this method. Add a simple output statement, for example:

void contextLoads() {
    System.err.println("DemoApplicationTests.contextLoads");
}

Then, execute the unit test, if it can be executed successfully, it means that the test environment is normal!

4. Display static page

In the src/main/resources of the SpringBoot project , there is a static folder by default . This folder is used to store static resources. When finally accessed, the files here will be the files under the root path in the URL.

Static resources: can be accessed directly by entering the URL in the address bar of the browser, usually .html files, .css files, .js files, image files, etc.

You can create index.html directly under the static folder and design the page content yourself, for example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello, SpringBoot!!!</title>
</head>
<body>
<h1>欢迎使用SpringBoot框架!!!</h1>
</body>
</html>

After completion, start the project, open the browser, and enter http://localhost:8080/to access the page.

At startup, you can see the following information:

Tomcat started on port(s): 8080 (http) with context path ''

Means: Tomcat has been started on port 8080, and the context pathvalue is set '', so when accessing the current project, just enter it directly http://localhost:8080/, and there is no need to add the project name in the URL as before!

At the same time, because index.html is the default access page, this page will be automatically accessed when the accessed resource is not explicitly specified in the URL. Therefore, there is no need to add files in the URL. Of course, if you explicitly add , It is also accessible.

You can also add other files in static . When accessing, you need to explicitly add the file name in the URL.

Under src/main/resources , there is also an application.properties file by default . This file is the configuration file of SpringBoot. When the project is started or the unit test is executed, the configuration information in this file will be loaded! Some configurations can be added/modified in the current file according to the requirements of SpringBoot use, for example:

server.port=80

Note: The attribute name of the fixed configuration content is fixed. If there is a spelling error, the configuration will be invalid. However, the current file also allows custom configuration, so even if there is a spelling error, the file itself will not report an error!

The above configuration means: change the port number that Tomcat runs on 80!

Since the 80port is the default port of the HTTP protocol, when accessing, there is no need to explicitly specify the port number in the URL. For example , when accessing the above index.html , you only need to enter it in the address bar of the browser http://localhostto access!

5. Use the controller to receive the request

Under src/main/java , there is a cn.tedu.demopackage originally . Create a child package under this package controllerto store the controller class, and then create the HelloControllercontroller under this package :

package cn.tedu.demo.controller;
​
import org.springframework.stereotype.Controller;
​
@Controller
public class HelloController {
}

Note: The SpringBoot project sets the cn.tedu.demopackage that has been created by default as a component scanned package, so all component classes created in the project must be placed in this package or its sub-packages!

Then, add a simple method to handle the request in the controller class:

@GetMapping("hello")
@ResponseBody
public String hello() {
    return "SpringBoot真好用!!!";
}

Note: The SpringBoot project sets the request path processed by the SpringMVC framework to /*(customized in the previous exercise cases) by default *.do, so all resources that access the current project will be processed by the SpringMVC framework. When configuring the request path, it is not necessary Use .doas the suffix of the resource name!

Note: The SpringBoot project sets all character encodings to UTF-8 by default.

After finishing the writing, restart the project and visit the address bar of the browser http://localhost/helloto access the above controller!

6. Connect to the database

By default, the SpringBoot project does not have its own database-related dependencies. If you need to implement database programming, you must add a dependency on connecting data and a dependency on a database programming framework, for example:

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.3</version>
</dependency>
​
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

For most of the commonly used dependencies, you do not need to specify the version number when adding, because SpringBoot has already set the version number, which is usually a newer and stable version.

Of course, if the version specified by SpringBoot may not match the current environment (for example, if the version of mysql-connector-java is higher, and the MySQL database version of the server is lower, you will not be able to connect), you can also add <version>nodes to specify the version by yourself. The currently specified version shall prevail!

After adding the above dependencies, an error will occur when the project is started, and the prompt message is as follows:

***************************
APPLICATION FAILED TO START
***************************
​
Description:
​
Failed to configure a DataSource: 'url' attribute is not 
specified and no embedded datasource could be configured.
​
Reason: Failed to determine a suitable driver class

Because when the SpringBoot project is started, if the current project adds a dependency on connecting to the database, it will automatically load the configuration information for connecting to the database, but the configuration is not currently added, resulting in the failure to read the information, and the above error occurred!

Therefore, you need to add the configuration to connect to the database in application.properties :

spring.datasource.url=jdbc:mysql://localhost:3306/tedu_ums?
useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root

Note: When starting the project, only the above configuration information will be read, and the database will not actually be connected, so even if the above configuration values ​​are wrong, no error will be reported!

In order to verify whether the above configuration information is correct, you can test in the cn.tedu.sample.SampleApplicationTests test class of src/test/java :

@Test
void getConnection() throws SQLException {
    Connection connection = dataSource.getConnection();
    System.err.println(connection);
}

In the SpringBoot project, all the getBean()objects that were acquired through Spring container calls (using ordinary Spring/SpringMVC or other Spring-based projects) can be changed to automatic assembly!

7. Realize user registration

7.1. Persistence layer

In order to ensure that there is no error when inserting data during registration, and to ensure the "user name unique" data rule, you should check whether the user name has been registered before inserting data. Therefore, the data access functions that need to be implemented during "registration" are:

SELECT * FROM t_user WHERE username=?

INSERT INTO t_user (除了id以外字段列表) VALUES (匹配的值列表)

 

First, entity classes should be created cn.tedu.sample.entityunder the Userpackage to encapsulate user data:

package cn.tedu.sample.entity;
​
public class User {
​
    private Integer id;
    private String username;
    private String password;
    private Integer age;
    private String phone;
    private String email;
    
    // Setters & Getters
    // toString()
    
}

Then, cn.tedu.sample.mappercreate an UserMapperinterface under the package to define the abstract method of the persistence layer:

package cn.tedu.sample.mapper;
​
import cn.tedu.sample.entity.User;
​
public interface UserMapper {
    
    Integer insert(User user);
    
    User findByUsername(String username);
    
}

Next, you need to configure it so that the MyBatis framework knows the location of this interface! You can add @MapperScanannotations before the declaration of the configuration class to configure the package where the interface is located!

In the SpringBoot project, the startup class is also a configuration class, so you can add this annotation before the declaration of the startup class for configuration:

package cn.tedu.sample;
​
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
​
@MapperScan("cn.tedu.sample.mapper")
@SpringBootApplication
public class SampleApplication {
​
    public static void main(String[] args) {
        SpringApplication.run(SampleApplication.class, args);
    }
​
}

Next, you also need to configure the SQL statements mapped by the above abstract methods. First , create a mappers folder under src/main/resources to store the XML files that configure the SQL statements. And configure the location of the XML file to be used in application.properties :

mybatis.mapper-locations=classpath:mappers/*.xml

Then, paste the UserMapper.xml file into the mappers folder , and configure the SQL statement corresponding to the abstract method in the above interface:

<?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="cn.tedu.sample.mapper.UserMapper">
​
    <insert id="insert" useGeneratedKeys="true"
        keyProperty="id">
        INSERT INTO t_user (
            username, password, age, phone, email
        ) VALUES (
            #{username}, #{password}, #{age}, #{phone}, #{email}
        )
    </insert>
​
    <select id="findByUsername"
            resultType="cn.tedu.sample.entity.User">
        SELECT * FROM t_user WHERE username=#{username}
    </select>
​
</mapper>

Next, the unit should be checked by testing whether the above functions can be run correctly, the src / test / java to cn.tedu.sample.mappercreate the package UserMapperTeststest class, and two or more test methods in this class:

package cn.tedu.sample.mapper;
​
import cn.tedu.sample.entity.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
​
@SpringBootTest
public class UserMapperTests {
​
    @Autowired(required=false)
    UserMapper userMapper;
​
    @Test
    void insert() {
        User user = new User();
        user.setUsername("boot");
        user.setPassword("1234");
        user.setAge(25);
        user.setPhone("13000130000");
        user.setEmail("[email protected]");
        Integer rows = userMapper.insert(user);
        System.err.println("rows=" + rows);
    }
​
    @Test
    void findByUsername() {
        String username = "boot";
        User user = userMapper.findByUsername(usernaUme);
        System.err.println(user);
    }
​
}

Note: The custom unit test class must also be under the root package cn.tedu.sampleof the project , otherwise it will not work properly! At the same time, you also need to add a comment before the declaration of the class (for specific comments to be added, please refer to the SampleApplicationTeststest class that already exists when the project is created )!

7.2. Controller

First cn.tedu.sample.utilcreate under the package JsonResult(custom class name), and declare 2 attributes in the class, respectively representing the status and information of the operation result:

package cn.tedu.sample.util;
​
public class JsonResult {
​
    private Integer state;
    private String message;
    
    // Setters & Getters
    
}

cn.tedu.sample.controllerCreate a UserControllerclass under the package, before @RestControllerand @RequestMapping("user")annotate the class declaration , and add a method to process the request in the controller class. This time, the JsonResulttype created above will be used as the return value type of the method:

package cn.tedu.sample.controller;
​
import cn.tedu.sample.entity.User;
import cn.tedu.sample.mapper.UserMapper;
import cn.tedu.sample.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
​
@RestController
@RequestMapping("user")
public class UserController {
​
    @Autowired(required = false)
    private UserMapper userMapper;
​
    // http://localhost:8080/user/reg?username=sample&password=8888&age=26&phone=13100131111&[email protected]
    @RequestMapping("reg")
    public JsonResult reg(User user) {
        System.err.println("UserController.reg"); // soutm
        System.err.println("user = " + user); // soutp
​
        String username = user.getUsername();
        User result = userMapper.findByUsername(username);
        // result.null
        JsonResult jsonResult = new JsonResult();
        if (result == null) {
            userMapper.insert(user);
            jsonResult.setState(1);
            jsonResult.setMessage("注册成功!");
        } else {
            jsonResult.setState(2);
            jsonResult.setMessage("注册失败!用户名已经被占用!");
        }
        return jsonResult;
    }
​
}

7.3 Respond to JSON data through the SpringMVC framework

In the SpringMVC framework (including the SpringBoot framework), when the method for processing the request is added before @ResponseBodyor before the controller class is used @RestController, the return value of the method for processing the request will be used as the response data to the client.

When the server responds to the client with data, the SpringMVC framework uses the "Converter" to convert the return value of the method, and the response headers when processing the response. For different return value types, the SpringMVC framework Different converters are also used automatically .

When the (type of return value of the method of processing requests) that the type of response data String, it will automatically use StringHttpMessageConverterthe converter, the converter string will automatically return to the client as response data, and, also in response to the first set, By default, the Content-Typeproperty will be set in the response header, and its value is text/html; charset=ISO-8859-1. Therefore, in the SpringMVC framework ( excluding the SpringBoot framework), the response Stringdoes not support Chinese by default !

When the response data type is a type that the SpringMVC framework does not recognize by default , and the current development environment adds a jackson-databinddependency, the SpringMVC framework will automatically use jackson-databindthe converter in the process, and jackson-databindthe working method of the converter is to organize the response results into JSON format data, and the response header Content-Typeset become application/json; charset=UTF-8!

In the project, you only need to make sure that the jackson-databinddependencies are added , no additional configuration is required, and there is no need to explicitly use a certain class in the framework!

If it is a SpringMVC project that uses XML for related configuration, you need to enable the annotation driver in the Spring configuration file, that is, add in the configuration file:

<annotation-driven />

In general, if you need the SpringMVC framework to be able to respond to data in JSON format, you need:

  • Use @RestControlleror @ResponseBodycomment;

  • Add jackson-databinddependencies in the project ;

  • Customize the return value type of the request processing method (as long as it is a custom type, it must be a type that the SpringMVC framework does not recognize by default)

Of course, in a certain controller class, if an @RestControllerannotation has been used , it will indicate that "all requests processed in the current controller class will respond to data", and no forwarding or redirection operation will be performed. If you must perform forwarding Or redirect, you can:

  • Do not use @RestControllerannotations, but add @ResponseBodyannotations one by one before each method that needs to respond to data ;

  • In @RestControllerthe case of use , declare the return value type of the method that needs to be forwarded or redirected as a ModelAndViewtype.

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户登录</title>
</head>
<body >
    <form id="from-login">
        <table border="1">
            <caption>用户登录</caption>
            <tr>
                <td>用户名:</td>
                <td><input name="username"><span>{
   
   {msg_err_username}}</span></td>
            </tr>
            <tr>
                <td>密码:</td>
                <td><input name="password"><span>{
   
   {msg_err_password}}</span></td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td><input id="btn-login" type="button" value="登录"></td>
            </tr>
        </table>
    </form>
    <!--将jQuery 文件复制到当前HTML 文件相同的文件夹-->
    <!--将jQuery 文件的版没有要求-->
    <script src="jquery-3.4.1.min.js"></script>
    <script src="vue.js"></script>
    <!--必须将登录按钮 的类型设置为button 不可以使用submit-->
    <!--需要为 登录按钮添加id-->
    <!--需要为表单  添加id-->
    <!--需要为body 标签添加id-->
    <script>
        //Vue
        let app = new Vue({
            el:'#from-login',
            data:{
                msg_err_username : null,
                msg_err_password : null
            }
        });

        //选中按钮后 调用click()函数 为按钮绑定点击事件
        $("#btn-login").click(function () {
            // alert("准备提交登录....");
            /**
             * alert("准备提交登录……");
             * 关于$.ajax()中JSON对象的属性:
             * url:将请求提交到哪里去
             * data:请求参数
             * type:请求方式
             * dataType:服务器端响应的数据的类型,取值可以是text/xml/json……取值以服务器端响应时,响应头中的Content-Type为准
             * success:服务器端成功响应(HTTP响应码为2xx,例如200)时的回调函数,函数的参数就是服务器端口响应的数据对象
             *
             */
            app.msg_err_username = null;
            app.msg_err_password = null;
            $.ajax({
                "url":"/user/login",
                "data":$("#from-login").serialize(),
                "type" : "post",
                "dataType":"json",
                "success": function (jsonData) {
                    if(jsonData.state ==1){

                        alert("恭喜!登录成功!");
                    }else if (jsonData.state==2){
                        //alert(jsonData.message);
                        app.msg_err_username = jsonData.message
                    }else {
                        app.msg_err_password = jsonData.message
                    }
                }
            });
        });

    </script>
</body>

</html>

 

Guess you like

Origin blog.csdn.net/c202003/article/details/107290613