【问题标题】:How to use Ajax JQuery in Spring Web MVC如何在 Spring Web MVC 中使用 Ajax JQuery
【发布时间】:2010-12-13 00:27:33
【问题描述】:

我正在为我的应用程序使用 Spring Web MVC。

我的 JSP 视图中有 1 个下拉列表,来自名为 savegroup.htm 的以下请求

<bean name="/savegroup.htm" class="com.sufalam.mailserver.presentation.web.GroupSaveController">
    <property name="sessionForm" value="true"/>
    <property name="commandName" value="Group"/>
    <property name="commandClass" value="com.sufalam.mailserver.presentation.bean.GroupViewBean"/>
    <property name="formView" value="common"/>
    <property name="successView" value="managegroup.htm"/>
    <property name="userSecurityProcessor" ref="IUserSecurityProcessor"/>
    <property name="domainsSecurityProcessor" ref="IDomainsSecurityProcessor"/>
    <property name="forwardingsSecurityProcessor" ref="IForwardingsSecurityProcessor"/>
</bean>

JSP 页面有:

<form:form name="groupSaveForm" action="savegroup.htm" commandName="Group" method="POST">
    Group Name :
    <form:input path="source"/><br><br>
    Domain List :
    <form:select id="domains" onchange="javascript:getUser();" path="domainsList" multiple="false" size="1">
        <form:option value="-" label="--Select--"/>
        <form:options items="${domainsList}" itemValue="domain" itemLabel="domain"/>
    </form:select>
</form:form>

现在我的要求是,在我的下拉列表的更改事件中,我想从服务器获取相关用户并在某个列表框中显示该用户列表。

为此,我该如何使用 jQuery AJAX 调用?

我应该在哪里处理接收请求并获取相关用户的服务器端代码?

如何在我的 JSP 中显示即将到来的用户集?

【问题讨论】:

    标签: java jquery ajax jsp spring-mvc


    【解决方案1】:

    有很多方法可以解决这个问题。在给你提供可靠的指导之前,我需要一些问题的答案。

    对于 ajax 请求,您偏好 XML 还是 JSON?

    有一点需要注意——我要告诉你做什么没有任何 jquery 特定的内容。您需要以对 jquery 有用的形式(最好是 XML 或 json)发回对 jquery 异步请求的响应,但在服务器端,它看起来就像一个正常的请求,恰好使用呈现 XML 的视图或 json 而不是 html。我个人的偏好是使用 JSON,特别是因为 spring-json 包工作得很好,一旦你了解它是如何工作的,它就很容易使用。我推荐 http://spring-json.sourceforge.net/ 提供的 spring-json 包,通读所有文档,你应该对它的工作原理有一个很好的了解。

    在最基本的形式中,您的解决方案需要执行以下操作:

    配置一个不使用 spring-json 视图的视图。在大多数情况下,我更喜欢 sojoView。

    向服务器发出异步请求,服务器将返回用户列表。如果传递一组用户所需的唯一信息是下拉列表的选定值,那么只需在查询字符串中发出带有选定域的 GET 请求就很简单了。在服务器端,您需要一个控制器,该控制器将映射到传入请求,并将发送回 json 或 xml 以供 jquery 处理。基本上,您可以编写一个完全正常的控制器,无论是通过 GET 还是 POST 方法访问,并在返回您的 json 视图的名称之前将您的用户列表添加到模型中。 spring-json 提供的 3 种 json 视图会将列表中的 bean 渲染为 json 结构并将其发送给客户端。您可以使用所有标准 DataBinder 功能来解析/转换传入参数,任何验证错误都会在 json 响应中生成字段或全局错误消息,您的客户端代码可以将这些消息呈现给用户。

    在最简单的情况下,我的代码看起来像这样(这都是 spring 2.5。它使用注释,但您可以在应用程序上下文中使用 xml 配置做同样的事情。):

    @Controller
    public class AjaxController {
    
        @RequestMapping("/some/path/selectDomain.json", method=RequestMethod.GET)
        public ModelAndView processDomainSelection(@RequestParam(value="domain", required="true") String selectedDomain) {
            List<User> users = service.loadUsersForDomain(selectedDomain);
            ModelAndView mv = new ModelAndView("sojoView", "users", users);
            return mv;
        }
    }
    

    如果我想通过 POST 请求进行处理,并且我希望从提交的 domainValue 加载一个实际的 Domain 对象,我可以这样做

    @Controller
    @RequestMapping("/some/path/selectDomain.json")
    public class SelectDomainController {
        public class FormBean {
            protected Domain domain;
            public Domain getDomain() {
                return domain;
            }
            public void setDomain(Domain domain) {
                this.domain = domain;
            }
        }
    
        @ModelAttribute("command")
        public FormBean getCommand() {
            return new FormBean();
        }
    
        @InitBinder
        public void initBinder(WebDataBinder binder, WebRequest request) {
            // this custom editor knows how to load a Domain object from the domainValue string
            // if it fails to convert, it can throw an exception, which will result in 
            // an error being logged against the "domain" field
            binder.registerCustomEditor(Domain.class, "domain", new DomainLookupEditor(domainService));
        }
    
        @RequestMapping(method=RequestMethod.POST)
        public String selectedDomain(@ModelAttribute("command") FormBean command,
                                           BindingResult result,
                                           Model model,
                                           HttpServletRequest request) {
            if (result.hasErrors()) {
                return "sojoView";
            }
            Domain domain = command.getDomain();
            List<User> users = domain.getUsers();
            model.addAttribute("users", users);
            return "sojoView";
        }
    }
    

    对于发出ajax 请求,您可以使用jquery ajaxForm 模块。假设您有一个 id 为“selectDomainForm”的表单,您需要看起来像这样的 js:

    function selectDomainSuccessHandler(json) {
        // it is possible to send back a 200 response after failing to process the request,
        // in which case, the sojoView will have set success=false in the json
        if (json.success == true) {
            // parse json here and render it into html in your document
        } else {
            // get field error and global error from json and present to user
        }
    }
    
    function(selectDomainErrorHandler(xhr, returnCode) {
        // do something based on the return code
    }
    
    var options = {
        success: selectDomainSuccessHandler,
        error: selectDomainErrorHandler,
        dataType: 'json'
    };
    
    $('selectDomainForm').ajaxForm(options);
    

    您可以搜索 ajaxForm 模块的文档,以了解如何发布而不是获取并仅发送抓取某些字段并将它们发送到不是表单预期 URL 的 URL。

    要在页面中显示用户列表,您的代码中将有一个 div,其 id 类似于“userList”,您可以在返回的 json 中迭代用户,为每个用户创建 html。只需将该 html 添加到“userList”div 中,它就会出现在浏览器中。

    【讨论】:

      【解决方案2】:

      URL 定义控制器

      如果你想使用 POST 方法:

      content.load('URL(.)or(#)sectionToLoad', {}, function(event) {
      ...
      });
      

      或者,如果你想使用 GET 方法:

      content.load('URL(.)or(#)sectionToLoad', function(event) {
      ...
      });
      

      使用 .click.submit 之类的函数调用它

      就是这样

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-29
        • 2015-01-04
        • 2011-12-04
        • 1970-01-01
        相关资源
        最近更新 更多