[AJAX학원, AJAX교육, AJAX/jQUERY]struts Ajax 자동완성기능(1)-김길재
자동완성 기능을 구현해 보았습니다.
Controller로 Struts2를 사용하였으니 관련된 부분은
제가 Struts란에
올린 게시물을 확인하시기 바랍니다.
/**************************************************************
ajax.js
**************************************************************/
var
AutoComplete = {
xmlHttp : null,
/*
* XMLHttp객체생성
*/
getXMLHttpRequest:
function() {
//인터넷 익스플로러일 경우
if(window.ActiveXObject){
try{
return new
ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
return new ActiveXObject("Microsoft.XMLHTTP");
}catch(e1){
return null;
}
}
}
//다른 브라우저일 경우
else
if(window.XMLHttpRequest){
return new
XMLHttpRequest();
}
//브라우저 식별 실패
else{
return null;
}
},
/*
* XMLHttp Request를 서버로
*/
ContentLoader: function(url, execFunction) {
xmlHttp = this.getXMLHttpRequest();
xmlHttp.onreadystatechange = execFunction;
xmlHttp.open("POST", url, true); // url의 주소를 GET방식으로 열 준비를 한다.
xmlHttp.send(); //서버에 전송한다.
},
/*
* XMLHttp Response가 서버로 부터 온전한 상태로 왔는지 확인
*/
getState: function() {
if(xmlHttp.readyState == 4){ //데이터의 전부를 받은 상태
if(xmlHttp.status == 200){//요청 성공
return true;
}else{
return false;
}
}
}
}
/**************************************************************
AutoComplete.jsp
**************************************************************/
<%@ page contentType="text/html; charset=EUC-KR"%>
<html>
<head>
<title>autoComplete</title>
<script
type="text/javascript" src="/common/ajax.js"></script>
<script>
var div;
var table;
var text;
/*
* 변수값 초기화
*/
function onLoad(){
div =
document.getElementById("autoCompleteDiv");
table =
document.getElementById("autoCompleteTable");
text =
document.getElementById("autoCompleteText");
}
/*
* 조회
*/
function
listAutoComplete(){
if(text.value !=
""){
if(event.keyCode != 229){
var url = "/ajax/autoComplete.action?word=" +
text.value;
AutoComplete.ContentLoader(url, viewTitleList);
}
}else{
clearTitleList();
}
}
/*
* 테이블을 DHTML로 작성
*/
function
viewTitleList(){
clearTitleList();
if(AutoComplete.getState()){ //데이터의 전부를 받은 상태
var tr, td;
var words = xmlHttp.responseXML.getElementsByTagName("word");
var size = words.length;
for(var i = 0 ; i < size ; i++){
tr = table.insertRow();
tr.style.width = "100%";
td = tr.insertCell();
td.style.width = "100%";
td.style.cursor = "hand";
td.innerText =
words[i].firstChild.nodeValue;
td.onclick = function() {
wordClick(this);};
td.onmouseover = function() {
mouseOver(this);};
td.onmouseout =
function() { mouseout(this);};
}
}
}
/*
* 테이블의 목록을 초기화
*/
function clearTitleList(){
var ind = table.rows.length;
for (var
i = ind - 1; i >= 0 ; i--) {
table.deleteRow(i);
}
}
/*
* 클릭시
*/
function
wordClick(oTd){
text.value = oTd.innerText;
}
/*
* 마우스오버
*/
function mouseOver(td){
td.style.background= "#CBE7BA";
}
/*
* 마우스아웃
*/
function mouseout(td){
td.style.background= "#FFFFFF";
}
</script>
</head>
<body
onLoad="onLoad()">
<input type="text" id="autoCompleteText"
style="width:200px" autocomplete="off"
onkeyup="javascript:listAutoComplete()"><br>
<div
id="autoCompleteDiv" style="position:absolute; width:200px; height:180px;
scrolling:yes; overflow-y:auto;">
<table
id="autoCompleteTable" style="width:100%"></table>
</div>
</body>
</html>
/**************************************************************
struts.xml
**************************************************************/
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts
PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant
name="struts.enable.DynamicMethodInvocation" value="true" />
<constant name="struts.devMode" value="true" />
<include file="ajax.xml" />
</struts>
/**************************************************************
ajax.xml
**************************************************************/
<?xml
version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="ajax" namespace="/ajax"
extends="struts-default">
<global-results>
<result
name="Exception">/exception.jsp</result>
</global-results>
<global-exception-mappings>
<exception-mapping exception="java.lang.Exception"
result="Exception" />
</global-exception-mappings>
<action
name="*" method="{1}" class="web.ajax.AjaxAction">
<interceptor-ref name="servlet-config" />
<interceptor-ref name="exception" />
<result
name="searchTitleList_success">/ajax/AutoComplete.jsp</result>
</action>
<action
name="defaultAction">
<result>/WrongAction.jsp</result>
</action>
</package>
</struts>
/**************************************************************
AjaxAction.java
**************************************************************/
package
web.ajax;
import javax.servlet.ServletContext;
import
javax.servlet.http.*;
import org.apache.log4j.Logger;
import
org.apache.struts2.ServletActionContext;
import
org.apache.struts2.interceptor.*;
import
org.springframework.web.context.WebApplicationContext;
import
org.springframework.web.context.support.WebApplicationContextUtils;
import com.opensymphony.xwork2.ActionSupport;
/**
*
Base Action class for the Tutorial package.
*/
public class AjaxAction
extends ActionSupport implements ServletRequestAware, ServletResponseAware {
private HttpServletRequest request;
private
HttpServletResponse response;
private Logger logger =
Logger.getLogger(this.getClass());
/**
* test1
* @throws Exception
*/
public String
autoComplete() throws Exception {
try{
logger.info("autoComplete start");
// request를 가져온다.
ServletContext servletContext =
ServletActionContext.getServletContext();
WebApplicationContext wac =
WebApplicationContextUtils.getWebApplicationContext(servletContext);
String[] wordArr = {"acrobat",
"adobe",
"bmw",
"brave",
"cbs",
"cnn",
"heaven",
"html",
"kbs",
"key",
"net",
"news",
"queen",
"quick",
"soup",
"super",
"ufo",
"usb",
"work",
"wow",
"zebra",
"zenith"};
StringBuffer xmlStr = new StringBuffer("");
boolean isTitleExist = false;
//실제업무에서는 비지니스 레이어에서 XML String을 구현한다.
//String xmlStr = ajax.getAutoCompleteTitleList(boardVO);
xmlStr.append("<?xml version="1.0"
encoding="EUC-KR"?>");
xmlStr.append("<words>");
for(int i = 0; i < wordArr.length ; i++){
if(wordArr[i].indexOf(request.getParameter("word")) != -1){
xmlStr.append("<word>");
xmlStr.append(wordArr[i]);
xmlStr.append("</word>");
isTitleExist = true;
}
}
xmlStr.append("</words>");
//logger.info("request.getParameter("title") : " +
request.getParameter("title"));
logger.info("xmlStr.toString() : " + xmlStr.toString());
if(isTitleExist){
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write(xmlStr.toString());
}else{
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}
logger.info("forward :" +
request.getParameter("forward"));
logger.info("autoComplete end");
return null;
}catch(Exception e){
logger.info("Error : " +
e.toString());
e.printStackTrace();
throw e;
}
}
public void
setServletRequest(HttpServletRequest request) {
this.request =
request;
}
public void
setServletResponse(HttpServletResponse response) {
this.response = response;
}
}
[개강임박강좌, 오프라인교육장에 오시면 보다 자세히 배울 수
있습니다.]
오라클자바커뮤니티에서 운영하는 개발자 전문교육 ,개인80%환급(www.onjprogramming.co.kr)
[주간]
[11/18]Spring3.X, MyBatis,
Hibernate실무과정
[11/18]iPhone 하이브리드 앱 개발
실무과정
[11/20]SQL초보에서실전전문가까지
[11/20]안드로이드개발자과정
[평일야간]
[11/19]iPhone하이브리드앱개발실무과정
[11/19]안드로이드개발자과정
[11/21]JAVA&WEB프레임워자실무과정
[11/21]Spring3.X, MyBatis,
Hibernate실무과정
[11/27]SQL초보에서실전전문가까지
[주말]
[11/16]JAVA&WEB프레임워크실무과정
[11/16]웹퍼블리싱 마스터
[11/23]SQL초보에서전문가까지
[11/23]C#,ASP.NET마스터
[11/30]PL/SQL,오라클힌트,SQL튜닝,사례연구
[11/31]Spring3.X,MyBatis,Hibernate실무과정
댓글 없음:
댓글 쓰기