Deep Exploration of Spring MVC: Building Elegant Web Applications


foreword

Spring MVC is one of the most popular web frameworks in Java. It provides developers with powerful tools and a flexible architecture to help build efficient, scalable, and easy-to-maintain web applications. This article will delve into the core concepts, usage methods and practical operations of Spring MVC.

1. What is Spring MVC

1.1 What is MVC

Before understanding what Spring MVC is, we first need to understand what MVC is.

MVC is the abbreviation of "Mode View Controller", which is a software design pattern used to divide the application into three core components, namely: Model (model), View (view) and Controller (controller) . Each component has its own unique responsibility, and they work together to achieve a layered design and low coupling of the application.

  • Model : Responsible for managing the data and business logic of the application. It is independent of the view and the controller, by providing a data interface for the view to display data, and it can also accept instructions from the controller to update the data state.

  • View (view) : Responsible for displaying data to the user and passing user input to the controller. It is usually the presentation of the user interface, such as HTML pages, user interface controls, and so on.

  • Controller (controller) : acts as an intermediary between the model and the view, handles the user's request and responds. It accepts user input, updates the model state based on the input, and selects the appropriate view to display the updated data.

MVC 模式的优点在于它能够是代码分离,使得应用程序更易于维护和实现. For example, when you need to change the appearance of your application, you only need to change the view layer without affecting the model and controller logic. This decoupling design enables team members to develop different components in parallel, thereby improving development efficiency.

1.2 What is Spring MVC

Spring MVC is a web framework in the Spring framework for building Java-based web applications . It is a lightweight, flexible and powerful framework that uses the MVC (Model-View-Controller) design pattern to divide the application into three main components: Model (Model), View (View) and Controller (Controller). ) .

Specifically, Spring MVC is defined as follows:

  1. Web framework : Spring MVC focuses on processing requests and responses of Web applications, providing core functions for processing HTTP requests and building Web pages.

  2. Based on Servlet API : Spring MVC is built on top of Java Servlet API and uses Servlet container to handle HTTP requests and responses, so it can be seamlessly integrated with common Java Web containers.

  3. MVC design pattern : Spring MVC adopts the MVC design pattern, which divides the application into three main components, so that the responsibilities of each component are clearly separated, thereby improving the maintainability and testability of the code.

  4. Lightweight and flexible : Spring MVC is a lightweight framework that does not require complex configuration and dependencies, and has high flexibility, allowing developers to customize the process of processing requests according to specific needs.

  5. Integration with Spring : Spring MVC is part of the Spring framework, so it can be seamlessly integrated with other Spring components (such as Spring Core, Spring Boot, etc.) to enjoy the rich features and convenience of the Spring ecosystem.

Spring MVC maps URL requests to corresponding controller methods through handler mapping (Handler Mapping). The controller method processes the request and updates the model state, and then selects the appropriate view to display the data to the user. It also provides a view resolver (View Resolver), which is used to map the logical view returned by the controller to a specific view technology (such as JSP, Thymeleaf, etc.).

Overall, Spring MVC is one of the most popular frameworks in Java Web development. It provides rich functions and features, enabling developers to quickly build efficient and maintainable Web applications.

2. Creation of Spring MVC project

2.1 Project creation

Spring WebThe creation of the Spring MVC project is the same as the creation of the Spring Boot project, because when creating the Spring Boot project before, a dependency called is always introduced . Therefore, when this dependency is introduced when creating a Spring Boot project, our project becomes a Spring MVC project.

2.2 The first Spring MVC program - Hello World

demoCreate a control layer class in the directory , TestControllerand when accessed through a browser, "Hello World" will be output on the page:

@RestController
public class TestController {
    
    
    @RequestMapping("/hello")
    public String hello(){
    
    
        return "Hello World";
    }
}

Run the startup class and access it through a browser http://localhost:8080/helloto get the following results:

3. @RequestMapping annotation

