常用注解
Controller
注解一個類表示控制器,Spring MVC會自動掃描标注了這個注解的類。
RequestMapping
請求路徑映射,可以标注類,也可以是方法,可以指定請求類型,預設不指定為全部接收。
RequestParam
放在參數前,表示隻能接收參數a=b格式的資料,即Content-Type為application/x-www-form-urlencoded類型的内容。
RequestBody
放在參數前,表示參數從request body中擷取,而不是從位址欄擷取,是以這肯定是接收一個POST請求的非a=b格式的資料,即Content-Type不為application/x-www-form-urlencoded類型的内容。
ResponseBody
放在方法上或者傳回類型前,表示此方法傳回的資料放在response body裡面,而不是跳轉頁面。一般用于ajax請求,傳回json資料。
RestController
這個是Controller和ResponseBody的組合注解,表示@Controller辨別的類裡面的所有傳回參數都放在response body裡面。
PathVariable
路徑綁定變量,用于綁定restful路徑上的變量。
@RequestHeader
放在方法參數前,用來擷取request header中的參數值。
@CookieValue;
放在方法參數前,用來擷取request header cookie中的參數值。
GetMapping PostMapping PutMapping..
*Mapping的是Spring4.3加入的新注解,表示特定的請求類型路徑映射,而不需要寫RequestMethod來指定請求類型。
示範
import org.dom4j.util.UserDataElement;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping(value = "/get/{no}", method = RequestMethod.GET)
@ResponseBody
public Object get(@PathVariable("no") String no) {
return new UserDataElement("");
}
@RequestMapping(value = "/save", method = RequestMethod.POST)
public void save(@RequestBody UserDataElement user) {
}
}