欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【SpringMvc学习笔记(二)】入门案例Demo以及RequestMapping详解

程序员文章站 2022-07-04 19:19:04
...

1、首先,我们需要创建一个Maven-webapp项目,并且在pom.xml中导入坐标依赖:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.ysw</groupId>
  <artifactId>springmvc_day01_01_start</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>springmvc_day01_01_start Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

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

    <!-- 导入SpringMVC坐标依赖 -->
    <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>

  <build>
    <finalName>springmvc_day01_01_start</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

2、导入坐标依赖成功之后,我们在webapp目录下创建一个index.jsp文件,用于案例的测试:

<%--
  Created by IntelliJ IDEA.
  User: Simon
  Date: 2020/3/6
  Time: 19:20
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

    <h3>入门程序</h3>
    <a href="hello">入门程序</a>

    <a href="user/testRequestMapping?username=hh">RequestMapping注解</a>

</body>
</html>

3、随后定义一个error.jsp页面,用于从controller层跳转到该页面:

<%--
  Created by IntelliJ IDEA.
  User: Simon
  Date: 2020/3/6
  Time: 19:43
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

    <h3>自定义的视图解析器测试</h3>

</body>
</html>

4、随后,我们在WEB-INF目录下的web.xml文件中创建一个自动加载我们SpringMvc.xml配置文件的资源,并且还要配置在第一次请求的时候就加载该SpringMvc.xml的配置文件,自动加载配置文件的路径:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <!-- 配置前端控制器 -->
  <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 -->
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>

5、到此,我们就可以在resources目录下创建SpringMvc.xml配置文件了,这个配置文件主要执行三个操作。第一,开启扫描包注解;第二,配置视图解析器,用于controller成功返回的时候跳转到指定目录的路径所用的(主要是指定文件前缀目录以及文件的后缀)。第三,开启SpringMvc框架对注解的支持。

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

    <!-- 开启注解的扫描 -->
    <context:component-scan base-package="com.ysw.controller"></context:component-scan>

    <!-- 配置试图解析器,用于controller成功之后返回的时候跳转用的 -->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 配置这个的目的是成功之后跳转到 /WEB-INF/pages/目录下的文件/WEB-INF/pages/ -->
        <!-- 这种是默认跳转到webapp路径下的 -->
        <property name="prefix" value="/"></property>
        <!-- 文件后缀名 -->
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!-- 开启SpringMvc框架对注解的支持 -->
    <mvc:annotation-driven></mvc:annotation-driven>

</beans>

6、最后编写我们的controller层代码,这里我们要对我们的类使用注解@Controller,用于将当前全限定类名存入Spring的IoC核心容器。同时该类名还可以通过使用@RequestMapping("/url")的方式指定要访问到该controller的路径。最后我们在方法中可以使用@RequestMapping("/url")来指定访问该方法的url。

     如果该controller层中的方法是String类型的返回值的话,这个返回值可以直接return一个.jsp文件的文件名,并且不需要后缀。因为在配置视图解析器的时候就已经配置好了的文件名后缀了。

     同时,我们还可以在@RequestMapping中使用:

     value、path、method(用于指定参数传递使用的是GET还是POST)、params(用于指定在传递参数的时候所传过来的参数名,这里在前端jsp页面跳转进来的时候,url地址一定要带上参数,否则是无法进入controller层的)。

package com.ysw.controller;

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

/**
 * 控制器类
 */
@Controller
@RequestMapping(path = "/user")
public class HelloController {

    @RequestMapping(path = "/hello") //请求映射
    public String sayHello(){
        System.out.println("Hello SpringMvc");
        //返回可以直接跳转路径,一般默认的是jsp的文件名
        return "error";
    }

    /**
     * method可以用于指定参数传递的方法是get还是post
     * params是用于指定在传过来的时候一定要有一个参数,不传的话不会执行
     *
     * @return
     */
    @RequestMapping(path = "/testRequestMapping",
            method = {RequestMethod.GET},
            params = {"username"})
    public String testRequestMapping(){
        System.out.println("测试requestMapping....");
        return "error";
    }

}

项目结构图如下所示:

【SpringMvc学习笔记(二)】入门案例Demo以及RequestMapping详解

相关标签: SpringMvc