1.配置web.xml
<?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">
<!--配置DispatchServlet:这个是springmvc核心,请求分发器,也叫前端控制器-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--DispatcherServlet要绑定Sprinmvc的配置文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<!--启动级别和tomcat服务器一起启动-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
2.配置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-3.0.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd
">
<!--自动扫描包,让指定包下的注解生效,由IOC容器统一管理-->
<context:component-scan base-package="com.xtfedu.controller"/>
<!--让SpringMVC不处理静态资源 .css .js .html .mp3 .mp4都是静态资源-->
<mvc:default-servlet-handler/>
<!--
支持mvc注解驱动
在spring中一般采用@RequestMapping注解来完成映射关系
要想使@RequestMapping注解生效
必须向上下文中注册DefaultAnnotationHandlerMapping
和一个AnnotationMethodHandlerAdapter实例
这两个实例分别在类级别和方法级别处理
而annotation-driven配置帮助我们自动完成上述两个实例的注入
-->
<mvc:annotation-driven/>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
3.
3.1创建controller类(一级路径)
@Controller//自动扫描到这个包下的类,识别为controller
public class HelloController {
//在一级路径下
//真实访问地址 项目名/hello.jsp
@RequestMapping("/hello")
public String hello(Model model){
//封装数据
//向模型中添加属性msg与值,可以在JSP页面中取出并渲染
model.addAttribute("msg","hello mvc annotation");
// /WEB-INF/jsp/hello.jsp
return "hello";//会被视图解析器处理
}
}
3.2 创建controller类(多级路径)
@Controller//自动扫描到这个包下的类,识别为controller
@RequestMapping("/hello")//项目目录
public class HelloController {
//在多级路径下
//真实访问地址 项目名/hello/h1.jsp
@RequestMapping("/h1")
public String hello(Model model){
//封装数据
//向模型中添加属性msg与值,可以在JSP页面中取出并渲染
model.addAttribute("msg","hello mvc annotation");
// /WEB-INF/jsp/hello.jsp
return "hello";//会被视图解析器处理
}
4.创建视图层
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${msg}
</body>
</html>
5.配置tomcat,运行