我有一个@Service
bean,其功能是将新的Member
实体保存到数据库:
@Service
public class AccountService {
// method A
public void saveMember(Member m) {
entityManager.persit(m);
}
// method B
public void saveMember(String username, String pwd, int age /* ... lots of parameters ... */) {
Member m = new Member();
m.setUsername(username);
m.setPassword(pwd);
// ... ...
entityManager.persit(m);
}
}
我将直接在saveMember()
bean中调用@Controller
。哪种方法更好?
如果我使用方法A,那么我必须在Member
bean中构造@Controller
实体,如下所示:
@Controller
public class Controller {
public String profile(@RequestParam String username,
@RequestParam String password
// ... ...
) {
Member m = new Member();
m.setXXX();
// ... ...
// lots of setters method invocation
accountService.saveMember(m);
}
}
如果使用方法B:
@Controller
public class Controller {
public String profile(@RequestParam String username,
@RequestParam String password
// ... ...
) {
accountService.saveMember(username, password /* lots of parameters */);
}
}
哪个更好? 谢谢!
答案 0 :(得分:2)
有第三种方法
在您的控制器中,您将获得Member
对象作为输入,您可以使用此对象来调用您服务中的方法。
@RequestMapping(value = "/saveMember", method = RequestMethod.POST)
@ResponseBody
public String saveAddress(@RequestBody Member member) {
accountService.saveMember(member);
....
}
以下是进行调用的javascript代码:
saveMember = function() {
var saveURL = '/saveMember';
var memberData = {};
memberData.username = 'some user name';
memberData.password = 'some password';
.... (your other fields)
$.ajax({
url : saveURL,
method : 'POST',
dataType : 'json',
contentType : 'application/json',
data : JSON.stringify(memberData),
success : function(result) {
...
}, error: function(errorObject) {
console.log(errorObject);
}
});
};