在使用spring的項目中,前台傳遞參數到后台是經常遇到的事, 我們必須熟練掌握一些常用的參數傳遞方式和注解的使用,廢話少說,直接上正文。
1. @requestMapping: 類級別和方法級別的注解, 指明前后台解析的路徑。 有value屬性(一個參數時默認)指定url路徑解析,method屬性指定提交方式(默認為get提交)
@RequestMapping(value = "/testing") public class QuestionSetDisplayController extends BaseController {}
@RequestMapping(value = "/applicant/recover") public BaseModel recover(String cellphone) throws OTPException { return userService.recover(cellphone); }
2. @RequestParam: 請求參數規則注解。 value屬性匹配前台傳遞的參數(一個參數時默認),required屬性此字段是否必須傳值(boolean,默認為true),defaultValue此參數的默認值(存在此參數時,說明前台不必需傳遞參數,required為false)
@RequestMapping("/login") //url: /login?name=tom public String login(@RequestParam(value="age",required=false,defaultValue="24") String agenum,@RequestParam("name") String name){ return "hello"; }
3. @PathVariable: url參數注解, 一般用於從url中獲取參數
@RequestMapping(value = "/system/getAllCodeTableData/{category}", method = RequestMethod.GET) //前台url: '/system/getAllCodeTableData/APPLICANT_ENGLISH'
public List<CodeTableModel> getCodeTableModelByCategory(@PathVariable String category) throws OTPException {
return codeTableService.getCodeTableModelByCategory(category);
}
4. 特殊的 屬性編輯器 在前台到后台data日期類型等的轉化會出錯,此時我們需要屬性編輯器進行屬性的轉化 //日期傳遞參數會產生異常,因此在傳遞時間參數時,需要進行類型轉換,在初始化時進行數據的綁定與轉化
@RequestMapping(value="/todate/{data}",method=RequestMethod.GET) public String todate(@PathVariable("data") Date date){ System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(date)); return "start"; } @InitBinder //初始化參數綁定, 日期類型的轉化, public void initBinder(ServletRequestDataBinder binder){ binder.registerCustomEditor(java.util.Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true)); }
---------------------------------------------------
關於前台angular使用get/post傳遞參數, 后台接收
get方式傳參
$scope.getFlows = function(key) { $scope.flows = Flow.search({type:key}) // 參數以{key: value, ...}傳遞 } @GetMapping("") @ResponseBody public List<DefinitionDTO> query( @RequestParam(value="type") String type) throws Exception { // 后台以requestparam來獲取參數 if (!type.equals("all")) { return activitiService.findByKey(type); } return activitiService.findAll(); }
post傳參
$scope.batchDelete = function() { $scope.selectedVehicles = getSelected(); if (angular.isDefined($scope.selectedVehicles) && $scope.selectedVehicles.length > 0) { var vehicle = {ids: $scope.selectedVehicles}; //前台封裝成對象 VehicleInfo.batchDelete(vehicle, function(response) { toPage(1, $scope.pageInfos.size, null); }); } } @PostMapping("/batchDelete") @ResponseBody //后台以requestbody注解來獲取請求對象參數 public void batchDelete(@RequestBody VehicleDTO vehicle) throws Exception { for (Long id : vehicle.getIds()) { vehicleService.deleteVehicle(id, Boolean.TRUE); } }