struts2+jquery+hibernate自动提示框

使用struts2+jquery+hibernate实现了一个自动提示框

jsp页面为(注意这里引入了jquery-1.6.js和jquery-ui-1.8.10.custom.min.js):

<%@ page contentType="text/html; charset=gbk" pageEncoding="gbk"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk">
<title>自动提示框</title>
<script type="text/javascript" src="js/jquery-1.6.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.10.custom.min.js"></script>
<script type="text/javascript">
$(function(){
	$("#autoName").autocomplete({
		minLength : 1,
		source : function(request,response){
			var studentNameIndex =$("#autoName").val();
		    var url = "ajaxStudentName.action";
		    var params = {
		    	//增加encodeURI以支持中文
		    	'studentNameIndex':encodeURI(studentNameIndex)
		    };
		    $.post(url, params, function callback(result,textStatus){
		    	alert(result);
		    	if(textStatus == 'success'){
		    		if(result!=''){
		    			var tmp = result.split(",");
			    		response(tmp);
		    		}else{
		    			response(result);
		    		}
		    	}
		    });
		}
	});
});
</script>
</head>
<body>
<input id="autoName" name="studentName" maxlength="10"/>
</body>
</html>

struts的配置文件为:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
	"http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
	<constant name="struts.devMode" value="true" />

	<package name="default" extends="struts-default" namespace="/">
      	<action name="ajaxStudentName" 
                 class="com.test.action.AjaxAction" method="getStudentName">  
      	</action>  
	</package>
</struts>

struts action:

package com.test.action;

import java.net.URLDecoder;
import java.util.Iterator;
import java.util.List;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.test.dao.StudentDAO;

public class AjaxAction extends ActionSupport{
	private static final long serialVersionUID = 1L;
	private String studentNameIndex;
	private String result;
	
	public String execute() throws Exception{
		return SUCCESS;
	}
	
	public String getStudentName() throws Exception{
		studentNameIndex = URLDecoder.decode(studentNameIndex, "utf-8");
		StudentDAO studentDAO = new StudentDAO();
		List<String> re = studentDAO.getStudentName(studentNameIndex);
		re.add("123");
		result = "";
		if(re!=null && re.size()>0){
			Iterator<String> it = re.iterator();
			while(it.hasNext()){
				String tmp = it.next();
				result = result + tmp + ",";
			}
			result = result.substring(0, result.length()-1);
		}
		ServletActionContext.getResponse().setContentType("gbk");
		ServletActionContext.getResponse().setCharacterEncoding("gbk");
                ServletActionContext.getResponse().getWriter().print(result);
        return null;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public String getStudentNameIndex() {
		return studentNameIndex;
	}

	public void setStudentNameIndex(String studentNameIndex) {
		this.studentNameIndex = studentNameIndex;
	}
}

hibernate实现的dao:

package com.test.dao;

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class StudentDAO {
	public List<String> getStudentName(String studentName){
	    Configuration conf = new Configuration();  
	    SessionFactory sessionFactory = conf.configure().buildSessionFactory();  
	    Session session = sessionFactory.openSession();  
	    String sql = 
        "select studentName from Student where studentName like '"+studentName+"%'";
	    Query query = session.createQuery(sql);
	    List<String> result = null;
	    result = query.list();
	    return result;
	}
}

hibernate实现的po:

package com.test.po;

import java.io.Serializable;

public class Student implements Serializable {

    private static final long serialVersionUID = 1L;
    private Integer studentId;
    private Integer studentName;

    public Student(){
    }

	public Integer getStudentId() {
		return studentId;
	}

	public void setStudentId(Integer studentId) {
		this.studentId = studentId;
	}

	public Integer getStudentName() {
		return studentName;
	}

	public void setStudentName(Integer studentName) {
		this.studentName = studentName;
	}
}

相应的配置文件为:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

<hibernate-mapping>
    <class name="com.test.po.Student" 
        table="D_STUDENT">
        <id name="studentId" column="studentId" type="java.lang.Integer">
            <generator class="assigned"/>
        </id>
        <property 
            name="studentName"
            column="studentName"
            update="true"
            insert="true"
            type="java.lang.String"
            not-null="true"
            unique="false"
            length="10"
        />
    </class>
</hibernate-mapping>

hibernate配置文件:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	 	"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
	<session-factory>
		<property name="show_sql">false</property>
	
		<property name="dialect">org.hibernate.dialect.OracleDialect</property>
		<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
		<property name="connection.url">jdbc:oracle:thin:@192.168.1.1:1522:TESTDB</property>
		<property name="connection.username">123</property>
		<property name="connection.password">123</property>
		<property name=" hibernate.jdbc.batch_size">100</property>

		<mapping resource="com/test/po/student.hbm.xml" />
	</session-factory>
</hibernate-configuration>

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>test</display-name>
    <filter>  
        <filter-name>struts2</filter-name>  
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>  
    </filter>  
    <filter-mapping>  
        <filter-name>struts2</filter-name>  
        <url-pattern>*.action</url-pattern>  
    </filter-mapping>  
    <filter-mapping>  
        <filter-name>struts2</filter-name>  
        <url-pattern>*.jsp</url-pattern>  
    </filter-mapping>  
	
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

student表的结构只有2列,一列为编号,一列为姓名:

-- Create table
create table D_STUDENT
(
  STUDENTID   NUMBER not null,
  STUDENTNAME VARCHAR2(10) not null
)

备注:

1,中文乱码需要特别注意,出现乱码要从3方面查找原因:1,前台传递到后台的数据是否是乱码。2,数据库中查询出的数据是否是乱码。3,后台返回给前台的查询结果是否是乱码。

2,输入需要过滤掉特殊字符或者其他的处理以防止sql注入



 

 

posted @ 2012-11-06 17:16  心意合一  阅读(182)  评论(0编辑  收藏  举报