Spring, Ajax, JQuery UI 를 이용한 자동 완성(Autocomplete) 텍스트 박스 만들기 :: 소림사의 홍반장!

Requirement

  1. Spring MVC Project (Spring Template Project)
  2. JQuery 세팅                               <--- 클릭하여 바로가기
  3. JQuery UI 다운로드 및 환경 세팅   <--- 클릭하여 바로가기
  4. Json Library 설치                       <--- 클릭하여 바로가기

 

 

 

 

AjaxController.java

package kr.co.khi.controller;

 

import java.util.*;

 

import javax.servlet.http.*;

 

import kr.co.khi.dao.*;

import kr.co.khi.dto.*;

 

import org.json.*;

import org.springframework.beans.factory.annotation.*;

import org.springframework.stereotype.*;

import org.springframework.web.bind.annotation.*;

 

@Controller

@RequestMapping("/ajax")

public class AjaxController {

   

    @Autowired MembersDao dao;

   

  

    @RequestMapping(value="/auto", method=RequestMethod.GET)

    public void auto(String term, HttpServletResponse response) throws Exception {

       

        List<MembersDto> list = dao.getAddrList(term);

       

        // 응답해야 하는 문자열 : [{label:~,value:~},{label:~,value:~}]

        JSONArray array = new JSONArray();

        for(MembersDto dto : list) {

            JSONObject obj = new JSONObject();

            obj.put("label", dto.getPost()+dto.getAddr2());

            obj.put("value", dto.getPost()+dto.getAddr1());

            array.put(obj);

        }

}

       

}

 

 

MembersDao.java

 

package kr.co.khi.dao;

 

import java.util.*;

 

import kr.co.khi.dto.*;

 

import org.apache.ibatis.session.*;

import org.springframework.beans.factory.annotation.*;

import org.springframework.stereotype.*;

 

@Repository

public class MembersDao {

 

    @Autowired

    private SqlSession mapper;

   

 

    public List getAddrList(String dong) {

        return mapper.selectList("members.getaddr", dong);

    }

 

 

}

 

 

MembersDto.java

package kr.co.khi.dto;

 

public class MembersDto {

    private String userid;  // 아이디

    private String pass;    // 비밀번호

    private String email;   // 이메일

    private String email1;  // 이메일1

    private String email2;  // 이메일2

    private String email3;  // 이메일3

    private String name;    // 이름

    private String tel;     // 전화번호

    private String gender;  // 성별

    private String bday;    // 생년월일

    private String post;    // 우편번호

    private String addr1;   // 기본주소

    private String addr2;   // 상세주소

    private String hday;    // 가입일

    private String path;    // 돌아갈 주소

   

    public String getUserid() {

        return userid;

    }

 

    public void setUserid(String userid) {

        this.userid = userid;

    }

 

    public String getPass() {

        return pass;

    }

 

    public void setPass(String pass) {

        this.pass = pass;

    }

 

    public String getEmail() {

        return email;

    }

 

    public void setEmail(String email) {

        this.email = email;

    }

 

    public String getName() {

        return name;

    }

 

    public void setName(String name) {

        this.name = name;

    }

 

    public String getTel() {

        return tel;

    }

 

    public void setTel(String tel) {

        this.tel = tel;

    }

 

    public String getGender() {

        return gender;

    }

 

    public void setGender(String gender) {

        this.gender = gender;

    }

 

    public String getBday() {

        return bday;

    }

 

    public void setBday(String bday) {

        this.bday = bday;

    }

 

    public String getPost() {

        return post;

    }

 

    public void setPost(String post) {

        this.post = post;

    }

 

    public String getAddr1() {

        return addr1;

    }

 

    public void setAddr1(String addr1) {

        this.addr1 = addr1;

    }

 

    public String getAddr2() {

        return addr2;

    }

 

    public void setAddr2(String addr2) {

        this.addr2 = addr2;

    }

 

    public String getHday() {

        return hday;

    }

 

    public void setHday(String hday) {

        this.hday = hday;

    }

 

    public String getEmail1() {

        return email1;

    }

 

    public void setEmail1(String email1) {

        this.email1 = email1;

    }

 

    public String getEmail2() {

        return email2;

    }

 

    public void setEmail2(String email2) {

        this.email2 = email2;

    }

 

    public String getEmail3() {

        return email3;

    }

 

    public void setEmail3(String email3) {

        this.email3 = email3;

    }

 

    public String getPath() {

        return path;

    }

 

    public void setPath(String path) {

        this.path = path;

    }

   

}

 

 

 

members.xml

 

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

<!DOCTYPE mapper

PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

 

<mapper namespace="members">

        <!-- Type value -->

        <!-- string : java.lang.String

                       int : java.lang.Integer

               hashmap : java.util.HashMap

        -->

       

<!--    <resultMap type="kr.co.khi.dto.MembersDto" id="addrResult"> -->

<!--           <result column="zipcode" property="post" /> -->

<!--    </resultMap> : 컬럼명과 필드명이 다를때 사용. 이런식으로 별칭을 안쓰고 세팅해줄 수 있음-->

              

        <select id="getaddr" parameterType="string" resultType="kr.co.khi.dto.MembersDto">

               select zipcode post, sido||' '||gugun||' '||dong addr1,

               sido||' '||gugun||' '||dong||bunji addr2

               from ziptbl

               where dong like '%'||#{value}||'%'    <!-- 하나만 들어올때는 value 한다 -->

               order by seq

        </select>

       

</mapper>

 

 

 

 

ajax4.jsp

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

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<% String cp = request.getContextPath(); %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<title>JQuery를 이용한 AJAX</title>

<link type="text/css" href="<%=cp %>/css/custom-theme/jquery-ui-1.8.23.custom.css" rel="stylesheet" />

<script type="text/javascript" src="<%=cp %>/js/jquery-1.8.0.min.js" ></script>

<script type="text/javascript" src="<%=cp %>/js/jquery-ui-1.8.23.custom.min.js" ></script>

<script type="text/javascript" src="<%=cp %>/js/jquery.ui.datepicker-ko.js" ></script>

<script type="text/javascript">

$(function(){

//      var source = ['난누군가','또여긴어딘가','누가날불러?'];

        // 자동으로 /ajax/auato 주소로 term 이란 파라미터가 전송된다.

        // 응답은 [{label:~~~,value:~~~},{label:~~~,value:~~~}] 형태가 된다.

<%--    $('#term').autocomplete({"source":"<%=cp%>/ajax/auto"}); --%>

        $('#term').autocomplete({"source":function(request,response){

               $.getJSON("<%=cp%>/ajax/auto",{"term":request.term},

                       function(result) {

                              return response($.map(result, function(item){

                                      var l = item.label.replace(request.term,

                                                     "<span style='color:red'>"+request.term+"</span>");

                                      return {label:l, value:item.value};

                              }));

               });

        }});

});

</script>

</head>

<body>

<input type="text" id="term" />

</body>

</html>

 

 

 

 

 

 

 

다른 카테고리의 글 목록

Dev. 스프링/참고소스 및 예제 카테고리의 포스트를 톺아봅니다