current position:Home>Spring MVC notes 02 domain object sharing data, view, restful, httpmessageconverter, file upload and download

Spring MVC notes 02 domain object sharing data, view, restful, httpmessageconverter, file upload and download

2022-04-29 06:36:20GYQ1

Domain objects share data

Use servletAPI( towards request Domain objects share data )

Use ModelAndView( towards request Domain objects share data )

test :

Use Model( towards request Domain objects share data )

Use Map( towards request Domain objects share data )

Use ModelMap( towards request Domain objects share data )

Model,Map,ModelMap The relationship between

The type of all three of the method parameters obtained by reflection is

class org.springframework.validation.support.BindingAwareModelMap

The inheritance relationship is as follows

This class can be used to create instantiated objects of the three


The source code parsing : After the controller method is executed, it will return the unified ModelAndView object

towards session Domain shared data

towards application Domain shared data

SpringMVC The view of

SpringMVC View in View Interface , The function of view is to render data , Put the model Model The data in is displayed to the user

SpringMVC There are many kinds of views , There is a forwarding view by default InternalResourceView And redirecting views RedirectView

When the project introduces jstl Dependence , The forwarding view is automatically converted to jstlView

If view technology is used, it is Thymeleaf, stay SpringMVC In the configuration file of Thymeleaf View parser , After the view parser parses it, the result is ThymeleafView

ThymeleafView

When the view name set in the controller method There is no prefix when , The view name will be SpringMVC The view parser configured in the configuration file parses , The view name is the final path obtained by splicing the view prefix and view suffix , Jump will be realized by forwarding .

Forwarding view

SpringMVC The default forwarding view in is InternalResourceView

SpringMVC Create a forwarding view in :

When the view name set in the controller method is marked with “ forward:” When prefixed , establish InternalResourceView View , At this time, the view name will not be SpringMVC The view parser configured by the configuration file parses , Instead, the prefix “forward:” Get rid of , The rest is used as the final path to jump through forwarding

Redirect view

SpringMVC The default redirection view in RedirectView

When the view name set in the controller method is marked with “redirect:” When prefixed , establish RedirectView View , At this time, the view name will not be SpringMVC The view parser configured by the configuration file parses , Instead, the prefix “redirect:” Get rid of , The rest is used as the final path to jump through redirection

View controller view-controller

springMVC.xml

Configured with view-controller after , All request mappings in the controller are invalid , Need to open MVC Annotation driven

view resolver InternalResourceViewResolver

RESTFul

brief introduction

It's a style of software architecture ( Format )

REST:Representational State Transfer, Presentation layer resource state transition

resources

It's a way of looking at servers , That is, the server is considered to be composed of many discrete resources . Each resource is a nameable abstraction on the server , So it can not only represent a file in the server file system , A table in the database and so on , We can design resources as abstract as possible . As long as imagination allows and client application developers can understand . Similar to object-oriented design , Resources are organized around terms , The first concern is the noun . A resource can be made up of one or more URI To mark .URI Is the name of the resource , It's also resources Web The address on the server , Client applications interested in a resource , The URI Interact with it .

Expression of resources

The description of a resource is a description of the state of a resource at a particular time . Can be on the client side - Transfer between servers ( In exchange for ). Resources can be expressed in a variety of formats , for example HTML/XML/JSON/ Pure text / picture / video / Audio and so on. . The presentation format of resources can be determined by negotiation mechanism , request - The response direction is usually expressed in different formats .

State shift

State transition is about : Transfer between client and server (transfer) Representation of resources , By transferring and manipulating the expression of resources , To achieve the purpose of operating resources indirectly .

RESTFul The implementation of the

specifically , Namely HTTP In the agreement , Four verbs for operation :GET、POST、PUT、DELETE.

They correspond to four basic operations :GET Used to obtain resources ,POST Used to create a new resource ,PUT Used to update resources ,DELETE Used to delete resources .

REST Style advocates the use of a unified style design , The words from front to back are separated by slashes , The request parameters are carried without question mark key value pairs , Instead, take the data to the server as URL Part of the address , To ensure the consistency of the overall style .

Use RESTFul Simulate the operation of user resources (get and post request )

@Controller
public class UserController {
    /**
     *  Use RESTFul Simulate the addition, deletion, modification and query of user resources 
     * /users  GET      Query all user information 
     * /user/1 GET      According to the user id Query all user information 
     * /user   POST     Add user information 
     * /user/1 DELETE   Delete user information 
     * /user   PUT      Update user information 
     */
    @RequestMapping(value = "/users", method = RequestMethod.GET)
    public String getAllUser() {
        System.out.println(" Query all user information ");
        return "success";
    }

    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
    public String getUserById() {
        System.out.println(" according to id Query user information ");
        return "success";
    }

