如何在Spring Web MVC中使用Ajax JQuery

时间:2021-03-15 14:30:26

I am using Spring Web MVC for my application.

我的应用程序使用Spring Web MVC。

I have 1 dropdown list in my JSP View, coming from following request called savegroup.htm

在我的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>

JSP page has:

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>

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.

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

For that how can I use jQuery AJAX call?

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

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

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

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

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

2 个解决方案

#1


35  

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

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

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

对于ajax请求,您更喜欢XML还是JSON ?

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.

需要注意的一点是,我要告诉你的事情没有jquery的具体内容。您需要以一种对jquery有用的形式(理想情况下是XML或json)向jquery异步请求发送回响应,但在服务器端,它看起来就像一个普通的请求,只是使用呈现XML或json而不是html的视图。我个人的偏好是使用JSON,特别是由于spring-json包工作得很好,而且一旦您理解了它的工作原理,就很容易使用它。我推荐您可以从http://spring-json.sourceforge.net/中获得的spring-json包,您应该对它的工作原理有一个很好的了解。

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

在最基本的形式下,您的解决方案需要做以下工作:

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

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

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.

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

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.):

在最简单的情况下,我的代码看起来是这样的(这是所有的spring2.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;
    }
}

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

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

@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";
    }
}

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:

对于发出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);

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.

您可以谷歌为ajaxForm模块提供文档,以便学习如何发布而不是get,以及如何只发送抓取特定字段,并将它们发送到一个URL,该URL不是表单的目标URL。

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.

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

#2


0  

Define the controller for the URL

定义URL的控制器。

If you want to use POST method:

如果你想使用POST方法:

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

or, if you want to use GET method:

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

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

Call it with a function like .click or .submit

使用.click或.submit这样的函数调用它

and that´s it

这´s

#1


35  

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

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

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

对于ajax请求,您更喜欢XML还是JSON ?

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.

需要注意的一点是,我要告诉你的事情没有jquery的具体内容。您需要以一种对jquery有用的形式(理想情况下是XML或json)向jquery异步请求发送回响应,但在服务器端,它看起来就像一个普通的请求,只是使用呈现XML或json而不是html的视图。我个人的偏好是使用JSON,特别是由于spring-json包工作得很好,而且一旦您理解了它的工作原理,就很容易使用它。我推荐您可以从http://spring-json.sourceforge.net/中获得的spring-json包,您应该对它的工作原理有一个很好的了解。

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

在最基本的形式下,您的解决方案需要做以下工作:

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

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

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.

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

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.):

在最简单的情况下,我的代码看起来是这样的(这是所有的spring2.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;
    }
}

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

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

@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";
    }
}

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:

对于发出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);

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.

您可以谷歌为ajaxForm模块提供文档,以便学习如何发布而不是get,以及如何只发送抓取特定字段,并将它们发送到一个URL,该URL不是表单的目标URL。

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.

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

#2


0  

Define the controller for the URL

定义URL的控制器。

If you want to use POST method:

如果你想使用POST方法:

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

or, if you want to use GET method:

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

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

Call it with a function like .click or .submit

使用.click或.submit这样的函数调用它

and that´s it

这´s