spring-mvc-demo/
├─ src/main/java/com/example/
│ ├─ config/ # 配置類
│ ├─ controller/ # 控制器
│ ├─ service/ # 服務層
│ ├─ dao/ # 資料存取
│ └─ entity/ # 實體類
├─ src/main/resources/
│ ├─ application.properties
│ └─ mybatis/ # 若整合 MyBatis
└─ src/main/webapp/
├─ WEB-INF/
│ └─ views/ # JSP/Thymeleaf 模板
└─ static/ # CSS/JS/圖片
@Configuration
@EnableWebMvc
@ComponentScan("com.example")
public class WebMvcConfig implements WebMvcConfigurer {
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver r = new InternalResourceViewResolver();
r.setPrefix("/WEB-INF/views/");
r.setSuffix(".jsp");
return r;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addHandler("/static/**").addResourceLocations("/static/");
}
}
public class WebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext ctx) {
AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
root.register(WebMvcConfig.class);
ctx.addListener(new ContextLoaderListener(root));
ServletRegistration.Dynamic dispatcher = ctx.addServlet("dispatcher", new DispatcherServlet(root));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
@Controller
@RequestMapping("/hello")
public class HelloController {
@GetMapping
public String index(Model model) {
model.addAttribute("msg", "Hello Spring MVC!");
return "hello"; // 對應 /WEB-INF/views/hello.jsp
}
@GetMapping("/api")
@ResponseBody
public Map api() {
return Map.of("status", "ok", "time", System.currentTimeMillis());
}
}
<%@ page contentType="text/html;charset=UTF-8" %>
<html><body>
<h1>${msg}</h1>
<a href="${pageContext.request.contextPath}/hello/api">呼叫 API</a>
</body></html>
| 技術 | 關鍵依賴 | 配置要點 |
|---|---|---|
| MyBatis | mybatis-spring-boot-starter | @MapperScan + application.yml 資料源 |
| Thymeleaf | thymeleaf-spring5 | ViewResolver 替換為 ThymeleafViewResolver |
| JPA/Hibernate | spring-boot-starter-data-jpa | Entity + JpaRepository |
| Validation | spring-boot-starter-validation | @Valid + BindingResult |
Spring MVC 核心只有 **DispatcherServlet + Controller + ViewResolver** 三大件。掌握 Java Config 風格,配合 IDEA 的 Maven/Tomcat 整合,即可快速啟動專案並專注業務開發。