In Spring MVC, @RequestMappingit is a very important annotation for mapping HTTP requests to controller processing methods. Through @RequestMappingannotations, we can define URL paths, HTTP request methods, and request parameters equal to the mapping relationship of controller methods.

3.1 Common properties

By viewing @RequestMappingthe source code of the annotation, you can see that there are many attributes in it:

The following are @RequestMappingcommon attributes of annotations and their descriptions:

attribute name illustrate
name Set the name of the handler method for reference in other components.
value Specifies the URL path, which can be a string or an array of strings.
path Equivalent to valueattribute, used to specify the URL path, which can be a string or an array of strings.
method Specifies the HTTP request method, which can be a RequestMethod enumeration value or a RequestMethod array.
params Specifies the condition of the request parameter, which can be a string or an array of strings.
headers Specifies the condition of the HTTP request header, which can be a string or an array of strings.
consumes Specifies the Content-Type media type of the request, which can be a string or an array of strings.
produces Specifies the Content-Type media type of the response, which can be a string or an array of strings.

@RequestMappingThe annotation is a meta-annotation, itself used by other annotations such as @GetMapping, @PostMapping, @PutMappingand . @DeleteMappingBy setting different attributes, you can flexibly define conditions such as URL mapping of controller methods, HTTP request methods, request parameters, and request headers, so as to achieve diversified request processing.

3.2 Method-level and class-level annotations

@RequestMappingAnnotations can be used both at the method level and at the class level.

Method level:

At the method level, the @RequestMapping annotation is used to specify a specific request mapping path. For example:

@Controller
public class UserController {
    
    
    // 方法级别路径为"/profile"
    // 最终请求路径为"/profile"
    @RequestMapping("/profile")
    public String userProfile() {
    
    
        // 处理方法逻辑
        return "profile";
    }
}

class level:

At the class level, @RequestMappingannotations are used to specify a common parent path for all handler methods in that class. For example:

@Controller
@RequestMapping("/users")
public class UserController {
    
    
    // 类中所有方法的父路径为"/users"
    // 具体路径为"/users/profile"
    @RequestMapping("/profile")
    public String userProfile() {
    
    
        // 处理方法逻辑
        return "profile";
    }
}

3.3 @GetMapping、@PostMapping、@PutMapping、@DeleteMapping

Going back to the first "Hello World" program, we can access it through a browser http://localhost:8080/hello, and then output "Hello World" on the page.

So what method is this HTTP request using?


It can be found through the browser packet capture that the GET request is used, so are other requests supported?

Send a POST request through Postman, and find that the returned content can also be obtained:

In addition, send PUT and DELETE method requests and find that the results can be obtained, that is to say, by default, @RequestMappingall methods are supported using annotations. Of course, if you want to support only a certain method, you can methodspecify it through its attribute, such as specifying the GET method:


Then, send a POST request through Postman again at this time:


It is found that the status code returned at this time is 405, that is, the POST request method is not supported.

To simplify @RequestMappingthe use of annotations, Spring MVC provides more specific abbreviated annotations: @GetMapping, @PostMapping, @PutMappingand @DeleteMapping. These annotations correspond to HTTP's GET, POST, PUT and DELETE request methods, which can make the code more concise and intuitive.

For example, the above code could be @GetMappingreplaced with:

@RestController
public class TestController {
    
    
    @GetMapping("/hello")
    public String hello(){
    
    
        return "Hello World";
    }
}

4. Spring MVC gets parameters

In web development, when processing a request submitted by a user, it is often necessary to obtain parameters from the request for subsequent processing. Spring MVC provides a variety of ways to obtain parameters, including obtaining simple parameters, obtaining objects, setting parameter renaming, and setting whether parameters must be passed, etc.

4.1 Get simple parameters

4.1.1 Get by URL query string

In an HTTP request, the query string is the part of the parameter in the URL that follows the question mark, for example: http://example.com?name=zhangsan&age=25. @RequestParamWe can use annotations to get the parameter values ​​in the query string by adding parameters in the controller method .

@RestController
public class TestController {
    
    
    @GetMapping("/get")
    public String  getParam(@RequestParam String name, @RequestParam Integer age){
    
    
        return "name = " + name + ", age = " + age;
    }
}


In the case of 查询字符串中的参数名和getParam1 , the annotation can be omitted, and Spring MVC will automatically bind the corresponding parameter value in the request to the method parameter. For example:中的参数名称一样@RequestParam

@RestController
public class TestController {
    
    
    @GetMapping("/get")
    public String  getParam(@RequestParam String name, @RequestParam Integer age){
    
    
        return "name = " + name + ", age = " + age;
    }
}

4.1.2 Get through the form form

When the form is submitted, @RequestParamthe parameter values ​​in the form can also be obtained through annotations. At this time, the method of obtaining the parameters in the query string is basically the same as above, except that the HTTP method becomes POST:

Form page:

<form action="/submit" method="post">
    <input type="text" name="name">
    <input type="number" name="age">
    <input type="submit" value="提交">
</form>

How to get it:

@RestController
public class TestController {
    
    
    @PostMapping("/submit")
    public String submitForm(@RequestParam String name, @RequestParam Integer age){
    
    
        return "name = " + name + ", age = " + age;
    }
}

Send form form data through Postman:

4.2 Get Objects

Create an entity class User:

4.2.1 Get through multiple parameters

At this point, parameters can be passed through the query string in the URL, or submitted through namethe form . As long as the passed parameter name matches the parameter name in the class, Spring MVC will automatically bind the parameters in the request to the object middle.ageformUserUser

@RestController
public class TestController {
    
    
    @RequestMapping("/user")
    public String getUser(User user){
    
    
        return user.toString();
    }
}

Access via browser http://localhost:8080/user?name=zhangsan&age1=25:

Of course, if the parameter names do not match, the corresponding parameters will not be obtained:

4.2.2 Receive JSON object through @RequestBody

When the client submits data in JSON format, @RequestBodyannotations can be used to bind the JSON data in the request body to Java objects.

@RestController
public class TestController {
    
    
    @RequestMapping("/user")
    public String getJsonUser(@RequestBody User user){
    
    
        return user.toString();
    }
}

Submit the content in the following JSON format via Postman:

{
    
    
    "name": "zhangsan",
    "age": 25
}

result:

4.3 Set parameter renaming through @RequestParam

When the front-end and back-end parameters do not match, if you do not deal with it, you cannot get the desired parameters correctly. At this time, you can @RequestParamset the renaming of the parameters through annotations.

You can view the source code of in the Java code @RequestParam:

the valueor namein it can be used to perform parameter renaming operations. For example, the query string in the front-end request URL is at this time username=zhangsan&age=25, and the back-end is used to receive nameand age:

@RestController
public class TestController {
    
    
    @GetMapping("/get")
    public String  getParam(@RequestParam(value = "username") String name, @RequestParam Integer age){
    
    
        return "name = " + name + ", age = " + age;
    }
}

Send request via browser:

4.4 Through @RequestParam, set the mandatory and optional parameters

For example, use the following code to get the request parameters in the URL:

@RestController
public class TestController {
    
    
    @GetMapping("/get")
    public String  getParam(@RequestParam String name, @RequestParam Integer age){
    
    
        return "name = " + name + ", age = " + age;
    }
}

At this point, if one less ageparameter is passed:

Then the received response status code is 400, that is, the request error. In the above @RequestParamcomments, we can find that there is a parameter called required, and its default value truemeans that the parameter is mandatory, and if the missing parameter will be saved, then at this time, we can set agethe parameter as optional, as follows Face code:

@RestController
public class TestController {
    
    
    @GetMapping("/get")
    public String  getParam(@RequestParam String name, @RequestParam(required = false) Integer age){
    
    
        return "name = " + name + ", age = " + age;
    }
}

