Spring MVC framework learning

Spring MVC framework learning

1. Basic theory

1. Three tier architecture

  • The development of server-side programs is generally based on two forms: a C/S architecture program and a B/S architecture program
  • The program of B/S architecture is basically developed using Java language, and the B/S architecture is divided into three layers
  • Three tier architecture
    1. Presentation layer: WEB layer, which is used for data interaction with the client. The presentation layer generally adopts MVC design mode
    2. Business layer: process specific business logic
    3. Persistence layer: used to operate the database

2. What is MVC

MVC is the abbreviation of model, view and controller. It is a software design specification.
It is a method of separating business logic, data and display to organize code.

The main function of MVC is to reduce the two-way coupling between view and business logic.

MVC is not a design pattern, MVC is an architecture pattern. Of course, there are differences between different MVCs.

  • Model: data model, which provides the data to be displayed, so it contains data and behavior. It can be regarded as domain model or
    JavaBean components (including data and behavior), but now they are generally separated: Value Object (data Dao) and service layer
    (behavior Service). That is, the model provides functions such as model data query and model data status update, including data and business.
  • View: it is responsible for displaying the model, which is generally the user interface we see and what customers want to see.
  • Controller: receives the user's request, delegates it to the model for processing (state change), and returns the returned model after processing
    The data is returned to the view, which is responsible for displaying. In other words, the controller does the work of a dispatcher.

The most typical MVC is the pattern of JSP + servlet + javabean.

3. What is spring MVC

Spring MVC is a request driven lightweight web framework based on Java that implements the MVC design model. It is a follow-up product of spring framework and has been integrated into Spring Web Flow. Spring framework provides a full-featured MVC module for building web applications. Spring can be inserted into MVC architecture, so when using spring for web development, You can choose spring MVC framework of spring or integrate other MVC development frameworks

Spring MVC has now become one of the mainstream MVC frameworks. Through a set of annotations, it makes a simple Java class become the controller for processing requests without implementing any interface. At the same time, it also supports RESTful programming style requests

3.1. Model1 Era

In the early development of web, model 1 is usually used.
Model1 is mainly divided into two layers: view layer and model layer.
Advantages of Model1: simple architecture, more suitable for small project development;
Model1 disadvantages: JSP responsibilities are not single, the responsibilities are too heavy, and it is not easy to maintain;

3.2. Model 2 era

Model 2 divides a project into three parts, including view, control and model.

  1. User sends request
  2. The Servlet receives the request data and calls the corresponding business logic method
  3. After the business is processed, the updated data is returned to the servlet
  4. servlet turns to JSP, which renders the page
  5. Respond to the updated page of the front end
    Responsibility analysis:
    Controller: controller
  6. Get form data
  7. Call business logic
  8. Go to the specified page
    Model: Model
  9. Business logic
  10. Status of saved data
    View: View
  11. Display page
    Model2 not only improves the reuse rate of code and the scalability of the project, but also greatly reduces the maintenance cost of the project. Of Model 1 mode
    The implementation is relatively simple and suitable for rapid development of small-scale projects. The JSP page in model 1 plays both the roles of View and Controller
    System logic and presentation logic are mixed together, resulting in very low reusability of code, which increases the scalability of application and the difficulty of maintenance.
    Model2 eliminates the disadvantages of Model1.

4. Advantages of spring MVC

(1) The spring MVC framework provides a complete set of components.

Unlike previous frameworks that only provide interfaces, and then let users write implementation classes according to the interfaces to realize functions, spring MVC provides a complete set of components that can be used directly. This is equivalent to that the previous framework only provided you with design drawings, and you need to make the tools according to the design drawings. Now spring MVC directly gives you a set of ready-made toolbox with various tools you can use.

Moreover, using the spring MVC framework to provide these tools is also very simple. It can be done through some simple annotations. There is no need to write cumbersome and lengthy code. It's even better than drinking sprite in summer.

(2) Spring MVC is a framework based on the powerful spring container.

If you have ever used Spring container, you must know how easy the object hosting function of Spring container is to use. It doesn't need you to create and release objects yourself. The Spring container helps you do it all! Similarly, there is no need to worry about the management of various tool classes in the Spring MVC toolbox that can be put into the Spring container. This advantage of saving time and effort is not available in other frameworks.

