溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

SpringBoot中的mvc怎么用

發布時間:2022-02-18 14:14:09 來源:億速云 閱讀:180 作者:小新 欄目:開發技術
# SpringBoot中的MVC怎么用

## 一、Spring MVC概述

Spring MVC是Spring框架提供的Web模塊,基于經典的MVC(Model-View-Controller)設計模式。在SpringBoot中,通過自動配置簡化了傳統Spring MVC的配置流程。

### 1.1 核心組件
- **DispatcherServlet**:前端控制器,統一處理請求
- **HandlerMapping**:請求到處理器的映射
- **Controller**:業務邏輯處理器
- **ViewResolver**:視圖解析器
- **Model**:數據模型載體

### 1.2 工作流程
1. 用戶發起HTTP請求
2. DispatcherServlet接收請求
3. HandlerMapping找到對應的Controller
4. Controller處理業務并返回ModelAndView
5. ViewResolver解析視圖
6. 渲染視圖返回響應

## 二、快速搭建SpringBoot MVC項目

### 2.1 創建項目
使用Spring Initializr創建項目時勾選:
- Spring Web(包含Spring MVC)
- Thymeleaf(可選模板引擎)

```xml
<!-- pom.xml關鍵依賴 -->
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
</dependencies>

2.2 基礎配置

# application.properties
server.port=8080
spring.mvc.view.prefix=/templates/
spring.mvc.view.suffix=.html

三、控制器(Controller)開發

3.1 基本控制器示例

@Controller
@RequestMapping("/demo")
public class DemoController {
    
    @GetMapping("/hello")
    public String sayHello(Model model) {
        model.addAttribute("message", "Hello Spring MVC!");
        return "hello"; // 對應templates/hello.html
    }
}

3.2 常用注解

注解 說明
@Controller 聲明為控制器
@RestController 控制器+@ResponseBody
@RequestMapping 請求映射基礎注解
@GetMapping GET請求映射
@PostMapping POST請求映射
@PathVariable 路徑變量
@RequestParam 請求參數
@RequestBody 請求體綁定
@ModelAttribute 模型屬性

3.3 參數綁定示例

@PostMapping("/user")
public String createUser(
    @RequestParam String username,
    @RequestParam(defaultValue = "18") int age,
    @RequestBody UserDTO user) {
    // 處理邏輯
    return "result";
}

四、視圖技術集成

4.1 Thymeleaf模板

<!-- templates/hello.html -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Demo Page</title>
</head>
<body>
    <h1 th:text="${message}">Default Message</h1>
</body>
</html>

4.2 返回JSON數據

@RestController
@RequestMapping("/api")
public class ApiController {
    
    @GetMapping("/data")
    public Map<String, Object> getData() {
        return Map.of(
            "status", 200,
            "data", "Some API Data"
        );
    }
}

五、異常處理機制

5.1 全局異常處理

@ControllerAdvice
public class GlobalExceptionHandler {
    
    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleException(Exception e) {
        return ResponseEntity
            .status(HttpStatus.INTERNAL_SERVER_ERROR)
            .body("Error: " + e.getMessage());
    }
}

5.2 自定義異常

@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
    public ResourceNotFoundException(String message) {
        super(message);
    }
}

六、RESTful API開發

6.1 標準REST控制器

@RestController
@RequestMapping("/api/users")
public class UserController {
    
    @GetMapping
    public List<User> listUsers() {
        // 返回用戶列表
    }
    
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        // 返回單個用戶
    }
    
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public User createUser(@RequestBody User user) {
        // 創建用戶
    }
    
    @PutMapping("/{id}")
    public User updateUser(@PathVariable Long id, 
                         @RequestBody User user) {
        // 更新用戶
    }
    
    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void deleteUser(@PathVariable Long id) {
        // 刪除用戶
    }
}

6.2 常用響應狀態碼

  • 200 OK - 成功GET請求
  • 201 Created - 成功創建資源
  • 204 No Content - 成功無內容返回
  • 400 Bad Request - 請求參數錯誤
  • 401 Unauthorized - 未認證
  • 403 Forbidden - 無權限
  • 404 Not Found - 資源不存在
  • 500 Internal Server Error - 服務器錯誤

七、高級特性

7.1 文件上傳

@PostMapping("/upload")
public String handleUpload(@RequestParam("file") MultipartFile file) {
    if (!file.isEmpty()) {
        // 保存文件邏輯
        return "Upload success";
    }
    return "Upload failed";
}

7.2 攔截器實現

public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, 
                           HttpServletResponse response, 
                           Object handler) throws Exception {
        // 認證邏輯
        return true; // 返回false則中斷請求
    }
}

// 注冊攔截器
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new AuthInterceptor())
                .addPathPatterns("/admin/**");
    }
}

7.3 跨域支持

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .maxAge(3600);
    }
}

八、最佳實踐

  1. 分層清晰:Controller只負責路由和參數處理,業務邏輯放在Service層
  2. 統一響應格式:使用ResponseEntity或自定義Result類
  3. 參數校驗:結合Hibernate Validator進行驗證
  4. 接口文檔:集成Swagger或OpenAPI
  5. 全局異常處理:避免直接拋出原生異常

九、常見問題解決

  1. 404錯誤

    • 檢查@RequestMapping路徑
    • 確認靜態資源位置正確
    • 查看是否被攔截器攔截
  2. 模板引擎不生效

    • 檢查thymeleaf依賴
    • 確認模板文件放在templates目錄
    • 檢查視圖解析器配置
  3. POST請求接收不到參數

    • 檢查是否缺少@RequestBody
    • 確認Content-Type為application/json
    • 檢查參數名是否匹配

十、總結

SpringBoot通過自動配置極大簡化了Spring MVC的使用,開發者只需: 1. 添加spring-boot-starter-web依賴 2. 創建@Controller或@RestController 3. 定義@RequestMapping方法 4. 處理業務邏輯并返回結果

結合Thymeleaf等模板引擎可以快速開發傳統Web應用,而@RestController則適合構建RESTful API。合理運用攔截器、異常處理等機制可以構建健壯的Web應用程序。 “`

(全文約2150字,涵蓋SpringBoot MVC核心用法和實用技巧)

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女