SpringMVC program development

Table of contents

1. Know Spring MVC

Definition of MVC

The relationship between MVC and SpringMVC

2. Create a SpringMVC project

1. @RequestMapping implements connection

2. @POSTMapping annotation realizes connection

3.@GETMapping realizes the connection

3. Get parameters

1. Get a single parameter

2. Get multiple parameters

3. Get common objects

4. Get the json object

5. Special scenes

6. Get the parameters before the URL?

7. Get the uploaded file @RequestPart

8. Get Cookie/Session/header

4. Return data

1. Return to a static page

2. Return text/html data

3. Return JSON object

4. Jump

1.forward, request forwarding

2.redirect, request redirection

3. The difference between request redirection and request forwarding

5. Hot deployment


1. Know Spring MVC

Spring MVC is a powerful, efficient and reliable web framework

Spring MVC is a module of Spring Framework, also called Web MVC framework, which is a web application development framework based on Java Servlet and JavaServer Pages (JSP) technology.

Spring MVC is a lightweight, flexible, and extensible web framework with the following key advantages:

  1. Ease of use: Spring MVC uses a convention-over-configuration approach to quickly create Web applications for development and testing.
  2. Highly customizable: Spring MVC provides many customizable options, for example, different view technologies, back-end data sources and validators can be used to meet various application needs.
  3. Easy integration: Spring MVC can be seamlessly integrated with many other Spring modules, for example, Spring Security, Spring Boot, etc.
  4. Ease of testing: Spring MVC uses the Model-View-Controller (MVC) architecture, a design pattern that makes it easy to write automated tests.

Definition of MVC

MVC is the abbreviation of Model View Controller. It is a software architecture pattern (a design pattern) in software engineering. The concept: divide the software system into three parts: model, controller, and view

1. User sends an HTTP request, comes to the controller, conducts security verification, controls user input and other operations, and then sends it to Model

2.Model is a data model, usually responsible for accessing data in the database and returning the response information to the controller

3. The controller returns data to the view for rendering, and the result is presented to the User

The relationship between MVC and SpringMVC

Same as IoC and DI, MVC is an idea, SpringMVC is a specific implementation, and inherits the Web framework of Servlet API

The importance of SpringMVCd: most Java projects are based on Spring/SpringBoot, and SpringMVC is the core module of Spring, so the Java project is approximately equal to the SpringMVC project

2. Create a SpringMVC project

SpringMVC establishment and connection creation

Use SpringBoot to create a SpringMVC project

 

Click Maven framework support, import dependencies

 achieve connection

The route /hello here can be a multi-level route. The full route name must be written when accessing, otherwise it cannot be accessed

Startup project 

This completes the connection

Establish connection conditions:

1. @RestController annotation, register the class into the Spring container

2. @RequestMapping annotation, route mapping

1. @RequestMapping implements connection

Methods supported by @RequestMapping

1. Support GET request

We access through the URL, so it must support the GET method

You can also view it through the developer tools

 2. POST request

We simulate POST requests through Apifox, which is also possible

So @RequsetMapping also supports POST method

@RequsetMapping supports both GET requests and POST requests. Other methods also support

 The part about the request method in the source code:

When using annotations, you can also set the method. After adding method parameters, it will automatically add value to the routing information. When there is only one parameter by default, it is the default, and multiple parameters will be displayed one by one.

@RequestMapping(value = "/hello",method = RequestMethod.POST)

Set to access after POST, at this time, the GET method through the URL is not allowed 

Status code: 405, method not allowed!

2. @POSTMapping annotation realizes connection

Changing to GET is not supported, it is more concise 

The @POSTMapping annotation can specify multiple attributes

The last two attributes: consumes, produces

  • The consumes attribute allows specifying the MIME type to use when accepting the request body. For example, @PostMapping(value="/example", consumes="application/json") will only match POST requests whose Content-Type is application/json

  • The produces attribute allows specifying the MIME type returned by the method. For example, @PostMapping(value="/example", produces="application/json") will instruct the handler method to return application/json data

MIME (Multipurpose Internet Mail Extensions) is an Internet standard for representing various types of data. It is widely used in email and is also adopted by HTTP and other application protocols. A MIME type usually consists of two parts: a main type and a subtype, separated by a slash, eg "text/html" or "image/jpeg". Each MIME type is associated with a particular file format and specifies how to handle data in that format. Clients and servers can use MIME types to determine how to correctly interpret and display transmitted data. 

3.@GETMapping realizes the connection

POST method is not supported 

Summarize:

@RequsetMapping supports both GET requests and POST requests. Other methods also support

@POSTMapping supports POST requests

@GETMapping supports GET requests

3. Get parameters

After establishing a connection, learn how to get parameters

1. Get a single parameter

There is no parameter passed in the URL, and the default value is null

 After parameter passing

One is the wrapper class, and the other is the basic data type. The result of the access without passing parameters

in conclusion:

When an object has no value set, the value is null

Basic data type, if there is no value, an error will be reported.

