Abstract:






Yq.aliyun.com/video/play/…


PPT download address: yq.aliyun.com/download/26…


Introduction to speakers



Lu Deqing (Flower: Yushan)












I. Introduction to Spring










IOC








































AOP






















Spring Web development















First, the sample project is managed using Maven, where Spring Boot dependencies are first defined. Spring Boot is a development suite that integrates the Spring framework to help developers develop Spring Web applications faster. You can also see Web dependencies, AOP dependencies, and the dependencies of the template engine Thymeleaf. The project POM file is as follows:

<? The 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 http://maven.apache.org/xsd/maven-4.0.0.xsd" > < modelVersion > 4.0.0 < / modelVersion > < groupId > Java. Alibaba < / groupId > < artifactId > spring - the boot - web - demo < / artifactId > < version > 1.0 - the SNAPSHOT < / version > < dependencies > <! --> <dependency> <groupId>org.springframework.boot</groupId> < artifactId > spring - the boot - starter - parent < / artifactId > < version > 2.0.1. RELEASE < / version > < / dependency > <! -- Web dependency --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter- Web </artifactId> The < version > 2.0.1. RELEASE < / version > < / dependency > <! GroupId > <artifactId> Spring-boot-starter-AOP </artifactId> The < version > 2.0.1. RELEASE < / version > < / dependency > <! --> <dependency> <groupId>org.springframework.boot</groupId> The < artifactId > spring - the boot - starter - thymeleaf < / artifactId > < version > 2.0.1. RELEASE < / version > < / dependency > < / dependencies > </project>Copy the code






package demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * Spring boot 启动类
 *
 * @author yushan.ldq
 * @date 2018/04/22
 */
@SpringBootApplication()
public class WebApplication {
    public static void main(String[] args) {
        SpringApplication.run(WebApplication.class, args);
    }
}
Copy the code

The following code shows the UserController class, on which you can see the @Controller annotation. Because of this annotation, UserController information will be injected into the IOC container. In UserController, you can see a member variable of UserService that is not initialized in the entire UserController. Since there is an @Autowired annotation, the UserController can be initialized with dependencies declared by the @AutoWired annotation, which will be injected by the IOC container. What it injects is an implementation of the UserService interface.

UserController class:

package demo.controller;

import demo.model.User;
import demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 *
 * @author yushan.ldq
 * @date 2018/04/22
 */
@Controller
@RequestMapping(value = "/users")
public class UserController {

    @Autowired
    @Qualifier("userServiceImpl")
    private UserService userService;

    @RequestMapping(method = RequestMethod.GET)
    public String getUsersPage(ModelMap modelMap) {
        modelMap.addAttribute("userList", userService.findAll());
        return "users";
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String createUserPage(ModelMap modelMap) {
        modelMap.addAttribute("user", new User());
        return "userCreate";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String createUser(@ModelAttribute User user) {
        userService.create(user);
        return "redirect:/users";
    }


    @RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
    public String deleteUser(@PathVariable Integer id) {
        userService.delete(id);
        return "redirect:/users";
    }
}
Copy the code

For the UserService interface, it has an implementation class with an @Service annotation. Because of this annotation, the implementation class of UserService will be injected into the IOC container. Finally, the IOC container can initialize an object of the implementation class of UserService. And inject the object into the UserController, so that a complete UserController object can be retrieved via IOC, and the dependencies are automatically assembled. That is the role of the IOC. There is no instantiation of UserService in any code; this is done jointly by SpringBoot and IOC.

UserService interface:

package demo.service;

import java.util.List;

import demo.model.User;

/**
 * @author yushan.ldq
 * @date 2018/04/22
 */
public interface UserService {

    User findById(Integer id);

    User create(User user);

    User update(User user);

    User delete(Integer id);

    List<User> findAll();
}
Copy the code


UserServiceImpl implementation class:

package demo.service.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import demo.model.User; import demo.service.UserService; import org.springframework.stereotype.Service; /** * @author yushan.ldq * @date 2018/04/22 */ @Service() public class UserServiceImpl implements UserService{ private Map<Integer, User> userDb = new HashMap<Integer, User>(); public User findById(Integer id) { return null; } public User create(User user) { user.setId(userDb.size() + 1); return userDb.put(user.getId(), user); } public User update(User user) { return null; } public User delete(Integer id) { return userDb.remove(id); } public List<User> findAll() { return new ArrayList<User>(userDb.values()); }}Copy the code


Because of LogAspect, subsequent code that executes all public methods in the Controller will print the method arguments before and the return values after the method. This is the benefit of AOP’s faceted programming approach.

LogAspect class:

package demo.aop; import java.util.Arrays; import javax.servlet.http.HttpServletRequest; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; /** * @author yushan.ldq * @date 2018/04/24 */ @Aspect @Component public class LogAspect { @Pointcut("execution(public *  demo.controller.*.*(..) Public void log(){} @before ("log()") public void doBefore(JoinPoint JoinPoint) throws Throwable { Record the request content ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder. GetRequestAttributes (); HttpServletRequest request = attributes.getRequest(); System.out.println("URL: "+ request.getrequestUrl ().toString()); System.out.println("HTTP_METHOD : " + request.getMethod()); System.out.println("IP : " + request.getRemoteAddr()); System.out.println("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()); } @afterreturning (returning = "ret", pointcut = "log()") public void doAfterReturning(Object RET) { System.out.println(" method return value: "+ ret); }}Copy the code

I will share with you the use of WebMVC as an architectural pattern. First, you need to understand what M, V, and C stand for in MVC. M stands for Model, or data Model. In the User class shown below, Model is the data carrier.

The User class:

package demo.model; /** * @author yushan.ldq * @date 2018/04/22 */ public class User { private Integer id; private String name; private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; }}Copy the code

