Hey, Nice to meet You. 

必有过人之节.人情有所不能忍者,匹夫见辱,拔剑而起,挺身而斗,此不足为勇也,天下有大勇者,猝然临之而不惊,无故加之而不怒.此其所挟持者甚大,而其志甚远也.          ☆☆☆所谓豪杰之士,

SpringMVC入门学习(二)----SpringMVC的第一个案例

1、创建一个maven工程

首先创建一个webapp模块的Maven项目,如下:

image

创建好之后导入如下Maven依赖:

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <spring.version>5.2.7.RELEASE</spring.version>
</properties>
<dependencies>
    <!--Spring相关依赖-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <!--Servlet相关依赖-->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
        <scope>provided</scope>
    </dependency>
    <!--jsp相关依赖-->
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.0</version>
        <scope>provided</scope>
    </dependency>
    <!--单元测试的依赖-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
    </dependency>
</dependencies>

创建后项目的整体目录如下:

image

2、在web.xml中配置DispatcherServlet(前端控制器)

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

    <!-- 配置编码过滤器,防止乱码 -->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <!--支持异步处理-->
        <async-supported>true</async-supported>
        <!-- 配置encoding,告诉指定的编码格式,这里设置为UTF-8 -->
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <!-- 解决请求乱码 -->
        <init-param>
            <param-name>forceRequestEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <!-- 解决响应乱码 -->
        <init-param>
            <param-name>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- 配置SpringMVC核心控制器 -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <!-- 配置DispatcherServlet的初始化参数:读取springmvc.xml -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <!-- servlet启动时加载 -->
        <load-on-startup>1</load-on-startup>
        <!--支持异步处理-->
        <async-supported>true</async-supported>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <!--
        /* 匹配所有资源(永远不要这样写)
        /  匹配所有请求(推荐)
        *.扩展名  匹配所有请求(推荐),例如*.do
        -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

注意:我们也可以不通过使用contextConfigLocation配置项来指定SpringMVC的配置文件,而使用默认的配置文件为: /WEB-INF/<servlet-name>-servlet.xml,那么SpringMVC会自动去WEB-INF下面找一个叫 [servlet名字]-servlet.xml的文件,不推荐使用这种方式。

  • DispatcherServlet:它是前端核心控制器,主要负责请求的分派。前端的请求由这里分派给指定的处理器。
  • load-on-startup:当值为0或者大于0时,表示容器在应用启动时就加载这个servlet;当是一个负数时或者没有指定时,则指示容器在该servlet被调用时才加载。正数的值越小,启动该servlet的优先级越高。
  • url-pattern:表示拦截哪些请求, “/” 表示拦截所有请求。也可以如”.扩展名”表示拦截所有以扩展名结尾的请求。例如”.do”

3、创建spring-mvc.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
       http://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.thr.controller"/>

    <!-- 配置注解驱动,它的主要的作用是:注册映射器HandlerMapping和适配器HandlerAdapter 两个类型的Bean -->
    <!--HandlerMapping的实现为实现类RequestMappingHandlerMapping,它会处理 @RequestMapping 注解,并将其注册到请求映射表中-->
    <!--HandlerAdapter的实现为实现类RequestMappingHandlerAdapter,它是处理请求的适配器,确定调用哪个类的哪个方法,并且构造方法参数,返回值 -->
    <!--在使用SpringMVC是一般都会加上该配置 -->
    <mvc:annotation-driven/>

    <!-- 注册视图解析器 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 配置前缀 -->
        <property name="prefix" value="/WEB-INF/pages/"/>
        <!-- 配置后缀 -->
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>
  • InternalResourceViewResolver解析器可以解析该资源。其主要职责是:根据处理器的返回值找到资源页面,然后装配页面数据,最后返回给前台。
  • prefix和suffix属性可以指定资源页面的前缀和后缀,可以直接把资源位置定位到项目的/WEB-INF下面。

4、创建Controller类

  • @Controller:将该Bean注册到Spring的容器中
  • @RequestMapping:该注解可以用在类和方法上,它是用来映射请求的URL。
    • 用在类上: 表示初步的请求映射信息,所有响应请求都是以该地址作为父路径。
    • 用在方法上: 表示在父路径的基础上进一步细分映射信息。
    • 类定义处未标注@RequestMapping:则映射的请求URL从方法处开始。
package com.thr.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller //声明Bean对象,为一个控制器组件
public class HelloController {
    /**
     * 1. @RequestMapping 注解是用来映射请求的 URL
     * 2. 返回值会通过视图解析器解析为实际的物理视图, 对应 InternalResourceViewResolver 视图解析器,它会做如下的解析:
     *      -通过 prefix + returnVal + suffix 这样的方式得到实际的物理视图, 然后做转发操作.
     *      -这里得到的物理视图为:/WEB-INF/pages/success.jsp
     */
    @RequestMapping("/hello")
    public String sayHello(){
        System.out.println("Hello SpringMVC");
        //访问成功后跳转到success页面
        return "success";
    }
}

5、编写视图文件

在webapp下编写index.jsp文件,项目启动后会默认访问该页面。

注意:在第一行中需要加入这个参数isELIgnored="false",否则到时候可能访问不到页面。

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/hello">第一个Spring MVC程序</a>
</body>
</html>

创建目标页面(success.jsp),在WEB-INF/pages/下创建success.jsp,注:WEB-INF下的文件是不能直接通过浏览器访问的,只能通过请求进行访问。

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Hello</title>
</head>
<body>
<h1>成功访问!!!</h1>
</body>
</html>

6、启动Tomcat服务器测试

启动Tomcat服务器,打开主页访问:

image

点击超链接,成功跳转到相应页面,说明我们的第一个SpringMVC程序创建成功了。

image


补充:新版IDEA(我的是2020.3)注意这里:

image

posted @ 2021-05-13 08:02  唐浩荣  阅读(1220)  评论(3编辑  收藏  举报