– overview for SpringMVC

  • Prior to us, the WEB layer used servlet technology, but each servlet requires a configuration that is too complex, SpringMVC can solve this problem;

  • SpringMVC is a WEB/ presentation layer framework based on the MVC pattern. It solves common problems in WEB development: parameter acceptance, file upload/download, form validation, internationalization, etc.

  • As a very important functional module of Spring framework, SpringMVC can be seamlessly integrated with Spring to improve development efficiency.

  • Spring is a lightweight Java development framework created to address the complexities of enterprise application development. Based on the Spring framework, SpringMVC provides a set of excellent solutions for the Web layer (presentation layer) in applications.

  • Many companies are using SpringMVC, and 90% of employers require familiarity with SpringMVC;

Note: The function of SpringMvc is the function of previous servlets, which can be understood as replacing servlets with SpringMvc;

– for SpringMVC introduction

  • The jar package management

    • SpringMVC is built on top of Spring. To use SpringMVC, you must first ensure that your project has a Spring runtime environment;

    • The first step to use the framework requires the official website of the framework to download the relevant files, but SpringMVC does not need to download separately, because SpringMVC exists as a module in Spring, so we only need to download Spring.

    • Jar packages required for SpringMVC:

      • Spring-webmvc-4.1.2.release.jar — SpringMVC core package
      • Spring-web-4.1.2.release.jar — Spring support for Web project projects
    • Add the relevant Spring JAR packages

      - com.springsource.org.apache.commons.logging-1.1.1.jar - spring - beans - 4.1.2. The jar - Spring-context-4.1.2.release.jar - spring-core- 4.1.2.release.jar - spring-expression- 4.1.2.release.jar - Jar -- Servlet -- api.jar -- SpringMVC uses servlets, so you need servletjarCopy the code

      Note: 1. Spring ORM, JDBC, TX-related JARS are added according to project use; 2. Do not mix spring.3 jar files with 4.x jar files.

    • SpringMVC core controller

      • Core Controller: This is used by all WebMvc frameworks for handling the core functions of the Web layer and before all controllers are executed. In SpringMVC, DispatcherServlet is used as the core controller. The core Controller of DispatcherServlet will intercept the matching request and distribute the intercepted request to the target Controller for processing according to the corresponding rules.

  • Configuring the Core Controller
    • The heart of the WebMVC framework is the core controller, which is responsible for the common functions of all requests and then distributes them to specific controllers (the ones we wrote), completes the business logic, and responds to the view;

    • The core controller is essentially a Servlet, but the Servlet is provided by the SpringMVC framework and does not need to be written, only configured and managed by the container. Configure the core controller in web.xml (the Sevlet instance object is created when the container is started and a file named spring-mVC.xml is loaded in the classpath);

<servlet> <! Create a unique name for the core controller --> <servlet-name>dispatcherServlet</servlet-name> <! -- Fully qualified name of the core controller --> <servlet --class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <! --init-paramThe position of the label must beload-on-startupThe above -- > <! - tellSpringMVCWhere to find the core configuration file --> <init-param> <! --contextConfigLocation--> <param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring-MVC.xml</param-value>
		</init-param> <! The value of this parameter ranges from 1 to 10. The lower the value, the higher the loading time.load-on-startup< / a > 1load-on-startup>
		
	</servlet>
	<servlet-mapping> <! -- Introduce core controller by name --> <servlet-name>dispatcherServlet</servlet-name> <! --url-patternThe parameter value can be written in two ways: 1./ Intercept all requests 2. *.do* : matches all meanings.do: in order to.do/* Intercept all requests --> <url-pattern> *.do</url-pattern>
	</servlet-mapping>
Copy the code
  • Prepare the SpringMVC core configuration file

    • SpringMVC is a module of Spring. Its configuration file is similar to that of Spring.

      
<beans xmlns="http://www.springframework.org/schema/beans"
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"
>
</beans>
Copy the code
  • Write the request handler Controller

  • Three ways: The first way

    • When we used to use servlets, we wrote a HelloServlet Controller class and implemented a servlet, now we use SpringMVC to implement a Controller

    • Write the HelloController

      • The two parameters of the handleRequest method are the same as the service method in our previous servlet, request and Response objects. We can use these two objects to do all the work of a request. For example, you can use Request to accept parameters, Or use response redirection and so on, notice that the method has a return value ModelAndView in addition to the return value;
      • ModelAndView is a unique object in SpringMVC controller that describes the data (Model) and View (View) of a response to a request.
package cn.itsource.springmvc_01;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

// Before we wrote the first HelloServlet, which is the implementation Servlet
// Now we write the first HelloController, and we implement a Controller interface

// The first implementation
public class HelloController01 implements Controller{

	/** * ModelAndView: Model and View * Model: background encapsulates the data, convenient front-end access * View: define the controller return path */
	@Override
	public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		// Create a ModelAndView
		ModelAndView modelAndView = new ModelAndView();
		// The previous way servlets pass parameters
// req.setAttribute(" MSG ", "hello controller!!") );
		// Encapsulate arguments in scope
		modelAndView.addObject("msg"."Hello controller!!");
		// Tell the controller the jump path
		modelAndView.setViewName("/WEB-INF/views/index.jsp");
		returnmodelAndView; }}Copy the code
  • Write pages and present data

    • Create the views folder in web-INF and create index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"% > <! DOCTYPE html> <html> <head> <meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

${msg}

</body>
</html>
Copy the code
  • Configuring the Controller

    • SpringMVC is based on Spring. The core of Spring is the Ioc container, and the most important member of the Ioc container is bean. The controller in SpringMVC is also bean by bean.

      
<beans xmlns="http://www.springframework.org/schema/beans"
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"
>
<! -- Id was a globally unique name when we learned about Spring. After introducing SpringMVC, ID is the request path that we exposed.
<! Class is the fully qualified name of the controller -->
<bean id="/hello1.do" class="cn.itsource.springmvc_01.HelloController01"></bean>

</beans>
Copy the code
  • Access controller
    • http://localhost/hello1.do

    Note: Since we set the intercept to *.do and exposed the connection request to hello1.do, we access hello1.do

    • To see the effect, show the values we set in ModelAndView

  • Three ways: the second way

    • Implement HttpRequestHandler interface
    • In addition to implementing the Controller interface this way, we can use a second approach
package cn.itsource.springmvc_01;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.HttpRequestHandler;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

// The second implementation
public class HelloController02 implements HttpRequestHandler{

	@Override
	public void handleRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setAttribute("msg"."Second way!!");
		req.getRequestDispatcher("/WEB-INF/views/index.jsp").forward(req, resp); }}Copy the code
  • Configure spring – the MVC. XML
<? xml version="1.0" encoding="UTF-8"? > <beans xmlns="http://www.springframework.org/schema/beans"
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"> <! Id used to be our globally unique name when we learned about Spring. After introducing SpringMVC, ID is our exposed request path. --classIs the fully qualified name of the controller --> <bean id="/hello2.do" class="cn.itsource.springmvc_01.HelloWordController02"></bean>

</beans>
Copy the code
  • Access controller

    • http://localhost/hello2.do
    • To see the effect, show the values we set in ModelAndView

  • Three ways: The third way
    • The first two approaches, both very similar to our Servlet approach, do not change our configuration complexity, if SpringMVC can only achieve this level, we do not need to learn from it, so let’s look at SpringMVC recommended approach, which is also our most common approach!

    • Creating a Controller

package cn.itsource.springmvc_01;

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

// The third implementation applies the Controller annotation to the class
// Identifies this class as a controller
@Controller
public class HelloController03 {

