Ajax asynchronous interaction

For Springmvc default MappingJackson2HttpMessageConverter are used to characterize the json data conversion, need to add Jackson bag; Also use < MVC :annotation-driven />

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.8</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.9.0</version>
</dependency>
Copy the code

@RequestBody

This annotation is used to declare the parameter of the Controller’s method, which is converted to the corresponding POJO object via the HttpMessageConverter interface when the contentType is specified as JSON in an Ajax submission.

<button id="btn1">Ajax asynchronous commit</button>
<script>
    $("#btn1").click(function () {
    let url = '${pageContext.request.contextPath}/ajaxRequest';
    let data = '[{" id ": 1," username ":" * * "}, {" id ": 2," username ":" bill "}]';
    $.ajax({
            type: 'POST'.url: url,
            data: data,
            contentType: 'application/json; charset=utf-8'.success: function (resp) {
                alert(JSON.stringify(resp))
            }
        })
    })
</script>
Copy the code
@RequestMapping(value = "/ajaxRequest")
public void ajaxRequest(@RequestBody List<User>list) {

    System.out.println(list);
}
Copy the code

@ResponseBody

This annotation is used to convert the object returned by the Controller method into data in the specified format, such as JSON, XML, etc., via the HttpMessageConverter interface, and send the Response to the client.

/* @RequestMapping produces = "application/json; Charset = UTF-8 "Mime type and encoding of the data returned in the response. Default is JSON */
@RequestMapping(value = "/ajaxRequest")
@ResponseBody
public List<User> ajaxRequest(@RequestBody List<User> list) {
    System.out.println(list);
    return list;
}
Copy the code

RESTful

What is a RESTful

Restful is a software architecture style, a design style, not a standard, but a set of design principles and constraints. Mainly used for client and server interaction class software, based on this style of design software can be more concise, more hierarchical, easier to implement caching mechanisms, etc.

A Restful request uses URL + request mode to indicate the purpose of a request. The following four VERBS indicate the operation mode in HTTP:

  • GET: Read
  • POST: Create
  • PUT: Update
  • DELETE: DELETE (DELETE)
Client request Original style URL address RESTful URL address
Query all /user/findAll GET /user
Query by ID /user/findById? id=1 GET /user/{1}
new /user/save POST /user
Modify the /user/update PUT /user
delete /user/delete? id=1 DELETE /user/{1}

Code implementation

@PathVariable

The value used to receive placeholders in RESTful request addresses

@RestController

RESTful style is used to separate the front end from the back end. The front end interacts asynchronously with the server through Ajax. Our processor usually returns JSON data, so we use @RestController instead of @Controller and @responseBody annotations.

// @Controller
@RestController
public class RestFulController {

    @GetMapping(value = "/user/{id}")
    @requestMapping (value = "/user/{id}",method = requestmethod.get)
    // @ResponseBody
    public String get(@PathVariable Integer id) {
        return "get:" + id;
    }

    @PostMapping(value = "/user")
    // @ResponseBody
    public String post(a) {
        return "post";
    }

    @PutMapping(value = "/user")
    // @ResponseBody
    public String put(a) {
        return "put";
    }

    @DeleteMapping(value = "/user/{id}")
    // @ResponseBody
    public String delete(@PathVariable Integer id) {
        return "delete:"+ id; }}Copy the code

File upload

There are three elements of file uploading

  • The form item type = “file”
  • Method =”POST”
  • The encType property of the form is the multi-part form encType = “multipart/form-data”

File Uploading Principles

  • Request.getparameter () becomes invalid when the form form changes to a multi-part form.
  • When the encType of the form form is Application/X-www-form-urlencoded,
    • The body content of the form is in the format of name= Value&Name =value
  • When the enctype value of the form form is mutilpart/form-data, the request body becomes multi-part:

Single file upload

  • Step analysis
Import Fileupload and IO coordinates. 2. Upload the configuration file to the parser. Write file upload codeCopy the code

1) Import fileupload and IO coordinates

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>
Copy the code

2) Configuration file upload parser

<! -- File upload resolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <! -- Set file upload Max to 5MB, 5*1024*1024 -->
    <property name="maxUploadSize" value="5242880"></property>
    <! If this parameter is smaller than this, temporary files will not be generated. Default is 10240 -->
    <property name="maxInMemorySize" value="40960"></property>
</bean>
Copy the code

3) Write file upload code

<form action="${pageContext.request.contextPath}/fileUpload" method="post" enctype="multipart/form-data">Name:<input type="text" name="username"> <br>File:<input type="file" name="filePic"> <br>
    <input type="submit" value="Single file upload">
</form>
Copy the code
@RequestMapping("/fileUpload")
public String fileUpload(String username, MultipartFile filePic) throws IOException {
    System.out.println(username);
    // Get the file name
    String originalFilename = filePic.getOriginalFilename();
    // Save the file
    filePic.transferTo(new File("d:/upload/"+originalFilename));
    return "success";
}
Copy the code

Multi-file upload

<form action="${pageContext.request.contextPath}/filesUpload" method="post" enctype="multipart/form-data">Name:<input type="text" name="username"> <br>Document 1:<input type="file" name="filePic"> <br>The file 2:<input type="file" name="filePic"> <br>
    <input type="submit" value="Multiple file upload">
