Hello,SpringMVC程序(注解版)

配置版:https://blog.csdn.net/shuati2000/article/details/121366774

1. 新建一个空的Maven项目

添加Web依赖

2.导包

spring-webmvc,servlet-api,jsp-api,jstl

3.配置在WEB-INF下的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">

    <!--注册DispatcherServlet-->
    <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>
        <!--启动级别-->
        <load-on-startup>1</load-on-startup>

    </servlet>
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>/</url-pattern>
        <!--注意这里的/与/*是有区别的
		/ :匹配所有请求(不包括.jsp)
		/*:匹配所有请求(包括.jsp)
		-->
    </servlet-mapping>
</web-app>

4.在resources下编写springmvc-servlet.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.feng.controller"/>
    <!--处理映射器和处理设配器-->
    <mvc:default-servlet-handler/>
    <mvc:annotation-driven/>

    <!--视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

5.编写Controller

@Controller
public class HelloController {
    
    

    @RequestMapping("/hello")
    public String hello(Model model){
    
    
        String result = "Hello,SpringMVC";
        model.addAttribute("msg",result);
        return "hello";
    }
}

6.编写需要跳转的页面

根据这个路径进行编写/WEB-INF/jsp/test.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

${msg}

</body>
</html>

7.配置Tomcat启动

Tomcat中项目名为空
在这里插入图片描述
结果如下:
在这里插入图片描述

注意

若在确保代码没有出现问题的时候,爆404错误

在这里插入图片描述

1.可以检查看是否缺少包
2.如果包存在,就在项目中添加lib依赖
3.重启Tomcat

猜你喜欢

转载自blog.csdn.net/shuati2000/article/details/121367347