SpringMVC - 01 - HelloWorld / @RequestMapping(1)

本文介绍使用IntelliJ IDEA、SpringMVC和Maven搭建基本Web应用框架的过程,包括配置pom.xml文件、web.xml文件、SpringMVC配置文件以及创建控制器和视图。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

更新于2018-04-26

使用Maven 重新构建项目

IDEA + SpringMVC + Maven 构建基本web框架

-----------------------------------------

快两个月没有写代码了,这两天稍微写了些,感觉自己都蠢炸了...

本来spring方面的内容就不扎实,现在好了了...感觉补补吧...

先来个Demo结构


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.st.server</groupId>
    <artifactId>MVCFreeMarker01</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>MVCFreeMarker01 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>
    </properties>

    <dependencies>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.0.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.0.0.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.0.0.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>5.0.0.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.0.0.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.7</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.3</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-collections/commons-collections -->
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.2</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.23</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>MVCFreeMarker01</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.0.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.7.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.20.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.0</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>

然后配置web.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>

    <!-- 配置DispathcerServlet -->
    <servlet>

        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <!-- 配置DispatcherServlet 的一个初始化参数: 配置SpringMVC配置文件的位置和名称-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/applicationContext.xml</param-value>
        </init-param>

        <!-- 第一次加载的时候就创建,而不是等发送请求的时候才创建 -->
        <load-on-startup>1</load-on-startup>

    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

然后加入SpringMVC的配置文件 applicationContext.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:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">


    <!-- 配置自动扫描的包 -->
    <context:component-scan base-package="com.mt.server"/>

    <!-- 配置视图解析器: 如何把handler 方法返回值解析为实际的物理视图 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

</beans>

接着,咱们来创建一个handler(控制器)

@Controller用于标记在一个类上,使用它标记的类就是一个SpringMVC Controller对象.

分发处理器将会扫描使用了该注解的类的方法,并检测该方法是否使用了@RequestMapping注解

@controller只是定义了一个控制器类,而使用@RequestMapping注解的方法才是真正处理请求的处理器,这个以后再说吧..

这里使用 @RequestMapping 来映射请求

package com.mt.server;

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

/**
 * HelloWorld-Test
 *
 * @author CYX
 * @create 2018-04-25-6:35
 */
@Controller
public class HelloWorldController {

    @RequestMapping(name = "/sayHelloWorld", method = RequestMethod.GET)
    public String sayHelloWorld() {
        System.out.println("hello world");
        return "success";
    }

}
然后咱们在配置两个用作测试的JSP页面....

index.jsp页面

通过映射请求,来调用相对应的方法

<%--
  Created by IntelliJ IDEA.
  User: CYX
  Date: 2018/4/25
  Time: 6:43
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Test Hello World</title>
</head>
<body>
<a href="sayHelloWorld">HelloWorld....</a>
</body>
</html>

然后再WEB-INF 下建一个views 文件夹,里面创建一个success.jsp

<%--
  Created by IntelliJ IDEA.
  User: CYX
  Date: 2018/4/25
  Time: 6:47
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Success</title>
</head>
<body>
<h4>Success</h4>
</body>
</html>

上面通过@RequestMapping(name = "/sayHelloWorld", method = RequestMethod.GET)来映射请求

返回值通过视图解析器(InternalResourceViewResolver)进行处理....

就会像这样子...

prefix + return Value + 后缀

就是dispatcher-servlet.xml中配置的这个

<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>

就会拼成一个这样的玩意: /WEB-INF/views/success.jsp 一个真实的物理视图...

然后做转发操作....

我们启动tomcat


点击 helloworld...之后


//--------------------------------------------------------------------------------

SpringMVC@RequestMapping 注解为控制器指定可以处理哪些URL请求
在控制器的类定义 以及方法定义处都可以标注.
类定义处:提供初步的请求映射信息,相对于WEB目录下的根目录.
方法处: 提供进一步的细分映射信息,相对于类定义处的URL,若类定义处未标注@RequestMapping,则方法处标记的URL相对于WEB应用的根目录
DispatcherServlet截获请求后,就通过控制器上@RequestMapping提供的映射信息确定请求所对应的处理方法

继续沿用是一个SpringMVC的例子...

Demo 结构图


handler代码

新建一个类,加上controller注解

package com.springmvc.test;

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

/**
 * Created by cyx on 2016/3/30.
 */

@RequestMapping("/springmvc")
@Controller
public class SpringMVCTest {

    private static final String SUCCESS = "success";

    /**
     * 1.@RequestMapping 除了修饰方法,还可以来修饰类 (类上面的就相当于WEB应用中的路径)
     *      http://localhost:8088/springmvc/testRequestMapping
     *
     * 2.类定义处: 提供初步的请求映射信息,相对于WEB目录下的根目录.
     *   方法处:   提供进一步的细分映射信息,相对于类定义处的URL,若类定义处未标注@RequestMapping,则方法处标记的URL相对于WEB应用的根目录
     *
     *
     */
    @RequestMapping("/testRequestMapping")
    public String testRequestMapping() {
        System.out.println("testRequestMapping");
        return SUCCESS;
    }

}
别忘记,因为这里我又创建了一个包,所以,配置文件中需要加上....
<?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"
       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">

       <!-- 配置自动扫描的包 -->
       <context:component-scan base-package="com.springmvc.handlers"/>
       <context:component-scan base-package="com.springmvc.test"/>

       <!-- 配置视图解析器: 如何把handler 方法返回值解析为实际的物理视图 -->
       <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
              <property name="prefix" value="/WEB-INF/views/"></property>
              <property name="suffix" value=".jsp"></property>
       </bean>

</beans>

然后在index.jsp文件中 加上一个请求

<%--
  Created by IntelliJ IDEA.
  User: cyx
  Date: 2016/3/30
  Time: 20:09
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title></title>
  </head>
  <body>
    <a href="/springmvc/testRequestMapping">@RequestMapping</a>
    <br><br>
    <a href="helloworld">HelloWorld</a>
  </body>
</html>
然后再部署,运行 就OK 了.......

---------------------------------------------------------------------------------------------------------------------------------

接上面继续....

@RequestMapping 除了可以使用请求URL映射请求外,还可以使用请求方法,请求参数以及请求映射请求

@RequestMapping 的value,method,params以及heads 分别表示请求URL,请求方法,请求参数及请求头,
他们之间是与的关系,联合使用多个条件,可以让请求映射更加精确化.

还是之前的例子...

结构不变,只是在test里面加上其他的方法....

package com.springmvc.test;

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

/**
 * Created by cyx on 2016/3/30.
 */

@RequestMapping("/springmvc")
@Controller
public class SpringMVCTest {

    private static final String SUCCESS = "success";

    /**
     * 1.@RequestMapping 除了修饰方法,还可以来修饰类 (类上面的就相当于WEB应用中的路径)
     *      http://localhost:8088/springmvc/testRequestMapping
     *
     * 2.类定义处: 提供初步的请求映射信息,相对于WEB目录下的根目录.
     *   方法处:   提供进一步的细分映射信息,相对于类定义处的URL,若类定义处未标注@RequestMapping,则方法处标记的URL相对于WEB应用的根目录
     *
     *
     */
    @RequestMapping("/testRequestMapping")
    public String testRequestMapping() {
        System.out.println("testRequestMapping");
        return SUCCESS;
    }



    /**
     *使用method属性来指定请求方式
     */
    @RequestMapping(value = "/testMethod", method = RequestMethod.POST)
    public String testMethod() {
        System.out.println("testMethod");
        return SUCCESS;
    }

}
然后修改index.jsp

分别模拟发送get请求和post请求...

<%--
  Created by IntelliJ IDEA.
  User: cyx
  Date: 2016/3/30
  Time: 20:09
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title></title>
  </head>
  <body>
<span style="white-space:pre">	</span><!--创建form表单 模拟post请求-->
      <form action="/springmvc/testMethod" method="post">
        <input type="submit" value="submit">
      </form>

      <!--这里先模拟一个get请求,因为RequestMapping设置为只接受POST请求,所以不会应答-->
      <a href="/springmvc/testMethod">testMethod</a>
    <br><br>
      <a href="/springmvc/testRequestMapping">@RequestMapping</a>
    <br><br>
      <a href="helloworld">HelloWorld</a>
  </body>
</html>
然后部署运行....

贴上两次的运行图...

get请求


post请求:



//--------------更新于2016-4-14

如果按照上面的测试,抛出异常,类似于404什么的...

建议检查下代码的 "/" 这个符号是不是都写了...

还有就是jar包,是不是都添加了....



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值