    @RequestMapping(value = "/user", method = RequestMethod.POST)
    public String insertUser(String username, String password) {
        System.out.println(" Add users ,username:" + username + "password:" + password);
        return "success";
    }
}

test

HiddenHttpMethodFilter Handle PUT and DELETE Request mode

Coding filters and HiddenHttpMethodFilter The order of : The coding filter is in the first order .

View source code

simulation PUT and DELETE request

 

But the general deletion is hyperlink , Need to bind click event , Cancel default jump , And submit the form .

RESTFul Case study

And traditional CRUD equally , Realize the addition, deletion, modification and query of employee information

preparation

Employee Entity class

public class Employee {
    private Integer id;
    private String lastName;
    private String email;
    private Integer gender;

    public Employee() {
    }

    public Employee(Integer id, String lastName, String email, Integer gender) {
        this.id = id;
        this.lastName = lastName;
        this.email = email;
        this.gender = gender;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getGender() {
        return gender;
    }

    public void setGender(Integer gender) {
        this.gender = gender;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", lastName='" + lastName + '\'' +
                ", email='" + email + '\'' +
                ", gender=" + gender +
                '}';
    }
}

 EmployeeDao

@Repository
public class EmployeeDao {
    private static Map<Integer, Employee> employees = null;

    static {
        employees = new HashMap<Integer, Employee>();
        employees.put(1001, new Employee(1001, "HUI", "[email protected]", 1));
        employees.put(1002, new Employee(1002, "DSA", "[email protected]", 0));
        employees.put(1003, new Employee(1003, "SSD", "[email protected]", 0));
        employees.put(1004, new Employee(1004, "FSA", "[email protected]", 1));
        employees.put(1005, new Employee(1005, "GFS", "[email protected]", 0));
    }

    private static Integer initId = 1006;

    public void save(Employee employee) {
        if (employee.getId() == null) {
            employee.setId(initId++);
        }
        employees.put(employee.getId(), employee);
    }

    public Collection<Employee> getAll() {
        return employees.values();
    }

    public Employee get(Integer id) {
        return employees.get(id);
    }

    public void delete(Integer id) {
        employees.remove(id);
    }
}

Function realization

View all employee information  


Delete function

Be careful : Hyperlink path

New folder

Introduce... Into the page vue.js, And add a click event to the hyperlink

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" xmlns:th="http://www.thymeleaf.org">
    <title> Employee information </title>
</head>
<body>
<table id="dataTable" border="1" cellspacing="0" cellpadding="0" style="text-align: center;">
    <tr>
        <th colspan="5">Employee Info</th>
    </tr>
    <tr>
        <th>id</th>
        <th>lastName</th>
        <th>email</th>
        <th>gender</th>
        <th>options</th>
    </tr>
    <tr th:each="employee:${employeeList}">
        <td th:text="${employee.id}"></td>
        <td th:text="${employee.lastName}"></td>
        <td th:text="${employee.email}"></td>
        <td th:text="${employee.gender}"></td>
        <td>
            <a @click="deleteEmployee" th:href="@{/employee/}+${employee.id}">delete</a>
            <a href="">update</a>
        </td>
    </tr>
</table>

<form id="deleteForm" method="post">
    <input type="hidden" name="_method" value="delete">
</form>

<script type="text/javascript" th:src="@{/static/js/vue.min.js}"></script>

<script type="text/javascript">
    var vue = new Vue({
        el: "#dataTable",
        methods: {
            deleteEmployee: function (event) {
                var deleteForm = document.getElementById("deleteForm");
                // The of the hyperlink that will trigger the click event href Property is assigned to the of the form action
                deleteForm.action = event.target.href;
                // Submit Form 
                deleteForm.submit();
                // Cancel the default behavior of hyperlinks 
                event.preventDefault();
            }
        }
    });
</script>

</body>
</html>

test , Still wrong 405

This is because the result of the current project packaging does not static Catalog , Need to repack

But not at this time , Because access to static resources at this time , By DispatcherServlet To deal with the .

To configure springMVC.xml

​​​​​

After configuration , First of all springMVC Processing the request map , If not found, give the current request to the default Servlet Handle .


Add functions

employee_add.html

test

Add success !


Modify the function

employee_update.html 

The contents of the check box are automatically associated with value Value comparison , Check if it is consistent

complete

HttpMessageConverter

HttpMessageConverter, Message information converter , Convert the request message into Java object , Or will Java Object is converted into a response message ,HttpMessageConvert Two annotations and two types are provided :@RequestBody,@ResponseBody

RequestEntity,ResponseEntity

@RequestBody

You can get the request body , You need to set a formal parameter in the controller method , Use @RequestBody Are identified , The request body of the current request will assign a value to the formal parameter identified by the current annotation

RequestEntity

RequestEntity A type of encapsulation request message , You need to set this type of formal parameter in the formal parameter of the controller method , The request message of the current request will be assigned to this parameter , Can pass getHeaders() Get request header information , adopt getBody() Get request body information

  

Output results

requestHeader:[host:"localhost:8080", connection:"keep-alive", content-length:"57", cache-control:"max-age=0", sec-ch-ua:"" Not A;Brand";v="99", "Chromium";v="100", "Microsoft Edge";v="100"", sec-ch-ua-mobile:"?0", sec-ch-ua-platform:""Windows"", upgrade-insecure-requests:"1", origin:"http://localhost:8080", user-agent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36 Edg/100.0.1185.50", accept:"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9", sec-fetch-site:"same-origin", sec-fetch-mode:"navigate", sec-fetch-user:"?1", sec-fetch-dest:"document", referer:"http://localhost:8080/springMVC_demo4/", accept-encoding:"gzip, deflate, br", accept-language:"zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6", cookie:"Idea-6aaab5b3=171a0ae7-91ce-403b-9084-01fc843ac0d3", Content-Type:"application/x-www-form-urlencoded;charset=UTF-8"]
requestBody:username=%E5%A4%A7%E8%8B%8F%E6%89%93144&password=153435hj

@ResponseBody

Method used to identify a controller , The return value of this method can be directly used as the response body of the response message to respond to the browser

SpringMVC Handle json

First step : Import jackson rely on

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

  The second step : stay SpringMVC Open... In the core configuration file of mvc Annotation driven , At this time in HandlerAdaptor A message converter will be automatically assembled in :MappingJackson2HttpMessageConvert, You can respond to the browser's Java Object to Json Format string

 

The third step : Use... On processor methods @ResponseBody Note to identify

Step four : take Java Object is returned directly as the put back value of the controller method , Will automatically convert to Json Format string

 

SpringMVC Handle ajax

Import required resources  

<div id="app">
    <a @click="testAxios" th:href="@{/testAxios}">springMVC Handle ajax</a>
</div>
<script type="text/javascript" th:src="@{/static/js/axios.min.js}"></script>
<script type="text/javascript" th:src="@{/static/js/vue.min.js}"></script>
<script type="text/javascript">
    var vue = new Vue({
        el: "#app",
        methods: {
            testAxios: function (event) {
                axios({
                    method: "post",
                    url: event.target.href,
                    params: {
                        username: "admin",
                        password: "123456"
                    }
                }).then(function (response) {
                    alert(response.data);
                });
                event.preventDefault();
            }
        }
    });
</script>

@RestController annotation

@RestController The note is springMVC A composite annotation provided , Identify on the class of the controller , It is equivalent to adding @Controller annotation , And for each of these methods @ResponseBody annotation

ResponseEntity

The return value type used for the controller method , The return value of the method of the controller is the response message to the browser

File upload and download

File download

Use ResponseEntity Realize the function of downloading files

    @RequestMapping("/testDownLoad")
    public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException {
        // obtain ServletContext object 
        ServletContext context = session.getServletContext();
        // Gets the real path of the file in the server 
        String realPath = context.getRealPath("/static/img/vs2.jpg");
        // Create input stream 
        FileInputStream is = new FileInputStream(realPath);
        // Create an array of bytes 
        byte[] bytes = new byte[is.available()];
        // Read the stream into the byte array 
        is.read(bytes);
        // establish HttpHeader Object to set the response header information 
        MultiValueMap<String, String> headers = new HttpHeaders();
        // Set the method to download and the name of the file to download 
        headers.add("Content-Disposition", "attachment;filename=1.jpg");
        // Set response status code 
        HttpStatus statusCode = HttpStatus.OK;
        // establish ResponseEntity object 
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, statusCode);
        // Close input stream 
        is.close();
        return responseEntity;
    }

Upload files

Introduce dependencies

To configure SpringMVC File upload parser

    <!-- Profile upload parser , Encapsulate the uploaded file as MultipartFile-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>

Code

    @RequestMapping("/testUp")
    public String testUp(MultipartFile photo, HttpSession session) throws IOException {
        // Get the file name of the uploaded file 
        String filename = photo.getOriginalFilename();
        // Solve the problem of file name duplication 
        // Get the suffix of the uploaded file 
        String suffixName = filename.substring(filename.lastIndexOf("."));
        // take UUID As the file name 
        String uuid = UUID.randomUUID().toString();
        // take uuid The result after splicing with the suffix is used as the final file name 
        filename = uuid + suffixName;
        // adopt ServletContext Get server photo Path to directory 
        ServletContext context = session.getServletContext();
        String photoPath = context.getRealPath("photo");
        File file = new File(photoPath);
        // Judge photoPath Whether the corresponding path exists 
        if (!file.exists()) {
            file.mkdir();
        }
        String finalPath = photoPath + File.separator + filename;
        photo.transferTo(new File(finalPath));
        return "success";
    }

copyright notice
author[GYQ1],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/04/202204290636169777.html

Random recommended