1. 创建静态页面:
在src/main/webapp/static目录下创建一个静态HTML页面,例如index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Static Page</title>
</head>
<body>
<h1>Welcome to the Static Page!</h1>
<p>This is a simple static HTML page served by Spring MVC.</p>
</body>
</html>
2. 创建Controller:
创建一个简单的Controller类,用于处理请求并返回静态页面:
package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class StaticPageController {
@RequestMapping(value = "/staticPage", method = RequestMethod.GET)
public String showStaticPage() {
return "static/index";
}
}
3. 配置spring-mvc-servlet.xml:
在src/main/webapp/WEB-INF目录下创建一个spring-mvc-servlet.xml文件,配置Spring MVC:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<!-- 开启组件扫描 -->
<context:component-scan base-package="com.example.controller" />
<!-- 开启注解驱动 -->
<mvc:annotation-driven />
<!-- 配置静态资源处理器 -->
<mvc:resources location="/static/" mapping="/static/**" />
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
4. 运行:
在你的IDE中运行或将项目打包并部署到支持Servlet容器的环境中。访问http://localhost:8080/your-project-name/staticPage,应该能看到静态页面的内容。
在这个例子中,StaticPageController的showStaticPage方法返回static/index,这会匹配到src/main/webapp/static/index.html。通过配置mvc:resources,Spring MVC会处理/static/**路径下的静态资源,使得这些静态资源可以直接被访问。
转载请注明出处:http://www.pingtaimeng.com/article/detail/6971/Spring