英文:
What is a good way to pass many parameters to controller?
问题
以下是翻译好的内容:
我在Java(Spring框架)和Javascript(AngularJs框架)上有一个应用程序。表格中有一系列对象,并且有两个文本字段用于筛选这些对象。筛选是在服务器端进行的,因此我将这些文本字段的值作为参数从文本字段传递给 @RestController 的方法,然后再传递给存储库方法。
客户端代码:
$http({
method: 'GET',
url: '/messages',
params: {sender: $scope.sender, recipient: $scope.recipient}
}).then(
function (res) {
$scope.messages = res.data;
},
function (res) {
console.log("Error: " + res.status + " : " + res.data);
}
);
服务器端代码:
@GetMapping("/messages")
@ResponseBody
public List<Message> getMessagesWithFilters(@RequestParam(required = true) String sender,
@RequestParam(required = true) String recipient) {
List<Message> messages = messageRepository.findBySenderNumberAndRecipientNumber(sender, recipient);
return messages;
}
当只有两个筛选条件时,这很简单,但如果有10个或20个呢?有没有一种好的方法来处理这个问题,我应该将它们作为 Map 或类似的结构传递吗?
英文:
I have an application on Java (Spring framework) and Javascript (AngularJs framework). There are list of objects in the table and two text fields for filtering this objects. Filtering happens on the server side so I pass these values from text fields to @RestController's method as params and then to the repository method.
Client side:
$http({
method: 'GET',
url: '/messages',
params: {sender: $scope.sender, recipient: $scope.recipient}
}).then(
function (res) {
$scope.messages = res.data;
},
function (res) {
console.log("Error: " + res.status + " : " + res.data);
}
);
Server side:
@GetMapping("/messages")
@ResponseBody
public List<Message> getMessagesWithFilters(@RequestParam(required = true) String sender,
@RequestParam(required = true) String recipient) {
List<Message> messages = messageRepository.findBySenderNumberAndRecipientNumber(sender, recipient);
return messages;
}
It's pretty easy when there're only two filters but what should I do if there are 10 or 20 of them? Is there a good way to do this, should I pass them as Map or something like that?
答案1
得分: 1
你可以像这样使用注解 @ModelAttribute
:
@GetMapping("/messages")
@ResponseBody
public List<Message> getMessagesWithFilters(@ModelAttribute Filter filter) {
List<Message> messages = messageRepository.findBySenderNumberAndRecipientNumber(filter.sender, filter.recipient);
return messages;
}
还有 Filter.java
文件:
public class Filter {
public String sender;
public String recipient;
}
然后你可以在你的控制器中使用 filter.sender
和 filter.recipient
。
英文:
You may use this Annotation @ModelAttribute
like :
@GetMapping("/messages")
@ResponseBody
public List<Message> getMessagesWithFilters(@ModelAttribute Filter filter) {
List<Message> messages = messageRepository.findBySenderNumberAndRecipientNumber(filter.sender, filter.recipient);
return messages;
}
and Filter.java
public class Filter {
public String sender;
public String recipient;
}
You might then use filter.sender
and filter.recipient
in your controller
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论