</form>
Copy the code
@RequestMapping("/filesUpload")
public String filesUpload(String username, MultipartFile[] filePic) throws IOException {
    System.out.println(username);
    for (MultipartFile multipartFile : filePic) {
        // Get the file name
        String originalFilename = multipartFile.getOriginalFilename();
        // Save to the server
        multipartFile.transferTo(new File("d:/upload/" + originalFilename));
    }
    return "success";
}
Copy the code

Exception handling

Exception handling ideas

In Java, exceptions are handled in one of two ways:

  • One is try-catch, which creates a coupling between business code and exception-handling code.
  • The other method does not process by itself but throws to the caller for processing (throws). The caller then throws to its caller, that is, throws upward all the way. On the basis of this approach, the exception handling mechanism of SpringMVC is derived.

The DAO, Service, and Controller of the system are thrown upward through throws Exception, and finally the SpringMVC front-end controller delivers the Exception processor for Exception processing, as shown in the following figure:

Custom exception handlers

  • Step analysis
1. Create an exception handler class to implement HandlerExceptionResolver 2. Configure the exception handler 3. Write the exception page 4. Test the exception jumpCopy the code

1) Create an exception handler class to implement HandlerExceptionResolver

public class GlobalExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("error", ex.getMessage());
        modelAndView.setViewName("error");
        returnmodelAndView; }}Copy the code

2) Configure exception handlers

@Component
public class GlobalExecptionResovler implements HandlerExceptionResolver {}
Copy the code
<bean id="globalExecptionResovler"
      class="com.lagou.exception.GlobalExecptionResovler"></bean>
Copy the code

3) Write exception pages

<%@ page contentType="text/html; charset=UTF-8" language="java" %><html>
<head>
    <title>error</title>
</head>
<body>
<h3>This is the display page for the final exception</h3>
<p>${error}</p>
</body>
</html>
Copy the code

4) Test abnormal jump

@RequestMapping("/testException")
public String testException(a) {
    int i = 1 / 0;
    return "success";
}
Copy the code

Exception handling mechanism of the Web

<! -- Handle 500 exceptions -->
<error-page>
    <error-code>500</error-code>
    <location>/500.jsp</location>
</error-page>
<! -- Handling 404 exceptions -->
<error-page>
    <error-code>404</error-code>
    <location>/404.jsp</location>
</error-page>
Copy the code

The interceptor

The role of the interceptor

Spring MVC’s interceptor is similar to the Filter used in Servlet development for pre-processing and post-processing of the processor.

Interceptors are joined in a chain in a certain order, which is called an InterceptorChain. When accessing the intercepted method or field, interceptors in the interceptor chain are called in the order they were previously defined. Interceptors are also concrete implementations of AOP ideas.

Interceptors and filters

The difference between interceptor and filter is as follows:

Quick start

  • Step analysis
Create an interceptor class that implements the HandlerInterceptor interface. Configure interceptors. 3. Test the interception effect of interceptorsCopy the code

1) Create an interceptor class that implements the HandlerInterceptor interface

public class MyInterceptor1 implements HandlerInterceptor {

    // Intercept the target method before it executes
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        System.out.println("preHendle1");

        return true;
    }

    // Execute after the target method is executed and before the view object returns
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        System.out.println("postHandle1");
    }

    // Execute after all processes are completed
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        System.out.println("afterCompletion1"); }}Copy the code

2) Configure interceptors

<! -- Configure interceptor -->
<mvc:interceptors>
    <mvc:interceptor>
        <! -- Which resources are intercepted -->
        <mvc:mapping path="/ * *"/>
        <bean class="com.lagou.interceptor.MyInterceptor1"/>
    </mvc:interceptor>
</mvc:interceptors>
Copy the code

3) Test the interception effect of interceptors

Write Controller, send request to Controller, jump to page

@Controller
public class TargetController {

    @RequestMapping("/target")
    public String targetMethod(a) {
        System.out.println("Target method executes...");
        return "success"; }}Copy the code

Writing JSP pages

<%@ page contentType="text/html; charset=UTF-8" language="java" %><html>
<head>
    <title>success</title>
</head>
<body>
<h3>success...</h3><% system.out. println(" view executed....") ); % ></body>
</html>
Copy the code

The interceptor chain

Interceptors can be used individually in development, or multiple interceptors can be used simultaneously to form a chain of interceptors. The development steps are the same as for a single interceptor, except that multiple interceptors are registered. Note that the order of registration represents the order in which interceptors are executed.

MyHandlerInterceptor2 = MyHandlerInterceptor2

<! -- Configure interceptor -->
<mvc:interceptors>
    <mvc:interceptor>
        <! Interceptor path configuration -->
        <mvc:mapping path="/ * *"/>
        <! -- Custom interceptor class -->
        <bean class="com.lagou.interceptor.MyInterceptor1"></bean>
    </mvc:interceptor>
    <mvc:interceptor>
        <! Interceptor path configuration -->
        <mvc:mapping path="/ * *"/>
        <! -- Custom interceptor class -->
        <bean class="com.lagou.interceptor.MyInterceptor2"></bean>
    </mvc:interceptor>
</mvc:interceptors>
Copy the code

Knowledge summary

The methods in the interceptor are described as follows: