如何使用Ajax JQuery的Spring Web MVC框架 [英] How to use Ajax JQuery in Spring Web MVC

查看:108
本文介绍了如何使用Ajax JQuery的Spring Web MVC框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Spring Web MVC框架对我的申请。

I am using Spring Web MVC for my application.

我有1下拉列表中我的JSP视图,从被称为以下请求到来 savegroup.htm

I have 1 dropdown list in my JSP View, coming from following request called 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页面:

JSP page has:

<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>

现在我的要求是,在我的下拉列表中的变化时,我希望获取相关用户服务器,并显示在某些列表框中的用户的列表中。

Now my requirement is that, on the change event of my drop down list, I want to fetch related users from server and display that list of users in some list box.

对于如何使用jQuery AJAX调用?

For that how can I use jQuery AJAX call?

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

Where should I handle server side code which receives request and fetch related user?

如何显示未来组用户在我的JSP?

How to display that coming set of users in my JSP?

推荐答案

有许多方法来解决这个问题。我需要几个问题的答案之前,我可以给你坚实的指导。

There are a number of ways to solve this. I need a few answers to questions before I can give you solid guidance.

你有一个preference对XML VS JSON的Ajax请求?

Do you have a preference for XML vs JSON for ajax requests?

需要注意的一点 - 没有什么jQuery的具体是什么,我要告诉你这样做。您需要发送回的形式jQuery的异步请求非常有用的jQuery(XML或JSON,理想情况下)的响应,但在服务器端,它只是看起来像一个正常的请求,这恰好使用呈现XML视图或者JSON而不是HTML。我个人的preference是使用JSON,特别是开春以来,JSON包工作得很好,很容易使用,一旦你了解它是如何工作的。我推荐的弹簧JSON包可从 http://spring-json.sourceforge.net/ 通读所有的文档你应该有一个很好的主意是如何工作的。

One thing to note - there is nothing jquery specific about what I am going to tell you to do. You need to send back a response to the jquery async request in a form that is useful to jquery (XML or json, ideally), but on the server side, it just looks like a normal request which happens to use a view that renders XML or json instead of html. My personal preference is to use JSON, especially since the spring-json package works very well and is easy to use once you understand how it works. I recommend the spring-json package available from http://spring-json.sourceforge.net/ Read through all of the documentation and you should have a very good idea how it works.

在最基本的形式,你的解决方案需要做到以下几点:

In the most basic form, your solution needs to do the following:

配置视图,它使用的弹簧JSON意见NOE。我preFER sojoView在大多数情况下。

Configure a view which uses noe of the spring-json views. I prefer sojoView for most cases.

使一个异步请求到服务器,这将返回的用户的列表。如果交付组用户需要的唯一信息是下降的选定值下降,这将是pretty的简单,只需发出带有查询字符串的选择域GET请求。在服务器侧,就需要将被映射到输入的请求和将发送回JSON或XML由jquery的处理的控制器。基本上,你可以写一个完全正常的控制器,无论是通过GET或POST方法访问,并返回你的JSON视图的疗法名称前添加用户到模型的列表。的3种类型的JSON视图由弹簧JSON中提供的将呈现在列表中的豆成JSON结构和发送到客户端。您可以使用所有标准的DataBinder功能解析/转换传入的参数和任何验证错误将生成JSON响应,您的客户端code能present到用户现场或全球性的错误消息。

make an async request to the server, which will return the list of users. If the only info needed to deliver the set of users is the selected value of the drop down, it would be pretty simple to just issue a GET request with the selected domain in the query string. On the server side, you need a controller that will be mapped to the incoming request and which will send back json or xml to be processed by jquery. Basically you can write a totally normal controller, whether accessed by GET or POST method, and add your list of users to the model before returning ther name of your json view. The 3 types of json view that are provided by spring-json will render the beans in your list into a json structure and send that to the client. You can use all of the standard DataBinder functionality for parsing/converting incoming parameters and any validation errors will generate field or global error messages in the json response which your client side code can present to the user.

在简单的情况下,我的code会是这个样子(这是所有Spring 2.5的它使用注释,但你可以用XML配置同样的事情在你的应用程序上下文。):

In the simplest case, my code would look something like this (this is all spring 2.5. It uses annotations but you can do the same things with xml configuration in your app context.):

@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加载一个实际的域对象,我可以做somethign这样

If I want to process via a POST request, and I wish to load an actual Domain object from the domainValue that is submitted, I can do somethign like this

@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,看起来是这样的:

For issuing the ajax request, you can use jquery ajaxForm module. Assuming you have a form with id "selectDomainForm" you need js that looks something like this:

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);

您可以以学习如何发布,而不是获取和发送抢只有特定的领域,并将它们发送到URL不是形式的目的URL谷歌弥补了当作ajaxForm模块的文档。

You can google up the documentation for the ajaxForm module in order to learn how to post instead of get and to send grab only certain fields and send them to a URL that is not the intended url of the form.

要显示在用户页面的列表,你会在你的code一个div包含用户列表的ID,您可以遍历用户在返回的JSON,创建HTML为每一个用户。简单地说HTML添加到用户列表分区,它就会出现在浏览器中。

To display the list of users in the page, you will have a div in your code with an id like "userList" and you can iterate over the users in the returned json, creating html for each user. Simply add that html to the "userList" div and it will appear in the browser.

这篇关于如何使用Ajax JQuery的Spring Web MVC框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