At this time, when you visit through a browser, you will find that no error will be reported:

4.5 Get the parameters in the URL path through @PathVariable

In Spring MVC, URL paths usually contain some placeholders that can be used to pass parameters. Through @PathVariableannotations, the parameter values ​​in these URL paths can be bound to the parameters of the method, so that these parameters can be used for processing in the controller method.

For example, suppose we have a URL path of /root/{name}/{age}, where {name}and {age}are placeholders. We can @PathVariablebind the value corresponding to this placeholder to the parameter of the method through the annotation, as follows:

@RestController
public class TestController {
    
    
    @RequestMapping("/root/{name}/{age}")
    public String getParam(@PathVariable String name, @PathVariable String age){
    
    
        return "name = " + name + ", age = " + age;
    }
}

Access through the browser, you can get the parameters in the URL:


In addition, it should be noted that @PathVariablethe parameter name of the annotation needs to be consistent with the placeholder name in the URL path. If the names are inconsistent, you can use @PathVariable("placeholderName")the name of the specified placeholder.

For example, suppose the URL path is /root/{username}/{age}, but you want to use it in the method nameto represent this parameter, you can do this:

@RestController
public class TestController {
    
    
    @RequestMapping("/root/{name}/{age}")
    public String getParam(@PathVariable(name = "username") String name, @PathVariable String age){
    
    
        return "name = " + name + ", age = " + age;
    }
}

5. @RequestPart implements file upload

@RequestPartAnnotations are used to implement file uploads. It is a way of handling file uploads in Spring MVC.

Usually, during the file upload process, the client submits the file data multipart/form-datato the server in the form of . In Spring MVC, you can use @RequestPartannotations multipart/form-datato bind the file part in to the parameters of the controller method, so as to realize the file upload.

For example, now to implement a picture upload function, it is required to save the uploaded picture in a folder, and each time the last picture cannot be overwritten by the next upload operation, the implementation code is as follows:

@RestController
public class TestController {
    
    
	private static final String SAVE_PATH = "C:\\Users\\Administrator\\Desktop\\image\\";

    @PostMapping("/upload")
    public Object uploadImg(@RequestPart("img") MultipartFile file) {
    
    
        if (file.isEmpty()) {
    
    
            return "请选择要上传的图片";
        }

        // 检查文件类型
        if (!isValidImageFile(file)) {
    
    
            return "只能上传图片文件";
        }

        // 检查文件大小
        if (!isValidFileSize(file)) {
    
    
            return "图片文件大小不能超过2MB";
        }

        String originalFileName = file.getOriginalFilename(); // 获取原始文件名称
        String extension = originalFileName.substring(originalFileName.lastIndexOf('.')); // 获取文件后缀
        String fileName = generateUniqueFileName(extension);

        File saveFile = new File(SAVE_PATH + fileName);

        try {
    
    
            file.transferTo(saveFile);
            return "上传成功";
        } catch (IOException e) {
    
    
            e.printStackTrace();
            return "上传失败";
        }
    }

    private boolean isValidImageFile(MultipartFile file) {
    
    
        // 实现文件类型校验,根据实际需求进行判断
        // 例如可以判断文件的后缀名是否为常见的图片格式:jpg/jpeg、png、gif等
        // return file.getContentType().startsWith("image/");
        return true; // 这里简化处理,总是返回true
    }

    private boolean isValidFileSize(MultipartFile file) {
    
    
        // 实现文件大小校验,根据实际需求进行判断
        // 例如可以判断文件的大小是否小于2MB
        return file.getSize() <= 2 * 1024 * 1024; // 2MB
    }

    private String generateUniqueFileName(String extension) {
    
    
        String fileName = UUID.randomUUID().toString() + extension;
        return fileName;
    }
}

This code implements a simple file upload function. The following is an analysis of the code:

  1. private static final String SAVE_PATH = "C:\\Users\\Administrator\\Desktop\\image\\";

    This is a constant indicating the path where the file is saved. In this example, the file will be saved to C:\Users\Administrator\Desktop\image\the directory.

  2. @PostMapping("/upload")

    This annotation indicates that uploadImgthe method is used to handle HTTP POST requests and maps to the path /upload.

  3. public Object uploadImg(@RequestPart("img") MultipartFile file)

    This method is used to handle file uploads. The annotation is used to bind the named part @RequestPart("img")of the request body to the parameter. It is an interface provided by the Spring framework for processing file uploads, which represents the uploaded file data.imgfileMultipartFile

  4. File upload processing logic:

    • First, check filewhether it is empty, and if it is empty, return the prompt message "Please select the picture to upload".

    • Next, isValidImageFilea method is called to check the file type. In the example, this method is simplified to always return true. In actual use, the file type check can be implemented as needed.

    • Then, call isValidFileSizethe method to check the file size. In the example, the file size cannot exceed 2MB (2*1024*1024 bytes).

    • If the file type or file size check fails, a corresponding error message will be returned.

    • Finally, if the file upload verification passes, generate a unique file name, by UUID.randomUUID().toString()generating a unique string, and splicing it into a complete file name according to the suffix of the original file. Then save the file to SAVE_PATHthe specified directory.

  5. private boolean isValidImageFile(MultipartFile file)

    This is a private method used to implement file type validation. In the example, this method is simplified to always return true. In actual use, the file type can be checked according to actual needs, such as judging whether the suffix of the file is a common image format: jpg/jpeg, png, gif, etc.

  6. private boolean isValidFileSize(MultipartFile file)

    This is a private method used to implement file size checks. In the example, the file size cannot exceed 2MB (2*1024*1024 bytes).

  7. private String generateUniqueFileName(String extension)

    This is a private method used to generate unique filenames. In the example, use to UUID.randomUUID().toString()generate a unique string, and then concatenate it into a complete file name according to the file extension.

Through this code, the uploaded picture is saved to the specified folder, and a unique identifier is added to the file name, avoiding the problem of file overwriting. At the same time, file type and size checks are added to enhance the robustness and security of the code. However, the actual file storage path, file type verification and file size verification need to be further adjusted and improved according to specific needs.

Initiate a request to upload an image through Postman:


Upload this picture multiple times:

6. Get the HTTP header field through @RequestHeader

Through @RequestHeaderannotations, you can get the value of the HTTP request header field.

In Spring MVC, the HTTP request header contains some metadata information, such as User-Agent, Content-Type, Authorizationand so on. Using @RequestHeaderannotations, the values ​​of these HTTP request header fields can be bound to the parameters of the controller method, so that these values ​​can be used for processing in the method.

The following is a sample code that demonstrates how to use @RequestHeaderGet the value of an HTTP header field:

@RestController
public class TestController {
    
    
    @GetMapping("/headers")
    public String getHeaders(@RequestHeader("User-Agent") String userAgent,
                             @RequestHeader("Accept-Language") String acceptLanguage
                             ) {
    
    
        // 在方法中使用获取到的HTTP头部字段值进行处理
        // ...
        return "User-Agent: " + userAgent + "<br>" +
                "Accept-Language: " + acceptLanguage;
    }

}

In the above example, we defined a getHeaderscontroller method called and used @GetMappingannotations to map that method to /headersthe path of the GET request. Access and capture the package through the browser, and find that the obtained content is exactly the same as the content of the captured package.

7. Obtaining Session and Cookie

7.1 Storage and acquisition of Session

In web applications, Session is used to store user state information on the server side. The method of storing and obtaining data in Session in Spring MVC is the same as that in Servlet.

7.1.1 Session storage

In Spring MVC, HttpSessionobjects can be used to store and retrieve data in the Session. HttpSessionThe object represents the current user's Session, and can be obtained through the method HttpServletRequestof the object getSession().

