首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Spring MVC 從零搭建完整教學(IntelliJ IDEA 版)

     編輯:程式設計綜合問答

環境準備

  • JDK 17+
  • Maven 3.8+
  • IntelliJ IDEA 2023+ (Ultimate 或 Community + Maven 插件)
  • Tomcat 9/10 或內嵌 Jetty

專案結構(Maven 標準目錄)

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/圖片

核心配置類(Java Config 替代 web.xml)

@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/");
    }
}

DispatcherServlet 初始化(無 web.xml)

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

@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());
    }
}

JSP 視圖 (/WEB-INF/views/hello.jsp)

<%@ page contentType="text/html;charset=UTF-8" %>
<html><body>
<h1>${msg}</h1>
<a href="${pageContext.request.contextPath}/hello/api">呼叫 API</a>
</body></html>

整合常用技術棧(可選)

技術關鍵依賴配置要點
MyBatismybatis-spring-boot-starter@MapperScan + application.yml 資料源
Thymeleafthymeleaf-spring5ViewResolver 替換為 ThymeleafViewResolver
JPA/Hibernatespring-boot-starter-data-jpaEntity + JpaRepository
Validationspring-boot-starter-validation@Valid + BindingResult

IntelliJ IDEA 專案建立步驟

  1. File → New → Project → Maven → 勾選「Create from archetype」→ 選 `webapp` 或手動建立。
  2. 專案右鍵 → Add Framework Support → 勾選 Spring、Spring MVC。
  3. Run → Edit Configurations → + → Tomcat Server → Local → Deployment 選擇 `war exploded`。
  4. 啟動,瀏覽器訪問 `https://localhost:8080/hello`。

學習資源推薦

總結

Spring MVC 核心只有 **DispatcherServlet + Controller + ViewResolver** 三大件。掌握 Java Config 風格,配合 IDEA 的 Maven/Tomcat 整合,即可快速啟動專案並專注業務開發。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved