如何在Spring Web MVC中使用Ajax JQuery

Nir*_*mal 23 java ajax jquery jsp spring-mvc

我在我的应用程序中使用Spring Web MVC.

我的JSP视图中有一个下拉列表,来自下面的请求 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>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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

为此我怎么能使用jQuery AJAX调用?

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

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

ide*_*tor 35

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

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

有一点需要注意 - 没有任何关于我要告诉你的事情的具体内容.您需要以对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结构并将其发送给客户端.您可以使用所有标准DataBinder功能来解析/转换传入参数,任何验证错误都会在json响应中生成字段或全局错误消息,客户端代码可以向用户显示这些消息.

在最简单的情况下,我的代码看起来像这样(这是所有的春天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;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我想通过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";
    }
}
Run Code Online (Sandbox Code Playgroud)

要发出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);
Run Code Online (Sandbox Code Playgroud)

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

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