Spring MVC (Next-1)

1.Restful request

restFul is a network API interface that conforms to the REST architectural style and fully recognizes that HTTP is used to identify resources. restFul URL is resource-oriented and can uniquely identify and locate resources. The operation performed on the resource identified by the URL is determined by the HTTP method. There are four rest request methods, including get, post, put, and delete. They correspond to obtaining resources, adding resources, updating resources, and deleting resources respectively.

RESTful style is a requirement for writing URLs

Many websites now use RESTful style URLs. In order to deal with this URL form, there are some annotations in SpringMVC to easily obtain the value in the URL.

A. Change the request parameters to key/value

For example, the request URL is like this. There are no request parameters in the captured request message, and the key/value value is in the URL.

In fact, this is how RESTful style is written. The request parameter does not use key=value, but key/value. Corresponding to this form, it is impossible to write a Handler method (control unit) for each request. Use the following method to wildcard multiple methods. URL

 //In the value attribute of the @RequestMapping annotation, you can use {} as a placeholder. The content of the placeholder is arbitrary.
        // Then pass the value of the @PathVariable annotation (fill in the placeholder variable),
        // The formal parameter can obtain the value of the corresponding placeholder
        @RequestMapping("RESTful/{name}/{id}")
        public User articleDetail(@PathVariable("name") String username,@PathVariable("id") Integer id) {
            return new User();
        }

Send the URL whether it is: http://localhost/RESTful/v/ 111, or http://localhost/RESTful/m /55555, you can see that the same Handler method (control unit) handles the request, and the formal parameters are part of the URL content

Usage in Java

To use this method in SpringMVC, you need the @PathVariable annotation (which can receive placeholder parameters in the path and bind it to the formal parameters of the control unit) combined with the @RequestMapping annotation, or the following annotation:

@GetMapping(“address”): Receives GET requests, generally used in query methods.

@DeleteMapping(“address”): Receives DELETE requests, generally used in delete methods.

@PostMapping(“address”): Receive POST request, general users can add it.

@PutMapping(“address”): Receives PUT requests, generally used for modification.

The corresponding annotation receives the corresponding request method:

@Controller
@RequestMapping("user")
public class UserController {
 
    @GetMapping("{id}")
    public String query(@PathVariable int id){
        System.out.println("restful->query-> " + id);
        return "success.jsp";
    }
 
    @DeleteMapping("{id}")
    public String del(@PathVariable int id){
        System.out.println("restful->delete-> " + id);
        return "success.jsp";
    }
 
    @PostMapping("{id}/{name}/{pwd}")
    public String add(@PathVariable int id, @PathVariable String name, @PathVariable int pwd){
        System.out.println("restful->add-> " + id + " " + name + " " + pwd);
        return "success.jsp";
    }
 
    @PutMapping("{id}/{name}/{pwd}")
    public String update(@PathVariable int id, @PathVariable String name, @PathVariable int pwd){
        System.out.println("restful->Modify-> " + id + " " + name + " " + pwd);
        return "success.jsp";
    }
}

2.@ResponseBody annotation

This annotation can be used on classes and methods. The classes and methods modified by this annotation indicate that the return value of the control unit method will no longer be parsed by the view parser | forwarding will not be used. Instead, the return value is put into the response stream to respond.

Notice:

1. Modified by this annotation The control unit can only return data of type String. If other types of data are returned without settings, a 406 status code will appear and the browser cannot receive it.
2. You can use @RequestMapping(produces = “text/plain;charset=utf-8”) to set the response content type and encoding format.
3. If the dependency of Jackson is introduced, the control unit can return JavaBean, array [JavaBean], List, Map, List, etc., SpringMVC will Automatically convert these types into json format strings, and automatically set the response content type to application/json;charset=utf-8.
4. Spring MVC supports converting return values into XML files. If you still use the jackson-databind dependency, by default you can only convert the return value to a control unit of class type. The return value is a List and cannot be converted to XML. At the same time, it is also required that the entity class must have @XmlRootElement before it can be converted.
5. If you want to automatically convert the return value into an XML file, you need to import the jackson-dataformat-xml dependency.

