本文目录导读:

我来为你创建一个完整的Spring MVC入门案例,这个案例将展示从配置到运行的全过程。
项目结构
springmvc-demo
├── pom.xml
└── src
└── main
├── java
│ └── com
│ └── example
│ ├── config
│ │ └── WebConfig.java
│ ├── controller
│ │ └── HelloController.java
│ └── init
│ └── WebAppInitializer.java
└── webapp
├── WEB-INF
│ └── views
│ ├── hello.jsp
│ └── index.jsp
└── static
└── css
└── style.css
配置依赖 (pom.xml)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>springmvc-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>5.3.9</spring.version>
</properties>
<dependencies>
<!-- Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Servlet API -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- JSP API -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
<scope>provided</scope>
</dependency>
<!-- JSTL -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Jackson for JSON -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.5</version>
</dependency>
</dependencies>
<build>
<finalName>springmvc-demo</finalName>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<port>8080</port>
<path>/</path>
<uriEncoding>UTF-8</uriEncoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
Web应用初始化器 (替代web.xml)
package com.example.init;
import com.example.config.WebConfig;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
// 如果有根配置类(如数据源配置),在这里返回
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
// Spring MVC配置类
return new Class[]{WebConfig.class};
}
@Override
protected String[] getServletMappings() {
// DispatcherServlet映射
return new String[]{"/"};
}
}
Spring MVC配置类 (替代XML配置)
package com.example.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan("com.example.controller")
public class WebConfig implements WebMvcConfigurer {
// 配置视图解析器
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
// 配置静态资源处理
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**")
.addResourceLocations("/static/");
}
}
控制器
package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.util.HashMap;
import java.util.Map;
@Controller
public class HelloController {
// 处理GET请求,返回视图
@GetMapping("/")
public String home() {
return "index";
}
// 处理GET请求,带参数
@GetMapping("/hello")
public String hello(@RequestParam(value = "name", defaultValue = "World") String name,
Model model) {
model.addAttribute("message", "Hello, " + name + "!");
return "hello";
}
// 处理POST请求
@PostMapping("/greet")
public String greet(@RequestParam String name,
@RequestParam String message,
Model model) {
model.addAttribute("message", "Hello " + name + ", " + message);
return "hello";
}
// 路径变量
@GetMapping("/user/{id}")
public String getUser(@PathVariable Long id, Model model) {
model.addAttribute("message", "User ID: " + id);
return "hello";
}
// 返回JSON数据
@GetMapping("/api/user/{id}")
@ResponseBody
public Map<String, Object> getUserJson(@PathVariable Long id) {
Map<String, Object> user = new HashMap<>();
user.put("id", id);
user.put("name", "User" + id);
user.put("email", "user" + id + "@example.com");
return user;
}
// 使用ModelAndView
@GetMapping("/model-and-view")
public ModelAndView getModelAndView() {
ModelAndView mav = new ModelAndView("hello");
mav.addObject("message", "This is from ModelAndView!");
return mav;
}
}
JSP视图
index.jsp (首页)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">Spring MVC 入门示例</title>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/css/style.css">
</head>
<body>
<div class="container">
<h1>Spring MVC 入门示例</h1>
<div class="form-section">
<h2>GET 请求示例</h2>
<a href="${pageContext.request.contextPath}/hello?name=张三" class="btn">点击发送GET请求</a>
</div>
<div class="form-section">
<h2>POST 请求示例</h2>
<form action="${pageContext.request.contextPath}/greet" method="post">
<input type="text" name="name" placeholder="请输入姓名" required>
<input type="text" name="message" placeholder="请输入消息" required>
<button type="submit" class="btn">发送POST请求</button>
</form>
</div>
<div class="form-section">
<h2>路径变量示例</h2>
<a href="${pageContext.request.contextPath}/user/123" class="btn">查看用户123</a>
</div>
<div class="form-section">
<h2>JSON响应示例</h2>
<button onclick="getUserJson()" class="btn">获取用户JSON</button>
<pre id="json-result"></pre>
</div>
<div class="form-section">
<h2>ModelAndView示例</h2>
<a href="${pageContext.request.contextPath}/model-and-view" class="btn">查看ModelAndView</a>
</div>
</div>
<script>
function getUserJson() {
fetch('${pageContext.request.contextPath}/api/user/1')
.then(response => response.json())
.then(data => {
document.getElementById('json-result').textContent =
JSON.stringify(data, null, 2);
})
.catch(error => console.error('Error:', error));
}
</script>
</body>
</html>
hello.jsp (结果页)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">响应结果</title>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/css/style.css">
</head>
<body>
<div class="container">
<h1>Spring MVC 响应结果</h1>
<div class="result-box">
<p class="message">${message}</p>
</div>
<a href="${pageContext.request.contextPath}/" class="btn">返回首页</a>
</div>
</body>
</html>
CSS样式
/* static/css/style.css */
body {
font-family: Arial, sans-serif;
background-color: #f5f5f5;
margin: 0;
padding: 20px;
}
.container {
max-width: 600px;
margin: 0 auto;
background: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
h1 {
color: #333;
text-align: center;
border-bottom: 3px solid #4CAF50;
padding-bottom: 15px;
}
h2 {
color: #666;
margin-top: 20px;
}
.form-section {
background: #f9f9f9;
padding: 15px;
margin: 15px 0;
border-radius: 5px;
border-left: 4px solid #4CAF50;
}
.form-section form {
display: flex;
gap: 10px;
flex-wrap: wrap;
margin: 10px 0;
}
input[type="text"] {
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
flex: 1;
min-width: 150px;
}
.btn {
display: inline-block;
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
text-decoration: none;
font-size: 14px;
transition: background-color 0.3s;
margin: 5px 0;
}
.btn:hover {
background-color: #45a049;
}
button.btn {
background-color: #007bff;
}
button.btn:hover {
background-color: #0056b3;
}
.result-box {
background: #e8f5e9;
padding: 20px;
border-radius: 5px;
text-align: center;
margin: 20px 0;
}
.message {
font-size: 18px;
color: #333;
}
#json-result {
background: #f0f0f0;
padding: 10px;
border-radius: 4px;
overflow-x: auto;
min-height: 100px;
font-size: 14px;
}
运行方法
使用Maven插件运行:
cd springmvc-demo mvn clean package mvn tomcat7:run
或者部署到Tomcat:
- 构建项目:
mvn clean package - 将生成的
springmvc-demo.war文件复制到Tomcat的webapps目录 - 启动Tomcat服务器
访问测试
访问地址:http://localhost:8080/springmvc-demo/
测试功能:
- GET请求:点击"点击发送GET请求"按钮
- POST请求:填写姓名和消息后点击"发送POST请求"
- 路径变量:点击"查看用户123"
- JSON响应:点击"获取用户JSON"按钮
- ModelAndView:点击"查看ModelAndView"
核心概念说明
| 注解/概念 | 说明 |
|---|---|
@Controller |
标识这是一个Spring MVC控制器 |
@RequestMapping |
映射HTTP请求到处理方法 |
@GetMapping |
只处理GET请求 |
@PostMapping |
只处理POST请求 |
@RequestParam |
获取请求参数 |
@PathVariable |
获取URL路径变量 |
@ResponseBody |
直接返回数据(JSON) |
Model |
向视图传递数据 |
ModelAndView |
同时返回模型和视图 |
这个入门案例涵盖了Spring MVC的核心功能,包括请求处理、参数绑定、视图解析、JSON响应等,通过修改代码,你可以逐步扩展更多的功能。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播