gpt4 book ai didi

jquery - Spring MVC jQuery 远程验证

转载 作者:行者123 更新时间:2023-12-01 01:12:02 24 4
gpt4 key购买 nike

我在服务器端使用 Spring MVC,但在其中一个页面中,我决定使用 jQuery 创建 AJAX 验证,而不是默认的 Spring 验证。一切都很好,除了当我必须进行远程验证以检查数据库中是否已存在“标题”时。对于 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);
}

但是,这不起作用,并且“标题”字段从未得到验证。我认为这样做的原因是我以以下方式返回答案:

{result:"TRUE"}

事实上,答案应该是:

{"TRUE"}

我不知道如何使用 ModelAndView 答案返回像这样的单个响应。

另一件事不起作用是“远程”验证的自定义消息:

    messages: {
title: {
required: "A title is required.",
remote: "This title already exists."
}
},

所需消息有效,但远程消息无效。我环顾四周,没有看到很多人同时使用 Spring 和 jQuery。至少,不要与 jQuery 远程验证和 Spring-Json 混合。我希望能在这里得到一些帮助。

最佳答案

我也遇到了和你一样的问题。

现在我做到了

@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();
}

关于jquery - Spring MVC jQuery 远程验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2463371/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com