[SpringMVC from entry to actual combat tutorial] Chapter 2 Introduction to SpringMVC

2. Introduction to SpringMVC

2.1 Building a SpringMVC project

2.1.1 Create a WEB project

2.1.2 Import Spring's jar package

    Among them, spring-webmvc-4.3.18.RELEASE.jar is the core jar package of SpringMVC.

Method 1: Import jar package

 Method 2: maven dependency configuration

<dependencies>
    <!-- spring核心包-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.3.18.RELEASE</version>
    </dependency>
    <!-- springbean包 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>4.3.18.RELEASE</version>
    </dependency>
    <!-- springcontext包 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.3.18.RELEASE</version>
    </dependency>
    <!-- spring表达式包 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-expression</artifactId>
        <version>4.3.18.RELEASE</version>
    </dependency>
    <!-- springAOP包 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>4.3.18.RELEASE</version>
    </dependency>
    <!-- springAspects包 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>4.3.18.RELEASE</version>
    </dependency>
    <!-- spring对web的支持 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>4.3.18.RELEASE</version>
    </dependency>
    <!-- springwebMVC -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.3.18.RELEASE</version>
    </dependency>

    <!-- 配置javaweb环境 -->
    <!-- servlet-api -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>
    <!-- jsp-api -->
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.1</version>
        <scope>provided</scope>
    </dependency>
    <!-- jstl -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
</dependencies>

2.1.3 Configure Front Controller

    Spring MVC is based on Servlet, and DispatcherServlet is the core of the entire Spring MVC framework, mainly responsible for intercepting requests and dispatching them to corresponding processors for processing. So to configure Spring MVC, you must first define DispatcherServlet. As with all servlets, the user must be configured in web.xml.
    
    When Spring MVC is initialized, it will look for a configuration file in the WEB-INF directory of the application. The naming rule of the configuration file is "servletName-servlet.xml", such as springmvc-servlet.xml.

    You can also store the Spring MVC configuration file anywhere in the application directory, but you need to use the init-param element of the servlet to load the configuration file, and specify the location of the Spring MVC configuration file through the contextConfigLocation parameter. The sample code is as follows.

Configure the front controller in web.xml:

<?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">
    <!-- 1、配置前端控制器 -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--
            springmvc的核心配置文件,格式与spring的applicationContext.xml一致
            默认路径:/WEB-INF/[前端控制器Servlet的名称]-servlet.xml
            4、自定义springmvc配置文件的名称和位置:
            通过Servlet的初始化参数,修改springmvc的配置文件的路径和名称
        -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <!-- 3、配置服务器启动时初始化前端控制器-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <!--
            2、配置进入Spring MVC的请求
            第一种:*.后缀名,表示由DispatcherServlet进行解析以某种扩展名结尾的请求路径。
                    例如:*.do,*.action,*.abc..但是不能配置*.jsp,*.css,*.js等视图类型的后缀或静态资源后缀
                    优点:不会导致静态资源的拦截(静态资源的访问不会进入springmvc的流程),无需单独排除静态资源
                    缺点:不支持RESTful风格的开发
            第二种:/,表示所有的访问服务器的路径都进入Spring MVC的流程中(.jsp文件除外)。
                    优点:支持RESTful风格的开发
                    缺点:当访问静态资源时,因没有相应的处理类,会报出404的错误,需要单独排除静态资源
            注意:/*,此种在Spring MVC中是错误的配置,因为它会拦截所有的静态资源,以及jsp文件。
        -->
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>
</web-app>

Configuration analysis:

    contextConfigLocation: Specifies the loading location of the springmvc configuration. If not specified, the default loading is /WEB-INF/[servlet name]-servlet.xml. For example: springmvc-servlet.xml.
    
    url-pattern: Please hand over the request path to be processed by DispatcherServlet.
        The first type: \*.do, which is parsed by DispatcherServlet and ends with a certain extension, which will not cause static resources (jpg, js, css) to be intercepted.
        The second type: /, so the accessed address is parsed by DispatcherServlet, and the parsing of static files needs to be configured to prevent DispatcherServlet from parsing. In this way, RESTful style url can be realized.
        The third type: /*, this configuration is incorrect. With this configuration, when it is finally forwarded to a jsp page, the DispatcherServlet will still resolve the jsp address. If the handler cannot be found according to the jsp page, an error will be reported.

2.1.4 Configure Processor Mapper

Configure the processor mapper in the springmvc configuration file:

<?xml version="1.0" encoding="UTF-8"?>
<beans
       xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/util
       http://www.springframework.org/schema/util/spring-util.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!-- 配置处理器映射器 -->
    <!--
        所有的处理器映射器都实现HandlerMapping接口
        BeanNameUrlHandlerMapping:根据处理器bean标签中name属性值来与请求路径匹配查找相应的处理器对象
    -->
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
</beans>

2.1.5 Configure Processor Adapter

<!-- 配置处理器适配器 -->
<!--
  所有的处理器适配器都实现HandlerAdapter接口
  SimpleControllerHandlerAdapter:要求在编写处理器时,必须实现org.springframework.web.servlet.mvc.Controller接口
-->
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>

By viewing the original code:

public class SimpleControllerHandlerAdapter implements HandlerAdapter {
    public SimpleControllerHandlerAdapter() {
    }

    public boolean supports(Object handler) {
        return handler instanceof Controller;
    }

    public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return ((Controller)handler).handleRequest(request, response);
    }

    public long getLastModified(HttpServletRequest request, Object handler) {
        return handler instanceof LastModified ? ((LastModified)handler).getLastModified(request) : -1L;
    }
}

    This adapter can execute Handlers that implement the org.springframework.web.servlet.mvc.Controller interface.

2.1.6 Develop Handler

The Controller interface needs to be implemented in order to be executed by the SimpleControllerHandlerAdapter adapter:

/**
 * 处理器:用于请求处理
 *
 * 问题:
 * 1.依赖Spring API的处理器
 * 2.每个处理器仅能处理一个请求
 */
public class HelloWorldController implements Controller {
    /**
     * 处理请求的方法
     * @param request 原生的请求对象
     * @param response 原生的响应对象
     * @return 模型与视图对象
     * @throws Exception
     */
    @Override
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("Hello Springmvc.....");
        
        //创建ModelAndView对象
        ModelAndView modelAndView = new ModelAndView();
        
        //设置数据(相当于将数据存放到域对象中,request域)
        modelAndView.addObject("message", "Hello Springmvc");
        
        //设置视图(相当于进行请求转发的页面路径)
        modelAndView.setViewName("/success.jsp");
        
        return modelAndView;
    }
}

ModelAndView: Contains model data and view names.

2.1.7 Configuring Handlers

Give the Handler object to SpringIOC container management:

<!-- 配置处理器-->
<bean name="/helloworld.do" class="com.newcapec.controller.HelloWorldController"/>

The name attribute value of the bean is used as the request url, and the path starts with a slash;

2.1.8 Configure View Resolver

<!-- 视图解析器 -->
<!--
  所有的视图解析器都实现ViewResolver接口
  InternalResourceViewResolver:JSP视图的解析器
-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"/>

2.1.9 View writing

index.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <base href="${pageContext.request.contextPath}/">
    <title>Title</title>
</head>
<body>
    <div style="text-align: center;">
        <h1>首页</h1>
        <p><a href="helloworld.do">测试helloworld</a></p>
    </div>
</body>
</html>

success.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <base href="${pageContext.request.contextPath}/">
    <title>Title</title>
</head>
<body>
    <div style="text-align: center;">
        <h1>跳转成功页面</h1>
        <div style="color:red;">${message}</div>
    </div>
</body>
</html>

2.2 Non-annotated processor mappers and adapters

2.2.1 Non-Annotated Processor Mapper

    org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping, when configuring the handler, configure the url corresponding to the handler when it is accessed on the name attribute of the bean tag.

    org.springframework.web.servlet.handler.SimpleUrlHandlerMapping, according to the matching of the id attribute value in the processor bean tag and the request path, finds the corresponding handler object. One handler object can correspond to multiple request paths.

<!--
  SimpleUrlHandlerMapping:
  根据处理器bean标签中id属性值与请求路径匹配查找相应的处理器对象,一个处理器对象可对应多个请求路径
-->
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="mappings">
        <props>
            <!-- 请求路径的url为key,处理器bean的id为value-->
            <prop key="/hello.do">helloController</prop>
            <prop key="/hello.action">helloController</prop>
        </props>
    </property>
</bean>

Note: In the same project, multiple mappers can coexist, and the front controller determines which mappers can map the url, and let the correct mapper handle it.

2.2.2 Non-annotated handler adapters

    org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter requires the written Handler to implement the Controller interface.

    org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter requires that the handler written must implement the org.springframework.web.HttpRequestHandler interface.

<!--
  HttpRequestHandlerAdapter:
  要求在编写处理器时,必须实现HttpRequestHandler接口
-->
<bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter"/>

2.2.3 Processor

code:

public class HelloController implements HttpRequestHandler {
    @Override
    public void handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
        System.out.println("HelloController执行了....");
        httpServletRequest.setAttribute("message", "hello");
        //重定向
        // httpServletResponse.sendRedirect("/success.jsp");
        //请求转发
      	httpServletRequest.getRequestDispatcher("/success.jsp").forward(httpServletRequest, httpServletResponse);
    }
}

Configuration:

<bean id="helloController" class="com.newcapec.controller.HelloController"/>

2.2.4 View writing

index.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <base href="${pageContext.request.contextPath}/">
    <title>Title</title>
</head>
<body>
    <div style="text-align: center;">
        <h1>首页</h1>
        <p><a href="helloworld.do">测试helloworld</a></p>
        <p><a href="hello.do">测试hello.do</a></p>
        <p><a href="hello.action">测试hello.action</a></p>
    </div>
</body>
</html>

2.3 Default configuration of SpringMVC

    There is a DispatcherServlet.properties resource file under the org.springframework.web.servlet package.

     The front controller loads the processor mapper, processor adapter, view resolver and other components from this property file. If it is not configured in springmvc.xml, it will be loaded by default.

2.4 Annotated processor mappers and adapters

2.4.1 Different processor mappers and adapters than in the default configuration

Use before spring3.1:

    org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping annotation handler mapper.
    
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter annotation processor adapter.

Use after spring3.1:

    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping annotation handler mapper.
    
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter annotation processor adapter.

2.4.2 Component scanning

<!-- springmvc的注解式开发 -->
<!-- 开启组件扫描 -->
<context:component-scan base-package="com.newcapec.controller"/>

2.4.3 RequestMappingHandlerMapping

    The annotation processor mapper maps the method marked @RequestMapping in the class, matches the method marked by RequestMapping according to the url defined by ResquestMapping, returns the HandlerMethod object to the front controller if the match is successful, and encapsulates the method Method corresponding to the url in the HandlerMethod object.

<!--配置处理器映射器-->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>

2.4.4 RequestMappingHandlerAdapter

The annotation processor adapter configuration is as follows:

<!--配置处理器适配器-->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>

2.4.5 Handler Processor

    The @Controller annotation is used to declare that an instance of a class is a controller.
    
    Spring MVC uses the scanning mechanism to find all annotation-based controller classes in the application. Therefore, in order for the controller class to be scanned by the Spring MVC framework, you need to declare spring-context in the configuration file and use <context:component-scan/> element specifies the base package for controller classes (make sure all controller classes are under the base package and its subpackages).

/**
 * 注解式处理器
 *
 * 好处:
 * 1.零侵入:无需继承或实现任何的接口或类
 * 2.一个处理器中可以处理多个请求,每个请求对应一个方法
 *
 * @Controller
 * 作用:配置bean和标识当前类为spirngmvc中的处理器
 */
@Controller
public class DemoController {

    /**
     * 处理请求的方法
     *
     * @RequestMapping
     * 作用:将请求的路径与处理请求的方法进行绑定...
     */
    @RequestMapping("/find.do")
    public ModelAndView find(){
        System.out.println("查询请求...");
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("message", "find");
        modelAndView.setViewName("/success.jsp");
        return modelAndView;
    }

    @RequestMapping("/add.do")
    public ModelAndView add(){
        System.out.println("新增请求...");
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("message", "add");
        modelAndView.setViewName("/success.jsp");
        return modelAndView;
    }
}

Note: Annotation mappers and annotation adapters must be used in pairs.

2.4.6 View writing

index.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <base href="${pageContext.request.contextPath}/">
    <title>Title</title>
</head>
<body>
    <div style="text-align: center;">
        <h1>首页</h1>
        <p><a href="find.do">测试find</a></p>
        <p><a href="add.do">测试add</a></p>
    </div>
</body>
</html>

success.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <base href="${pageContext.request.contextPath}/">
    <title>Title</title>
</head>
<body>
    <div style="text-align: center;">
        <h1>跳转成功页面</h1>
        <div style="color:red;">${message}</div>
    </div>
</body>
</html>

2.5 Summary of Getting Started Program

  • Understand the usage of SpringMVC front controller, processor mapper , processor adapter and view resolver through the starter program. Non-annotative understanding is enough, and annotation must be mastered proficiently.

Guess you like

Origin blog.csdn.net/ligonglanyuan/article/details/125104384