Primitive data types in Java (such as int, double, etc.) cannot be null because they are primitive types rather than objects

        In Java, passing a possibly null value to a parameter of a primitive data type results in a compilation error. Because primitive data types cannot be null, a NullPointerException is thrown when trying to access a variable with a null value. To avoid this situation, the corresponding wrapper class can be used instead of the basic data type, because the instance of the wrapper class can be null. If you need to perform operations such as arithmetic operations, you can use the valueOf() method of the wrapper class to convert it to a basic data type

 Here is the same as the method of obtaining Servlet parameters, which proves that:
Servlet is a core component in Java Web development, which is responsible for receiving HTTP requests and returning HTTP responses. Spring MVC is a web framework built on the Servlet API, which provides a convenient way to process and respond to HTTP requests

Both objects can be used, here will be redirected directly to sougou

2. Get multiple parameters

Add parameters directly, and the order of the parameters is not important, and the KV in the URL can be passed successfully

 

The output result is correct, the order of passing parameters in the URL does not affect the output result, what affects the result is whether the KV corresponds

3. Get common objects

The framework implements automatic parameter mapping

in conclusion:

In Spring MVC, the return value type can be declared as a type, and Spring MVC will automatically match the appropriate data type return code Objectaccording to the Accept header information of the request and the annotation on the processing method .@RequestMapping

For example, if the request's Accept header information is application/json, and the processing method uses @ResponseBodyannotations, Spring MVC will automatically convert the return value to JSON format and set the return code to 200.

Similarly, if the request's Accept header information is application/xml, and the processing method uses @ResponseBodyannotations, Spring MVC will automatically convert the return value to XML format and set the return code to 200.

If the return value type cannot be automatically converted to JSON or XML format, Spring MVC will try to convert it in other ways or return an error code directly. Therefore, when using it Objectas a return value type, it is necessary to ensure that the return value can be correctly converted into a supported format to avoid the problem that the return value cannot be serialized.

4. Get the json object

The front end passes parameters using apifox simulation

return result:

As you can see, the json object cannot be obtained

To get the json object, you must add annotation @RequestBody

In Spring MVC, you can use the @RequestBody annotation to get request parameters in JSON format. When we add the @RequestBody annotation to the input parameter of the Controller method, Spring MVC will automatically convert the JSON string in the request body into the corresponding Java object and bind it to the input parameter

The @RequestBody annotation acts on the input parameter of the PoeopleComponent type, indicating that the current request parameter is a JSON object and converts it into a PoeopleComponent object. In this way, we can easily obtain the request parameters in JSON format. It should be noted that when the front end sends a request, the Content-Type of the request header needs to be set to application/json, and the format has been set to json when using the spifox mode

Send json object data again

Get parameters successfully

5. Special scenes

When the front-end passes a parameter with a different name from the back-end, you can use the renaming method to receive the front-end parameter

Parameters can still be received after renaming

Note: At this time, the parameter cannot be empty, and the parameter must be passed. See the source code:

The default is true.. It is required to pass parameters!

To work around missing parameter values ​​for the @RequestParam annotation, you can use one of the following methods:

  1. Provide the necessary request parameters. Provide the value of the required parameter in the request, ensuring that it matches the method parameter annotated with @RequestParam

  2. Use the defaultValue attribute. Specify the default value by setting a value for the defaultValue attribute of the @RequestParam annotation. If the parameter is not passed in the request, the default value will be used

  3. Set the required attribute of the @RequestParam annotation to false. This attribute is used to indicate whether a request parameter is required. Setting it to false makes the parameter optional and allows requests not to provide it without throwing an error. When the request does not provide this parameter, the method parameter will be given a null value

6. Get the parameters before the URL?

Get the parameters from the base URL.. Note, not get the parameters from the URL parameters part

It is necessary to add the annotation @PathVariable before the parameter, otherwise the front-end URL parameter cannot be obtained

Also note: When the basic part of the URL is different from the name of the formal parameter, it is necessary to set the parameter so that no error will be reported. The parameter will still not be obtained

It can be solved by setting parameters in the annotation

Summarize:

@PathVariable Get the parameters before URL? (less applicable parameters, more concise)

@RequestParam gets the parameters after URL? (multiple parameters, flexible)

  /user/12345Both of /user?id=12345these two parameter passing methods can achieve the effect of passing parameters to the URL, but their implementation methods are different.

        Among them, /user/12345is an implementation of RESTful API, which represents the address of the user resource on the server side, and 12345represents unique identifier of the user resource. This method is usually used to request a specific resource, and the relevant information of the user can be obtained directly according to the requested URL.

/user?id=12345The         parameter is passed to the URL through the query string, where idindicates the parameter name and 12345the corresponding parameter value. This method is more flexible, you can pass multiple parameters, you can also pass only part of the parameters, for example /user?id=12345&name=John&age=25.

Generally speaking, the way /user/12345of is more intuitive and concise, with clear semantics, and more in line with the specification of RESTful API design. /user?id=12345The way to use is more flexible, you can pass multiple parameters, and it is easy to get parameter values. Choose different ways to pass parameters according to specific needs and scenarios.

