Quantcast
Channel: CSDN博客推荐文章
Viewing all articles
Browse latest Browse all 35570

jQuery(8)---jQuery中googlesuggest的实现(数据库调用@Hibernate+struts2)

$
0
0

页面如下:


核心源码如下:

suggest.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<base href="<%=basePath%>">

		<title>My JSP 'suggest.jsp' starting page</title>

		<meta http-equiv="pragma" content="no-cache">
		<meta http-equiv="cache-control" content="no-cache">
		<meta http-equiv="expires" content="0">
		<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
		<meta http-equiv="description" content="This is my page">
		<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
		<script type="text/javascript"
			src="${ pageContext.request.contextPath}/js/jquery-1.9.1.js">
</script>
		<script type="text/javascript"
			src="${ pageContext.request.contextPath}/js/suggest.js">
</script>

		<style type="text/css">
.s_ipt {
	width: 405px;
	height: 30px;
	font: 16px/ 22px arial;
	margin: 5px 0 0 7px;
	background: #fff;
	outline: 0;
	-webkit-appearance: none;
}

.s_wds {
	width: 405px;
	height: 200px;
	font: 16px/ 22px arial;
	background: #fff;
	display: none;
}
</style>
	</head>

	<body>
		<div align="center">
		<h2>jQuery中googlesuggest的实现</h2><hr/>
			<div>
				<input type="text" id="keyword" class="s_ipt" />
				  
				<input type="button" value="百度一下" />				
			</div>
			<div>
				<select id="words" multiple="multiple" size="10" class="s_wds"></select>
				            
				
			</div>
		</div>
	</body>
</html>

suggest.js

$(document).ready(function() {
	
	// 给input输入框注册 keyup事件
	$("#keyword").bind("keyup", function() {
		$("#words").show();
		// 获取收入的值
		var keyVal = $(this).val();
		
		if ("" == keyVal) {
			// 清空
			$("#words").empty().hide();// 对象链式操作
			return;
		}
		// 发送ajax请求
		$.post("./csdn/UserAction_keyVals.action?time=" + new Date().getTime(),
				{
					keyword : keyVal
				}, function(data) {
					// 清空
					$("#words").empty();

					// 获取所有的相关的数据
					var jsonusers = data.users;
					// 遍历数组
					for (var i = 0; i < jsonusers.length; i++) {
						// 得到具体的user对象
						var jsonuser = jsonusers[i];
						// 创建option
						var $optu = $("<option></option>");
						// 设置文本
						$optu.text(jsonuser.name);

						// 把创建的option添加到select中
						$("#words").append($optu).show();
					}

				}, "json");

	});

	$("#words").bind("dblclick", function() {
				$("#keyword").val($(this).val());
				$("#words").empty().hide();
			});

	$("#words").bind("keyup", function(event) {
				var key = event.which;
				if (key == 13) {
					$("#keyword").val($(this).val());
					$("#words").empty().hide();
				}

			});

});


User.java

package www.csdn.project.domain;

public class User {
	
	
	private String name;
	private Integer id;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public User(String name, Integer id) {
		super();
		this.name = name;
		this.id = id;
	}
	public User() {
		super();
		// TODO Auto-generated constructor stub
	}
	
	
	

}


User.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="www.csdn.project.domain">
   <class name="User" catalog="csdn" table="user">
        <id column="id" name="id" type="java.lang.Integer">
          <generator class="native"></generator>
        </id>
        <property name="name" column="name" type="java.lang.String" length="60" unique="true" not-null="true"/>
        
   </class>
</hibernate-mapping>


UserDAO.java接口

package www.csdn.project.dao;

import java.util.List;

import www.csdn.project.domain.User;

public interface UserDAO extends BaseDAO<User, Integer>{
	/**
	 * 验证用户名是否存在
	 * 
	 * @param name
	 * @param className
	 * @return
	 */
	public boolean checkName(String name, Class className);

	/**
	 * 根据关键字查询用户信息
	 * @param keyword
	 * @param className
	 * @return
	 */
	public List<User> findByKeyVal(String keyword, Class className);

}


UserDaoImpl.java

package www.csdn.project.dao;

import java.util.List;

import org.hibernate.criterion.Restrictions;

