SPRING

Spring.스프링 프레임워크 - Rest

calla1013 2025. 6. 7. 12:12

 

 

@RestController와 @ModelAttribute로 동적 드롭다운 만들기 (Ajax 연동)

안녕하세요, 오늘은 Spring MVC에서 @RestController@ModelAttribute를 활용해 실시간 중분류 조회가 가능한 2단 드롭다운을 만드는 방법을 소개합니다.
Ajax를 이용해 REST API와 통신하며 사용자에게 더 나은 UI 경험을 제공해보세요!

1. 데이터 모델 설계 (COMM_CODE 테이블 + VO)

CREATE TABLE COMM_CODE (
    COMM_CD VARCHAR2(4) PRIMARY KEY,
    COMM_NM VARCHAR2(100),
    COMM_PARENT VARCHAR2(4)
);
// CodeVO.java
public class CodeVO {
    private String commCd;
    private String commNm;
    private String commParent;
    // Getter, Setter
}

2. DAO & 서비스 레이어 구성

// ICodeDAO.java
@Mapper
public interface ICodeDAO {
    List<CodeVO> getCodeListByParent(String parentCode);
}
<!-- code.xml (MyBatis 매퍼) -->
<select id="getCodeListByParent" resultType="CodeVO" parameterType="String">
  SELECT comm_cd, comm_nm, comm_parent
  FROM comm_code
  WHERE 1=1
  <choose>
    <when test="parentCode == null">
      AND comm_parent IS NULL
    </when>
    <otherwise>
      AND comm_parent = #{parentCode}
    </otherwise>
  </choose>
</select>
// CodeService.java
@Service
public class CodeService {
    @Autowired
    ICodeDAO codeDao;

    public List<CodeVO> getCodeListByParent(String parentCode) {
        return codeDao.getCodeListByParent(parentCode);
    }
}

3. REST API 구현 (@RestController)

// CodeController.java
@RestController
@RequestMapping("/api")
public class CodeController {
    @Autowired
    CodeService codeService;

    @GetMapping("/getSubCodes")
    public List<CodeVO> getSubCodes(@RequestParam String parentCode) {
        return codeService.getCodeListByParent(parentCode);
    }
}
📌 핵심 요약:
- @RestController: JSON 응답용 컨트롤러
- @RequestParam: 쿼리 파라미터 수신 (예: ?parentCode=XXXX)

4. @ModelAttribute로 대분류 공통 데이터 주입

// BoardController.java
@ModelAttribute("comList")
public List<CodeVO> getMainCodes() {
    return codeService.getCodeListByParent(null); // 대분류만 가져오기
}
<!-- JSP 대분류 드롭다운 -->
<select id="mainSelect">
  <option value="">-- 선택하세요 --</option>
  <c:forEach items="${comList}" var="code">
    <c:if test="${code.commParent eq null}">
      <option value="${code.commCd}">${code.commNm}</option>
    </c:if>
  </c:forEach>
</select>

5. Ajax로 중분류 동적 조회

<table>
  <tr>
    <th>대분류</th>
    <td>
      <select id="mainSelect"></select>
    </td>
    <th>중분류</th>
    <td>
      <select id="subSelect">
        <option value="">-- 선택하세요 --</option>
      </select>
    </td>
  </tr>
</table>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $('#mainSelect').on('change', function() {
    const selectedCode = $(this).val();

    if (!selectedCode) {
      $('#subSelect').html('<option>-- 선택하세요 --</option>');
      return;
    }

    $.ajax({
      url: "",
      type: "GET",
      data: { parentCode: selectedCode },
      dataType: "json",
      success: function(data) {
        $('#subSelect').empty().append('<option>-- 선택하세요 --</option>');
        $.each(data, function(i, code) {
          $('#subSelect').append(
            '<option value="' + code.commCd + '">' + code.commNm + '</option>'
          );
        });
      },
      error: function(err) {
        console.error("중분류 조회 실패:", err);
      }
    });
  });
</script>
✅ 이 구조의 장점:
- 뷰 렌더링 시 대분류는 서버 사이드에서 주입
- 중분류는 클라이언트에서 비동기 방식으로 요청
- 유지보수성과 확장성이 탁월한 구조!

🔥 마무리

이번 포스트에서는 @RestController, @ModelAttribute, Ajax를 결합하여 실시간 2단 드롭다운을 구현해보았습니다.
이런 방식은 게시판 분류, 지역 선택, 직무 선택 등 다양한 웹 애플리케이션에 유용하게 활용될 수 있습니다!