我在服务器端使用Spring MVC,但在其中一个页面中,我决定使用jQuery创建AJAX验证,而不是默认的Spring验证。一切都很好,除了我必须进行远程验证来检查"title“是否已经存在于数据库中时。对于javascript,我有以下内容:
var validator = $("form").validate({
rules: {
title: {
minlength: 6,
required: true,
remote: {
url: location.href.substring(0,location.href.lastIndexOf('/'))+"/checkLocalArticleTitle.do",
type: "GET"
}
},
html: {
minlength: 50,
required: true
}
},
messages: {
title: {
required: "A title is required.",
remote: "This title already exists."
}
}
});然后,我使用Spring-Json进行验证并给出响应:
@RequestMapping("/checkLocalArticleTitle.do")
public ModelAndView checkLocalArticleTitle(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Map model = new HashMap();
String result = "FALSE";
try{
String title = request.getParameter("title");
if(!EJBRequester.articleExists(title)){
result = "TRUE";
}
}catch(Exception e){
System.err.println("Exception: " + e.getMessage());
}
model.put("result",result);
return new ModelAndView("jsonView", model);
}但是,这不起作用,并且字段"title“永远不会被验证。我认为这样做的原因是我以这样的方式返回答案:
{result:"TRUE"}实际上,答案应该是:
{"TRUE"}我不知道如何使用ModelAndView answer返回像这样的单个响应。
另一件不起作用的事情是“远程”验证的自定义消息:
messages: {
title: {
required: "A title is required.",
remote: "This title already exists."
}
},所需的消息有效,但远程消息无效。我环顾四周,但没有看到很多人同时使用Spring和jQuery。至少,不会与jQuery远程验证和Spring-Json混合使用。如果能帮上忙我会很感激的。
发布于 2010-06-15 00:18:12
我在你身上遇到了同样的问题。
现在我知道了
@RequestMapping(value = "/brand/check/exists", method = RequestMethod.GET)
public void isBrandNameExists(HttpServletResponse response,
@RequestParam(value = "name", required = false) String name)
throws IOException {
response.getWriter().write(
String.valueOf(Brand.findBrandsByName(name).getResultList()
.isEmpty()));
}可能不是一个好的解决方案。但不管怎样,这是可行的。
如果有更好的方法,请让我知道:)
更新:
在Spring 3.0中,我们可以使用@ResponseBody来做到这一点
@RequestMapping(value = "/brand/exists/name", method = RequestMethod.GET)
@ResponseBody
public boolean isBrandNameExists(HttpServletResponse response,
@RequestParam String name) throws IOException {
return Brand.findBrandsByName(name).getResultList().isEmpty();
}发布于 2014-01-14 10:51:29
下面是Spring MVC jQuery远程验证的另一个示例,用于检查用户的唯一性。参数作为json传递,服务器返回布尔值。
Js:
$('#user-form').validate({ // initialize the plugin
rules: {
username: {
required: true,
remote: function() {
var r = {
url: 'service/validateUsernameUnique',
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{"username": "' + $( "#username" ).val() + '"}'
}
return r;
}
},
},
messages: {
username: {
remote: jQuery.format("User {0} already exists")
}
}
});弹簧控制器:
@RequestMapping(value="/AdminUserService/validateUsernameUnique", method = RequestMethod.POST)
public @ResponseBody boolean validateUsernameUnique(@RequestBody Object username) {
@SuppressWarnings("unchecked")
String name = ((LinkedHashMap<String, String>)username).get("username");
return userService.validateUsernameUnique(name);
}https://stackoverflow.com/questions/2463371
复制相似问题