7. Get the uploaded file @RequestPart

The path of the uploaded file needs to be specified according to the actual situation. The specific format can be in the following two ways:

  1. Absolute path: refers to the complete path starting from the root directory of the disk. For example: /var/www/html/uploads/image.jpg

  2. Relative path: refers to the relative path relative to the directory where the current file is located. For example: ../../uploads/image.jpg

Start, the front end simulates data

Error message: The image size exceeds the maximum upload limit 

 Re-upload the smaller picture, the upload is successful

 

 Another solution:

The maximum default size of a single uploaded file in SpringMVC is 1MB. However, we can adjust the maximum upload file size by making modifications in the Spring MVC configuration file. The specific modification method is as follows:

1. Open the application.yml configuration file.

2. Add the following configuration:

spring:
  servlet:
    multipart:
      max-file-size: 50MB
      max-request-size: 100MB

We upload this file to demo6

It should be noted that if the path is not modified, the last uploaded image will be overwritten

To fix coverage issues:

There are also many types of uploaded image files, and the file extension needs to be obtained

Then use the UUID plus the suffix name to solve the coverage problem

        UUID (Universally Unique Identifier) ​​is the abbreviation of Universal Unique Identifier, also known as GUID (Global Unique Identifier). It is a standardized format for representing a 128-bit value that can be used to uniquely identify an entity or object .

        The generation algorithm of UUID is calculated according to some specific standards or random numbers, which ensures the global uniqueness of the generated UUID. The specific generation method includes timestamp, hardware address, random number, etc. Moreover, UUID is immutable, once generated, it cannot be changed.

Upload pictures after startup, the original pictures will not be overwritten

Uploaded three identical files, none of them will be overwritten

code:

@RequestMapping("/getFile")
    public Object getFile(@RequestPart("myimg")MultipartFile file) throws IOException {
        String fileName = UUID.randomUUID() +//文件名
                file.getOriginalFilename().//文件后缀
                        substring(file.getOriginalFilename().lastIndexOf("."));
        File file1 = new File("D:\\projets\\demo6\\"+fileName);
        try{
            file.transferTo(file1);
            return true;
        }
        catch (IOException e){
            e.printStackTrace();
        }
        return false;
    }

8. Get Cookie/Session/header

Get Request and Response objects

 Annotate Get Cookie-@CookieValue

After setting non-required

no error

Forge a cookie at this time

 

 visit again

Get header - @RequestHeader

 result

 9. Store session and get session

Storage cannot be implemented with annotations, or in the way of acquisition in servlets

Get-@SessionAttribute

 

4. Return data

1. Return to a static page

 

return "index.html" without adding /, is looking for the index.html page in the test directory, which is not accessible. Because the index.html page is placed in the root directory, adding / will be in the root path Look for the index.html page to get it

2. Return text/html data

Methods can be annotated with @ResponseBody

3. Return JSON object

4. Jump

request forwarding or request redirection

return can not only return a view, but also realize jump. There are two ways to jump:

1.forward, request forwarding

Request forwarding can also be performed using the request object

2.redirect, request redirection

You can also redirect using the response object

3. The difference between request redirection and request forwarding

Request redirection (Redirect) and request forwarding (Forward) are two commonly used jump methods in Web applications.

        Request redirection means that after the server receives the request, it returns a response instructing the client to resend the request to another URL address. After the client receives this response, it will resend a new request to the new URL to complete the jump. Request redirection is to re-initiate a GET request after this request is completed, so its disadvantage is that it will consume more server resources, but its advantage is that it can avoid problems such as repeated form submissions, and can also avoid problems such as repeated form submissions .

advantage: 

Avoid problems such as repeated form submissions.

Avoid problems such as repeated form submissions.

shortcoming:

consume more server resources

        Request forwarding means that when the client initiates a request to the server, the server does not directly respond to the client request, but forwards the request to another resource for processing, and returns the response result to the client. Request forwarding is done inside the server, and the client cannot perceive the process because there is only one request and one response. Request forwarding does not need to re-initiate a new request, which is faster than request redirection, but its disadvantage is that it can only be redirected within the same web application, and cannot achieve cross-domain redirection.

advantage:

faster.

Request forwarding does not require re-initiating a new request.

shortcoming:

Unable to achieve cross-domain jump

5. Hot deployment

Finally, let me introduce the hot deployment function provided by IDEA

Java's hot deployment (Hot Deployment) refers to the ability to update the code or resources of the application during the running of the application without restarting the application or redeploying the application. It can also be understood as dynamically loading new code or resources into the application without stopping the application. It facilitates the work we develop

step:

1. Add support for hot deployment framework

2.Settings to open the project automatic compilation

It needs to be configured twice, once for this project and once for a new project.

3.Advanced Settings

4. Use Debug to start

After the code changes, it will automatically restart 

Guess you like

Origin blog.csdn.net/chenchenchencl/article/details/130603583