SpringMVC的简单示例(HelloWorld注解版)

参考链接:SpringMVC的简单示例(HelloWorld配置文件版)

1、工程搭建

  • 创建一个普通的maven项目;

  • 将maven项目添加web application支持;

  • 添加相关依赖

    <dependencies>
      <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>servlet-api</artifactId>
          <version>2.5</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>5.3.3</version>
      </dependency>
    </dependencies>
    

2、相关配置

web.xml

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

    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
    </servlet>

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

</web-app>

springmvc-servlet.xml

  • 在resource的根目录下创建该配置文件
  • 该文件是在web.xml中指定的,DispatcherServlet将请求统一分发关联的就是该文件;
  • 这是Spring工厂的配置文件,所有的控制器创建都在该配置文件中定义或生成;
  • 注解的方式创建控制器只需要指定注解扫描的包即可
<?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 https://www.springframework.org/schema/context/spring-context.xsd">
    <context:component-scan base-package="com.yusian.controller"/>
</beans>

3、控制器实现

HomeController.java

  • 控制器类名上加@Controller注解
  • 某个方法中加@RequestMapping注解
package com.yusian.controller;

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

@Controller
public class HomeController {

    @RequestMapping("/index")
    public String index(Model model) {
        model.addAttribute("message", "Hello SpringMVC Annotation...");
        return "index.jsp";
    }
}

index.jsp

<%--
  Created by IntelliJ IDEA.
  User: yusian
  Date: 2021/2/26
  Time: 10:16 上午
  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>
  ${message}
  </body>
</html>

4、测试结果

在浏览器中打开http://localhost:8080/index就能看到页面上输出 Hello SpringMVC Annotation…

Leave a Reply