我需要知道Spring启动如何在运行时将URL中的请求参数映射到POJO。
以下是带参数
的示例网址 http://localhost:8080/api/public/properties?serviceType.in=SALE&title.contains=some text&price.greaterOrEqualThan=500&price.lessOrEqualThan=50000&propertyType.in=HOUSE&locationId.in=1,2&landSize.greaterOrEqualThan=100&landSize.lessOrEqualThan=1000&bedrooms.greaterOrEqualThan=2&bedrooms.lessOrEqualThan=5&bathrooms.greaterOrEqualThan=1&bathrooms.lessOrEqualThan=3&ageType.in=BRAND_NEW
我有许多Criteria类,它们都扩展了PropertyCriteria类。举个例子,如果请求不包含任何参数,我希望控制器使用PropertyCriteria。如果请求包含卧室参数,我希望控制器使用HousePropertyCriteria等。请参阅以下控制器方法示例
@GetMapping("/public/properties")
public ResponseEntity<List<Property>>
getAllPropertiesNested(HttpServletRequest request) {
if (condition1 == true) {
EntityOnePropertyCriteria c1 = new EntityOnePropertyCriteria();
//populate c1 using request object
} else {
EntityTwoPropertyCriteria c2 = new EntityTwoPropertyCriteria();
//populate c2 using request object
}
}
答案 0 :(得分:0)
手动执行此操作的两种方法: 1)我想知道在你的项目中你是否可以访问HttpServletRequest对象。如果是这种情况,您可以使用方法request.getParameter(nameParam)来填充您需要的对象。
2)使用beanutils库并使用该方法 BeanUtils.copyProperties(dest,source) 使用&#34; @RequestParam Map source&#34;在您的控制器中并替换您想要填充的目标对象
答案 1 :(得分:0)
我在this link找到了答案。
public static void applyMapOntoInstance(Object instance,Map properties){
if (properties != null && !properties.isEmpty()) {
BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(instance);
beanWrapper.setAutoGrowNestedPaths(true);
for (Iterator<?> iterator = properties.entrySet().iterator(); iterator.hasNext();) {
Map.Entry<String, ?> entry = (Map.Entry<String, ?>) iterator.next();
String propertyName = entry.getKey();
if (beanWrapper.isWritableProperty(propertyName)) {
beanWrapper.setPropertyValue(propertyName, entry.getValue());
}
}
}
}
我的控制器方法现在看起来像:
@GetMapping("/public/properties")
@Timed
public ResponseEntity<List<Property>> getAllPropertiesNested(HttpServletRequest request) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
HttpHeaders headers = null;
if (requestContains("bedrooms", request)) {
HousePropertyCriteria housePropertyCriteria = new HousePropertyCriteria();
applyMapOntoInstance(housePropertyCriteria, request.getParameterMap());
Page<HouseProperty> page = housePropertyQueryService.findByCriteriaNested(housePropertyCriteria, pageable);
headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/public/properties");
return new ResponseEntity(page.getContent(), headers, HttpStatus.OK);
} else {
Page<Property> page = propertyQueryService.findByCriteriaNested(criteria, pageable);
headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/public/properties");
return new ResponseEntity(page.getContent(), headers, HttpStatus.OK);
}
}