Introduction to spring MVC and SSM integration

Posted by gregambrose on Sun, 30 Jan 2022 18:43:06 +0100

1. Introduction to spring MVC

1.1 MVC mode

MVC is a software architecture mode 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): display content
  • C (controller): responsible for scheduling and distribution (1. Receiving requests, 2. Calling models, 3. Forwarding to views)

1.2 spring MVC overview

Spring MVC is a lightweight (less resource consumption at startup) Web framework based on Java to realize MVC design pattern. Through a set of annotations, it makes a simple java class become the controller to process requests without implementing any interface. It also supports RESTful programming style requests.

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

2. 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 After adaptation, call the specific processor(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

2.2.1 front end controller: dispatcher Servlet

When the user 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.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 mapping methods, such as configuration file mode, implementation interface mode, annotation mode, etc.

2.2.3 processor adapter: HandlerAdapter

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

2.2.4 view resolver: ViewResolver

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.

Written test question: three components of spring MVC?

  • Processor mapper, processor adapter, view parser

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">

    <!--1.Component scan: scan only controller-->
    <context:component-scan base-package="com.lagou.controller"/>

    <!--2.mvc Annotation enhancement:Processor mapper and processor adapter-->
    <mvc:annotation-driven/>

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

2.3 spring MVC annotation parsing

@Controller

If you need to label Spring Controller in Spring Controller container, you need to use Spring Controller to label Spring Controller in Spring Controller container:

spring-mvc.xml

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

@RequestMapping

* effect:
	Used to establish the request URL And the method of processing the request
	
* Location:
    1.On class: request URL First level access directory. 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 limit the way a request is made
    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 parameters money Can't be 100

3. Spring MVC request

Spring MVC can receive the following types of parameters:

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

The format of the 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.

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

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

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

Chinese garbled code filter

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

web.xml

<!--Chinese garbled code filter: solution post Garbled code submitted by-->
<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.3 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.

3.4 get set (complex) type parameters

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


4. Response of spring MVC

4.1 page Jump

4.1.1 return string logical view (common)

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

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

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

forward forwarding

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

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

You can set the data Model in the request field through the Model addAttribute("key", "value").

@RequestMapping("/forward")
public String forward(Model model) {
	model.addAttribute("username", "Solicit recruitment");
	return "forward:/WEB-INF/pages/success.jsp";
}

Front end jsp

<body>
    index.....${username}
</body>

Request forwarding is a request, and ${username} can take a value.

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.

@RequestMapping("/redirect")
public String redirect(Model model) {
    // Reqeust is still used at the bottom SetAttribute ("username", "pull hook education") 
    // Domain scope: one request
	model.addAttribute("username", "Pull hook Education");
	return "redirect:/index.jsp";
}

Front end jsp

<body>
    index.....${username}
</body>

Redirection is two requests, so the page ${username} cannot get a value.

4.1.2 void original servlet API

We can implement the response through request and response objects.

@RequestMapping("/returnVoid")
public void returnVoid(HttpServletRequest request, HttpServletResponse response)throws Exception {
    // Forward through request
	request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);
    
    // Redirect through response
	response.sendRedirect(request.getContextPath() +"/index.jsp");
}

WEB-INF is a secure directory. The jsp in it cannot be accessed directly. Either forward the request inside the server or move the pages inside to the webapp directory.

The request address bar does not change, and the response address bar changes.

4.1.3 ModelAndView

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 to set the view in the method.

@RequestMapping("/returnModelAndView")
public ModelAndView returnModelAndView(ModelAndView modelAndView) {
    /*
        Model:Model encapsulation data
        View: View display data
    */
    //Set model data
    modelAndView.addObject("username", "lagou");
    //Set view name
    modelAndView.setViewName("success");
    return modelAndView;
}

4.2 return data

4.2.1 directly return string data

// Directly respond to data through response 		
response.setContentType("text/html;charset=utf-8"); response.getWriter().write("Pull hook net");

4.2.2 converting objects or collections into json returns

By default, spring MVC uses MappingJackson2HttpMessageConverter to convert json data, which needs to be added to jackson's package; Use < MVC: annotation driven / >

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.8</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.9.0</version>
</dependency>
@RequestBody

This annotation is used for the formal parameter declaration of the Controller's method. When the content type is submitted using ajax and specified as json, it is converted to the corresponding POJO object through the HttpMessageConverter interface.

@ResponseBody

This annotation is used to convert the object returned by the Controller method into data in the specified format through the HttpMessageConverter interface, such as json,xml, etc., and respond to the client through Response.

5. Enable static resource access

When a static resource needs to be loaded, such as jquery file, it is found through the packet capture of Google developer tool that it is not loaded into jquery file. 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, Instead, it is processed by the DispatcherServlet of the front-end Controller to match the path with @ RequestMapping("/servletAPI"), but there is no such path in the Controller, so it cannot be loaded.

We can specify the release of static resources in the following two ways:

spring-mvc.xml

<!--Method 1: release the specified static resources mapping:Released mapping path  location: Directory of static resources-->
<mvc:resources mapping="/js/**" location="/js/"/>
<mvc:resources mapping="/css/**" location="/css/"/>
<mvc:resources mapping="/img/**" location="/img/"/>
<!--Method 2: release all static resources:stay springmvc Open in configuration file DefaultServlet Processing static resources-->
<mvc:default-servlet-handler/>

6. SSM integration

Step analysis

  1. Prepare database and table records

  2. Create a web project

  3. Writing mybatis can be used alone in the ssm environment

    1. pom.xml import dependency
    2. Writing entity classes
    3. Write Dao interface
    4. Write a mapping configuration file (interface proxy method, which has the same name as Dao package, i.e. * * dao.xml)
    5. Write the core configuration file sqlmapconfig xml
  4. Writing spring can be used alone in the ssm environment

    1. pom.xml import dependency
    2. Write Service interface and entity class
    3. Write the core configuration file ApplicationContext xml
  5. spring integrates mybatis

    1. pom.xml import dependency

      <!--mybatis integration spring coordinate-->
      <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis-spring</artifactId>
          <version>1.3.1</version>
      </dependency>
      
    2. spring profile management mybatis

  6. Writing spring MVC can be used alone in ssm environment

    1. pom.xml import dependency
    2. Write the core configuration file spring MVC xml
    3. Write web xml
    4. Write Controller class and corresponding jsp page
  7. Spring MVC (spring and web container integration)

    1. web.xml ContextLoaderListener loading

      <!--spring And web Container integration-->
      <listener>
          <listener-class>
        		org.springframework.web.context.ContextLoaderListener
          </listener-class>
      </listener>
      <context-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:applicationContext.xml</param-value>
      </context-param>
      

Topics: Java Web Development Spring