Java learning summary SpringBoot integration Spring MVC

1. For SpringMVC overview

MVC (Model — View — Controller) is a software architecture pattern in software engineering. Based on this pattern, a software system is divided into three basic parts: Model, View, and controller. The purpose of this design is to make the program structure more concise, intuitive, reduce the complexity of the problem. The responsibilities of each component are: View – UI designer for graphical interface design, responsible for the implementation of user interaction. Controller – Is responsible for getting requests, processing requests, and responding to results. Model – Business logic, data logic implementation.

When we design software, we usually follow certain design principles. In the design of MVC architecture pattern, first of all, based on the SRP-single responsibility principle, each object should perform its own duties and do its best. Then, based on the design idea of “high cohesion, low coupling”, the interaction between the related layer objects is realized. This can improve the maintainability and extensibility of the application. In the JavaEE technology system, the implementation of MVC design idea is shown in Figure 14:

In the figure above, the Servlet acts as the Controller in MVC, calling the Model to handle the business, forwarding or redirecting a page, and rendering data on the page (view). The module encapsulates the application of Servlet technology and simplifies the data processing of programmers in the process of request and response. Spring MVC is a module implemented in Spring framework based on MVC design for handling Web requests. Its simple architecture analysis is shown in the figure below:

DispatcherServlet: Front-end controller, entry point for processing requests. HandlerMapping: A mapper object used to manage the mapping between urls and controllers. Interceptors: Interceptors that implement common processing of requests and responses. Controller: back-end Controller -handler, responsible for handling the control logic of requests. ViewResolver: a ViewResolver that resolves the corresponding view relationship (prefix +viewname+ suffix). Note: If you want to know the detailed processing flow of Spring MVC, you can trace it based on breakpoint debugging method.

2. Perform initial configuration

1. Add Spring MVC dependencies

Edit the pop.xml file and add a Web dependency, Thymeleaf dependency, as follows: Web dependency (provides the Spring MVC core API and will embed a Tomcat server)

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

Thymeleaf dependency (provides a view resolver object and data binding mechanism)

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

Among them: Spring Web Starter provides Spring MVC dependency support and automatically adds a Tomcat dependency for use as an embedded Web server. Thymeleaf is an HTML template engine that provides an API for integration with Spring MVC. Can be used as the View layer of Web applications in MVC architecture.

2. Configure the Spring MVC core object

Add the graph parser configuration to the applicate. proper view ties file (default if not, default prefix to classpath:/templates/ and default suffix to.html).

spring.thymeleaf.prefix=classpath:/templates/pages/
spring.thymeleaf.suffix=.html
Copy the code

Note: Create a templates/pages directory in the SRC /main/resources directory based on your configuration

3. Get started with Spring MVC

Step 1: Write the GoodsController class and hand it over to Spring to manage. Such a Controller is commonly referred to as a Handler in the SpringMVC specification, and we sometimes think of this object in the enterprise as a back-end Controller.

package com.cy.pj.goods.controller;
@Controller
	
@RequestMapping("/goods/")
public class GoodsController {
     @RequestMapping("doGoodsUI")
public String doGoodsUI() {
	   return "goods"; }}Copy the code

Step 2: You need to create the goods.html in the /templates/pages/ directory. Step 3: Start the server (tomcat is embedded in the default project) and open the browser for access testing. http://localhost:8080/goods/doGoodsUI API application design, as shown:

Lesson Exercise 1: Query commodity data from the database and update it to the page.

Query timing analysis:

Step 1: define the pojo object (com. Cy. Pj. Goods. Pojo. Goods)

package com.cy.pj.goods.pojo; import java.util.Date; /** * PoJO object, based on which the object encapsulates the data queried from the database * think: how do objects store data? Attribute */ public class Goods {private Long id; //id bigint primary key auto_increment private String name; //name varchar(100) not null private String remark; //remark text private Date createdTime; //createdTime datetime public LonggetId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }

    public Date getCreatedTime() {
//        System.out.println("==getCreatedTime==");
        return createdTime;
    }

    public void setCreatedTime(Date createdTime) {
        this.createdTime = createdTime;
    }

    @Override
    public String toString() {
        return "Goods{" +
                "id=" + id +
                ", name='" + name + '\'' + ", remark='" + remark + '\'' + ", createdTime=" + createdTime + '}'; }}Copy the code

Step 2: Define the GoodsDao interface and methods

package com.cy.pj.goods.dao; import com.cy.pj.goods.pojo.Goods; import org.apache.ibatis.annotations.*; import java.util.List; /** * @mapper is an annotation defined by the Mybatis framework that describes the data layer interface object (all annotations serve a descriptive function) * Mybatis framework will create its interface implementation class based on @mapper annotation description, and give its implementation class object to Spring management */ @mapper public interface GoodsDao @Select("SELECT id,name,remark,createdTime FROM tb_goods")
    List<Goods> findObjects();

}

Copy the code

Step 3: Define the GoodsService interface and its implementation classes

GoodsService

package com.cy.pj.goods.service;

import com.cy.pj.goods.pojo.Goods;

import java.util.List;

public interface GoodsService {
    List<Goods> findGoods();
}

Copy the code

GoodsServiceImpl

package com.cy.pj.goods.service.impl; import com.cy.pj.goods.dao.GoodsDao; import com.cy.pj.goods.pojo.Goods; import com.cy.pj.goods.service.GoodsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; */ @service public class GoodsServiceImpl implements GoodsService {@autoWired private GoodsDao goodsDao; @Override public List<Goods>findGoods() {
        Long start=System.currentTimeMillis();
        List<Goods> list=goodsDao.findObjects();
        long end=System.currentTimeMillis();
        System.out.println("query time:"+(end-start));
        returnlist; }}Copy the code

Step 4: Define GoodsController and its URL mapping

package com.cy.pj.goods.controller;

import com.cy.pj.goods.pojo.Goods;
import com.cy.pj.goods.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller

@RequestMapping("/goods/")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;
    
    //http:localhost:8080/goods/doGoodsUI // This access path will be passed to the DispatcherServlet object // The DispatcherServlet object will find the corresponding controller and method based on the URL entered by the user // The DispatcherServlet layer will call the corresponding control layer method @requestMapping ("doGoodsUI")
    public String doGoodsUI(Model) {List<Goods> List = goodsservice.findGoods (); // Store data in the scope object model.addattribute ("list", list); // Respond the page to the clientreturn "goods"; / / the view name / / the view is returned to the front controller DispatcherServlet / / front controller view invokes the parser to parse the view, adding prefixes and suffixes / / templates/pages/goods. The HTML // Finally, the DispatcherServlet sends the page response to the client}}Copy the code

Step 5: Define goods.html and render the active data on the page using the Thymeleaf template

<! DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <table>
        <thead>
            <th>id</th>
            <th>name</th>
            <th>remark</th>
            <th>createdTime</th>
        </thead>
        <tbody>
            <tr th:each="g:${list}" >
                <td th:text="${g.id}"></td>
                <td th:text="${g.name}"></td>
                <td th:text="${g.remark}"></td>
                <td th:text="${#dates.format(g.createdTime,'yyyy/MM/dd HH:mm')}"></td>
            </tr>
        </tbody>
    </table>
</body>
</html>
Copy the code

Step 6: Run Application to start the server and enter the URL in the web page

Start the server:

Enter the url in your web page address: http://localhost:8080/goods/doGoodsUI query results are as follows:

Exercise 2: Delete commodity information from commodity database based on ID

Timing analysis:

Step 1: Define a method in GoodsDao to delete records based on id deleteById(Integer ID);

package com.cy.pj.goods.dao; import com.cy.pj.goods.pojo.Goods; import org.apache.ibatis.annotations.*; import java.util.List; /** * @mapper is an annotation defined by the Mybatis framework that describes the data layer interface object (all annotations serve a descriptive function) * */ @mapper public Interface GoodsDao {/** * Delete commodity information in database based on ID * @param id * @return
     */
    @Delete("delete from tb_goods where id=#{id}") int deleteById(Integer id); /** * find all product information * @return
     */
    @Select("SELECT id,name,remark,createdTime FROM tb_goods")
    List<Goods> findObjects();

}
Copy the code

Step 2 :GoodsService and its implementation class define the deleteById(Integer ID) method to perform record deletion of GoodsService

package com.cy.pj.goods.service;

import com.cy.pj.goods.pojo.Goods;

import java.util.List;

public interface GoodsService {
    List<Goods> findGoods();

    void deleteById(Integer id);
}
Copy the code

GoodsServiceImpl

package com.cy.pj.goods.service.impl; import com.cy.pj.goods.dao.GoodsDao; import com.cy.pj.goods.pojo.Goods; import com.cy.pj.goods.service.GoodsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; */ @service public class GoodsServiceImpl implements GoodsService {@autoWired private GoodsDao goodsDao; @Override public List<Goods>findGoods() {
        Long start=System.currentTimeMillis();
        List<Goods> list=goodsDao.findObjects();
        long end=System.currentTimeMillis();
        System.out.println("query time:"+(end-start));
        returnlist; } @Override public void deleteById(Integer id) { int rows=goodsDao.deleteById(id); }}Copy the code

Step 3: Define the doDeleteById(Integer ID) method in ActivityController to handle delete requests

package com.cy.pj.goods.controller;

import com.cy.pj.goods.pojo.Goods;
import com.cy.pj.goods.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller

@RequestMapping("/goods/")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    //http://localhost:8080/goods/doDeleteById
    @RequestMapping("doDeleteById")
    public String doDeleteById(Integer ID){// Call the business layer object to delete goodsService.deleteById(id); // Think: what do I do after deleting? // In the current business we can redirect to the query pagereturn "redirect:doGoodsUI";
    }

    //http:localhost:8080/goods/doGoodsUI // This access path will be passed to the DispatcherServlet object // The DispatcherServlet object will find the corresponding controller and method based on the URL entered by the user // The DispatcherServlet layer will call the corresponding control layer method @requestMapping ("doGoodsUI")
    public String doGoodsUI(Model) {List<Goods> List = goodsservice.findGoods (); // Store data in the scope object model.addattribute ("list", list); // Respond the page to the clientreturn "goods"; / / the view name / / the view is returned to the front controller DispatcherServlet / / front controller view invokes the parser to parse the view, adding prefixes and suffixes / / templates/pages/goods. The HTML // Finally, the DispatcherServlet sends the page response to the client}}Copy the code

Step 4: Define goods.html and render the active data on the page using the Thymeleaf template

<! DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <table>
        <thead>
            <th>id</th>
            <th>name</th>
            <th>remark</th>
            <th>createdTime</th>
        </thead>
        <tbody>
            <tr th:each="g:${list}" >
                <td th:text="${g.id}"></td>
                <td th:text="${g.name}"></td>
                <td th:text="${g.remark}"></td>
                <td th:text="${#dates.format(g.createdTime,'yyyy/MM/dd HH:mm')}"></td>
                <td><a th:href="@{/goods/doDeleteById(id=${g.id})}">delete</a></td>
            </tr>
        </tbody>
    </table>
</body>
</html>
Copy the code

Step 5: Run Application to start the server and enter the URL in the web page

Start the server:

Enter the url in your web page address: http://localhost:8080/goods/doGoodsUI

Click the delete

Lesson 3: Write the product information entered by the user to the database

Time series analysis

Step 1: Define insert(Goods Entity) methods and SQL mappings in GoodsDao

package com.cy.pj.goods.dao; import com.cy.pj.goods.pojo.Goods; import org.apache.ibatis.annotations.*; import java.util.List; /** * @mapper is an annotation defined by the Mybatis framework that describes the data layer interface object (all annotations serve a descriptive function) * */ @mapper public Interface GoodsDao {/** * Delete commodity information in database based on ID * @param id * @return
     */
    @Delete("delete from tb_goods where id=#{id}") int deleteById(Integer id); /** * Batch delete operation based on ID * @param ids * @return
     */
    //int deleteObjects(@Param("ids")Integer... ids); Earlier versions required the @param annotation int deleteObjects(Integer... ids); // SQL mapping can use array, IDS parameter name to receive method parameters /** ** find all commodity information * @return
     */
    @Select("SELECT id,name,remark,createdTime FROM tb_goods")
    List<Goods> findObjects();

    @Insert("insert into tb_goods (name,remark,createdTime) values(#{name},#{remark},now())")
    int insert(Goods entity);
}

Copy the code

Step 2: Add insert(Goods Entity) to GoodsService interface and implementation class

GoodsService

package com.cy.pj.goods.service;

import com.cy.pj.goods.pojo.Goods;

import java.util.List;

public interface GoodsService {
    List<Goods> findGoods();

    void deleteById(Integer id);

    int insert(Goods entity);
}

Copy the code

GoodsServiceImpl

package com.cy.pj.goods.service.impl; import com.cy.pj.goods.dao.GoodsDao; import com.cy.pj.goods.pojo.Goods; import com.cy.pj.goods.service.GoodsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; */ @service public class GoodsServiceImpl implements GoodsService {@autoWired private GoodsDao goodsDao; @Override public List<Goods>findGoods() {
        Long start=System.currentTimeMillis();
        List<Goods> list=goodsDao.findObjects();
        long end=System.currentTimeMillis();
        System.out.println("query time:"+(end-start));
        return list;
    }

    @Override
    public void deleteById(Integer id) {
        int rows=goodsDao.deleteById(id);
    }

    @Override
    public int insert(Goods entity) {
        int rows=goodsDao.insert(entity);
        returnrows; }}Copy the code

Step 3: Add the doSaveGoods method to the GoodsController object and define the URL mapping

package com.cy.pj.goods.controller;

import com.cy.pj.goods.pojo.Goods;
import com.cy.pj.goods.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller

@RequestMapping("/goods/")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;


    //http://localhost:8080/goods/doDeleteById
    @RequestMapping("doDeleteById")
    public String doDeleteById(Integer ID){// Call the business layer object to delete goodsService.deleteById(id); // Think: what do I do after deleting? // In the current business we can redirect to the query pagereturn "redirect:doGoodsUI";
    }

    @RequestMapping("doSaveGoods")
    public String doSaveGoods(Goods entity){
        goodsService.insert(entity);
        return "redirect:doGoodsUI";
    }

    //http:localhost:8080/goods/doGoodsUI // This access path will be passed to the DispatcherServlet object // The DispatcherServlet object will find the corresponding controller and method based on the URL entered by the user // The DispatcherServlet layer will call the corresponding control layer method @requestMapping ("doGoodsUI")
    public String doGoodsUI(Model) {List<Goods> List = goodsservice.findGoods (); // Store data in the scope object model.addattribute ("list", list); // Respond the page to the clientreturn "goods"; / / the view name / / the view is returned to the front controller DispatcherServlet / / front controller view invokes the parser to parse the view, adding prefixes and suffixes / / templates/pages/goods. The HTML // Finally, the DispatcherServlet sends the page response to the client}}Copy the code

Step 4: Add the form (user-filled data) to the goods.html page and style it

<! DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
   <form action="/goods/doSaveGoods" method="post">
       <ul>
           <li>name:
           <li><input type="text" name="name">
           <li>remark:
           <li><textarea rows="5" cols=""50 name="remark"></textarea>
           <li><input type="submit" value="save"></li> </ul> </form> <fieldset> </legend> <table width="50%">
    <table>
        <thead>
            <th>id</th>
            <th>name</th>
            <th>remark</th>
            <th>createdTime</th>
        </thead>
        <tbody>
            <tr th:each="g:${list}" >
                <td th:text="${g.id}"></td>
                <td th:text="${g.name}"></td>
                <td th:text="${g.remark}"></td>
                <td th:text="${#dates.format(g.createdTime,'yyyy/MM/dd HH:mm')}"></td>
                <td><a th:href="@{/goods/doDeleteById(id=${g.id})}">delete</a></td>
            </tr>
        </tbody>
    </table>
</body>
</html>
Copy the code

Step 5: Enter the data in the form and click the Save button to pass the data to the server

The last

If you don’t understand anything, please leave a message below to discuss it. You can also choose private letter to ask me. Private letter will be returned to me after I see it.