Crazy liver strongest Java EE framework high-intensity learning

Posted by Stalingrad on Tue, 01 Feb 2022 20:09:21 +0100

SpringBean container:
Beans are java objects. The container is responsible for the management of the whole life cycle of java objects, including creation, modification and destruction

IOC control reversal
IOC: it's an idea
IOC container: the implementation container of IOC thought

DI
One of the ways to implement IOC, dependency injection, is to dynamically inject dependencies into objects during IOC operation

Through the idea of Ioc, the Ioc container is introduced, and the decoupling between objects is realized by dependency injection
The function of ioc is explained in the design to reduce the coupling between codes. The implementation method is di. Di can be implemented in two ways

Register the Bean and use it on the class. Once it is scanned by the class, the Bean object will be generated and registered in the container in the form of annotation
Controller:web request response processing, and the controller layer completes operations such as request data verification
Service: the service layer of business logic completes business logic according to method parameters
Repository: access operation of relational database in data access layer
Component: general component
Mode 2
@Bean annotation on method
More flexible, you can modify attributes

Mode 3
@configuration
Used to customize the configuration of some resources

Method 4: factorybean
The bean object of the factory,
Object of factory mode production

Traditional three-tier architecture design: controller, service DAO

Assembly bean
@Autowired auto assembly
@Qualifier ("first name")
@Resource JDK spring has also been implemented

@Role of Scope(prototype)
When a Bean object is obtained, a new object, singleTon, and the same object will be created
T is usually used in stateful beans

Bean life cycle
1. Instantiate Bean
2. Dependency injection
3. Inject the method parameter object of Aware interface, such as sequentially executing BeanNameAwar e
Before initializing the bean.before method
5.Bean object initialization: execute some annotations and interface methods
6. Execute the after method of beanPostProcessor
7. When the container is closed, execute the destruction method of Bean object

springboot project preparation
1. Create a normal maven project
2. Adjust POM XML file: introducing the dependency of springBoot
3.src/main/resources
Create public static to store web static resource files
Create application Properties, the default configuration file of springboot
4. Create a startup class casually: it must be written under a package. When starting, the package of the automatic class will be automatically scanned
5. Modify the debug log: application Debug in property file
6. Adjust the startup without error
7. Direct operation startup class

Small hole in the front relative path

js takes the html path in as the starting point of the relative path

css takes the request path of the file itself as the starting point of the request

Front end code: Ajax detail analysis:
The asynchronous request will not jump to the page and block the subsequent code. After receiving the response data, execute the callback method:
(1) Response code 200, execute the success callback function
(2)4XX,5xx failed to execute callback function

The browser provides the implementation of native ajax technology
At present, they all use the jQuery framework, and everything changes

$(function(){ //Method to execute after html page loading and execution
    $("#login_form").submit(function() {/ / bind the submission event of the form, and execute the subsequent method after submission
        //Execute ajax commit
        $.ajax({
            //Get resp from here
            //url:"../data/login.json",
            url:"../data/login2.json",
            type:"get",//Request method 
            //dataType: '', / / request data type content type
            data:$("#login_form").serialize(), / / request data: use the data of the form, and the key is equal to the value
            contentType:"json",//Response data type: content type
            //Return the data of a json
            success:function (resp) {//The response status starts with 2 and enters success
                //Return data success == true jump to maven page
                if (resp.success == true){
                    //Put the url in the address bar to the specified value
                    window.location.href = "main.html";
                }else{
                    alert("Error code: " + resp.code+"\n error message: "+resp.message)
                    //alert(JSON.stringify(resp)) / / prompt box: convert json object to string
                }
            },
            error:function (req,textStatus,err) {//4 big head response status code
                alert(req.status)
            }
        })

        //Verify alert("submit")
        return false;//The return value determines whether the form is submitted by default
    })
})

springMVC
Tomcat and servlet execution process
resources:
(1) If it is a static resource, tomcat returns directly
(2) If it's a servlet
----Call service()
----Request: parse the request data of http protocol and encapsulate it as request
----Response: the call to service() has not responded, but the response object has been created
----tomcat constructs the corresponding data of http protocol according to the response object

mvc model '
RequestMapping

@Controller
public class Test2Controller {
    @RequestMapping("/test2")
    public String test(){
        return "forward:/home.html";
    }
}

Function of String return type

@controller:web front-end controller
@RequestMapping: on classes and methods, value path and method specify the method of the service. Method does not. All methods are supported by default
@ResponseBody: return value as corresponding body
The return type is String, and the String is used as the content of the response body
The return type is a custom java type, Object, serialized as a JSON string
Combined notes
1. Restcontroller: comments of controller + ResponseBody
2.GetMapping: requestmapping+get is used on the method
3.PostMapping:
Parameters in request mapping method in Controller
(1)@RequestParam: except for application/json, other value s can be obtained through key. It is required by default and not required

required=false
 Acceptable form-data,Include files 
 @RequestMapping("login")
    public Object login(@RequestParam String username,@RequestParam String password){
         log.debug("Get path request parameters username "+ username + "password" + password);
         Map<String,Object> map = new HashMap<>();
         map.put("ok",true);
         return map;
     }
     @RequestMapping("/register")
    public Object register(@RequestParam String username, @RequestParam String password, @RequestParam MultipartFile file) throws IOException {
        log.debug("Get request path parameters : username={},  password={}",username,password);
        log.debug("Avatar information,name={},content={}",file.getOriginalFilename(),new String(file.getBytes()));
         Map<String,Object> map = new HashMap<>();
         map.put("ok",true);
         return map;
     }
     public Object holiday(@PathVariable String day){
        log.debug("Get path request parameters" + day);
        Map<String,Object> map = new HashMap<>();
        map.put("ok",true);
        return map;
     }

(2)POJO object is the same as @ RequestParam

How to obtain the request data:
(1) pojo is relatively easier to write than @ RequestParam
(2) The request data is relatively small. Generally, json is not used. If there is no user-defined type correspondence, you can directly use the packaging type

(3) There are a lot of request data, which may be designed as request data type or json. The default format of the form is formdata(pojo)
@json for RequestBody

RequstPart
Binary file, default required=true

@PostMapping("/file")
    public Object file(@RequestPart MultipartFile file) throws IOException {
        log.debug("Avatar information,name={},content={}",file.getOriginalFilename(),new String(file.getBytes()));
        Map<String,Object> map = new HashMap<>();
        map.put("ok",true);
        return  map;
    }

SevletApi
Similar to native servlets, spring MVC will pass in servlet objects directly as method parameters
Generally: reponse returns binary and custom output, such as binary files and session processing

Spring MVC requests and responses, used by the backend
(1) Return attempt without responsebody annotation. The return type is String

(2) Return json data: the method is annotated with Responsebody (the class also acts on the method, and the return type is Object)

(3) Request data type is json@RequestBody , if an error is reported, the request data has a key. Check the access data format. There is no such attribute in the deserialized java object. If an error is reported, there is an attribute in the deserialized java object. If the request JSON data does not have the key, no error will be reported. The attribute in java is the default value; Basic data types are not recommended

(4) The request data type is not json, or it is a get request:
Using pojo, others can understand
Note: if the property of the pojo object is found to be null, the request must not have this key

(5)Servlet related Api:session related

Url variable binding:
@pathVariable
HandlerInterceptor Interceptor: similar to filter, provided by mvc

Precautions for front and rear end interaction

Debugging means in the previous paragraph: Developer Tools
Backend Debug
What's wrong? Find the logic of the previous process

Implementation of user unified session management: HandlerIntertceptor
Unified management of service resources to be considered in the server
Open permission access permission after login (access is not allowed before login)
Article list, add and modify html, add to the blacklist and prohibit access
(1) Front end resources

(2) Backend resource user login registration (/ user / * *)

Black and white list: List < < white list >, list < < blacklist > do a business. The white list is allowed to operate, and the blacklist is not allowed to operate

Adding interceptors uses the idea of black-and-white list. The white list sets the path of resources to be intercepted, and the blacklist excludes the path of resources to be intercepted

When actually configuring the resource path, we will consider: configuring the minimum set + flexible expansion (maintainability)
SpringMVC

HandlerInterceptor,Filter
(1) Multiple can be matched at the same time
(2) Method returns boolean type, indicating whether to call the chain and whether to execute down
(3) If you need to go down, return true
(4) If you can't continue to visit, return false; If (condition) returns a response to the client return false;