@RestController
public class TestController {
    
    
    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request){
    
    
        HttpSession session = request.getSession(true);
        session.setAttribute("username", "zhangsan");
        return "session has set.";
    }
}

In the above example, /setSessiona method is defined under the path setSession. When the user visits the path, if the session has not been created, Sessionan attribute named "username" will be stored in it, and the record whose value is "zhangsan" will be set .

By capturing the package with Fiddle, you can find that it has been successfully set up Session:

It is worth noting that:

  • In Spring MVC, when @RequestMappingthe annotated method parameters contain HttpServletRequestand HttpServletResponse, Spring MVC will automatically pass the current HttpServletRequestand HttpServletResponseobject to these method parameters.
  • This means that in @RequestMappingthe annotated method, you can directly declare HttpServletRequestand HttpServletResponsetype parameters without additional configuration or processing, and Spring MVC will automatically pass the request and response objects to these parameters.

7.2.2 Session acquisition

To get the data stored in the Session, you can use the methods HttpSessionof the object getAttribute()to get it.

@Controller
public class TestController {
    
    

    @RequestMapping("/getSession")
    public String getSession(HttpServletRequest request) {
    
    
        HttpSession session = request.getSession(false);
        String username = (String) session.getAttribute("username");
        return "Session中的username值为:" + username;
    }
}

In the above example, we /getSessiondefined a getSessionmethod under the path. When the user accesses the path, the attribute named "username" will be obtained from the Session and its value will be returned to the user.

7.2 Get Cookie via @CookieValue

In addition to using Sessionto store user status information, web applications can also use cookies to store a small amount of user information. Spring MVC provides @CookieValueannotations to get the value of Cookie.

@RestController
public class TestController {
    
    

    @GetMapping("/getCookie")
    public String getCookie(@CookieValue("username") String username) {
    
    
        return "Cookie中的username值为:" + username;
    }
}

In the above example, we /getCookiedefined a getCookiemethod under the route, when the user visits the route, get the value named "username" from the cookie and return it to the user.

Note that when using @CookieValueannotations, make sure that the specified cookie name exists. If it does not exist, you can use defaultValuethe attribute to specify a default value, or use requiredthe attribute to set whether it must exist. If requiredthe attribute is trueand the cookie does not exist, an exception will be thrown.

Eight, Spring MVC data return

8.1 Return data content

In Spring MVC, controller methods can return different types of data content. These data contents can be returned to the client as a response.

@Controller
public class DataController {
    
    

    // 返回字符串
    @GetMapping("/hello")
    @ResponseBody
    public String sayHello() {
    
    
        return "Hello, World!";
    }

    // 返回数字
    @GetMapping("/number")
    @ResponseBody
    public int getNumber() {
    
    
        return 42;
    }

    // 返回布尔值
    @GetMapping("/boolean")
    @ResponseBody
    public boolean getBoolean() {
    
    
        return true;
    }
}

In the above example, we defined a DataControllercontroller called and used @GetMappingannotations to map three different methods to different paths.

  • sayHelloThe method returns a string "Hello, World!". Using @ResponseBodyannotations, return the returned string directly to the client as the response body.

  • getNumbermethod returns an integer 42. Also use @ResponseBodyannotations to return the returned integer directly to the client as the response body.

  • getBooleanmethod returns a boolean true. Annotations are also used @ResponseBodyto return the boolean value returned directly to the client as the response body.

8.2 Return to static page

In addition to returning data content, Spring MVC also supports returning static pages. This is typically used to return HTML pages or other static resources.

@Controller
public class PageController {
    
    
    @GetMapping("/index")
    public String showPage() {
    
    
        return "/index.html";
    }
}

In the above example, we defined a PageControllercontroller called and used @GetMappingannotations to showPagemap methods to the path of the GET request /index. In this example, the logical name of the returned view is "index", and Spring MVC will look for the index.htmlHTML template named and return it to the client.

8.3 Return JSON object

In Spring MVC, data in JSON format can also be returned, which is usually used to provide API interfaces.

@Controller
public class JSONController {
    
    

    @GetMapping("/user")
    @ResponseBody
    public User getUser() {
    
    
        User user = new User("zhangsan", 30);
        return user;
    }
}

In the above example, a JSONControllercontroller named is defined and @GetMappingannotations are used to getUsermap methods to the path of the GET request /user.

getUserThe method returns an object, which is converted to JSON format Userusing annotations, and returned directly to the client as the response body.@ResponseBody

In practical applications, it may also be necessary to introduce a JSON serialization library (such as Jackson) to convert Java objects into JSON format. But Spring MVC will automatically convert the return value to JSON format and set the correct Content-Typeheader so that the client can correctly parse the returned JSON data.

9. Request forwarding and request redirection

9.1 Request forwarding forward

Request forwarding refers to forwarding a request from one Servlet to another Servlet or JSP page. The forwarding process is completed on the server side, and the client browser does not perceive it. In Spring MVC, RequestDispatcherobjects can be used to implement request forwarding.

@Controller
public class ForwardController {
    
    

    @GetMapping("/forward")
    public String forward() {
    
    
        // 实现请求转发到 /index.html路径
        return "forward:/index.html";
    }
}

In the above example, a ForwardControllercontroller named is defined and @GetMappingannotations are used to forwardmap methods to the path of the GET request /forward.

forwardThe method returns a string "forward:/index.html", which means forward the request to /index.htmlthe path. Spring MVC will forward the request on the server side and hand over the control right to /index.htmlthe processor method corresponding to the path.

Access the address through a browser http://localhost:8080/forward:

9.2 request redirect redirection

Request redirection means that after receiving a request, the server sends an HTTP response, the response header contains a Locationfield, and the client resends a new request based on the content of this field. Therefore, 请求重定向涉及两次请求和响应过程,客户端感知到的是两次请求的结果.

@Controller
public class RedirectController {
    
    

    @GetMapping("/redirect")
    public String redirect() {
    
    
        // 实现请求重定向到 /index.html路径
        return "redirect:/index.html";
    }
}

In the above example, a RedirectControllercontroller named is defined and @GetMappingannotations are used to redirectmap methods to the path of the GET request /redirect.

redirectThe method returns a string "redirect:/index.html", which means redirect the request to /index.htmlthe path. Spring MVC will send an HTTP response on the server side, and the response header contains Locationfields telling the client to redirect to /index.htmlthe path.

Access the address through a browser http://localhost:8080/redirect:

finally jump to it http://localhost:8080/index.html.

You can view the details through Fiddle capture:


It can be found that http://localhost:8080/redirectthere are two request results at the end of the request.

When requesting /redirect, the server will tell the browser to request /index.html:

9.3 The difference between forward and redirect

  1. Execution phase:

    • Request forwarding yes 在服务器端完成的,客户端浏览器不感知. The request is forwarded from one Servlet to another Servlet or JSP page, and the whole process is done inside the server.
    • Request redirection 涉及两次请求和响应过程. After the client receives the response to the first request, it will Locationsend a new request according to the fields in the response header.
  2. Address bar changes:

    • Request forwarding 不会改变The contents of the address bar of the browser, the URL of the original request is still in the address bar.
    • Request redirection 会改变The contents of the address bar of the browser, and the redirected URL will be displayed in the address bar.
  3. Request attribute passing:

    • Request forwarding can share request attributes during the forwarding process, and the Servlet before forwarding can set the request attributes to the values ​​required by the forwarded Servlet or JSP page.
    • Request redirection cannot directly share request attributes between two requests, because the two requests are independent.

Choosing to use request forwarding or request redirection depends on specific needs. Request forwarding is applicable to situations such as implementing page jumps and sharing request attributes inside the server. Request redirection is suitable for situations where you need to modify the browser address bar, avoid repeated form submissions, and refresh the page.

Guess you like

Origin blog.csdn.net/qq_61635026/article/details/132144269