SPRING MVC 结合jquery autocomplete 与 json 的例子

autocomplete 是一个很不错的WEB展现,幸运的是jquery 已经提供了这样的一个插件. 应该包含在jquery UI 中。在用搜索引擎的时候,比如,百度,谷歌,当我们输入一些要查询的内容的时候,会自动出现一些相关的东西,这就是autocomplete. 其实应该是不难的。先自己想想,在没有任何插件的情况下,一般是这样完成的,根据输入的内容,发送AJAX请求到后台,然后返回内容,在前台用DIV 展示。基本就是这样,当然有很多细节要处理。这里讲一个简单的例子:
有两个字段,一个 country, 一个Technologies,这两个字段都是autocomplete特性。唯一不同的是,country 字段只能选择一个值,而Technologies字段可以选择多个值,并且用 逗号(,)分开.

先看看主要用到的东西吧:
JQuery UI (autocomplete)
spring mvc 3.0 以上,还要包含jackson这个jar包,因为打算返回json对象给前端。
具体连接数据库部分,就省略,可以先dummy一个。
程序代码 程序代码

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
  
public class DummyDB {
    private List<String> countries;
    private List<String> tags;
    
    public DummyDB() {

        String data = "Afghanistan, Albania, Algeria, Andorra, Angola, Antigua & Deps,"+
                "United Kingdom,United States,Uruguay,Uzbekistan,Vanuatu,Vatican City,Venezuela,Vietnam,Yemen,Zambia,Zimbabwe";

        countries = new ArrayList<String>();
        StringTokenizer st = new StringTokenizer(data, ",");
        
        //Parse the country CSV list and set as Array
        while(st.hasMoreTokens()) {
            countries.add(st.nextToken().trim());
        }

        String strTags = "SharePoint, Spring, Struts, Java, JQuery, ASP, PHP, JavaScript, MySQL, ASP, .NET";
        tags = new ArrayList<String>();
        StringTokenizer st2 = new StringTokenizer(strTags, ",");
        
        //Parse the tags CSV list and set as Array
        while(st2.hasMoreTokens()) {
            tags.add(st2.nextToken().trim());
        }
    
    }
  
    public List<String> getCountryList(String query) {
                
        String country = null;
        query = query.toLowerCase();
        List<String> matched = new ArrayList<String>();
        for(int i=0; i < countries.size(); i++) {
            country = countries.get(i).toLowerCase();
            if(country.startsWith(query)) {
                matched.add(countries.get(i));
            }
        }
        return matched;
    }

    public List<String> getTechList(String query) {
        String country = null;
        query = query.toLowerCase();
        List<String> matched = new ArrayList<String>();
        for(int i=0; i < tags.size(); i++) {
            country = tags.get(i).toLowerCase();
            if(country.startsWith(query)) {
                matched.add(tags.get(i));
            }
        }
        return matched;
    }
}

这个类,包含了country 和 technologies 的值,通过getCountryList,getTechList方法 得到相关的值,比如在参数中传入一个 ch ,那么所有以 ch 开头的国家都筛选出来了。 其实这里没模拟的就是 sql like语句 .
下面再看controller 层怎么写的。

程序代码 程序代码

import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class UserController {

    private static DummyDB dummyDB = new DummyDB();

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public ModelAndView index() {

        User userForm = new User();

        return new ModelAndView("user", "userForm", userForm);
    }

    @RequestMapping(value = "/get_country_list",
                    method = RequestMethod.GET,
                    headers="Accept=*/*")
    public @ResponseBody List<String> getCountryList(@RequestParam("term") String query) {
        List<String> countryList = dummyDB.getCountryList(query);
        
        return countryList;
    }

    @RequestMapping(value = "/get_tech_list",
                    method = RequestMethod.GET,
                    headers="Accept=*/*")
    public @ResponseBody List<String> getTechList(@RequestParam("term") String query) {
        List<String> countryList = dummyDB.getTechList(query);
        
        return countryList;
    }
}

注意,用了 @ResponseBody annotation 在方法 getCountryList() 和getTechList() 上. Spring MVC 会将这些list 转为JSON对象

在看一下 spring-servlet 的配置
程序代码 程序代码

<?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
        
    
    <context:component-scan base-package="net.viralpatel.spring.autocomplete" />  

    <mvc:annotation-driven />


    <bean id="jspViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>


再看下视图层是怎么样的
程序代码 程序代码

<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
    <title>Spring MVC Autocomplete with JQuery & JSON example</title>
    <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" />

    <script type="text/javascript"
        src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script type="text/javascript"
        src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>

</head>
<body>

<h2>Spring MVC Autocomplete with JQuery & JSON example</h2>
<form:form method="post" action="save.html" modelAttribute="userForm">
<table>
    <tr>
        <th>Name</th>
        <td><form:input path="name" /></td>
    </tr>
    <tr>
        <th>Country</th>
        <td><form:input path="country" id="country" /></td>
    </tr>
    <tr>
        <th>Technologies</th>
        <td><form:input path="technologies" id="technologies" /></td>
    </tr>
    <tr>
        <td colspan="2">
            <input type="submit" value="Save" />
            <input type="reset" value="Reset" />
        </td>
    </tr>
</table>  
<br />
    
</form:form>

<script type="text/javascript">
function split(val) {
    return val.split(/,\s*/);
}
function extractLast(term) {
    return split(term).pop();
}

$(document).ready(function() {

    $( "#country" ).autocomplete({
        source: '${pageContext. request. contextPath}/get_country_list.html'
    });
    
    $( "#technologies").autocomplete({
        source: function (request, response) {
            $.getJSON("${pageContext. request. contextPath}/get_tech_list.html", {
                term: extractLast(request.term)
            }, response);
        },
        search: function () {
            // custom minLength
            var term = extractLast(this.value);
            if (term.length < 1) {
                return false;
            }
        },
        focus: function () {
            // prevent value inserted on focus
            return false;
        },
        select: function (event, ui) {
            var terms = split(this.value);
            // remove the current input
            terms.pop();
            // add the selected item
            terms.push(ui.item.value);
            // add placeholder to get the comma-and-space at the end
            terms.push("");
            this.value = terms.join(", ");
            return false;
        }
    });
    
});
</script>

</body>
</html>


运行就可以看到效果了。



除非申明,文章均为一号门原创,转载请注明本文地址,谢谢!
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags: spring jquery autocomplete
相关日志:
评论: 0 | 引用: 0 | 查看次数: -
发表评论
昵 称:
密 码: 游客发言不需要密码.
内 容:
验证码: 验证码
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.