1.环境搭建
2.注册DispatcherServlet
在web.xml中配置如下
<!--1.注册DispatcherServlet-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--关联一个springmvc的配置文件:【servlet-name】-servlet.xml-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<!--启动级别-1-->
<load-on-startup>1</load-on-startup>
</servlet>
<!--/ 匹配所有的请求;(不包括.jsp)-->
<!--/* 匹配所有的请求;(包括.jsp)-->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
3.编写Springmvc配置文档springmvc-servlet.xml
<context:component-scan base-package="com.controller"/>:自动扫描包 <mvc:default-servlet-handler />:禁止访问静态资源 <mvc:annotation-driven />: 帮助完成DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter实例的注入
<?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.controller"/>
<mvc:default-servlet-handler />
<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>
4.创建Controller
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
// @Controller 不用在实现 Controller 接口,且不用配置bean
// 类名上面的@RequestMapping("HelloController")表示,
// 要请求类中的所有方法前都得加上/HelloController
// 例如想请求hello方法,请求路径为localhost:8080/HelloController/hello
@Controller
@RequestMapping("/HelloController")
public class HelloController {
// 请求hello时会匹配到这个方法
@RequestMapping("/hello")
public String hello(Model model){
// 封装数据
model.addAttribute("msg","hello,springmvcannotation");
return "hello";//会被视图解析器处理
}
}
5.编写视图层
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>hello</title>
</head>
<body>
${msg}
</body>
</html>
6.测试
启动tomcat:
结果: