wordpress好看的背景圖片/杭州優(yōu)化公司在線留言
目錄
基本概念
編寫 Controller 的步驟和要點
1. 定義 Controller 類
2. 映射請求
3. 處理請求參數(shù)
4. 調(diào)用業(yè)務(wù)邏輯
5. 返回響應(yīng)
場景示例
1. 簡單的 Hello World 示例
2. 處理路徑變量和請求參數(shù)
3. 處理表單提交
4. 處理 JSON 數(shù)據(jù)
5. 異常處理
基本概念
Controller 是 Spring MVC 架構(gòu)中的核心組件之一,它負責(zé)接收客戶端的請求,調(diào)用相應(yīng)的業(yè)務(wù)邏輯進行處理,并將處理結(jié)果返回給客戶端。通常,Controller 會根據(jù)請求的 URL 和 HTTP 方法,將請求分發(fā)到具體的處理方法上。
編寫 Controller 的步驟和要點
1. 定義 Controller 類
使用?@Controller
?注解標(biāo)記一個類,表明該類是一個 Spring MVC 的控制器。也可以使用?@RestController
?注解,它是?@Controller
?和?@ResponseBody
?的組合,適用于返回 JSON 或 XML 等數(shù)據(jù)的場景。
2. 映射請求
使用?@RequestMapping
、@GetMapping
、@PostMapping
?等注解將 HTTP 請求映射到 Controller 中的具體方法上。這些注解可以指定請求的 URL、HTTP 方法、請求參數(shù)等。
3. 處理請求參數(shù)
使用?@RequestParam
、@PathVariable
、@RequestBody
?等注解來獲取請求中的參數(shù),并將其綁定到方法的參數(shù)上。
4. 調(diào)用業(yè)務(wù)邏輯
在處理方法中調(diào)用業(yè)務(wù)邏輯層(如 Service 層)的方法,完成具體的業(yè)務(wù)處理。
5. 返回響應(yīng)
可以返回視圖名、ModelAndView
?對象、ResponseEntity
?對象或直接返回數(shù)據(jù)(使用?@ResponseBody
?注解)。
場景示例
1. 簡單的 Hello World 示例
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;@Controller
public class HelloController {@GetMapping("/hello")@ResponseBodypublic String sayHello() {return "Hello, World!";}
}
解釋:
@Controller
?注解標(biāo)記?HelloController
?類為控制器。@GetMapping("/hello")
?注解將?/hello
?的 GET 請求映射到?sayHello
?方法上。@ResponseBody
?注解表示方法的返回值將直接作為 HTTP 響應(yīng)的主體內(nèi)容返回給客戶端。
2. 處理路徑變量和請求參數(shù)
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;@Controller
public class UserController {@GetMapping("/users/{id}")@ResponseBodypublic String getUserById(@PathVariable("id") int userId) {return "User ID: " + userId;}@GetMapping("/search")@ResponseBodypublic String searchUsers(@RequestParam("keyword") String keyword) {return "Searching for users with keyword: " + keyword;}
}
解釋:
@GetMapping("/users/{id}")
?定義了一個帶有路徑變量的請求映射,{id}
?表示路徑中的變量部分。@PathVariable("id")
?注解將路徑變量?id
?的值綁定到?userId
?參數(shù)上。@GetMapping("/search")
?定義了一個普通的請求映射。@RequestParam("keyword")
?注解將請求參數(shù)?keyword
?的值綁定到?keyword
?參數(shù)上。
3. 處理表單提交
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;@Controller
public class FormController {@GetMapping("/form")public String showForm() {return "form"; // 返回視圖名}@PostMapping("/form")public String processForm(@RequestParam("name") String name, @RequestParam("age") int age, Model model) {model.addAttribute("name", name);model.addAttribute("age", age);return "result"; // 返回視圖名}
}
解釋:
@GetMapping("/form")
?處理 GET 請求,返回?form
?視圖,通常是一個表單頁面。@PostMapping("/form")
?處理表單提交的 POST 請求,使用?@RequestParam
?獲取表單數(shù)據(jù),并將數(shù)據(jù)添加到?Model
?中,最后返回?result
?視圖,顯示處理結(jié)果。
4. 處理 JSON 數(shù)據(jù)
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;@Controller
public class JsonController {@PostMapping("/json")@ResponseBodypublic ResponseEntity<User> processJson(@RequestBody User user) {// 處理用戶數(shù)據(jù)return new ResponseEntity<>(user, HttpStatus.OK);}
}class User {private String name;private int age;// Getters and Setterspublic String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}
}
解釋:
@PostMapping("/json")
?處理 POST 請求。@RequestBody
?注解將請求體中的 JSON 數(shù)據(jù)轉(zhuǎn)換為?User
?對象。ResponseEntity
?用于封裝響應(yīng)數(shù)據(jù)和 HTTP 狀態(tài)碼,將處理后的?User
?對象以 JSON 格式返回給客戶端。
5. 異常處理
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;@Controller
public class ExceptionController {@GetMapping("/error")@ResponseBodypublic String throwException() {throw new RuntimeException("Something went wrong!");}@ExceptionHandler(RuntimeException.class)@ResponseBodypublic ResponseEntity<String> handleException(RuntimeException ex) {return new ResponseEntity<>(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);}
}
解釋:
@GetMapping("/error")
?方法故意拋出一個?RuntimeException
。@ExceptionHandler(RuntimeException.class)
?注解定義了一個異常處理方法,當(dāng) Controller 中拋出?RuntimeException
?時,會調(diào)用該方法進行處理,返回錯誤信息和 HTTP 狀態(tài)碼 500。
通過以上示例,可以看到 Controller 在不同場景下的編寫方式和應(yīng)用,根據(jù)具體的需求選擇合適的注解和處理方式,能夠高效地處理客戶端請求。