Notes on SpringBook Knowledge

Creation and hot deployment of Springboot project
1. You need to choose your own dependencies when you create them. Idea will automatically generate the corresponding directory and startup classes. (Startup classes should be at the same level as other packages, otherwise resources will not be found.)
2.springboot Hot Deployment in idea
[File]-[Settings...]-[Build,Execution,Deployment]-[Compiler],
Check "Build project automatic" and then go to the lower right corner [Apply] -- [OK]
Search "Registry" with Ctrl+Shift+A shortcut key, and select the first one you find.
Find "compiler.automake.allow.when.app.running", check, [Close] close
Adding dependencies:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
<scope>true</scope>
</dependency>

maven configuration

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <fork>true</fork>//This configuration must
            </configuration>
        </plugin>
    </plugins>
</build>

springboot integrates Swagger

1. Introducing dependencies

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.7.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.7.0</version>
</dependency>

2. Configure Swagger's configuration file ==> Swagger. Java

@Configuration
@EnableSwagger2
public class Swagger2 {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2).groupName("api")
                .apiInfo(apiInfo())
                .enable(true)
                .select()
                .apis(RequestHandlerSelectors.basePackage("Scanning path api File"))
                .paths(PathSelectors.any())//Path Judgment
                .build()
                .ignoredParameterTypes(WebBean.class); //The entity class property is not shown in swagger
    }



   private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("")//Headline
                .description("")//Detailed description
                .termsOfServiceUrl("http://king.yiyoupay.net/apiservice/")
                .contact()//author
                .version("1.0")//Edition
                .build();
    }
}

3. Use the configuration in the code

@RestController    analysis json object
@Api(value = "Tested demo",tags = {"Build environment test code"})
public class DemoController {

    @Autowired
    private UserDao userDao;

    @ApiOperation(value = "test restful",notes = "Test Engineering")
    @ApiImplicitParam(value = "Full name",name="name")  
    @ApiResponses({
            @ApiResponse(code = 200, message = "Success"),
            @ApiResponse(code = 400, message = "fail")
   		 })
    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    public String sayHello(String name){
        return name;
    }

}

Common Notes:

  • @ Api() is used for classes;
    Represents the resource that identifies the class as swagger, that is, the annotation of the class
  • @ ApiOperation() is used for methods;
    Represents the operation of an http request, the annotation of a method
  • @ ApiParam() is used for method, parameter, field description;
    Represents the addition of metadata to a parameter (description or whether it is necessary to fill in, etc.), i.e. the annotation of the parameter
  • @ ApiModel() for classes
    Represents a description of a class for parameters to be received by an entity class, i.e. a comment returning an entity
  • @ ApiModelProperty() for methods, fields
    Represents a description of the model property or a change in data operation, that is, a comment on the property of the returned entity
  • @ ApiIgnore() for classes, methods, method parameters
    Indicates that the method or class is ignored, that is, it is unrealistic to ignore the method.
  • @ ApiImplicitParam() for methods
    Represents a separate request parameter, that is, a comment on a single parameter
  • @ ApiImplicitParams() is used for methods, including multiple @ApiImplicitParams
    @ ApiResponses: Used to represent a set of responses
    @ ApiResponse: Used in @ApiResponses to convey an incorrect response
    L code: Numbers, such as 400
    L message: Information, such as "Request parameters not filled in"
    L response: Class that throws an exception

Start-up project:
Browse the address and visit the home page: http://localhost:8080/swagger-ui.html#
Browse the address and visit sagger's proprietary Json API: http://localhost:8080/v2/api-docs

Use of Handler Interceptor Interceptor Interceptor in SpringBoot

There are several very simple ways to define an Interceptor. Here are two simple ways to define an Interceptor
1. Class implements Spring's Hadler Interceptor interface
2. Class inheritance implements the Handler Interceptor interface, such as the abstract class that has been provided to implement the Handler Interceptor interface.

HandlerInterceptorAdapter
Introduction of Three Methods in Handler Interceptor

/**
 *
 * Called before the business processor processes the request. Pre-processing, can be coded, security control, authority verification and other processing;
 * @param httpServletRequest
 * @param httpServletResponse
 * @param o
 * @return
 * @throws Exception
 */
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
//If retrun false   
//Reset response
httpServletResponse.reset();
//Setting the encoding format
httpServletResponse.setCharacterEncoding("UTF-8");
httpServletResponse.setContentType("application/json;charset=UTF-8");
httpServletResponse.getWriter().write("Privilege Check Failed,Please login again");
    return true;
}

/**
 * After the execution of the request is completed by the business processor, it is executed before the view is generated. Post-processing (calling Service and returning ModelAndView without page rendering)
 * Having the opportunity to modify the Model AndView (this blogger is basically useless);
 * @param httpServletRequest         
 * @param httpServletResponse                       
 * @param o                                       
 * @param modelAndView
 * @throws Exception
 */
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

}

/**
 * Called after Dispatcher Servlet has fully processed the request, which can be used to clean up resources, etc. Return processing (page rendered);
 * @param httpServletRequest
 * @param httpServletResponse
 * @param o
 * @param e
 * @throws Exception
 */
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

}

New WebAppConfigurer to Implement WebMvcConfigurer Interface
In fact, they all inherited the WebMvcConfigurerAdapter class before, but the WebMvcConfigurerAdapter method over SpringBoot 2.0 is outdated. There are two alternatives:
1. Inheriting WebMvc Configuration Support
2. Implementing WebMvcConfigurer
However, inheriting WebMvc Configuration Support will invalidate Spring-boot's automatic configuration of mvc. Select according to the project situation. Now most projects are front-end and back-end separated, and there is no need to automatically configure static resources, so inheriting WebMvc Configuration Support is also necessary.

 /**
     * Spring MVC To configure
     */
    @Configuration
    public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
     //Solving cross-domain problems
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }

    //Adding interceptors
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //Interface signature authentication interceptor, this signature authentication is relatively simple, and can be replaced by Json Web Token or other better ways in actual projects.
//        if (!"dev".equals(env)) {// Development environment ignores signature authentication
        //Jwt Authentication Interception
        registry.addInterceptor(jwtInterceptor).addPathPatterns("/**")
                .excludePathPatterns("Path of release");
//                excludePathPatterns("/**"); // No token check first
                }
    }
}

Tags: SpringBoot Spring JSON Maven

Posted on Mon, 26 Aug 2019 06:16:29 -0700 by 0p3n_p0rT