day2021-10-12(mvc common knowledge points)

Keywords: Java Spring mvc

2. mvc common knowledge points

2.1 @RequestMapping

  • Basic use
@RequestMapping("/user")						//value omission
@RequestMapping(value = "/user")				//Omission of values
@RequestMapping(value = {"/user"})				//The type String [] of value needs to be {} expanded
  • Request mode setting:

    • Review the common request methods of forms: get and post

      • get --> /userServlet?username=jack&password=1234
      • Post -- > form submission < form method = "post" >
    • Set the request method through the method property

      //Modified methods can be accessed through post and get requests.
      @RequestMapping(value="/selectAll",method = {RequestMethod.GET, RequestMethod.POST} )
      
      //The modified method can only be accessed through get request.
      @RequestMapping(value="/selectAll",method = RequestMethod.GET)
      
      //The modified method can only be accessed by post request.
      @RequestMapping(value="/selectAll",method = RequestMethod.POST )
      
      // If the method is not set, all requests can be accessed by default.
      

2.2 method return value

2.2.1 default return value ModelAndView

package com.czxy.mvcanno.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Uncle Tong
 * @email liangtong@itcast.cn
 */
@Controller
@RequestMapping("/book")
public class BookController {

    @RequestMapping("/list")
    public ModelAndView list() {

        //1 create object
        ModelAndView modelAndView = new ModelAndView();
        //2 set view
        modelAndView.setViewName("book");       //Previously return "book";
        //3. Set model data key value
        modelAndView.addObject("username","jack");

        return modelAndView;
    }
}

2.2.2 setting Model + String

    @RequestMapping("/list2")
    public String list2(Model model) {
        // Just set the data
        model.addAttribute("username","rose");

        return "book";
    }

2.2.3 return value void

  • Scenario 1: if there is no response to the browser, the jsp corresponding to the default view name will be adapted. Generally, this page does not exist and a 404 exception will be thrown.

    • Default view name: access path

      [the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-jeoorxqz-1634085790385) (assets / image-20211012155024686. PNG)]

          @RequestMapping("/void1")
          public void void1() {
              System.out.println("void1 Yes ");
          }
      
  • Scenario 2: operation through request scheduler (request forwarding / request inclusion)

        @RequestMapping("/void2")
        public void void2(HttpServletRequest request , HttpServletResponse response) throws Exception {
    
            request.setAttribute("username","void2");
            // Request forwarding
            request.getRequestDispatcher("/WEB-INF/pages/book.jsp").forward(request, response);
    
            // Request contains
    //        request.getRequestDispatcher("/WEB-INF/pages/book.jsp").include(request, response);
        }
    
  • Scenario 3: response data to the browser in a streaming manner through response.

        @RequestMapping("/void3")
        public void void3(HttpServletRequest request , HttpServletResponse response) throws Exception {
            response.getWriter().print("void3");
        }
    
  • Scenario 4: respond with JSON data, and the annotation @ ResponseBody must be added

        @RequestMapping("/void4")
        @ResponseBody
        public void void4() throws Exception {
            System.out.println("ha-ha");
        }
    

2.2.4 return string

  • There are two return value strings: request forwarding (default) and redirection

    [the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-es3CKD9D-1634085790389)(assets/image-20211012161947842.png)]

  • Default: request forwarding

    public String list() {
        return "View name";
    }
    
  • Request forwarding

    public String list() {
        return "forward:View name";
    }
    
  • redirect

    public String list() {
        return "redirect:route";
    }
    

2.3 exception handling

2.3.1 objectives

  • Use the global exception handler to uniformly maintain exception information.

2.3.2 steps

  • Step 1: write a custom exception
  • Step 2: write Controller, a parameter, and control logic code (normal, system exception, custom exception)
  • Step 3: write an exception handling class
  • Step 4: exception information display page