	// Is the exposed resource path
	@RequestMapping("/hello3")
	public ModelAndView hello3(a) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("msg"."Third implementation!!");
		modelAndView.setViewName("/WEB-INF/views/index.jsp");
		returnmodelAndView; }}Copy the code
  • Since we are using annotations, we need to add annotation scans to the configuration file

      
<beans xmlns="http://www.springframework.org/schema/beans"
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/context
http://www.springframework.org/schema/context/spring-context.xsd"
>
<! -- Id was a globally unique name when we learned about Spring. After introducing SpringMVC, ID is the request path that we exposed.
<! Class is the fully qualified name of the controller -->
<bean id="/hello1.do" class="cn.itsource.springmvc_01.HelloWordController01"></bean>
<bean id="/hello2.do" class="cn.itsource.springmvc_01.HelloWordController02"></bean>

<! This is to configure which package below the annotations need to be scanned -->
<context:component-scan base-package="cn.itsource"/>

</beans>
Copy the code
  • Access controller
    • http://localhost/hello3.do
    • To see the effect, show the values we set in ModelAndView

– The urL-pattern of the front-end controller is configured

  • Url-pattern sets our blocking mode, and it has three blocking modes
    • The first type: *.do is not recommended

      • Intercepts all requests ending in.do

      • Problem: This request mode requires that your request path must be.do to access my core controller

    • Second: /* Not recommended

      • Intercept all requests

      • Problem: This request intercepts when we jump to the JSP page, causing us to jump to the page 404 after visiting the controller

    • The third type: / recommended

      • Intercepts all requests, does not intercept page resources, and supports restful style

      • Problem: If the interception path is /, it will overwrite tomcat’s own servlets. The overwritten servlets are other people’s servlets that handle static resources, so we cannot access static resources

      • Solution: springMVC gives us access to the solution, so we need to add the following configuration to the springMVC core controller

        • Introduce MVC namespaces
        • Adding < MVC :default-servlet-handler /> indicates static resource release
        • Adding static resource release will invalidate springMVC annotations @requestMapping (“/hello3”), so you need to enable springMVC annotations

      
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd"
>
<! -- Id was a globally unique name when we learned about Spring. After introducing SpringMVC, ID is the request path that we exposed.
<! Class is the fully qualified name of the controller -->
<bean id="/hello1.do" class="cn.itsource.springmvc_01.HelloWordController01"></bean>
<bean id="/hello2.do" class="cn.itsource.springmvc_01.HelloWordController02"></bean>

<! This is to configure which package below the annotations need to be scanned -->
<context:component-scan base-package="cn.itsource"/>

<! Static resource release -->
<mvc:default-servlet-handler/>

<! Enable support for springMVC annotations -->
<mvc:annotation-driven/>

</beans>
Copy the code

Note: There are some issues with configuration /, but springMVC has provided us with a solution, so we recommend using/to configure interceptions, which is the most popular way to use them now

– a restful style

  • REST(REST) Representational State Transfer (REST) is an architectural style, a design style, and an idea of Web services. Rest is also not specific to a programming language.

  • In the past, when we wrote the interface access path, we would use the path to distinguish which method we specifically access

http://localhost:8080/admin/getUser (query users)

http://localhost:8080/admin/addUser (new users)

http://localhost:8080/admin/updateUser (update)

http://localhost:8080/admin/deleteUser (remove users)

  • Rest architecture: A request path corresponds to multiple methods, and the request distinguishes which method the request goes to

GET http://localhost:8080/admin/user (query users)

POST to http://localhost:8080/admin/user (new users)

PUT http://localhost:8080/admin/user (update)

The DELETE (DELETE the user http://localhost:8080/admin/user

– Five ways to receive parameters

  • When we used to use servlets, the way we received parameters was HttpServletRequest, and there are five ways to get parameters in SpringMVC
  • The first:

/** * SpringMVC receives parameters from HttpServletRequest (not recommended) *@param username
	 * @param age
	 */
	@RequestMapping("/param/03")
	public void param03(HttpServletRequest request) {
		System.out.println(request.getParameter("username"));
		System.out.println(request.getParameter("password"));
	}
