Java 如何在 Spring Web MVC 中使用 Ajax JQuery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1673656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 19:00:59  来源:igfitidea点击:

How to use Ajax JQuery in Spring Web MVC

javajqueryajaxjspspring-mvc

提问by Nirmal

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 视图中有 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 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 中显示即将到来的一组用户?

采纳答案by ideasculptor

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.

配置一个使用 noe spring-json 视图的视图。大多数情况下,我更喜欢 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 结构并将其发送给客户端。

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

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

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 模块的文档,以了解如何发布而不是获取和发送仅抓取某些字段并将它们发送到不是表单预期 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,它就会出现在浏览器中。

回答by Defrag

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 .clickor .submit

使用类似.click或的函数调用它.submit

and that′s it

就是这样