2.3.3 realization

  • Step 1: write a custom exception

    • Runtime exception: RuntimeException [recommended], and reconstruct the method.

      package com.czxy.mvcanno.exception;
      
      /**
       * @author Uncle Tong
       * @email liangtong@itcast.cn
       */
      public class CustomExcption extends RuntimeException {
          public CustomExcption() {
          }
      
          public CustomExcption(String message) {
              super(message);
          }
      
          public CustomExcption(String message, Throwable cause) {
              super(message, cause);
          }
      
          public CustomExcption(Throwable cause) {
              super(cause);
          }
      
          public CustomExcption(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
              super(message, cause, enableSuppression, writableStackTrace);
          }
      }
      
      
    • Compile time Exception: Exception

  • Step 2: write Controller, a parameter, and control logic code (normal, system exception, custom exception)

    package com.czxy.mvcanno.controller;
    
    import com.czxy.mvcanno.exception.CustomExcption;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    /**
     * @author Uncle Tong
     * @email liangtong@itcast.cn
     */
    @Controller
    @RequestMapping("/item")
    public class ItemController {
    
        @RequestMapping("/list")
        public String list(Integer id ) {
            if(id == 1) {
                // System exception
                int i = 1 / 0;
            } else if( id == 2 ) {
                // custom
                throw new CustomExcption("Custom exception information");
            }
            //normal
            return "list";
        }
    }
    
    
    <a href="${pageContext.request.contextPath}/item/list.action?id=1">exception handling id =1 System exception</a> <br/>
    <a href="${pageContext.request.contextPath}/item/list.action?id=2">exception handling id =2 Custom exception </a> <br/>
    <a href="${pageContext.request.contextPath}/item/list.action?id=3">Exception handling is normal</a> <br/>
    
  • Step 3: write an exception handling class

    • Note: check the configuration class and whether to scan the exception handling class

      [the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-7d9eoKhs-1634085790391)(assets/image-20211012171154927.png)]

    package com.czxy.mvcanno.resolver;
    
    import com.czxy.mvcanno.exception.CustomExcption;
    import org.springframework.stereotype.Component;
    import org.springframework.web.servlet.HandlerExceptionResolver;
    import org.springframework.web.servlet.ModelAndView;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    /**
     * @author Uncle Tong
     * @email liangtong@itcast.cn
     */
    @Component
    public class CustomExceptionResolver  implements HandlerExceptionResolver {
        @Override
        public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
            // 1. Unified exception
            CustomExcption customExcption = null;
            if(e instanceof CustomExcption) {
                customExcption = (CustomExcption) e;
            } else {
                customExcption = new CustomExcption("The system is busy, please try again later!");
            }
    
            // 2 error message return
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.addObject("message" ,customExcption.getMessage());
            modelAndView.setViewName("error");
    
            return modelAndView;
        }
    }
    
    
  • Step 4: exception information display page

    <%--
      Created by IntelliJ IDEA.
      User: Administrator
      Date: 2021-10-12
      Time: 17:09
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Friendly page</title>
    </head>
    <body>
        ${message}
    </body>
    </html>
    
    
  • effect

    [the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-gMhXjvLJ-1634085790392)(assets/image-20211012171233103.png)]

2.3.4 summary

  • In actual development, users cannot see 404 / 500 and other abnormal information. An optimization page is required.
  • Unified exception handling is a display form of friendly pages.
  • Note: when configuring classes, do you want to scan various classes?

2.4 file upload

2.4.1 single file upload

  • Step 1: build the environment and copy the jar package

    [the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (IMG eskmbk3p-1634085790393) (assets / image-20211012180803305. PNG)]

  • Step 2: build the environment and write the configuration class

    [the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-Q7pfweA4-1634085790394)(assets/image-20211012180837144.png)]

        @Bean
        public CommonsMultipartResolver multipartResolver(){
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
            // Set the total size of all uploaded files to 10M
            multipartResolver.setMaxInMemorySize(10*1024*1024);
            // Set the upload size of a single file to 4M
            multipartResolver.setMaxUploadSize(4*1024*1024);
            multipartResolver.setDefaultEncoding("utf-8");
            return multipartResolver;
        }
    
  • Step 3: write a form

        <form action="${pageContext.request.contextPath}/file/upload.action" method="post" enctype="multipart/form-data">
          Select file: <input type="file" name="image" /> <br/>
          <input type="submit" value="upload"/> <br/>
        </form>
    
  • Step 4: write a processing class

    package com.czxy.mvcanno.controller;
    
    import org.apache.commons.io.FileUtils;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.multipart.MultipartFile;
    
    import java.io.File;
    import java.io.IOException;
    
    /**
     * @author Uncle Tong
     * @email liangtong@itcast.cn
     */
    @Controller
    @RequestMapping("/file")
    public class FileController {
    
        @RequestMapping("/upload")
        public String upload(MultipartFile image) throws Exception {
            System.out.println("Upload file name:" + image.getOriginalFilename());
            System.out.println("Upload file stream:" + image.getInputStream());
    
            File file = new File("D:\\xml", image.getOriginalFilename());
            FileUtils.copyInputStreamToFile(image.getInputStream(), file );
            return "book";
        }
    }
    
    

Summary:
1. The content of today's study is rather empty and not well understood in the project. However, exception notification and file upload and storage are more useful and can be directly linked to the project.
Good, another day from work!!!!

Posted by nishith82 on Tue, 12 Oct 2021 17:57:27 -0700