V refers to the View, in this case the two HTML template files defined under the Templates folder that will eventually be read by the introduced Thymeleaf dependent template engine. Here you can think of a template file as a Java class.

userCreate.html

<! DOCTYPE HTML > < HTML lang="en"> <head> <meta charset="UTF-8"> <title> Create user </title> </head> <body> <form Th :action="@{/users}" method="post" > <div> <label for="user_name" class=" col-SM-2 control-label"> User name :</label> <input Type = "text" id = "user_name" name = "name" th: field = "* {user. The name}" / > < / div > < div > < label for = "user_age" > age: < / label > < input Type = "text" id = "user_age" name = "age" th: field = "* {user. Age}" / > < / div > < div > < input type = "submit" value = "submit" / > < / div > </form> </body> </html>Copy the code


user.html

<! DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>Users</title> </head> <body> <table> <thead> <tr> The < th > user id < / th > < th > name < / th > < th > age < / th > < / tr > < thead > < tbody > < tr th: each = "user: ${userList}"> <th scope="row" th:text="${user.id}"></th> <td th:text="${user.name}"></td> <td Th: text = "${user. Age}" > < / td > < td > < a th: href = "@ {/ users / {id} / delete (id = ${user. Id})}" > delete < / a > < / td > < / tr > < / tbody > < / table > The < div > < a href = "/ users/add" > new user < / a > < / div > < / body > < / HTML >Copy the code



/**
 *
 * @author yushan.ldq
 * @date 2018/04/22
 */
@Controller
@RequestMapping(value = "/users")
public class UserController {

    @Autowired
    @Qualifier("userServiceImpl")
    private UserService userService;

    @RequestMapping(method = RequestMethod.GET)
    public String getUsersPage(ModelMap modelMap) {
        modelMap.addAttribute("userList", userService.findAll());
        return "users";
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String createUserPage(ModelMap modelMap) {
        modelMap.addAttribute("user", new User());
        return "userCreate";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String createUser(@ModelAttribute User user) {
        userService.create(user);
        return "redirect:/users";
    }


    @RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
    public String deleteUser(@PathVariable Integer id) {
        userService.delete(id);
        return "redirect:/users";
    }
}Copy the code








































The entire process is defined by a class, configured by annotations, and not instantiated by a class. This is all in IOC’s hands because of inversion of control. Because of Spring Boot, there is no need to define a Tomcat. Spring Boot already defines a Tomcat to provide external services by default. This is the benefit of Spring Boot, which can help us develop Web applications very quickly.

This article is organized and edited by Jia Zijia, a cloud habitat volunteer group