Spring MVC + Ajax

利用Spring MVC + Ajax实现模糊查询。

Spring用的是3.0。

工程结构图:


Web.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
	xmlns="http://java.sun.com/xml/ns/j2ee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

	<display-name>Spring MVC</display-name>

	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>
			org.springframework.web.servlet.DispatcherServlet
		</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>*.htm</url-pattern>
	</servlet-mapping>

	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>

</web-app>

springmvc-servlet.xml配置:

<?xml version="1.0" encoding="UTF-8"?>

<!-- Copyright : adobocode.com , 2010 -->

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean
        class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
    <context:component-scan base-package="com.springmvc" />
    <!-- 该 BeanPostProcessor 将自动对标注 @Autowired 的 Bean 进行注入 -->     
  <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>  
    <bean id="studentService" class="com.springmvc.service.StudentService"></bean>
    <bean id="personService" class="com.springmvc.service.PersonService"></bean>
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass">
            <value>org.springframework.web.servlet.view.JstlView</value>
        </property>
        <property name="prefix">
            <value>/WEB-INF/jsp/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

</beans>

StudentIndexController.java:

/**
 * 文件:StudentIndexController.java
 * 描述:TODO
 * 作者:luckystar2008
 * 日期:2011-9-30
 */
package com.springmvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author luckystar2008
 *
 */
@Controller
public class StudentIndexController {
	
	@RequestMapping("/student/ajax.htm")
	public String handle() {
		return "studentAjax";
	}
}

StudentController.java:

/**
 * 文件:StudentController.java
 * 描述:TODO
 * 作者:luckystar2008
 * 日期:2011-9-29
 */
package com.springmvc.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.springmvc.bean.Student;
import com.springmvc.service.StudentService;

/**
 * @author luckystar2008
 *
 */
@Controller
public class StudentController {
    private Log log = LogFactory.getLog(StudentController.class);
    @Autowired
    private StudentService studentService;
    
    @RequestMapping("/student/fuzzy.htm")
    public void fuzzy(@RequestParam(value="name") String name,HttpServletResponse res) {
        List<Student> studentList = studentService.getFuzzyList(name);
        log.info("查找的字符串:" + name);
        log.info("查找到的符合条件的记录:" + studentList.size());

        if (studentList.size() > 0 ) {
            StringBuffer sbf = new StringBuffer();
            for (Student s : studentList) {
                String sname = s.getName();
                if (sname != null && !"".equals(sname)) {
                    sbf.append(sname).append("|");
                }
            }
            
            String outer = sbf.substring(0, sbf.toString().lastIndexOf("|"));
            log.info(outer);
            try {
                log.info("res==null?" + res);
                PrintWriter out = res.getWriter();
                out.print(outer);
                out.flush();
                out.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

StudentService.java:

/**
 * 文件:StudentService.java
 * 描述:TODO
 * 作者:luckystar2008
 * 日期:2011-9-29
 */
package com.springmvc.service;

import java.util.ArrayList;
import java.util.List;

import com.springmvc.bean.Student;

/**
 * @author luckystar2008
 *
 */
public class StudentService {
	public List<Student> list = new ArrayList<Student>();
	
	public StudentService() {
		System.out.println("开始初始化List。。。");
		for (int i=0;i<100;i++) {
			Student s = new Student();
			s.setId(i);
			s.setName("Student__" + i);
			s.setAge(i);
			list.add(s);
		}
		System.out.println("共放入"+list.size()+"个对象到List。");
	}
	
	/**
	 * 模糊查询。
	 * @param name:要查询的名字
	 * @return 匹配此名字的Student List。
	 */
	public List<Student> getFuzzyList(String name) {
		List<Student> tmpList = new ArrayList<Student>();
		
		if (name != null && !"".equals(name)) {
			for (Student s : list) {
				if (s != null) {
					if (s.getName().indexOf(name) != -1) {
						tmpList.add(s);
					}
				}
			}
		}
		
		return tmpList;
	}
}

studentAjax.jsp:

<%@ page language="java" session="false"
	contentType="text/html; charset=UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<html>
	<head>
		<title>Ajax模糊查询</title>
		<script type="text/javascript">
			// 记录上一次查询的内容
			var lastValue = "";
			var timeout = 0;
			
			function doAjax() {
				// 1.5s请求一次,因为是onkeyup事件,每输入一个字符就会请求,所以改成从输入开始到1.5s后才提交查询。
				timeout = setTimeout('searchIt()',1500); 
			}
			
			function searchIt() {
				var obj = document.getElementById('name');
				if (lastValue == obj.value ) return; // 2次的内容一样不查询。
				var quzzyUrl = "/springmvc/student/fuzzy.htm";
				quzzyUrl += "?name=" + obj.value + "&time=" + (new Date()).toLocaleString() + "";
				var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
				xmlhttp.open("post",quzzyUrl,true);
				xmlhttp.onreadystatechange = function() {
					if (xmlhttp.readyState == 4) {
						if (xmlhttp.status == 200) {
							var data = xmlhttp.responseText;
							var div = document.getElementsByTagName("div")[0];
							if (data.length > 0) {
								var arr = data.split('|');
								div.innerHTML = "<span style='color:red;'>找到记录:"+arr.length+"条</span><br>";
								for (var i=0;i<arr.length;i++) {
									div.innerHTML += "<span style='position:absolute;width:220px;'>" + arr[i] + "</span><br>";
								}

								div.style.display = "block";
								var spans = div.document.getElementsByTagName('span');
								
								for (var i=1;i<spans.length;i++) {
									spans[i].onmouseover = function() {
										this.style.background = 'blue';
										this.style.color = 'red';	
									}
									spans[i].onmouseout = function() {
										this.style.background = 'white';
										this.style.color = 'black';	
									}	
									spans[i].onclick = function() {
										obj.value = this.innerText;
										div.innerHTML = "";
										div.style.display = 'none';	
									}
								}
							}
						}
						else {
							alert("Problem retrieving data");
							}
					}
				}
				xmlhttp.send(null);
				clearTimeout(timeout);
				lastValue = obj.value;	
			}
		</script>
	</head>
	<body>
		<label>姓名:</label>
		<input type="text" id="name" name="name" οnkeyup="doAjax();" style="position:absolute;left:100px;width:150px;"><br>
		<div style="position:absolute;border:1px dotted blue;left:100px;display:none;width:220px;height:150px;overflow:scroll;"></div>
	</body>
</html>



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值