(3) The configuration of the framework is simple and flexible.

The common configuration items of spring MVC framework have covered 80% of the configuration requirements of the project. Simple projects can even achieve zero configuration, which can be used immediately.

(4) The code is highly reusable.

Translated into vernacular, a mature, online and stable spring MVC project can be used as the basis for the development of another new project after simple modification or even no modification. This will save a lot of effort in developing new projects.

(5) Good scalability.

If the tools provided by the spring MVC framework can not meet 100% of your needs, you need to customize the development. The spring MVC framework also provides corresponding interfaces for tool upgrading. In this way, when you encounter a powerful elite monster, you can still beat it with the spring MVC framework.

(6) Clear role division

  • Front end controller (dispatcher servlet)
  • Request to processor mapping
  • Handler adapter
  • View resolver
  • Processor or page Controller
  • Validator
  • Command object (the object to which the command request parameter is bound is called a command object)
  • Form Object (the object provided by Form Object for form display and submission is called Form Object)

(7) Analysis on the advantages and disadvantages of spring MVC and struts 2

common ground:

  • They are all presentation layer frameworks, which are written based on MVC model
  • Their bottom layer is inseparable from the original servlet API
  • Their mechanism for handling requests is a core controller

difference:

  • The entry of Spring MVC is Servlet and struts 2 is Filter
  • Spring MVC is designed based on methods, while struts 2 is designed based on classes. Struts 2 creates an action class every time it executes. All spring MVCs are faster than struts 2
  • Spring MVC is simpler to use and supports JSR303, making it easier to handle ajax requests
  • The OGNL expression of struts 2 makes the development efficiency of the page higher than that of spring MVC, but the execution efficiency is not higher than that of JSTL

2. Introduction case of spring MVC

Case requirements:


  • archetypeCatalog
  • internal

Import dependent package POM xml

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.example</groupId>
  <artifactId>SpringMAC</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>SpringMAC Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <spring-version>5.0.2.RELEASE</spring-version><!--Version locking is referenced below Spring All versions will be the same-->
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring-version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring-version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring-version}</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>

  <build>
    <finalName>SpringMAC</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

Create two folders java and resources as their respective root

Spring mvc.net needs to be configured XML configuration file


Configure Tomcat server

Configure web xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <!--Front end controller-->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--load springmvc.xml file-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
    <!--Slash is that any request will be controlled-->
  </servlet-mapping>
</web-app>

Configure spring MVC xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
                            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--Enable annotation scanning-->
    <context:component-scan base-package="com.springT"/>
    <!--Open view parser-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--open SpringMVC Annotation framework support-->
    <mvc:annotation-driven/>
</beans>

Configure test page jsp

<%--
  Created by IntelliJ IDEA.
  User: Programmer Xiao Xu
  Date: 2022-01-25
  Time: 10:39
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>hell SpringMVC</title>
</head>
<body>
<h3>Entry program</h3>
<a href="hello">Jump page</a>
</body>
</html>

Configure test success page

<%--
  Created by IntelliJ IDEA.
  User: Programmer Xiao Xu
  Date: 2022-01-25
  Time: 10:49
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h3>Conversion succeeded</h3>
</body>
</html>

Write and implement jump class

package com.springT.Controller;

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

/**
 * @author : Programmer Xu dada
 * @description: TODO
 * @date : 2022-01-25 10:41
 */
//control class
    @Controller
public class ControllerDemo {
        //request
        @RequestMapping(path = "/hello")
    public String hellspring(){
        System.out.println("hell springmvc");
        return "success";
    }
}

return the returned value was successfully loaded into success JSP page

1. Configuration process

1. Where server, load the configuration file

  • Creating a DIspatcherServlet object
  • springmvc. The XML is loaded
  • Create ControllerDemo as an object

2. Send request, background processing


The principle of spring MVC is shown in the following figure:
When a request is initiated, the front controller intercepts the request, generates a proxy request according to the request parameters, and finds the actual control corresponding to the request
The controller processes the request, creates the data model, accesses the database, and responds the model to the central controller. The controller uses the model and view
Render the view result, return the result to the central controller, and then return the result to the requester.

2.3 implementation principle of spring MVC


Briefly analyze the execution process

  1. Dispatcher servlet represents the front controller and is the control center of the whole spring MVC. The user makes a request,
    The dispatcher servlet receives the request and intercepts it.
    We assume that the requested url is: http://localhost:8080/SpringMVC/hello
    As above, the url is divided into three parts:
    http://localhost:8080 Server domain name
    Spring MVC is a web site deployed on the server
    hello indicates the controller
    Through analysis, the above url is expressed as: request the hello controller of the spring MVC site located on the server localhost:8080.
  2. HandlerMapping is processor mapping. Dispatcher servlet calls HandlerMapping, which is based on
    Request url to find Handler.
  3. HandlerExecution refers to a specific Handler. Its main function is to find the controller according to the url. The above url is used to find the controller
    Is: hello.
  4. HandlerExecution passes the parsed information to DispatcherServlet, such as parsing controller mapping.
  5. The HandlerAdapter represents a processor adapter that executes the Handler according to specific rules.
  6. The Handler lets the specific Controller execute.
  7. The Controller returns the specific execution information to the HandlerAdapter, such as ModelAndView.
  8. The HandlerAdapter passes the logical name or model of the view to the dispatcher servlet.
  9. DispatcherServlet calls the view resolver to resolve the logical view name passed by the HandlerAdapter.
  10. The view parser passes the parsed logical view name to the dispatcher servlet.
  11. DispatcherServlet calls the specific view according to the view result parsed by the view parser.
  12. The final view is presented to the user.

2. Explanation of involved components

2.1 dispatcher servlet: front end controller
When the user's request reaches the front-end controller, it is equivalent to c in mvc mode. Dispatcher servlet is the center of the whole process control. It calls other components to process the user's request. The existence of dispatcher servlet reduces the coupling between components
2.2 HandlerMapping: process mapper
handlerMapping is responsible for finding the Handler, that is, the processor, according to the user's request. Spring MVC provides different mappers to implement different mapping methods, such as configuration file mode, implementation interface mode and annotation mode
2.3 Handler: processor
The processor is executed through the HandlerAdapter, which is an application of the adapter mode. More types of processors can be executed through the extension adapter
2.3 View Resolver: View resolver
The View Resolver is responsible for generating the processing results into the View view. The View Resolver first resolves the logical View name into the physical View name, that is, the specific page address, and then generates the View object. Finally, it renders the View and displays the processing results to the user through the page
2.4 View: View
Spring MVC framework provides support for many View types, including jstlView, FreemarkerView, pdfView, etc. our most commonly used View is jsp

Generally, the model data needs to be displayed to users through the page through the page label or page template technology, and the programmer needs to develop specific pages according to the business needs

2.5 < MVC: annotation driver > description

Among the various components of spring MVC, processor mapper, processor adapter and view parser are called the three major components of spring MVC
Use < MVC: annotation driver > to automatically load RequestMappingHandlerMapping and RequestMappingHandlerAdapter, which can be used in spring MVC Use < MVC: annotation driver > in the XML configuration file to replace the configuration of annotation processor and adapter
It is equivalent to configuring in xml:

 <!--open SpringMVC Annotation framework support-->
    <mvc:annotation-driven/>

RequestMapping attribute: value: the URL used for the request, and the path attribute have the same function
Path: used to specify the request path
Method: used to specify the method of the request
As like as two peas: params: Specifies the condition for restricting the request parameters, which supports simple expressions. The key and value of the request parameters must be exactly the same as the configuration.
For example:
params = {"accountName"}, indicating that the request parameter must have accountName
params = {"money! 100"}, indicating that the request parameter money cannot be 100
headers: used to specify the conditions that restrict the request header

method = {RequestMethod.POST} the restrictions imposed by the current request method

public class ControllerDemo {
        //request
        @RequestMapping(path = "/hello" ,method = {RequestMethod.POST},params = {"username"})
    public String hellspring(){
        System.out.println("hell springmvc");
        return "success";
    }
}

3 use annotation @ Controller

  • @The Controller annotation type is used to declare that the instance of the Spring class is a Controller (another three notes were mentioned when talking about IOC)
    Solution);
  • Spring can use the scanning mechanism to find all annotation based controller classes in the application. In order to ensure that spring can find your controller
    Controller, component scanning needs to be declared in the configuration file.
<!-- Automatically scan the specified package and submit all the following annotation classes to IOC Container management -->
<context:component-scan base-package="com.kuang.controller"/>
  • Add a ControllerTest2 class and implement it with annotations;
//@The class annotated by the Controller is automatically added to the Spring context
@Controller
public class ControllerTest2{
//Map access path
@RequestMapping("/t2")
public String index(Model model){
//Spring MVC will automatically instantiate a Model object to pass values to the view
model.addAttribute("msg", "ControllerTest2");
//Return to view location
return "test";
}
}

4RequestMapping

  • @RequestMapping
  • @The RequestMapping annotation is used to map URLs to a controller class or a specific handler method. Can be used on classes or methods.
    Used on a class, indicating that all methods in the class that respond to requests take this address as the parent path.
    In order to test the conclusion more accurately, we can add a project name to test myweb
    Only annotate on Methods
@Controller
public class TestController {
@RequestMapping("/h1")
public String test(){
return "test";
}
}
  • Annotate classes and methods at the same time
@Controller
@RequestMapping("/admin")
public class TestController {
@RequestMapping("/h1")
public String test(){
return "test";
}
}

5RestFul style

concept
Restful is a style of resource positioning and resource operation. It's not a standard or agreement, it's just a style. Based on this style
The software can be more concise, more hierarchical, and easier to implement caching and other mechanisms.
function
Resources: all things on the Internet can be abstracted as resources
Resource operation: use POST, DELETE, PUT and GET to operate resources with different methods.
Add, delete, modify and query respectively.
Operate resources in traditional way: achieve different effects through different parameters! Single method, post and get
Learning test

  1. Create a new class RestFulController
@Controller
public class RestFulController {
}
  1. In Spring MVC, you can use the @ PathVariable annotation to bind the value of the method parameter to a URI template variable
    Come on.
@Controller
public class RestFulController {
//Map access path
@RequestMapping("/commit/{p1}/{p2}")
public String index(@PathVariable int p1, @PathVariable int p2,
Model model){
int result = p1+p2;
//Spring MVC will automatically instantiate a Model object to pass values to the view
model.addAttribute("msg", "result:"+result);
//Return to view location
return "test";
}
}

Think: what are the benefits of using path variables?
Make the path more concise;
It is more convenient to obtain parameters, and the framework will automatically carry out type conversion.
Access parameters can be constrained by the type of path variable. If the type is different, the corresponding request method cannot be accessed, as shown in this figure
If the access path in is / commit/1/a, the path does not match the method, and it will not be the failure of parameter conversion.

  1. Let's modify the corresponding parameter type,
//Map access path
@RequestMapping("/commit/{p1}/{p2}")
public String index(@PathVariable int p1, @PathVariable String p2, Model
model){
String result = p1+p2;
//Spring MVC will automatically instantiate a Model object to pass values to the view
model.addAttribute("msg", "result:"+result);
//Return to view location
return "test";
}

Use the method property to specify the request type
It is used to restrict the type of request and narrow the request range. Specify the type of request predicate, such as GET, POST, HEAD, OPTIONS, PUT,
PATCH, DELETE, TRACE, etc

//The mapped access path must be a POST request
@RequestMapping(value = "/hello",method = {RequestMethod.POST})
public String index2(Model model){
model.addAttribute("msg", "hello!");
return "test";
}

Summary:
Spring MVC's @ RequestMapping annotation can handle HTTP request methods, such as get, put, post and delete
And PATCH.
All address bar requests will be of HTTP GET type by default.
Method level annotation variants are as follows: combined annotation

@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping

@GetMapping is a composite annotation
It acts as a shortcut to @ RequestMapping(method =RequestMethod.GET).
Usually use more!

6 result jump method

6.1,ModelAndView

Set the ModelAndView object and jump to the specified page according to the name of the view and the view parser
Page: {view parser prefix} + viewName + {view parser suffix

<!-- view resolver  -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- prefix -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- suffix -->
<property name="suffix" value=".jsp" />
</bean>

Corresponding controller class

public class ControllerTest1 implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) throws Exception {
//Returns a model view object
ModelAndView mv = new ModelAndView();
mv.addObject("msg","ControllerTest1");
mv.setViewName("test");
return mv;
}
}

6.2,ServletAPI

By setting the servlet API, no view parser is required

  1. Output through HttpServletResponse
  2. Redirection via HttpServletResponse
  3. Forward through HttpServletResponse
@Controller
public class ResultGo {
@RequestMapping("/result/t1")
public void test1(HttpServletRequest req, HttpServletResponse rsp)
throws IOException {
rsp.getWriter().println("Hello,Spring BY servlet API");
}
@RequestMapping("/result/t2")
public void test2(HttpServletRequest req, HttpServletResponse rsp)
throws IOException {
rsp.sendRedirect("/index.jsp");
}
@RequestMapping("/result/t3")
public void test3(HttpServletRequest req, HttpServletResponse rsp)
throws Exception {
//forward
req.setAttribute("msg","/result/t3");
req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,rsp);
}
}

6.3,SpringMVC

Realize forwarding and redirection through spring MVC - no view parser is required;
Before testing, you need to comment out the view parser

@Controller
public class ResultSpringMVC {
@RequestMapping("/rsm/t1")
public String test1(){
//forward
return "/index.jsp";
}
@RequestMapping("/rsm/t2")
public String test2(){
//Forwarding II
return "forward:/index.jsp";
}
@RequestMapping("/rsm/t3")
public String test3(){
//redirect
return "redirect:/index.jsp";
}
}


Forward and redirect through spring MVC - view parser;
Redirection does not require a view parser. Its essence is to re request a new place, so pay attention to the path problem
You can redirect to another request implementation

@Controller
public class ResultSpringMVC2 {
@RequestMapping("/rsm2/t1")
public String test1(){
//forward
return "test";
}
@RequestMapping("/rsm2/t2")
public String test2(){
//redirect
return "redirect:/index.jsp";
//return "redirect:hello.do"; //hello.do for another request/
}
}

7. Data processing

7.1. Processing submitted data

1. The submitted domain name is consistent with the parameter name of the processing method
Submit data: http://localhost:8080/hello?name=kuangshen

@RequestMapping("/hello")
public String hello(String name){
System.out.println(name);
return "hello";
}

2. The submitted domain name is inconsistent with the parameter name of the processing method
Submit data: http://localhost:8080/hello?username=kuangshen

//@Requestparam ("username"): the name of the domain submitted by username
@RequestMapping("/hello")
public String hello(@RequestParam("username") String name){
System.out.println(name);
return "hello";
}

3. Submitted is an object
It is required that the submitted form field and the attribute name of the object are consistent, and the parameter can use the object

  1. Entity class
public class User {
private int id;
private String name;
private int age;
//structure
//get/set
//tostring()
}

  1. Submit data: http://localhost:8080/mvc04/user?name=kuangshen&id=1&age=15
  2. Treatment method:
@RequestMapping("/user")
public String user(User user){
System.out.println(user);
return "hello";
}

Background output: user {id = 1, name = 'kuangshen', age=15}
Note: if an object is used, the parameter name passed by the front end must be consistent with the object name, otherwise it is null.

7.2 data display to the front end

First: through ModelAndView
This has always been the case before us Just explain more

public class ControllerTest1 implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) throws Exception {
//Returns a model view object
ModelAndView mv = new ModelAndView();
mv.addObject("msg","ControllerTest1");
mv.setViewName("test");
return mv;
}
}

Second: through ModelMap
ModelMap

@RequestMapping("/hello")
public String hello(@RequestParam("username") String name, ModelMap model){
//Encapsulates the data to be displayed in the view
//Equivalent to req setAttribute("name",name);
model.addAttribute("name",name);
System.out.println(name);
return "hello";
}

Third: through Model
Model

@RequestMapping("/ct2/hello")
public String hello(@RequestParam("username") String name, Model model){
//Encapsulates the data to be displayed in the view
//Equivalent to req setAttribute("name",name);
model.addAttribute("msg",name);
System.out.println(name);
return "test";
}

7.3 comparison

Model There are only a few methods that are only suitable for storing data, simplifying novices' understanding of Model Operation and understanding of objects;
ModelMap Inherited LinkedMap ,In addition to implementing some of its own methods, the same inheritance LinkedMap Methods and characteristics of
 Sex;
ModelAndView While storing data, you can set the returned logical view and control the jump of the display layer.

Of course, more future development is more about performance and optimization, so it can't be limited to this understanding.
Please use 80% of the time to lay a solid foundation, and the remaining 18% of the time to study the framework and 2% of the time to learn some English. The official documents of the framework
Always the best tutorial.

7.4. Garbled code

Test steps:

  1. We can write a submission form on the home page
<form action="/e/t" method="post">
<input type="text" name="name">
<input type="submit">
</form>
  1. Write the corresponding processing class in the background
@Controller
public class Encoding {
@RequestMapping("/e/t")
public String test(Model model,String name){
model.addAttribute("msg",name); //Get the value of the form submission
return "test"; //Jump to the test page and display the entered value
}
}
  1. Input Chinese test, found garbled code
    It has to be said that the problem of garbled code is a very common problem in our development, and it is also a big problem for our program ape!
    In the past, the problem of garbled code was solved through filters, and spring MVC provided us with a filter, which can be found on the web Configuration in XML
    The xml file has been modified. You need to restart the server!
<filter>
<filter-name>encoding</filter-name>
<filterclass>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

But we found that in some extreme cases This filter does not support get well
Treatment method:
4. Modify the tomcat configuration file: set the code!

<Connector URIEncoding="utf-8" port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
  1. Custom filter
package com.kuang.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
/**
* Filter to solve all the garbled codes of get and post requests
*/
public class GenericEncodingFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse
response, FilterChain chain) throws IOException, ServletException {
//Handle the character encoding of the response
HttpServletResponse myResponse=(HttpServletResponse) response;
myResponse.setContentType("text/html;charset=UTF-8");
// Transformation into agreement related objects
HttpServletRequest httpServletRequest = (HttpServletRequest)
request;
// Enhanced request packaging
HttpServletRequest myrequest = new
MyRequest(httpServletRequest);
chain.doFilter(myrequest, response);
}
@Override
public void init(FilterConfig filterConfig) throws
ServletException {
}
}
//Custom request object, wrapper class of HttpServletRequest
class MyRequest extends HttpServletRequestWrapper {
private HttpServletRequest request;
//Coded flag
private boolean hasEncode;
//Define a constructor that can be passed into the HttpServletRequest object to decorate it
public MyRequest(HttpServletRequest request) {
super(request);// super must write
this.request = request;
}
// Override methods that need to be enhanced
@Override
public Map getParameterMap() {
// Get request method first
String method = request.getMethod();
if (method.equalsIgnoreCase("post")) {
// post request
try {
// Handle post garbled code
request.setCharacterEncoding("utf-8");
return request.getParameterMap();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else if (method.equalsIgnoreCase("get")) {
// get request
Map<String, String[]> parameterMap =
request.getParameterMap();
if (!hasEncode) { // Make sure that the get manual encoding logic runs only once
for (String parameterName : parameterMap.keySet()) {
String[] values = parameterMap.get(parameterName);
if (values != null) {
for (int i = 0; i < values.length; i++) {
try {
// Handle get garbled code
values[i] = new String(values[i]
.getBytes("ISO-8859-1"), "utf8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
}
hasEncode = true;
}
return parameterMap;
}
return super.getParameterMap();
}
//Take a value
@Override
public String getParameter(String name) {
Map<String, String[]> parameterMap = getParameterMap();
String[] values = parameterMap.get(name);
if (values == null) {
return null;
}
return values[0]; // Retrieve the first value of the parameter
}
//Take all values
@Override
public String[] getParameterValues(String name) {
Map<String, String[]> parameterMap = getParameterMap();
String[] values = parameterMap.get(name);
return values;
}
}


This is also written by some great gods I found on the Internet. Generally, the default garbled code processing of spring MVC can be very good
Solved!
Then on the web Configure this filter in XML!
The problem of garbled code needs more attention at ordinary times. The unified coding UTF-8 should be set wherever possible!

3. If you have any questions, please leave a message to me and I will try my best to answer them. If you think the article is good, please praise it

Keywords: Spring Spring MVC mvc

Added by wmhop on Thu, 27 Jan 2022 08:24:44 +0200