本文目录导读:

我来为你提供一个Java SpringMVC的快速入门指南,从环境搭建到第一个案例。
📋 环境准备
开发工具
- IDE: IntelliJ IDEA 或 Eclipse
- JDK: 1.8+
- Maven: 3.6+
- 服务器: Tomcat 8+
创建Maven项目
在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>
<spring.version>5.3.20</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>
<!-- JSTL -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
</project>
🏗️ 项目结构
springmvc-demo/
├── src/
│ └── main/
│ ├── java/
│ │ └── com/example/
│ │ └── controller/
│ │ └── HelloController.java
│ ├── webapp/
│ │ ├── WEB-INF/
│ │ │ ├── web.xml
│ │ │ └── views/
│ │ │ └── hello.jsp
│ │ └── index.jsp
│ └── resources/
│ └── springmvc-servlet.xml
└── pom.xml
🔧 核心配置
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">
<!-- 配置SpringMVC DispatcherServlet -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 配置字符编码过滤器 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
SpringMVC配置文件 (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">
<!-- 扫描控制器包 -->
<context:component-scan base-package="com.example.controller"/>
<!-- 开启SpringMVC注解支持 -->
<mvc:annotation-driven/>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 配置静态资源处理 -->
<mvc:default-servlet-handler/>
</beans>
💻 创建控制器和视图
控制器类 (HelloController.java)
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.ArrayList;
import java.util.List;
@Controller
public class HelloController {
// 简单返回视图
@RequestMapping("/hello")
public String hello(Model model) {
model.addAttribute("message", "Hello Spring MVC!");
return "hello";
}
// 带参数请求
@RequestMapping("/greet")
public String greet(@RequestParam(value = "name", defaultValue = "Guest") String name,
Model model) {
model.addAttribute("message", "Hello, " + name + "!");
return "hello";
}
// RESTful风格参数
@RequestMapping("/user/{id}")
public String getUser(@PathVariable("id") Integer id, Model model) {
model.addAttribute("message", "User ID: " + id);
return "hello";
}
// 返回JSON数据 (需要Jackson依赖)
@RequestMapping("/api/user")
@ResponseBody
public User getUserJson() {
return new User(1, "张三", "zhangsan@example.com");
}
// 列表数据展示
@RequestMapping("/users")
public String listUsers(Model model) {
List<User> users = new ArrayList<>();
users.add(new User(1, "张三", "zhangsan@example.com"));
users.add(new User(2, "李四", "lisi@example.com"));
users.add(new User(3, "王五", "wangwu@example.com"));
model.addAttribute("users", users);
return "userList";
}
// 使用ModelAndView
@RequestMapping("/modelview")
public ModelAndView modelAndView() {
ModelAndView mv = new ModelAndView("hello");
mv.addObject("message", "This is ModelAndView example");
return mv;
}
// 内部类 - 用户实体
static class User {
private int id;
private String name;
private String email;
public User(int id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
// Getters and Setters
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
}
}
JSP视图文件
hello.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>Spring MVC Demo</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 50px;
text-align: center;
}
.message {
color: #2c3e50;
font-size: 24px;
margin: 20px;
}
.link {
display: inline-block;
margin: 10px;
padding: 10px 20px;
background-color: #3498db;
color: white;
text-decoration: none;
border-radius: 5px;
}
.link:hover {
background-color: #2980b9;
}
</style>
</head>
<body>
<h1>Spring MVC 入门案例</h1>
<div class="message">${message}</div>
<div>
<h3>测试链接:</h3>
<a href="${pageContext.request.contextPath}/hello" class="link">Hello</a>
<a href="${pageContext.request.contextPath}/greet?name=SpringMVC" class="link">Greet</a>
<a href="${pageContext.request.contextPath}/user/123" class="link">User ID</a>
<a href="${pageContext.request.contextPath}/users" class="link">用户列表</a>
</div>
</body>
</html>
userList.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>用户列表</title>
<style>
body { font-family: Arial, sans-serif; margin: 50px; }
table {
border-collapse: collapse;
width: 60%;
margin: 20px auto;
}
th, td {
border: 1px solid #ddd;
padding: 12px;
text-align: left;
}
th { background-color: #3498db; color: white; }
tr:nth-child(even) { background-color: #f2f2f2; }
</style>
</head>
<body>
<h2 style="text-align: center;">用户列表</h2>
<table>
<tr>
<th>ID</th>
<th>姓名</th>
<th>邮箱</th>
</tr>
<c:forEach items="${users}" var="user">
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.email}</td>
</tr>
</c:forEach>
</table>
<div style="text-align: center;">
<a href="${pageContext.request.contextPath}/hello" class="link">返回首页</a>
</div>
</body>
</html>
🚀 运行测试
配置Tomcat
- 运行配置 → 添加 Tomcat Server
- Deployment 中选择你的项目
- Application context 设置为
/springmvc-demo
访问测试
# 基本测试 http://localhost:8080/springmvc-demo/hello # 带参数测试 http://localhost:8080/springmvc-demo/greet?name=张三 # RESTful风格 http://localhost:8080/springmvc-demo/user/100 # 列表展示 http://localhost:8080/springmvc-demo/users
📚 核心注解说明
| 注解 | 用途 |
|---|---|
@Controller |
标记为控制器类 |
@RequestMapping |
映射请求路径 |
@RequestParam |
获取请求参数 |
@PathVariable |
获取RESTful路径变量 |
@ResponseBody |
直接返回数据(不解析视图) |
@ModelAttribute |
绑定模型数据 |
🎯 进阶学习方向
- 数据验证: 使用
@Valid和@NotBlank等注解 - 拦截器: 实现
HandlerInterceptor接口 - 异常处理: 使用
@ControllerAdvice+@ExceptionHandler - 国际化: 配置
LocaleResolver和消息资源文件 - 文件上传: 配置
MultipartResolver - RESTful API: 使用
@RestController+ 状态码处理
⚠️ 常见问题解决
403错误:检查静态资源配置 404错误:检查视图路径和请求映射 乱码问题:确保编码过滤器配置正确 Java版本冲突:检查Maven依赖版本兼容性
这个入门案例包含了SpringMVC的核心要素:控制器、请求映射、参数处理、视图解析和JSTL标签库的使用,掌握这些基础后,你就可以开始构建更复杂的Web应用了!
版权声明:足球直播
足球直播
足球直播
足球直播
足球直播
中超直播
中超直播
中超直播
中超直播
中超直播
英超直播
英超直播
英超直播
英超直播
英超直播
德甲直播
德甲直播
德甲直播
德甲直播
德甲直播
西甲直播
西甲直播
西甲直播
西甲直播
西甲直播
意甲直播
意甲直播
意甲直播
意甲直播
意甲直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
足球直播
足球直播
足球直播
足球直播
足球直播
中超直播
中超直播
中超直播
中超直播
中超直播
英超直播
英超直播
英超直播
英超直播
英超直播
德甲直播
德甲直播
德甲直播
德甲直播
德甲直播
西甲直播
西甲直播
西甲直播
西甲直播
西甲直播
意甲直播
意甲直播
意甲直播
意甲直播
意甲直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
足球直播
足球直播
足球直播
足球直播
足球直播
中超直播
中超直播
中超直播
中超直播
中超直播
英超直播
英超直播
英超直播
英超直播
英超直播
德甲直播
德甲直播
德甲直播
德甲直播
德甲直播
西甲直播
西甲直播
西甲直播
西甲直播
西甲直播
意甲直播
意甲直播
意甲直播
意甲直播
意甲直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播