如何在Spring Web MVC中使用Ajax JQuery


问题内容

我正在为我的应用程序使用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中显示该组即将到来的用户?


问题答案:

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

对于ajax请求,您是否偏爱XML与JSON?

需要注意的一件事-
我要告诉您的操作没有特定的jQuery。您需要以对jquery有用的形式(理想情况下为XML或json)发送回对jquery异步请求的响应,但是在服务器端,它看起来就像是一个普通请求,恰好使用呈现XML的视图或json而不是html。我的个人偏好是使用JSON,尤其是因为spring-
json包工作得很好并且一旦您了解了它的工作原理就易于使用。我推荐从http://spring-
json.sourceforge.net/
获得的spring-
json包。通读所有文档,您应该对它的工作原理有个很好的了解。

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

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

向服务器发出异步请求,服务器将返回用户列表。如果传递用户集所需的唯一信息是下拉列表的选定值,则只需在查询字符串中使用选定域发出GET请求,这将非常简单。在服务器端,您需要一个控制器,该控制器将映射到传入请求,并将发回json或xml以供jquery处理。基本上,您可以编写一个完全普通的控制器(无论是通过GET还是POST方法访问),然后在返回json视图的名称之前将用户列表添加到模型中。spring-
json提供的3种json视图类型会将您列表中的bean呈现为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);

您可以在google上查找有关ajaxForm模块的文档,以了解如何发布而不是获取,以及如何仅获取某些字段并将其发送到不是该表单的预期URL的URL。

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