本文目录导读:

在Java中整合SpringMVC有多种方式,我为你详细介绍最常见的几种方案:
传统XML配置方式(适用于Servlet 3.0以下容器)
项目结构
src/main/java
├── com/example/controller
│ └── UserController.java
├── com/example/config
│ └── WebConfig.java
src/main/webapp/WEB-INF
├── web.xml
└── views
└── index.jsp
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_3_1.xsd"
version="3.1">
<!-- 1. 配置Spring根容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 2. 配置SpringMVC前端控制器 -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
SpringMVC配置文件(springmvc.xml)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="...">
<!-- 开启注解驱动 -->
<mvc:annotation-driven/>
<!-- 扫描Controller -->
<context:component-scan base-package="com.example.controller"/>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 静态资源处理 -->
<mvc:resources mapping="/static/**" location="/static/"/>
</beans>
全注解配置方式(推荐,适用于Servlet 3.0+)
启动类(实现WebApplicationInitializer)
package com.example.config;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;
public class WebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) {
// 1. 创建Spring应用上下文
AnnotationConfigWebApplicationContext context =
new AnnotationConfigWebApplicationContext();
// 2. 注册配置类
context.register(WebConfig.class);
// 3. 创建DispatcherServlet
DispatcherServlet dispatcherServlet = new DispatcherServlet(context);
// 4. 注册Servlet
ServletRegistration.Dynamic registration =
servletContext.addServlet("dispatcher", dispatcherServlet);
registration.setLoadOnStartup(1);
registration.addMapping("/");
}
}
SpringMVC配置类
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(basePackages = "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/");
}
}
Controller示例
package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller
@RequestMapping("/users")
public class UserController {
// 返回视图
@GetMapping("/list")
public String list() {
return "userList"; // 对应 /WEB-INF/views/userList.jsp
}
// RESTful接口
@GetMapping("/{id}")
@ResponseBody
public User getUser(@PathVariable Long id) {
return userService.findById(id);
}
// 接收表单数据
@PostMapping
public String createUser(User user) {
userService.save(user);
return "redirect:/users/list";
}
}
Spring Boot方式(最简捷)
依赖配置(pom.xml)
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- JSP支持(可选) -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
启动类
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
application.yml配置
spring:
mvc:
view:
prefix: /WEB-INF/views/
suffix: .jsp
resources:
static-locations: classpath:/static/
整合关键要点
组件扫描配置
// 确保扫描到所有组件
@ComponentScan({
"com.example.controller",
"com.example.service",
"com.example.dao"
})
异常处理
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = Exception.class)
public ModelAndView handleException(Exception e) {
ModelAndView mv = new ModelAndView();
mv.addObject("error", e.getMessage());
mv.setViewName("error");
return mv;
}
}
拦截器配置
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/login", "/static/**");
}
}
CORS跨域配置
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://localhost:8080")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*");
}
}
推荐整合方案
- 新项目:优先使用Spring Boot + 注解配置
- 旧项目改造:使用全注解方式,逐步替换XML配置
- 学习测试:传统XML配置便于理解底层原理
选择合适的整合方式取决于你的项目需求和技术栈,Spring Boot是目前最推荐的方式,因为它大大简化了配置工作。