In depth understanding and learning of spring MVC - Basics

Keywords: Java Spring MVC

SpringMVC

1, Introduction to spring MVC

1. What is spring MVC?

The framework Spring MVC framework developed on the basis of Spring is the controller framework C-layer framework (struts 2 is also the C-layer framework)

Essence: replace the struts 2 framework as a controller

In order to enable Spring to plug into MVC architecture, Spring framework develops Spring MVC framework based on Spring, so you can choose to use Spring's Spring MVC framework as the controller framework of web development when using Spring for web development.

  • MVC development mode
1,M Model layer entity+dao+Service
2,V View layer  WebApp Page under root HTml+Jsp
3,C Control layer   Action/Controller Struts2/SpringMVC

2. SpringMvc benefits

(1)SpringMvc be based on Spring Framework development, and Spring Seamless integration of framework
(2)SpringMvc The operating efficiency is higher than Struts2
    (Spring Object defaults to singleton mode, but Struts2 Is a multi instance mode,Save running time)
(3)SpringMvc It supports annotation development, which is simple, fast and more efficient

3. Summary

Spring MVC controller framework based on Spring Development

1,receive data 
2,Call service
3,Jump page

Spring MVC is lightweight and a typical MVC framework. It acts as a controller framework in the whole MVC architecture. Compared with struts 2 framework, spring MVC runs faster and its annotation development is more efficient and flexible.

2, Component parsing of spring MVC

1. Execution process of struts 2

Client request:

1. after web.xml Medium Struts2 Core filter to deliver user requests to Struts2,
2. First pass Struts.xml of package Lower namespance
3,Find it again action Medium name load Class Lower Action Class through reflection or Class Methods in
4,stay Action Method, call the service, and jump to the page
5,Return to Result,Load jump page
6,Return to the client through the filter again, and return the corresponding results to the corresponding user

2. Execution process of spring MVC

Client request:

1,First pass Web.xml Intercept request forward request(DispatcherServlet)to SpringMvc
2,Processor mapper(RequesMappingHandelMapping)Resolve request path
3,On class RequestMapping(Equivalent to Struts2 Medium namespace to configure)
4,Methodological RequestMapping(Equivalent to Struts2 Medium Action of name Attribute value)
5,Receive data from the front end RequestMappingHandelAdapter The processor adapter is responsible for receiving and parsing data
6,InternalResourceViewResolver view resolver 
   (Parse the return value and prefix the current jump position/And suffix.jsp)
   Return result: 
       Prefix:/
       suffix:.jsp
       Results: prefix+Returned string+suffix

3. Detailed execution process:

(1)The user sends a request to the front-end controller DispatcherServlet. 

(2)DispatcherServlet Request call received HandlerMapping Processor mapper.

(3)The processor mapper finds the specific processor(Can be based on xml Configuration and annotation for searching),
    Generate processor object and processor interceptor(Generate if any)Return to DispatcherServlet. 
(4)DispatcherServlet call HandlerAdapter Processor adapter.

(5)HandlerAdapter The specific processor is called after adaptation(Controller,Also called back-end controller). 

(6)Controller Execution completion return ModelAndView. 

(7)HandlerAdapter take controller results of enforcement ModelAndView Return to DispatcherServlet. 

(8)DispatcherServlet take ModelAndView Pass to ViewReslover View parser.

(9)ViewReslover Return specific information after parsing View. 

(10)DispatcherServlet according to View Render the view (that is, fill the view with model data). DispatcherServlet Respond to the user.

4. Spring MVC component parsing

(1) Front end controller: dispatcher Servlet

When the user requests to reach the front-end controller, it is equivalent to C in MVC mode. The dispatcher servlet is the center of the whole process control

It calls other components to process user requests. The existence of dispatcher servlet reduces the coupling between components.

(2) Processor mapper: HandlerMapping

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 functions

Mapping mode, such as configuration file mode, implementation interface mode, annotation mode, etc.

(3) Processor adapter: HandlerAdapter

The processor is executed through the HandlerAdapter, which is an application of adapter mode. More types of processing can be performed through the extension adapter

The actuator.

(4) Processor: Handler

It is the specific business controller to be written in our development. The dispatcher servlet forwards the user request to the Handler. from

Handler handles specific user requests.

(5) View resolver: View Resolver [r ɪ’ z ɒ lv ə]

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.

(6) Views: View

Spring MVC framework provides support for many View types, including jstlView, freemarkerView, pdfView, etc. the most commonly used View is jsp. Generally, model data needs to be displayed to users through pages through page tags or page template technology, and programmers need to develop specific pages according to business needs

3, The first spring MVC project

1. Introduce related dependencies

 <!--junit-->
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-core</artifactId>
          <version>4.3.2.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>4.3.2.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context-support</artifactId>
          <version>4.3.2.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-jdbc</artifactId>
          <version>4.3.2.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-aop</artifactId>
          <version>4.3.2.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-beans</artifactId>
          <version>4.3.2.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-expression</artifactId>
          <version>4.3.2.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-aspects</artifactId>
          <version>4.3.2.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-tx</artifactId>
          <version>4.3.2.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-web</artifactId>
          <version>4.3.2.RELEASE</version>
      </dependency>
      <!--springmvc Core dependency-->
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>4.3.2.RELEASE</version>
      </dependency>
      <!--servlet-api-->
      <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>servlet-api</artifactId>
          <version>2.5</version>
          <scope>provided</scope>

2. Write the spring MVC configuration file (applicationContext.xml)

  <!--Enable annotation scanning: component:assembly[kəmˈpoʊnənt]-->
    <context:component-scan base-package="com.tjcu"></context:component-scan>
    <!--Register processor mapper-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>
    <!--Register processor adapter-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean>
    <!--Register view parser-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--prefix:[ˈpriːfɪks] prefix-->
        <property name="prefix" value="/"></property>
        <!--suffix: [ˈsʌfɪks] suffix-->
        <property name="suffix" value=".jsp"></property>
    </bean>

3. Configure the core Servlet of spring MVC

  <!--Responsible for forwarding requests-->
    <servlet>
        <servlet-name>mvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--appoint mvc The location and name of the configuration file-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>mvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
  • Note: the spring configuration is also loaded here by writing init in the servlet ­ param tag, or contextConfigLocation attribute, value is used to load the spring MVC configuration file

  • The default Servlet singleton is created at the first request. If you don't want to write < init param >, you can put the configuration file under Web-INF and name it mvc-servlet.xml

4. Create controller

//Responsible for control layer component object creation
@Controller("userController")
//The controller mapper on class is equivalent to the namespace in struts 2
@RequestMapping("user")
public class UserController{
    //Method, which is equivalent to name in Struts
    @RequestMapping("queryAll")
    public String queryAll(){
        System.out.println("A lot of data was queried");
        //Parsing result: prefix + return value + suffix
        return "index";
    }
  • @Controller: this annotation is used to identify this is a controller component class and create an instance of this class

  • @RequestMapping:

Modification scope: used on methods or classes

Annotation function: used to specify the request path of the class and the methods in the class

Notes:

When used on a class, it is equivalent to the namespace in struts 2. Methods in the access class must first add this path

The name attribute, which is equivalent to the action tag on the method, is used to indicate the path to access the method

5. Deploy the project and start project testing

Access path: http://localhost:8080/SpringMvc/user/queryAll

6. Summary of development steps of spring MVC

① import spring MVC related coordinates (spring, servlet API, spring MVC, etc.)

② configure the spring MVC core controller DispathcerServlet

③ create Controller class and view page

④ use the annotation to configure the mapping address of the business method in the Controller class

⑤ configure SpringMVC core file SpringMVC.xml (three core components)

⑥ client initiated request test

4, Jump mode in spring MVC

1. Jump mode

Note: there are two ways to jump: forward and * * redirect * *[ ˌ ri ː d əˈ rekt ].

(1) Servlet jump mode [bottom layer]

#forward jump,
Once requested, the address bar remains unchanged and can be used request Scope pass data,

#redirect jumps multiple times,
The address bar has changed and the scope cannot be used

(2) Jump mode in struts 2 (distinguish the target resource type of jump)

#Action--->jsp
  forward[default] type="dispatcher"
  redirect      type="redirect"

#Action--->Action
   forward    type="chain"
   redirect   type="redirectAction"

(3) Spring MVC jump mode

# 1.Controller jumps to JSP
   forward Jump to page: Default is forward Jump
                     Syntax: return "Business logic name"
                     example: return "showUer"---->/showUser.jsp
                     
   redirect Jump to page: Using SpringMVC provide rediret:Keyword to redirect page Jump
                 Syntax: return "redirect:/index.jsp"
                 Note: use redirect The jump page does not pass through the view parser
                 
# 2. Jump to Controller

   forward Jump to Controller: 
   use SpringMvc Keywords provided forward
   Syntax: forward:/Jump class@requestMapping Value of/Method in jump class@RequestMapping Value of
   example: return "forward:test:/";  
   
   redirect Jump to Controller:use SpringMvc Keywords provided redirect
   Syntax: redirect:/Jump class@requestMapping Value of/Method in jump class@RequestMapping Value of
  • forward jump to page (. jsp) diagram:

  • Schematic diagram of redirect to page (. jsp):

  • forward method: schematic diagram of controller layer jumping to another controller:

  • If you skip a controller method of this class, see the diagram below:

  • redirect method: schematic diagram of controller layer jumping to another controller:

2. Jump method summary

5, Parameter receiving in spring MVC

Syntax description of receiving parameters: Spring MVC uses the controller method parameters to collect the request parameters of the client. Therefore, when receiving the request parameters, the controller method declaration is directly required. Spring MVC can automatically complete the type conversion operation according to the specified type

1. Receive parameters of scattered type

For example: eight basic types + String + date type

  • The parameter name of the business method in the Controller should be consistent with the name of the request parameter, and the parameter value will be mapped and matched automatically. And can automatically type

transformation;

  • Automatic type conversion refers to the conversion from String to other types

(1) Front end transfer parameters

#Pass parameters in get mode
http://localhost:8080/SpringMvc/user/register?
      name=Wang Hengjie&password=234&sex=true&birthday=1999/12/03&salary=20000
      
#Pass parameters in post mode
<form action="${pageContext.request.contextPath}/user/register" method="posst">
  full name:<input type="text" name="name"><br/>
  password:<input type="password" name="password"><br/>
  Gender:<input type="text" name="sex"><br/>
  birthday:<input type="text" name="birthday"><br/>
  Salary:<input type="text" name="salary"><br/>
    <input type="submit" value="Submit"><br/>
</form>

(2) Background Controller receives data

//Responsible for control layer component object creation
@Controller("userController")
//The controller mapper on class is equivalent to the namespace in struts 2
@RequestMapping("user")
public class UserController {
    @RequestMapping("register")
    public String register(String name, String password, Boolean sex, Date birthday, Double salary) {
        System.out.println("login was successful");
        System.out.println("full name" + name);
        System.out.println("password" + password);
        System.out.println("Gender" + sex);
        System.out.println("birthday" + birthday);
        System.out.println("wages" + salary);
        return "index";
    }

  • Note: when spring MVC receives date type parameters, the date format must be yyyy/MM/dd HH:mm:ss

2. Receive object type parameters

(1) Front end transfer parameters

<form action="${pageContext.request.contextPath}/user/register" method="get">
  full name:<input type="text" name="name"><br/>
  password:<input type="password" name="password"><br/>
  Gender:<input type="text" name="sex"><br/>
  birthday:<input type="text" name="birthday"><br/>
  Salary:<input type="text" name="salary"><br/>
    <input type="submit" value="Submit"><br/>
</form>
  • Note: when receiving object type parameters, unlike struts 2, spring MVC automatically encapsulates the object according to the consistency between the passed parameter name and the attribute name in the object

(2) Background Controller receives data

  • Entity class
public class User implements Serializable {
    private static final Long serialVersionUID=1L;
    private String name;
    private String password;
    private String sex;
    private String birthday;
    private String Salary;
  • Receive front-end data in the controller
//Responsible for control layer component object creation
@Controller("userController")
//The controller mapper on class is equivalent to the namespace in struts 2
@RequestMapping("user")
public class UserController{
    @RequestMapping("register")
    public String register(User user){
        System.out.println("login was successful");
        System.out.println("full name"+user.getName());
        System.out.println("password"+user.getPassword());
        System.out.println("Gender"+user.getSex());
        System.out.println("birthday"+user.getBirthday());
        System.out.println("wages"+user.getSalary());
        return "redirect:/index.jsp";
    }

3. Receive array type parameters

(1) Front end transfer parameters

(2) Background Controller receives data

//Responsible for control layer component object creation
@Controller("userController")
//The controller mapper on class is equivalent to the namespace in struts 2
@RequestMapping("user")
public class UserController{
    @RequestMapping("register")
    public String register(User user, String[] hobby){
        System.out.println("login was successful");
        System.out.println("full name:"+user.getName());
        System.out.println("password:"+user.getPassword());
        System.out.println("Gender:"+user.getSex());
        System.out.println("birthday:"+user.getBirthday());
        System.out.println("wages:"+user.getSalary());
        System.out.println("hobby:");
        for (String s : hobby) {
            System.out.println(s);
        }
        return "redirect:/index.jsp";
    }

4. Spring MVC receive parameter Chinese garbled code solution

(1) When using post to receive request parameters, the problem of Chinese garbled data is solved

   <filter-class>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>charset</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

(2) Chinese garbled code in set mode

Change tomcat's server.xml configuration file to add URIEncoding="UTF-8" on more than 50 lines

# 1. For GET Chinese garbled code solution:
<Connector connectionTimeout="20000"
             port="8080" 
             protocol="HTTP/1.1" 
            redirectPort="8443" URIEncoding="UTF-8"/>

  • After successful setting, the received data will not be garbled!

5. Receive collection type parameters

Note: Spring MVC does not support directly declaring the receiving set as a controller method parameter for receiving. If you want to receive the set type parameter, you must use an object to encapsulate the receiving type

(1) Front end transfer parameters

<form action="${pageContext.request.contextPath}/user/register" method="post">
    full name:<input type="text" name="name"><br/>
    password:<input type="password" name="password"><br/>
    Gender:<input type="text" name="sex"><br/>
    birthday:<input type="text" name="birthday"><br/>
    Salary:<input type="text" name="salary"><br/>
    <span> Hobbies:</span>
    having dinner:<input type="checkbox" name="hobby" value="having dinner">
    Sleep?<input type="checkbox" name="hobby" value="sleep">
    AI Yang Fujun:<input type="checkbox" name="hobby" value="Love Yang Fujun">
    Smoking:<input type="checkbox" name="hobby" value="smoking">
    Drinking:<input type="checkbox" name="hobby" value="drink">
    have a perm:<input type="checkbox" name="hobby" value=" have a perm">
    <br/>
    <span> Good at technology:</span><br>
    <input type="checkbox" name="lists" value="python">python<br>
    <input type="checkbox" name="lists" value="java">java<br>
    <input type="checkbox" name="lists" value="c++"> c++<br>
    <input type="checkbox" name="lists" value="linux">linux<br>
    <input type="checkbox" name="lists" value="computer network">computer network<br>
    <input type="checkbox" name="lists" value="go">go<br>
    <br/>
    <input type="submit" value="Submit"><br/>
</form>

(2) Background Controller interface

// 1. Encapsulate and receive collection type objects ----- > used to receive collection type parameters in spring mvc
class Collection{
    private List<String> lists;

    public List<String> getLists() {
        return lists;
    }

    public void setLists(List<String> lists) {
        this.lists = lists;
    }
}

// 2. Receive set type parameters in the controller
//Responsible for control layer component object creation
@Controller("userController")
//The controller mapper on class is equivalent to the namespace in struts 2
@RequestMapping("user")
public class UserController{
    @RequestMapping("register")
    public String register(User user, String[] hobby,Collection collection){
        System.out.println("login was successful");
        System.out.println("full name:"+user.getName());
        System.out.println("password:"+user.getPassword());
        System.out.println("Gender:"+user.getSex());
        System.out.println("birthday:"+user.getBirthday());
        System.out.println("wages:"+user.getSalary());

        System.out.println("hobby:");
        for (String s : hobby) {
            System.out.print(s);
        }

        //Line feed
        System.out.println();

        System.out.println("Personal skills");
        for (String list : collection.getLists()) {
            System.out.print(list+" ,");
        }
        return "redirect:/index.jsp";
    }

(3) Receive set and array data using Lambda optimization

  • Error reason: JDK8 version or above is required to use Lambda

  • After optimization, the c ontroller receives the data code
class Collection{
    private List<String> lists;

    public List<String> getLists() {
        return lists;
    }

    public void setLists(List<String> lists) {
        this.lists = lists;
    }
}

//Responsible for control layer component object creation
@Controller("userController")
//The controller mapper on class is equivalent to the namespace in struts 2
@RequestMapping("user")
public class UserController{
    @RequestMapping("register")
    public String register(User user, String[] hobby,Collection collection){
        System.out.println("login was successful");
        System.out.println("full name:"+user.getName());
        System.out.println("password:"+user.getPassword());
        System.out.println("Gender:"+user.getSex());
        System.out.println("birthday:"+user.getBirthday());
        System.out.println("wages:"+user.getSalary());

        //Optimized version, using Lambda expressions to receive sets and arrays
        System.out.println("hobby:");
        Arrays.asList(hobby).forEach(item -> System.out.println(item));

        //Line feed
        System.out.println();

        System.out.println("Personal skills");
        collection.getLists().forEach(name-> System.out.println(name));
        return "redirect:/index.jsp";
    }

}

6, Data transfer mechanism in spring MVC

1. Data transmission mechanism

# 1. How to save data
      Servlet Scope         Struts2  Scope        SpringMVC Scope
# 2. How to get data
      Servlet EL expression      Struts2  EL expression      SpringMVC EL expression
# 3. How to display data    
      Servlet JSTL label      Struts2  JSTl label     SpringMVC  JSTl label

2. Use forward jump to transfer data

# 1. Use the original request scope in the servlet to transfer data
    request.setAttribute("key",value);
   

# 2. The Model and ModelMap objects encapsulated in spring MVC are used (the request scope is encapsulated at the bottom)
    model.addAttribute(key,value);
    modelMap.addAttribute(key,value);

(1) Pass data using the original request scope in the servlet

#How to obtain the request object and response object in the spring MVC controller method? 

 Note: direct request,response Object is declared as a controller method parameter 
  • The controller layer uses request to pass data
   //Method, which is equivalent to name in Struts
    @RequestMapping("queryAll")
    public String queryAll(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("SpringMvc use Request data");
        request.setAttribute("name","Wang Hengjie");
        //Parsing result: prefix + return value + suffix
        return "index";
    }
  • The client uses EL to receive data
<%@page  pageEncoding="UTF-8" isELIgnored="false" %>
<html>
<body>
<h2>Display user data</h2>
SpringMVC use request Data transferred, jsp use EL Receive data: ${requestScope.name}
</body>
</html>

(2) Saving data using Model objects

3. Use Redirect to transfer data

# 1. Use the address bar for data transmission
   url?name=zhangsan&age=21

# 2. Use session scope
  session.setAttribute(key,value);
  session.getAttribute(key);
   //Method, which is equivalent to name in Struts
    @RequestMapping("queryAll")
    public String queryAll(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("SpringMvc use Request data");
        request.setAttribute("name","Wang Hengjie");
        //Parsing result: prefix + return value + suffix
        return "index";
    }
  • The client uses EL to receive data
<%@page  pageEncoding="UTF-8" isELIgnored="false" %>
<html>
<body>
<h2>Display user data</h2>
SpringMVC use request Data transferred, jsp use EL Receive data: ${requestScope.name}
</body>
</html>

(2) Saving data using Model objects

3. Use Redirect to transfer data

# 1. Use the address bar for data transmission
   url?name=zhangsan&age=21

# 2. Use session scope
  session.setAttribute(key,value);
  session.getAttribute(key);

Posted by jjoves on Thu, 18 Nov 2021 07:14:28 -0800