ControllerAdvice

1. The current class is a unified aspect class of controller
2. Unified processing method can be defined
@controllerAdvice
public class XXX{
@Exceptionhandler (exception. class)
public return type method name (passed in parameter)
}

 @ExceptionHandler(AppException.class)
    public Object handle1(AppException e){
        JSONResponse json  = new JSONResponse();
        //Customize the exception and save our error code and error message
        json.setCode(e.getCode());
        json.setMessage(e.getMessage());
        log.debug(transfer(e));
        //Non custom exception (English error message, stack information, which cannot be shown to the user):
        // Specify an error code, error message (unknown error, please contact the administrator)
        return json;
    }
    @ExceptionHandler(Exception.class)
    public Object handle2(Exception e){
        JSONResponse json  = new JSONResponse();
        //Customize the exception and save our error code and error message
        json.setCode("ERR000");
        json.setMessage("unknown error,Please contact the administrator");
        log.debug(transfer(e));
        //Non custom exception (English error message, stack information, which cannot be shown to the user):
        // Specify an error code, error message (unknown error, please contact the administrator)
        return json;
    }

Exceptions need to be mastered
(1) The order of code execution when an exception occurs (se)
(2) How to throw exceptions? Throw exceptions manually (user-defined exceptions). Throw exceptions when there is a bug in the code
(3) How to handle exceptions? The framework encapsulates our trycatch and requires a unified exception handling scheme
(4) How to find the abnormal code line according to the exception and debug the code
According to the stack information, find which class and which method threw it, analyze the try catch, and analyze our code line, specifically which line of code
(3)ControllerAdvice
Class implements the ResponseBodyAdvice interface and rewrites the content of the response body according to conditions
Rewriting support: returns boolean, indicating whether to rewrite beforeBodyWrite after executing the Controller request mapping method: how to rewrite, use the response object to rewrite

AOP
Concept: aspect oriented programming is a programming idea


(1) Inheritance mode
Static agent design pattern:
Inherit the original class / proxied class, and the subclass is the proxy class
Override the parent method, adding the enhanced business before and after calling the parent class method.

(2) Interface mode
Primitive class The proxy class implements the same interface
Use the proxy object to create a proxy class -------- public proxy class (proxy class) {}
Proxy class interface method rewriting is to add enhanced business before and after calling the method of the proxy class object

Static weaving technology

Weaving time: compilation period, class loading period
Representative technology ASpectJ

Dynamic agent
AOP
(1) Static agent design pattern
(2) Static weaving
(3) Dynamic agent
java says AOp, basically spring AOp, basically dynamic proxy

Dynamic weaving during operation

Implementation of dynamic agent:
Jdk implementation:
The proxy is required to implement the interface
Through the invocationhandler and proxy of JDK NEWP roxyinstance to generate proxy classes

Spring provides annotation syntax support for aspectJ, which is essentially implemented by jdk and CGLIB - Method enhancement

@Aspect//Perform slice programming
@Component
//Connection point
public class TestAOP {
    //Section location
    //Any class under the package Any method, any parameter
    @Pointcut("execution(* com.example.mvclearn.controller.*.*(..))")
    public void loginPointcut(){

    }
}

AOP terminology

@Aspect//Program the section and define the section
@Component
//Connection point
public class TestAOP {
    //Cut location, define cut point
    //Any class under the package Any method, any parameter
    @Pointcut("execution(* com.example.mvclearn.controller.*.*(..))")
    public void loginPointcut(){

    }
    //Notification, pre notification, incoming pointcut method name ()
    @Before("loginPointcut()")
    public void beforeRequest(){
        System.out.println("Before advice ");
    }
    @After("loginPointcut()")
    public void afterRequest(){
        System.out.println("Request mapping method execution completed");
    }
    @AfterReturning
    public void afterRequestReturn(){
        System.out.println("Request mapping method return");
    }
    @AfterThrowing("loginPointcut()")
    public void afterRequestThrow(){
        System.out.println("The request mapping method threw an exception");
    }
    //Around Advice 

}


Understanding of AOP

(3)Spring dynamic proxy
Weaving time: running period (generated upon startup)
Implementation method:
1.JDK: interface based implementation (the proxy class implements the interface, and the interface method needs to be enhanced)
API:InvocationHandler,Proxy
Principle: when running, the bytecode proxy class is dynamically generated for class loading, and the container is full of proxy class objects
2.CGLIB: inheritance based implementation (the proxy class may not implement the interface)
The proxy code is generated based on the principle of lib and CG asm

Mybatis
Suggested xml configuration method
jdbc operation review

ORM framework:
Mybatis

Entity class

Configure mapper interface

Mybatis execution process

Dao layer unit test method

Why can I use the UserMapper interface
@mapper annotation
...
Mybatis framework uses Aop to dynamically generate proxy classes based on the interface of mapper annotation in scanning container
Call the method of Mapper implementation class

Practice a little

Mybatis relational mapping
One to one mapping

property attribute: specify the corresponding attribute in Article, that is, user.
resultMap attribute: Specifies the associated result set mapping. User data will be organized based on the mapping configuration.
columnPrefix attribute: when Binding one-to-one objects, it is through columnPrefix + association resultMap. column
To map result set fields. association.resultMap.column refers to the resultmap attribute in the tag,
In the corresponding result set mapping, the column field.

Many to many mapping

```xml
<resultMap>In result set mapping, one to many relationships need to be used<collection>Label, method of use and<association>similar.
The following is UserMapper.xml Result set mapping configuration for:
The following is the unit test code:
<select id="selectAll" resultMap="BaseResultMap">
   select
   a.id a_id,
   a.title a_title,
   a.content a_content,
   a.view_count a_view_count,
   a.user_id a_user_id,
   a.create_time a_create_time,
   u.id,
   u.username,
   u.password,
   u.nickname,
   u.sex,
   u.birthday,
   u.head,
   u.create_time
   from article a
   join user u
   on u.id=a.user_id
</select>
<!-- Define result set mapping relationship: bind result set fields and transform java Relationship between objects -->
<resultMap id="BaseResultMap" type="org.example.model.User">
    <!-- Result set fields and java Mapping of object properties -->
    <id column="id" property="id" />
    <result column="username" property="username" />
    <result column="password" property="password" />
    <result column="nickname" property="nickname" />
    <result column="sex" property="sex" />
    <result column="birthday" property="birthday" />
    <result column="head" property="head" />
    <result column="create_time" property="createTime" />
    <collection property="articles"
                columnPrefix="a_"
                resultMap="org.example.mapper.ArticleMapper.BaseResultMap" />
</resultMap>
```java
package org.example.mapper;
import org.example.model.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
//Specified as a unit test in the Spring environment
@RunWith(SpringRunner.class)
//It is specified as the unit test of SpringBoot environment, and Application is the startup class
@SpringBootTest(classes = Application.class)
//Using transactions, it will be rolled back automatically in the unit test of SpringBoot
@Transactional
public class UserMapperTest {
    @Autowired
    private UserMapper userMapper;
    @Test
    public void selectAll(){
        List<User> users = userMapper.selectAll();
        users.stream()
               .forEach(System.out::println);
   }
}

dynamic sql statement
label

<insert id="insert" parameterType="org.example.model.User"
useGeneratedKeys="true" keyProperty="id">
 insert into user(
         username,
         password,
         nickname,
          <if test="sex != null">
           sex,
          </if>
         birthday,
         head
     ) values (
         #{username},
         #{password},
         #{nickname},
          <if test="sex != null">
           #{sex},
          </if>
         #{birthday},
         #{head}

Note that sex in test is an attribute in the incoming object, not a database field.

label
In the previous insert user function, only one sex field may be optional. If there are multiple fields, labels are generally considered
Combined with tags, multiple fields are dynamically generated.
The tag has the following attributes:
Prefix: represents the entire statement block, prefixed with the value of prefix
Suffix: indicates the whole statement block, with suffix value as suffix
prefixOverrides: indicates the prefix to be removed from the whole statement block
suffixOverrides: indicates the suffix to be removed from the whole statement block

<insert id="insert" parameterType="org.example.model.User"
useGeneratedKeys="true" keyProperty="id">
 insert into user
    <trim prefix="(" suffix=")" suffixOverrides=",">
        <if test="username != null">
         username,
        </if>
        <if test="password != null">
         password,
        </if>
        <if test="nickname != null">
         nickname,
        </if>
        <if test="sex != null">
         sex,
        </if>
        <if test="birthday != null">
               birthday,
        </if>
        <if test="head != null">
         head,
        </if>
        <if test="createTime != null">
         create_time,
        </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
        <if test="username != null">
         #{username},
        </if>
        <if test="password != null">
         #{password},
        </if>
        <if test="nickname != null">
         #{nickname},
        </if>
        <if test="sex != null">
         #{sex},
        </if>
        <if test="birthday != null">
         #{birthday},
        </if>
        <if test="head != null">
         #{head},
        </if>
        <if test="createTime != null">
         #{createTime},
        </if>
    </trim>
</insert>

During the above sql dynamic parsing, the first part will be processed as follows:
Based on the prefix configuration, add(
Based on suffix configuration (add at the end)
The statements of multiple organizations end with, and the spliced string will end with, based on
The suffixOverrides configuration removes the last one,
Note that createTime in < if test = "createTime! = null" > is the attribute of the incoming object

The above labels can also be replaced.
The unit test code is as follows:
The user data is updated according to the attributes of the incoming user object. You can use tags to specify dynamic content.
Modify user method in UserMapper interface: modify other non null attributes according to the passed in user id attribute:
UserMapper. Add update user sql in XML:

<select id="selectByCondition" parameterType="org.example.model.User"
resultMap="BaseResultMap">
   select id, username, password, nickname, sex, birthday, head, create_time
       from user
    <where>
        <if test="username != null">
           and username=#{username}
        </if>
        <if test="password != null">
           and password=#{password}
        </if>
        <if test="nickname != null">
           and nickname=#{nickname}
        </if>
        <if test="sex != null">
           and sex=#{sex}
        </if>
        <if test="birthday != null">
           and birthday=#{birthday}
        </if>
        <if test="head != null">
           and head=#{head}
        </if>
        <if test="createTime != null">
           and create_time=#{createTime}
        </if>
    </where>
</select>
@Test
public void selectByCondition(){
    User user = new User();
    user.setUsername("e");
    user.setPassword("5");
    List<User> users = userMapper.selectByCondition(user);
    System.out.println(users);
}
@Test
public void selectByCondition2(){
    User user = new User();
    user.setSex(false);
    List<User> users = userMapper.selectByCondition(user);
    System.out.println(users);
}

label
The user data is updated according to the attributes of the incoming user object. You can use tags to specify dynamic content.
Modify user method in UserMapper interface: modify other non null attributes according to the passed in user id attribute:
UserMapper. Add update user sql in XML:

<update id="updateById" parameterType="org.example.model.User">
   update user
        <set>
            <if test="username != null">
               username=#{username},
            </if>
            <if test="password != null">
               password=#{password},
            </if>
            <if test="nickname != null">
               nickname=#{nickname},
            </if>
            <if test="sex != null">
               sex=#{sex},
            </if>
            <if test="birthday != null"> 
               birthday=#{birthday},
            </if>
            <if test="head != null">
               head=#{head},
            </if>
            <if test="createTime != null">
               create_time=#{createTime},
            </if>
        </set>
   where id=#{id}
   </update>

label
This tag can be used when traversing a collection. The tag has the following properties:
Collection: the collection in the binding method parameter, such as List, Set, Map or array object
item: each object during traversal
open: the string at the beginning of the statement block
close: the string at the end of the statement block
separator: the string between each traversal
Example: delete article data according to multiple article IDs.

<delete id="deleteByIds">
   delete from article
   where id in
   //Variable: item
    <foreach collection="list" item="item" open="(" close=")" separator=",">
       #{item}
    </foreach>
</delete>
<insert id="batchIn">
        insert into user(
            id,
            username,
            password,
            nickname,
             sex,
            birthday,
            head
        ) values
        <foreach collection="list" item="item" separator=",">
            (
            #{item.id},
            #{item.username},
            #{item.password},
            #{item.nickname},
            #{item.sex},
            #{item.birthday},
            #{item.head}
            )
        </foreach>
    </insert>

mybatis generation tool
slightly

Topics: Java Mybatis Spring Spring Boot Ajax