Step it up now

Notice 조건 검색 과정 본문

카테고리 없음

Notice 조건 검색 과정

케잉 2024. 1. 9. 20:41

 

 


 

 

클라이언트가 분류를 '제목' 에 두고 '공지'를 검색했을때 일어나는 과정 

 

 


 

 

 

NoticeList.jsp

function noticeSearch(){
	console.log('noticeSearch');
    // n_title을 선택시 value값은 n_title 이고 const gubun에 n_title 담김		
    const keyword = document.querySelector("#keyword").value; 	
    console.log(`${gubun} , ${keyword}`);
	const gubun = document.querySelector("#gubun").value; 
	
    //검색버튼 누르는 순간 주소창이 바뀌기 때문에 NoticeController에 전달해주기 위한 코드임 
    //-> NoticeController 이동
    location.href="/notice/noticeList?gubun="+gubun+"&keyword="+keyword;  
			
        //검색 후에 검색창은 다시 초기화됨
		document.querySelector("#gubun").value = '분류선택';
   		document.querySelector("#keyword").value = '';
	}

 

 

 

 

NoticeController.java

@GetMapping("noticeList")
    // noticeList 메소드는 공지사항 목록 표시 요청을 처리 -> 두 가지 매개변수가 필요
    //1.Model: 뷰에 데이터를 전달하는 데 사용되는 Spring 프레임워크 클래스
    //2.요청 매개변수를 pmap 매개변수에 바인딩하는 데 사용(요청과 함께 전송된 매개변수를 나타냄)
public String noticeList(Model model, @RequestParam Map<String, Object> pmap) { 
//ㄴnoticeList?gubun=n_title&keyword=제목 => 순서1.pmap = {gubun=n_title, keyword=제목}
        logger.info("noticeList");
        List<Map<String, Object>> nList = null; // [{},{},{}]
        // 순서2.pmap = {gubun=n_title, keyword=제목}가지고 logic으로 감
        nList = noticeLogic.noticeList(pmap); 
       //nList에 데이터가 담기고 가상공간"nList"라는 이름으로 nList값 저장
        model.addAttribute("nList", nList); //-> jsp에 전달할 수 있다  
        return "forward:noticeList.jsp";// webapp아래에서 찾는다
    }

 

 

 

 

NoticeLogic.java

// pmap = {gubun=n_title, keyword=공지}
public List<Map<String, Object>> noticeList(Map<String, Object> pmap) { 
      logger.info("noticeList");
      List<Map<String, Object>>list = new ArrayList<>();
      ////// @Service, @Autowired       
      // noticeDao변수는 NoticeLogic에서 선언만 되었다. new가 없다- ApplicationContext가 생성해줌
      // 왜냐면 NoticeLogic앞에 @Service가 붙어 있어서...
      // 이렇게 주입받은 객체의 인스턴스변수로 NoticeDao에 선언된 noticeList메소드를 호출하고 있다.
      // NoticeLogic과 NoticeDao의 연관관계에 대해 고민해 볼 것
      list = noticeDao.noticeList(pmap); //=dao에서 return된 list값을 가지고있다 
      // pmap = {gubun=n_title, keyword=공지}
      return list;
      }// end of noticeList

 

 

📢  List<Map<String, Object>>list = new ArrayList<>();

제네릭을 활용한 ArrayList를 선언

 

  1. List<Map<String, Object>>: 리스트를 선언 

List는 여러 요소를 저장할 수 있는 동적 배열임

Map<String, Object>은 맵 객체를 나타내며, 키와 값의 쌍으로 이루어진 데이터를 저장

이 리스트는 Map 객체를 요소로 갖는 리스트를 의미

 

2. new ArrayList<>();: 이 변수를 ArrayList로 초기화합니다. ArrayList는 동적 배열을 구현한 클래스로, 크기를 동적으로 조절할 수 있다. <>는 타입 파라미터를 생략가능

 

이 코드는 Map<String, Object>을 요소로 갖는 동적 배열(리스트)을 선언하고 초기화한 것

이 리스트를 활용하여 키와 값의 쌍을 저장하는 작업에 활용 가능하다

 

 

 

 

NoticeDao.java

 // gubun:n_title, keyword:공지
 public List<Map<String, Object>> noticeList(Map<String, Object> pmap) {
        logger.info("noticeList");
        // JAVA -> MyBatis -> Oracle
        // pmap = {gubun=n_title, keyword=공지}
        List<Map<String, Object>> list = sqlSessionTemplate.selectList("noticeList", pmap); 
        logger.info(list.toString());
        return list;
    }

 

 

 

 

Notice.xml

	<!--  pmap = {gubun=n_title, keyword=공지} -->
	<select id="noticeList" parameterType="map"  resultType = "map">
		select n_no, n_title, n_content, n_writer from notice
		
        <!--조건검색-->
        <where>
			<if test="n_no!=null">AND n_no=#{n_no}</if>
			<if test="gubun!=null">
				<choose>
<!--select n_no, n_title, n_content, n_writer 
		                    from notice where gubun=n_title and n_title like %공지% -->
					<when test='gubun.equals("n_title")'>
						AND n_title LIKE '%'||#{keyword}||'%'
					</when>
					<when test='gubun.equals("n_content")'>
						AND n_content LIKE '%'||#{keyword}||'%'
					</when>
					<when test='gubun.equals("n_writer")'>
						AND n_writer LIKE '%'||#{keyword}||'%'
					</when>
				</choose>