Copy the code
  • Second: by receiving parameters directly, SpringMVC can automatically inject values into the parameters, but with the same parameter types and names on the front and back ends
/** * SpringMVC accepts arguments in the second way (recommended) *@param username
	 * @param age
	 */
	@RequestMapping("/param/01")
	public void param01(String username, Integer age) {
		System.out.println("username = " + username);
		System.out.println("age = " + age);
	}
Copy the code
  • Third: if there are too many parameters, then we can encapsulate an entity class and receive them through the entity class
/** * SpringMVC receives arguments in three ways (recommended) *@param username
	 * @param age
	 */
	@RequestMapping("/param/02")
	public void param02(User user) {
		System.out.println("user = " + user);
	}
Copy the code
  • Fourth: Restful style, when parameters are used as access paths
/** * SpringMVC receives parameters in four ways (Restful style is recommended, using parameters as paths, this time should be annotated@PathVariableParameter corresponding to the path parameter) *@param username
	 * @param age
	 */
	@RequestMapping("/param/04/{username}/{password}")
	public void param04(@PathVariable("username")String username,@PathVariable("password")Integer password) {
		System.out.println(username);
		System.out.println(password);
	}
Copy the code
  • Fifth: in fact, with the second is very similar, but the difference is that if the parameter name is inconsistent before and after how to deal with
/** * SpringMVC receives parameters in five ways (can be used when the front and back end parameters are inconsistent)@RequestParam("name") specifies the front end parameter name to be injected into the back end parameter@param username
	 * @param age
	 */
	@RequestMapping("/param/05")
	public void param05(@RequestParam("name")String username,@RequestParam("pword") Integer password) {
		System.out.println(username);
		System.out.println(password);
	}
Copy the code

– Extracting the URL address

  • When we looked at the five parameter types, you can see that we have a param in front of each request, so since I need a param for each request path, can I extract it?

    • Solution: In SrpringMVC, we can use @requestMapping (/ public path) to set the public address of our controller
package cn.itsource.springmvc_01;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

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

@Controller
RequestMapping("") specifies the public path for this class
@RequestMapping("/param2")
public class ParamController {
	
	/** * SpringMVC accepts arguments in one way (recommended) *@param username
	 * @param age
	 */
	@RequestMapping("/01")
	public void param01(String username, Integer age) {
		System.out.println("username = " + username);
		System.out.println("age = " + age);
	}
	
	/** * SpringMVC accepts arguments in the second way (recommended) *@param username
	 * @param age
	 */
	@RequestMapping("/02")
	public void param02(User user) {
		System.out.println("user = " + user);
	}
	
	
	/** * SpringMVC accepts arguments in three ways (not recommended) *@param username
	 * @param age
	 */
	@RequestMapping("/03")
	public void param03(HttpServletRequest request) {
		System.out.println(request.getParameter("username"));
		System.out.println(request.getParameter("password"));
	}
	
	/** * SpringMVC receives parameters in four ways (Restful style is recommended, using parameters as paths, this time should be annotated@PathVariableParameter corresponding to the path parameter) *@param username
	 * @param age
	 */
	@RequestMapping("/04/{username}/{password}")
	public void param04(@PathVariable("username")String username,@PathVariable("password")Integer password) {
		System.out.println(username);
		System.out.println(password);
	}
	
	/** * SpringMVC receives parameters in five ways (can be used when the front and back end parameters are inconsistent)@RequestParam("name") specifies the front end parameter name to be injected into the back end parameter@param username
	 * @param age
	 */
	@RequestMapping("/05")
	public void param05(@RequestParam("name")String username,@RequestParam("pword") Integer password) { System.out.println(username); System.out.println(password); }}Copy the code

