spring mvc的配置|hello world!

429 阅读2分钟
  1. 先创建一个maven的webapp项目,然后添加好相应缺失的文件夹

  2. 在resource文件夹中,添加springmvc.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"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
        <context:component-scan base-package="com.kehao.controller" ></context:component-scan>
    
        <mvc:annotation-driven ></mvc:annotation-driven>
    </beans>
    

    第一个是包扫描,就是扫描出所需要的controller
    第二个是帮你自动注册处理器映射器、处理器适配器(其实也可以不用配置这一项,因为springmvc会自动帮你注册,但是默认会使用旧版的,如果加上了这句话就会用新版的处理器映射器、处理器适配器)

    HandlerMapping的实现类的作用:
    实现类RequestMappingHandlerMapping,它会处理@RequestMapping 注解,并将其注册到请求映射表中。
    HandlerAdapter的实现类的作用:
    实现类RequestMappingHandlerAdapter,则是处理请求的适配器,确定调用哪个类的哪个方法,并且构造方法参数,返回值。

  3. 配置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">
        <servlet>
            <servlet-name>dispatcherServlet</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:springmvc.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
    
        <servlet-mapping>
            <servlet-name>dispatcherServlet</servlet-name>
            <url-pattern>*.do</url-pattern>
        </servlet-mapping>
    
    </web-app>
    

    web.xml是给tomcat去读取的,那么首先得给他注册对应的servlet,tomcat才能处理请求
    springmvc将所有的请求使用同一个servlet ,所以就给他配置DispatcherServlet
    然后DispatcherServlet,需要加载springmvc的配置文件,所以给他配置初始化参数
    最后load-on-startup是为了让它在启动的时候就加载,否则第一次访问会很慢,数字其实可以随便填,因为只有一个servlet,优先度就没有意义

    load-on-startup 元素标记容器是否应该在web应用程序启动的时候就加载这个servlet,(实例化并调用其init()方法)。
    它的值必须是一个整数,表示servlet被加载的先后顺序。
    如果该元素的值为负数或者没有设置,则容器会当Servlet被请求时再加载。
    如果值为正整数或者0时,表示容器在应用启动时就加载并初始化这个servlet,值越小,servlet的优先级越高,就越先被加载。值相同时,容器就会自己选择顺序来加载。

  4. 随便写个controller,然后调用测试之

    @RestController
    public class HelloWorldController {
    
        @RequestMapping(value = "helloworld")
        public String helloWorld(){
            return "Hello World";
        }
    }