import www.csdn.project.domain.User;
import www.csdn.project.util.BaseHibernateDAO;
import www.csdn.project.util.HiberSessionFactory;

public class UserDAOImpl extends BaseHibernateDAO implements UserDAO{

	@SuppressWarnings("unchecked")
	public boolean checkName(String name, Class className) {
		boolean flag=false;
		try{
			@SuppressWarnings("unused")
			User user=(User) getSession().createCriteria(className).add(Restrictions.eq("name",name)).uniqueResult();
			if(user!=null){
				flag = true;
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			HiberSessionFactory.closeSession();
		}
		return flag;
	}

	@SuppressWarnings("unchecked")
	public List<User> findByKeyVal(String keyword, Class className) {
	List<User> users=null;
	try{
		users=getSession().createCriteria(className).add(Restrictions.like("name", keyword+"%")).list();
	}catch(Exception e){
		e.printStackTrace();
	}finally{
		HiberSessionFactory.closeSession();
	}
		return users;
	}

	public void deleteObject(User entity) {
		// TODO Auto-generated method stub
		
	}

	public void deleteObjectById(Integer id) {
		// TODO Auto-generated method stub
		
	}

	public List<User> getAllObjects(Class<User> entityClass) {
		// TODO Auto-generated method stub
		return null;
	}

	public User getObjectById(Class<User> entityClass, Integer id) {
		// TODO Auto-generated method stub
		return null;
	}

	public User loadObjectById(Class<User> entityClass, Integer id) {
		// TODO Auto-generated method stub
		return null;
	}

	public void saveObject(User entity) {
		// TODO Auto-generated method stub
		
	}

	public void updateObject(User entity) {
		// TODO Auto-generated method stub
		
	}

}

UserAction.java

package www.csdn.project.action;

import java.util.List;

import www.csdn.project.domain.User;
import www.csdn.project.service.UserService;
import www.csdn.project.service.UserServiceImpl;

import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport {

	// 业务对象
	private UserService userService = new UserServiceImpl();

	// 用户名称
	private String name;
	// 判断用户名称后返回的信息
	private String msg;

	// 关键字
	private String keyword;
	private List<User> users;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public String getKeyword() {
		return keyword;
	}

	public void setKeyword(String keyword) {
		this.keyword = keyword;
	}

	public List<User> getUsers() {
		return users;
	}

	public void setUsers(List<User> users) {
		this.users = users;
	}

	public String checkName() {

		// 业务查询操作
		boolean flag = userService.checkName(name, User.class);

		if (flag) {
			msg = "用户名已经存在";
		} else {
			msg = "用户名可以使用";
		}
		return "checkName";
	}

	// 通过关键字查询的方法
	public String keyVals() {
		users = userService.findByKeyVal(keyword, User.class);
		return "keyVals";
	}
}


struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
	<!--<include file="www/csdn/project/resource/struts-constant.xml" />
	--><include file="strutsppc.xml"></include>
	<package name="tests" namespace="/csdn" extends="json-default">
		<action name="UserAction_*" class="www.csdn.project.action.UserAction"
			method="{1}">
			<result name="checkName" type="json">
			    <param name="root">msg</param>
			</result>
			<result name="keyVals" type="json">
				<param name="includeProperties">users\[\d+\]\.name</param>
			</result>
			<result name="input">/index.jsp</result>
		</action>	
	</package>

</struts>


hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
	<property name="myeclipse.connection.profile">localhost</property>
	<property name="connection.url">
		jdbc:mysql://localhost:3306/csdn
	</property>
	<property name="connection.username">root</property>
	<property name="connection.password">root</property>
	<property name="connection.driver_class">
		com.mysql.jdbc.Driver
	</property>
	<property name="dialect">
		org.hibernate.dialect.MySQLDialect
	</property>
	<property name="show_sql">true</property>
	<mapping resource="www/csdn/project/domain/City.hbm.xml" />
	<mapping resource="www/csdn/project/domain/Country.hbm.xml" />
	<mapping resource="www/csdn/project/domain/Province.hbm.xml" />
	<mapping resource="www/csdn/project/domain/User.hbm.xml" />

</session-factory>
</hibernate-configuration>




 

作者:sgx425021234 发表于2013-3-22 23:42:30 原文链接
阅读:112 评论:0 查看评论

Viewing all articles
Browse latest Browse all 35570

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>