我需要一些技术输入来解决这个问题:
我想搜索具有不同参数的合约。现在我搜索五个参数:FromDate,EndDate,Season,Name和Category。将来应该可以搜索动态的参数方式。所有参数都是合同域对象的值。
var contract= {fromDate:moment($('#datepickerVon').val(), 'DD-MM-YYYY').format('DD-MM-YYYY'),
endDate:moment($('#datepickerBis').val(), 'DD-MM-YYYY').format('DD-MM-YYYY'),
season:$('#season').val(),
name:$('#name').val(),
category:$('#category').val()};
$.ajax({
url:'/contract/search/',
dataType: "json",
type: "GET",
traditional : true,
contentType: "application/json",
data: contract,
success: function(data) {
}
});
我使用了这种控制器方法
@RequestMapping(value = "/search/", method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<String> getContractFromSearch(
@RequestParam Map<String, String> allRequestParams, ModelMap model) {List<Vertrag> result = Contract.findAllContractsPerParameter(
allRequestParams.get("fromDate"),
allRequestParams.get("endDate"),
Season.findSeason(allRequestParams.get("season").toUpperCase()),
Name.findName(allRequestParams.get("name").toUpperCase()),
Category.findCategory(allRequestParams.get("category").toUpperCase()));
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json; charset=utf-8");
return new ResponseEntity<String>(Contract.toJsonArray(result), headers,
HttpStatus.OK);
}
季节,名称,类别是合同的依赖关系。所以对于jpa查询,我需要每个的完整Object。为此,我想要一种动态的方式,而不是为所有人编写类似的代码。但我确信还有另一种更好的解决方案。 也许可以使用契约对象(domain和json)ittelf以及jpa查询来完成它。
感谢您的投入。
答案 0 :(得分:0)
来自您的问题描述我猜您可以开发名为Contract
的命令对象 class Contract{
private Date fromDate;
private Date endDate;
private String season;
private String name;
private String category;
// Getters and setters
}
然后您可以将其传递给 getContractFromSearch(方法,如下所示:
public ResponseEntity<String> getContractFromSearch(
@ModelAttribute Contract contract, ModelMap model) {
此处契约对象将由Spring Binder从您的JSON数据填充。您可能需要编写Date Objects的附加转换逻辑。
答案 1 :(得分:0)
我尝试了这个例子,它对我有用。
json看起来像这样:
contract = {fromDate:moment($('#datepickerVon').val(), 'DD-MM-YYYY').format('DD-MM-YYYY'), endDate:moment($('#datepickerVon').val(), 'DD-MM-YYYY').format('DD-MM-YYYY'), Season: {
season: "SO14"}, name: {name: "peter"}, category:{category:"SomeString"}};
console.log(contract);
$.ajax({
url:'/contracts/search/',
dataType: "json",
type: "POST",
mimeType: 'application/json',
contentType: "application/json",
data: JSON.stringify(contract),
success: function(data) {
console.log(data);
}
});
Controller接收如下:
@RequestMapping(value = "/search/", method = RequestMethod.POST, headers = "Accept=application/json")
public ResponseEntity<String> getVertagFromSearch(@RequestBody String json, UriComponentsBuilder uriBuilder){
Contract contract = contract.fromJsonToContract(json);
//do Stuff
return new ResponseEntity<String>(Contract.toJsonArray(result), headers, HttpStatus.OK);
}
反序列化就在这里:
public static contract fromJsonToContract(String json) {
return new JSONDeserializer<Contract>().use(Calendar.class, new CalendarTransformer("dd-MM-yyyy HH:mm")).use(null, Contract.class).deserialize(json);
}