Spring MVC basic application

Main contents of course tasks:

* SpringMVC brief introduction
* SpringMVC Component overview
* SpringMVC request
* SpringMVC response
* Static resource on

I. Introduction to spring MVC

1.1 MVC mode

MVC is a software architecture pattern in software engineering. It is a development idea that separates business logic and display interface.

* M(model)Model: process business logic and encapsulate entities

* V(view) Views: displaying content

* C(controller)Controller: responsible for dispatching and distribution (1).Receive request, 2.Call model, 3.Forward to view)

1.2 spring MVC overview

Spring MVC is a lightweight Web framework based on Java to implement MVC design pattern. It is a follow-up product of spring framework and has been integrated into Spring Web Flow.

Spring MVC has become one of the most mainstream MVC frameworks, and with the release of spring 3.0, it has comprehensively surpassed struts 2 and become the best MVC framework. Through a set of annotations, it makes a simple Java class a controller for processing requests without implementing any interface. It also supports RESTful programming style requests.

summary

The framework of spring MVC encapsulates the common behavior in the original Servlet; For example: parameter encapsulation, view forwarding, etc.

1.3 spring MVC quick start

demand

The client initiates the request, the server receives the request, executes logic and jumps the view.

Step analysis

1. establish web Projects, importing SpringMVC Related coordinates

2. to configure SpringMVC Front end controller DispathcerServlet

3. to write Controller Classes and view pages

4. Use annotation configuration Controller Mapping address of business method in class

5. to configure SpringMVC Core document spring-mvc.xml

1) Create a web project and import spring MVC related coordinates

<!-- Set to web engineering -->
<packaging>war</packaging>
<dependencies>
    <!--springMVC coordinate-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.1.5.RELEASE</version>
    </dependency>
    <!--servlet coordinate-->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>
    <!--jsp coordinate-->
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.2</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

2) Configuring the spring MVC front-end controller DispathcerServlet

<?xml version="1.0" encoding="UTF-8"?>
<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_4_0.xsd"
         version="4.0">

    <!-- springMVC Front end controller: DispatcherServlet-->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- Load core profile -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <!-- When the application starts, it is completed servlet Instantiation and initialization of -->
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <!-- /: It will match all access paths, but it will not match images*.jsp In this way url -->
        <!-- /and/*Differences between
             /: You can match to a path without a suffix, similar to:/login /add,But cannot match with suffix:/a.jsp
             /*: All access paths can be matched
        -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

3) Writing Controller classes and view pages

UserController.java

public class UserController {
    
    public String quick() {
        System.out.println("quick running.....");
        return "/WEB-INF/pages/success.jsp";
    }
}

/WEB-INF/pages/ success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>success</title>
</head>
<body>
    <h3>Request succeeded!</h3>
</body>
</html>

4) Use the annotation to configure the mapping address of the business method in the Controller class

@Controller
public class UserController {
    
    @RequestMapping("/quick")
    public String quick() {
        System.out.println("quick running.....");
        return "/WEB-INF/pages/success.jsp";
    }
}

5) Configure spring MVC core file spring-mvc.xml

<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">
    
    <!--Configure annotation scanning-->
    <context:component-scan base-package="com.lagou.controller"/>
    
</beans>

1.4 web project execution process

1.5 knowledge summary

* SpringMVC Yes MVC An implementation of design pattern, which belongs to lightweight WEB Frame.

* SpringMVC Development steps:
    1.establish web Projects, importing SpringMVC Related coordinates
    2.to configure SpringMVC Front end controller DispathcerServlet
    3.to write Controller Classes and view pages
    4.Use annotation configuration Controller Mapping address of business method in class
    5.to configure SpringMVC Core document spring-mvc.xml

II. Overview of spring MVC components

2.1 execution process of spring MVC

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).

11. DispatcherServlet The rendered view responds to the user.

2.2 spring MVC component parsing

1. Front end controller: DispatcherServlet
    When a user request reaches the front-end controller, it is equivalent to MVC In mode C,**DispatcherServlet It is the center of the whole process control, which calls other components to process user requests, DispatcherServlet The existence of reduces the coupling between components.
    
2. Processor mapper: HandlerMapping
     **HandlerMapping Responsible for finding according to the user's request Handler Processor**,SpringMVC Different mappers are provided to implement different mapping modes, such as configuration file mode, implementation interface mode, annotation mode, etc.
     
3. Processor adapter: HandlerAdapter
    adopt HandlerAdapter Execute on the processor. This is an application of adapter mode. More types of processors can be executed by extending the adapter.
    
4. Processor: Handler[**Written by developers**]
    **It is the specific business controller to be written in our development.**from DispatcherServlet Forward user requests to Handler. from Handler Process specific user requests.
    
5. View parser: ViewResolver
    **View Resolver Responsible for generating processing results View View,**View Resolver First, the logical view name is resolved into the physical view name, that is, the specific page address, and then generated View View objects, and finally View Render and display the processing results to the user through the page.
    
6. View: View [**Written by developers**]
    SpringMVC The framework provides a lot of View Support for view types, including: jstlView,freemarkerView,pdfView Wait.**The most common view is jsp. Generally, the model data needs to be displayed to users through pages through page label or page template technology. Programmers need to develop specific pages according to business requirements.**
    
    ***Written test questions: springmvc What are the three components in?
    	Processor mapper, processor adapter and view parser (four components including front-end controller)
<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">
    
    <!-- open IOC Annotation scan -->
    <context:component-scan base-package="com.soldier"/>

    <!-- The processor mapper and processor adapter are configured and enhanced: support json Reading and writing-->
    <mvc:annotation-driven/>
    
    <!-- To configure the view parser: ViewResolver -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- success: Resolve the logical view name into a specific physical file address, and resolve it through the splicing of prefix and suffix-->
        <!-- prefix -->
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <!-- suffix -->
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans>

2.3 spring MVC annotation parsing

@Controller

Spring MVC is based on the spring container, so during spring MVC operation, you need to store the Controller in the spring container. If you use the @ Controller annotation, you need to use:

<!--Configure annotation scanning-->
<context:component-scan base-package="com.lagou.controller"/>

@RequestMapping

* effect:
    **Used to establish the request URL And processing request methods
    
* Location:
    1.**On class: request URL First level access directory for.**If it is not written here, it is equivalent to the root directory of the application. What you write needs to be written in English/start.
        The purpose of its emergence is to make our URL It can be managed according to modularity:
            User module
                /user/add
                /user/update
                /user/delete
                ...
            Account module
                /account/add
                /account/update
                /account/delete
    2.**Method: request URL The second level access directory and the first level directory form a complete directory URL route.**
* Properties:
    1.value: Used to specify the of the request URL. It and path The function of attribute is the same
    2.method: Used to define the way of the request
    3.params: Conditions used to qualify request parameters
     For example: params={"accountName"} Indicates that there must be in the request parameters accountName
          pramss={"money!100"} Indicates in the request parameter money Can't be 100
package com.soldier.controller;

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

@Controller
@RequestMapping("/user") //First level access directory
/*
    path: The function is equivalent to value, which is also the mapping address of the setting method
    method: RequestMethod.POST: this method can only be accessed in the form of post request, and other request methods will report errors
    params: The condition params={"accountName"} used to qualify the request parameters indicates that there must be accountName in the request parameters
 */
public class UserController {

    //http://localhost:8080/springmvc_quickstart/user/quick / primary access directory / secondary access directory
    @RequestMapping(path = "/quick",method = RequestMethod.POST,params={"accountName"} ) // Secondary access directory
    public String quick(){

        // Business logic
        System.out.println("springmvc Successful entry...");

        // View jump
        return "success";
    }

    @RequestMapping("/quick2")
    public String quick2(){

        // Business logic
        System.out.println("springmvc Successful entry...");

        // View jump
        return "a";
    }

    @RequestMapping("/quick3")
    public String quick3(){

        // Business logic
        System.out.println("springmvc Successful entry...");

        // View jump
        return "b";
    }
}

2.4 knowledge summary

* SpringMVC Three components of
    Processor mapper: HandlerMapping
    Processor adapter: HandlerAdapter
    View parser: View Resolver
    
* Written by developers
    Processor: Handler
    View: View

Three spring MVC requests

3.1 introduction to request parameter types

The format of client request parameters is: name = value & name = value

When the server wants to obtain the requested parameters, it needs type conversion and sometimes data encapsulation

Spring MVC can receive the following types of parameters:

  • Basic type parameters
  • Object type parameter
  • Array type parameter
  • Set type parameter

3.2 obtaining basic type parameters

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 do type conversion; Automatic type conversion refers to the conversion from String to other types.

<a href="${pageContext.request.contextPath}/user/simpleParam?id=1&username=jack">
    Basic type
</a>
@RequestMapping("/simpleParam")
public String simpleParam(Integer id,String username) {
    System.out.println(id);
    System.out.println(username);
    return "success";
}

3.3 obtaining object type parameters

The POJO attribute name of the business method parameter in the Controller is consistent with the name of the request parameter, and the parameter value will be mapped and matched automatically.

<form action="${pageContext.request.contextPath}/user/pojoParam" method="post">
    No.:<input type="text" name="id"> <br>
    user name:<input type="text" name="username"> <br>
    <input type="submit" value="object type">
</form>
public class User {
    
    Integer id;
    String username;
    // setter getter...
}
@RequestMapping("/pojoParam")
public String pojoParam(User user) {
    System.out.println(user);
    return "success";
}

3.4 Chinese garbled code filter

When post requests, the data will be garbled. We can set a filter to filter the encoding.

<!--Configuring global filtering filter-->
<filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <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>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

3.5 get array type parameters

The name of the business method array in the Controller is consistent with the name of the request parameter, and the parameter value will be mapped and matched automatically.

<form action="${pageContext.request.contextPath}/user/arrayParam">
    No.:<br>
    <input type="checkbox" name="ids" value="1">1<br>
    <input type="checkbox" name="ids" value="2">2<br>
    <input type="checkbox" name="ids" value="3">3<br>
    <input type="checkbox" name="ids" value="4">4<br>
    <input type="checkbox" name="ids" value="5">5<br>
    <input type="submit" value="Array type">
</form>
@RequestMapping("/arrayParam")
public String arrayParam(Integer[] ids) {
    System.out.println(Arrays.toString(ids));
    return "success";
}

3.6 get set (complex) type parameters

When obtaining set parameters, the set parameters should be wrapped in a POJO.

<form action="${pageContext.request.contextPath}/user/queryParam" method="post">
    Search keywords:
    <input type="text" name="keyword"> <br>
    user Object:
    <input type="text" name="user.id" placeholder="number">
    <input type="text" name="user.username" placeholder="full name"><br>
    list aggregate<br>
    First element:
    <input type="text" name="userList[0].id" placeholder="number">
    <input type="text" name="userList[0].username" placeholder="full name"><br>
    Second element:
    <input type="text" name="userList[1].id" placeholder="number">
    <input type="text" name="userList[1].username" placeholder="full name"><br>
    map aggregate<br>
    First element:
    <input type="text" name="userMap['u1'].id" placeholder="number">
    <input type="text" name="userMap['u1'].username" placeholder="full name"><br>
    Second element:
    <input type="text" name="userMap['u2'].id" placeholder="number">
    <input type="text" name="userMap['u2'].username" placeholder="full name"><br>
    <input type="submit" value="Complex type">
</form>
public class QueryVo {
    
    private String keyword;
    private User user;
    private List<User> userList;
    private Map<String, User> userMap;
}
@RequestMapping("/queryParam")
public String queryParam(QueryVo queryVo) {
    System.out.println(queryVo);
    return "success";
}

3.7 custom type converter

Spring MVC already provides some common type converters by default; For example, the string submitted by the client is converted to int for parameter setting. The date format type is required to be yyyy/MM/dd, otherwise an error will be reported. For unique behaviors, spring MVC provides a user-defined type converter to facilitate developers to customize processing.

<form action="${pageContext.request.contextPath}/user/converterParam">
    birthday:<input type="text" name="birthday">
    <input type="submit" value="Custom type converter">
</form>
public class DateConverter implements Converter<String, Date> {
    public Date convert(String dateStr) {
        //Returns a date string converted to a date object
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = format.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
}
<!--Processor mapper and adapter enhancements-->
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
<!--Custom converter configuration-->
<bean id="conversionService" 
class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <bean class="com.lagou.converter.DateConverter"></bean>
        </set>
    </property>
</bean>
@RequestMapping("/converterParam")
public String converterParam(Date birthday) {
    System.out.println(birthday);
    return "success";
}

3.8 relevant notes

@RequestParam

When the requested parameter name is inconsistent with the business method parameter name of the Controller, the binding displayed through the @ RequestParam annotation is required

<a href="${pageContext.request.contextPath}/user/findByPage?pageNo=2">
    Paging query
</a>
/*
   @RequestParam() annotation
      defaultValue Set parameter defaults
      name  Matches the name of the page pass parameter
      required Set whether parameters must be passed. The default value is true; If the default value is set, the value is automatically changed to false
*/
@RequestMapping("/findByPage")
public String findByPage(@RequestParam(name = "pageNo", defaultValue = "1") 
Integer pageNum, @RequestParam(defaultValue = "5") Integer pageSize) {
    System.out.println(pageNum);
    System.out.println(pageSize);
    return "success";
}

@RequestHeader

Gets the data of the request header.

@RequestMapping("/requestHead")
public String requestHead(@RequestHeader("cookie") String cookie) {
    System.out.println(cookie);
    return "success";
}

@CookieValue

Get the data in the cookie.

@RequestMapping("/cookieValue")
public String cookieValue(@CookieValue("JSESSIONID") String jesessionId) {
    System.out.println(jesessionId);
    return "success";
}

3.9 get Servlet related API s

Spring MVC supports using the original servlet API object as the parameter of the controller method for injection. The common objects are as follows:

@RequestMapping("/servletAPI")
public String servletAPI(HttpServletRequest request, HttpServletResponse 
response, HttpSession session) {
    System.out.println(request);
    System.out.println(response);
    System.out.println(session);
    return "success";
}

IV. response of spring MVC

4.1 introduction to spring MVC response mode

Page Jump

  1. Return string logical view
  2. void raw servlet API
  3. ModelAndView

Return data

  1. Directly return string data
  2. Turn the object or collection into json return (Task 2 demonstration)

4.2 return string logic view

Directly return string: this method will splice the returned string with the pre suffix of the view parser and jump to the specified page

@RequestMapping("/returnString")
public String returnString() {
    return "success";
}

4.3 void original servlet API

We can implement the response through request and response objects

/*
        Page Jump through the original servlet API
     */
    @RequestMapping("/returnVoid")
    public void returnVoid(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {

        // Direct return data
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("Chinese Red");
        
        // Complete request forwarding with request object
        //request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);

        // Redirect the WEB-INF: Secure directory with the help of the response object. External requests are not allowed to directly access the directory resources, but can only be forwarded within the server
        /response.sendRedirect(request.getContextPath() + "/index.jsp");
    }

4.4 forwarding and redirection

In enterprise development, we generally use the return string logical view to realize page Jump. This method is actually request forwarding.

We can also write forward

If forward: is used, the path must be written as the actual view url, not the logical view. It is equivalent to:

request.getRequestDispatcher("url").forward(request,response)

With request forwarding, it can be forwarded to jsp or other controller methods.

/*
        Demonstrates the forward keyword for request forwarding
     */
    @RequestMapping("/forward")
    public String forward(Model model){

        // What if you want to set some values in the model?
        model.addAttribute("username","China");

        // With request forwarding, it can be forwarded to jsp or other controller methods
        return "forward:/WEB-INF/pages/success.jsp";
    }

Redirect redirect

We can not write the virtual directory. The spring MVC framework will automatically splice the data in the Model to the url address

/*
        Demonstrate the Redirect keyword for redirection: for secondary requests, the bottom layer of the model model uses the request.setAttribute() field,
        The scope of the domain is a request. The redirection is beyond the scope of the domain and the value in the model cannot be retrieved
            When the redirect or forward keyword is written, the view parser will not be used for splicing
     */
    @RequestMapping("/redirect")
    public String redirect(Model model){

        // The bottom layer of the model still uses the request.setAttribute("username", "Chinese red") domain. Domain scope: one request redirection: two requests
        model.addAttribute("username","Chinese Red");

        return "redirect:/index.jsp";
    }

4.5 ModelAndView

4.4.1 mode I

The ModelAndView object is created and returned by the method in the Controller, and the view name is set

@RequestMapping("/returnModelAndView1")
public ModelAndView returnModelAndView1() {
    /*
        Model:Model action encapsulates data
        View: View function: display data
    */
    ModelAndView modelAndView = new ModelAndView();
    //Set model data
    modelAndView.addObject("username", " lagou");
    //Set view name
    modelAndView.setViewName("success");
    return modelAndView;
}

4.4.2 mode II

You can directly declare ModelAndView on the method parameter in the Controller without creating it in the method. You can also jump to the page by directly using the object in the method to set the view

@RequestMapping("/returnModelAndView2")
public ModelAndView returnModelAndView2(ModelAndView modelAndView) {
    //Set model data
    modelAndView.addObject("username", "itheima");
    //Set view name
    modelAndView.setViewName("success");
    return modelAndView;
}

4.6 @SessionAttributes

If data is shared among multiple requests, you can mark a @ SessionAttributes on the controller class to configure the data range to be stored in the session. Spring MVC will temporarily store the corresponding data stored in the model in HttpSession.

Note: @ SessionAttributes can only be defined on a class

@Controller
@SessionAttributes("username") //When the key stored in the request domain is username, it is synchronized to the session domain
public class UserController {
    @RequestMapping("/forward")
    public String forward(Model model) {
        model.addAttribute("username", "Zi Mu");
        return "forward:/WEB-INF/pages/success.jsp";
    }
    @RequestMapping("/returnString")
    public String returnString() {
        return "success";
    }
}

4.7 knowledge summary

* Page Jump adopts the logical view of return string
    1.forward forward
        Can pass Model towards request Set data in domain
    2.redirect redirect
        Write the resource path directly, virtual directory springMVC Automatic splicing of frames
    
* Data storage to request In domain
    Model model
        model.addAttribute("username", "Zi Mu");

V. opening of static resource access

When static resources need to be loaded, such as jquery files, it is found that they are not loaded into jquery files through the packet capture of Google developer tools. The reason is that the URL pattern of DispatcherServlet, the front-end controller of spring MVC, is configured as / (default), which means that all static resources are processed, so the default servlet processing built in Tomcat will not be executed, We can specify the release of static resources in the following two ways:

Mode 1

<!--Method 1: release the specified static resources mapping:Released mapping path location: The directory where the static resource is located-->
<mvc:resources mapping="/js/**" location="/js/"/>
<mvc:resources mapping="/css/**" location="/css/"/>
<mvc:resources mapping="/img/**" location="/img/"/>

Mode II

<!--Method 2: release all static resources: in springmvc Open in configuration file DefaultServlet Processing static resources-->
<mvc:default-servlet-handler/>

Posted by mastercjb on Tue, 09 Nov 2021 15:52:49 -0800