Because Spring MVC uses Jackson as the JSON conversion tool by default, you must ensure that there is a dependency on Jackson in the project.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.10.8</version>
</dependency>

3.@RequestBody annotation

@RequestBody is mainly used to receive the data in the json string passed by the client to the server (the data in the request body), and convert it into Map, class, List, List< Map> and other types.

Note:

  1. The @RequestBody annotation is used to receive data in the request body, so GET requests cannot be used.
  2. If the front end sends an ajax request, it needs to set the contentType attribute to application/json or application/xml.
  3. This annotation can be used together with the @RequestParam annotation. When used together, the @RequestParam annotation receives parameters in the form of key-value, while the @RequestBody annotation receives parameters in the request body.

4. File upload and download

File upload and download using SpringMVC requires the introduction of commons-fileupload dependency and commons-io dependency, because commons-fileupload already depends on commons-io dependency. So based on the transitivity of dependencies, you only need to add the commons-fileupload dependency.

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.4</version>
</dependency>

File upload:

Front-end requirements:

The request method is post request, and the request body is used to complete the file transfer.
enctype: multipart/form-data

Backend requirements:

Configuration file parser, MultipartResovler (interface), the commonly used implementation class is CommonsMultipartResovler
Introducing Commons-Fileupload dependency, CommonsMultipartResovler encapsulates Commons-Fileupload.
The request parameters passed by the client are parsed by the file parser, and ordinary form data and uploaded file objects are parsed out.
Ordinary form data -> Normal reception
File object -》MultipartFile
The method transferTo() in MultipartFile completes the upload

ajax upload:

FormData data = new FormData(form form dom object);
processData: false -》ajax does not serialize parameters in the form
contentType: false -》Do not specify type
enctype: multipart/form-data

File download:

Set the “Content-Disposition” of the response header, and the attribute value is “attachment;filename=filename”;
Use the copy (input stream object, output stream object) method in the IOUtils class, pass in the input stream object of the file, get the response output stream object, and pass it in.

Upload:

 @ResponseBody
    @RequestMapping("upload")
    public String upload(Integer id, String name, Integer age, MultipartFile photo, MultipartFile resume, HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println(id);
        System.out.println(name);
        System.out.println(age);
        System.out.println(photo);
        System.out.println(resume);
        //File upload server
        String originalFilename = photo.getOriginalFilename();
        System.out.println(originalFilename);
        String path = request.getServletContext().getRealPath("upload/image");
        File file = new File(path);
        if (!file.exists()){
            file.mkdirs();
        }
        photo.transferTo(new File(path,originalFilename));

        String originalFilename1 = resume.getOriginalFilename();
        System.out.println(originalFilename1);
        String path1 = request.getServletContext().getRealPath("upload/txt");
        File file1 = new File(path1);
        if (!file1.exists()){
            file1.mkdirs();
        }
        resume.transferTo(new File(path1,originalFilename1));
        //The file is saved in the location of the server and transferred to the database
        People people = new People(id, name, age, originalFilename, originalFilename1);
        int i = peopleService.insert(people);

        return "ok";
    }

download:

 @RequestMapping("download")
    @ResponseBody
    public String download(HttpServletRequest request,HttpServletResponse response,String filename) throws IOException {

        //Solve the problem of Chinese garbled file names
        String fileNewName = new String(filename.getBytes(), "iso8859-1");

        //Set the response header (the file is downloaded directly instead of opened)
        response.setHeader("Content-Disposition","attachment;filename=" + fileNewName);

        //Get the absolute path of the file
        String realPath = request.getServletContext().getRealPath("upload/image");

        //Specify this path as the file operation path
        File file = new File(realPath);

        //Go to the operation path to obtain the input stream, and read the file fileNewName in the path
        FileInputStream fis = new FileInputStream(file + "/" + fileNewName);

        //After reading, obtain the output stream through the response object
        ServletOutputStream outputStream = response.getOutputStream();

        //Just pass in the input stream and output stream through the functions encapsulated in the dependencies of file upload and download.
        IOUtils.copy(fis, outputStream);

        outputStream.close();
        fis.close();

        return "ok";
    }