Note: the/in front of the path is optional, because SpringMVC will automatically add it for us. But the canonical way to write it let’s write it

– Three ways to pass values to a page

  • We used to back in the Servlet era when we passed values to the front end through our HttpServletRequest, and SpringMVC could pass values in three different ways

  • The first kind of

/** * Mode 1: the way we used to do servlets *@return* /
	@RequestMapping("/transfer03")
	public String transfer03(HttpServletRequest request) {
		request.setAttribute("msg"."Hello word third way!!");
		// Specify the jump path
		return "/WEB-INF/views/index.jsp";
	}
Copy the code
  • The second,
/** * Mode 2: Use Model to encapsulate data *@return* /
	@RequestMapping("/transfer02")
	public String transfer02(Model model) {
		// Encapsulate the data in Model
		model.addAttribute("msg"."Hello word second way!!");
		// Specify the jump path
		return "/WEB-INF/views/index.jsp";
	}
Copy the code
  • The third kind of
/** * Mode 3: Use ModelAndView for data encapsulation, path jump *@return* /
	@RequestMapping("/transfer01")
	public ModelAndView transfer01(a) {
		// Initialize a ModelAndView
		ModelAndView modelAndView = new ModelAndView();
		// Encapsulate data to ModelAndView
		modelAndView.addObject("msg"."Hello word first way!!");
		// Specify the path to jump to
		modelAndView.setViewName("/WEB-INF/views/index.jsp");
		/ / returns ModelAndView
		return modelAndView;
	}
Copy the code

Note: none of the three methods is good or bad, but all can be used

– SpringMVC view parser

  • We can see that when we return to the page, the page path is the same before, and our page type is JSP, so can we extract the common page path, and automatically give us the.jsp suffix?

    • Provided the InternalResourceViewResolver for SpringMvc, used in matching unified view management response;
    • Once used, the response data is parsed by the view parser and then turned to the response page, the response view in the controller is simpler to write;

      
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd"
>
<! -- Id was a globally unique name when we learned about Spring. After introducing SpringMVC, ID is the request path that we exposed.
<! Class is the fully qualified name of the controller -->
<bean id="/hello1.do" class="cn.itsource.springmvc_01.HelloWordController01"></bean>
<bean id="/hello2.do" class="cn.itsource.springmvc_01.HelloWordController02"></bean>

<! This is to configure which package below the annotations need to be scanned -->
<context:component-scan base-package="cn.itsource"/>

<! Static resource release -->
<mvc:default-servlet-handler/>

<! Enable support for springMVC annotations -->
<mvc:annotation-driven/>

<! -- Configure the view parser -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<! -- Add my public path before my access path -->
<property name="Prefix" value="/WEB-INF/views/"></property>
<! -- Add.jsp to the name of my access page -->
<property name="Suffix" value = ".jsp"></property>
</bean>

</beans>
Copy the code

– Four ways for SpringMVC to jump to a page

  • If my prefix and suffix are not the configured view resolver, how do I jump?
package cn.itsource.springmvc_01;

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

@Controller
public class JumpController {
	
	/** * SpringMVC can jump to a path if there is a path under the public path, then we can jump to the previous path *@return* /
	@RequestMapping("/list")
	public String list(a) {
		return "/student/list";
	}
	
	/** * SpringMVC redirects to a page with a suffix that is not a common suffix type specified by you, then you cannot return the path directly * you must return the full path and add forward or redirect * forward: * Redirect: Requests are redirected and the access path changes *@return* /
	@RequestMapping("/01")
	public String list01(a) {
		return "forward:/WEB-INF/views/student/student.html";
	}
	
	/** * If the return type of SpringMVC is ModelAndView, * must also be the full path with forward or redirect * forward: * Redirect: Requests are redirected and the access path changes *@return* /
	@RequestMapping("/02")
	public ModelAndView list02(a) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("forward:/WEB-INF/views/student/student.html");
		return modelAndView;
	}
	
	/** * SpringMVC redirect 4: If it is a static resource in a webapp, * use the forward or redirect redirect to access the page. Redirect, the access path will change *@return* /
	@RequestMapping("/03")
	public String list03(a) {
		return "forward:/student.html"; }}Copy the code

Filter –

  • In the old days when we used servlets, we solved Post garbled by configuring character set encoding req.setEncoding (“UTF-8”) in each Servlet, Using this approach in SpringMVC will not solve our Post garbled problem, so we need to use filters to help us solve the garbled problem

    • A Filter is a Web component that intercepts requests and responses to access;
    • The Filter can be used to intercept and process a resource before it is accessed by the Web container, or to intercept and process a resource before it returns a response to the Web container.

  • Filter writing
    • Write a class that implements the Filter interface and implements all the methods in the interface.
    • Configure or use annotations to configure @webfilter (“/”) in web.xml
package cn.itsource.springmvc_01;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

// The filter path can be configured if annotations are used
@WebFilter("/*")
public class AFilter implements Filter{
	
	/** * executes */ when Tomcat is started
	@Override
	public void init(FilterConfig arg0) throws ServletException {
		System.out.println("Tomcat starts executing the init method of the filter...");
		
	}
	
	/** * Filter core method */
	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("Before release...");
		// Set the character set encoding
		req.setCharacterEncoding("UTF-8");
		// Allow interception
		chain.doFilter(req, resp);
		System.out.println("After release...");
		
	}

	/** * Execute when Tomcat is shut down
	@Override
	public void destroy(a) {}}Copy the code
<! -- Web.xml configure the interception path, if using annotations do not need to configure, either -->
  <filter>
  	<filter-name>first</filter-name>
  	<filter-class>cn.itsource.filter.FirstFilter</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>first</filter-name>
  	<url-pattern>/ *</url-pattern>	
  </filter-mapping>
Copy the code
  • Configure a character encoding filter
    • The SpringMVC framework itself does not handle request encoding, but the Spring framework provides an encoding filter for us. Developers simply need to configure a Spring built-in request encoding filter. Configure a request encoding filter in web.xml:


      

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  version="3.1"
  metadata-complete="false">

	<servlet>
		<! Give the core controller a unique name -->
		<servlet-name>dispatcherServlet</servlet-name>
		<! -- Fully qualified name of core controller -->
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<! -- Init-param tag must be located above load-on-startup -->
		<! Tell the DispatcherServlet core controller where to find the core configuration file.
		<init-param>
		<! -- contextConfigLocation (contextConfigLocation)
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring-MVC.xml</param-value>
		</init-param>
		<! The value of this parameter ranges from 1 to 10. The lower the value, the higher the loading time.
		<load-on-startup>1</load-on-startup>
		
	</servlet>
	<servlet-mapping>
		<servlet-name>dispatcherServlet</servlet-name>
		<! / block all requests (recommended), but it does not block page resources, and supports restful style problems: *. Do: Your request path must end in.do to access my core controller * : Match all meaning. Do: 3./* : also blocks all requests, but it will also block JSP jumps (this is not recommended) -->
		
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
	<! -- Resolve SpringMVC POST submission error -->
	<filter>
	<filter-name>characterEncodingFilter</filter-name>
	<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
	<! -- Specify character encoding set -->
	<init-param>
	<param-name>encoding</param-name>
	<param-value>UTF-8</param-value>
	</init-param>
	<! -- Enforces a character encoding, even if request or Response has a character encoding, the current setting will be enforces, in any case enforces this encoding -->
	<init-param>
	<param-name>forceEncoding</param-name>
	<param-value>true</param-value>
	</init-param>
	</filter>
	<filter-mapping>
	<filter-name>characterEncodingFilter</filter-name>
	<url-pattern>/ *</url-pattern>
	</filter-mapping>
	
</web-app>

Copy the code

That’s the end of SpringMVC fundamentals