导入maven依赖
SpringMVC还是基于servlet实现的,所以还是要导入servlet依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.17.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
1、新建一个Maven工程
添加框架依赖 ,最原始的Maven项目是没有web文件夹的,我们需要手动添加。
注意:新建的Maven项目,java和resources和测试的java都是白的,我们刷新一下maven就行了。
2、创建Controller包
package com.guanzhu.controller;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class SkippingRope {
@RequestMapping("/s")
public String skippingRope(Model model){
model.addAttribute("skippingRope","我爱跳绳,一天三千!");
return "sport";
}
}
3、创建对应的jsp文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1 style="color: red">
${skippingRope}
</h1>
</body>
</html>
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 http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--扫描controller所有的类,让其注解生效-->
<context:component-scan base-package="com.guanzhu.controller"/>
<!--不处理静态资源 比如:html,css-->
<mvc:default-servlet-handler/>
<!--代替适配器和映射器-->
<mvc:annotation-driven/>
<!--以上三条代码都是死的-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="WEB-INF/jsp/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
5、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">
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!--这里写对应的:springmvc-servlet.xml文件的名字-->
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<!--启动级别,越低启动越快-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<!-- /正斜杠,只能写正斜杠 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
6、发布项目