고인돌 프로젝트/[Step 3] 모델 2(MVC) Spring boot

4.Controller 생성 , DI(IoC) 적용하기

고인돌개발자 2021. 8. 24. 21:19

▶ 참고 : 이 프로젝트는 | [Web 모델 1] Jsp,beans + Oracle | [Web 모델2] Servlet ,beans,jsp + Oracle 에 이어지는 프로젝트 입니다. 기존 진행했던 프로젝트를 먼저 진행하셔야 쉽게 따라올 수 있습니다.

 

▶ 참고 : 이과정에서는 Di/Ioc 에 대한 다른 설명은 하지 않습니다. 위에 언급했듯이, 모델1 - 2 - 스프링의 진행과정을 통해
           MVC 와 스프링을 익히는데 목표를 두고 있습니다. IoC 에 대한 설명은 제가 별도로 만든 자료를 참고해 주세요.

IoC / DI 설명자료 : https://old-developer.tistory.com/120?category=929141



※ 디렉토리 구조 참고 ( di 패키지를 생성하여 작업 함, 향후 다른 작업시 구분을 하기 위함 )

<프로젝트 디렉토리 구조>


1. Controller 소스코드 
    @Controller , @RequestMapping("/PeopleList") 작업을 통한 서블릿 요청 적용.   
    

더보기

/src/main/java/com/model2/spring/di/controller/PeopleList.java

package com.model2.spring.di.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.model2.spring.di.service.PeopleService;
import com.model2.spring.di.vo.People;
import com.model2.spring.di.vo.People_lombok;

import lombok.extern.slf4j.Slf4j;

@Controller
@Slf4j
public class PeopleList {
	
	@Autowired
	PeopleService peopleService;
	
	/*
	@Autowired
	public PeopleList(PeopleService peopleService) {
		this.peopleService = peopleService;		
	}
	*/
	
	@RequestMapping("/PeopleList")
	public String getPeopleList(HttpServletRequest request) {
		
		List<People> list = new ArrayList<>();
	    
		System.out.println("1. list size"+ list.size());
	    //PeopleService peopleService = new PeopleService();
	    
	    list = peopleService.doSelect();
	   	System.out.println("2. list size"+ list.size());	
			// 리스트의 값을 Attribute 를 통해 주고 받는다.
			request.setAttribute("people", list);
			
			System.out.println("Hi Spring - DI - Model2_Spring_War");	
		
		return "list";
		//return "/WEB-INF/view/list.jsp";
	
	}
	
	@RequestMapping("/PeopleList_Lombok")	
	public String getPeopleList_lombok(HttpServletRequest request) {		
		
		List<People_lombok> list = new ArrayList<>();
	    
		System.out.println("1. list size"+ list.size());
	    //PeopleService peopleService = new PeopleService();
	    
	    list = peopleService.doSelect_lombok();
	   	System.out.println("2. list size"+ list.size());	
			// 리스트의 값을 Attribute 를 통해 주고 받는다.
			request.setAttribute("people", list);
			
			System.out.println("Hi Spring - Lombok ");	
		
		return "list_lombok";
		//return "/WEB-INF/view/list.jsp";
	
	}

}

/src/main/java/com/model2/spring/di/controller/RegistPeople.java

package com.model2.spring.di.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.model2.spring.di.service.PeopleService;
import com.model2.spring.di.service.RegistService;
import com.model2.spring.di.vo.People;

@Controller
public class RegistPeople {
	
	@Autowired
	RegistService registservice ;
	
	@Autowired
	PeopleService peopleService;
	
	/*
	@Autowired
	public RegistPeople(PeopleService peopleService) {
		this.peopleService = peopleService;		
	}
	*/
	
	@RequestMapping("/RegistPeople")
	public String getRegistPeople(HttpServletRequest request) throws UnsupportedEncodingException {
		
		/* ID , Name, Age 를 받는 부분 */
		request.setCharacterEncoding("UTF-8");
    	
	    String strID 	= request.getParameter("input_id");
	    String strName 	= request.getParameter("input_name");
	    String strAge	= request.getParameter("input_age");
		
		/* 해당 인자값을 던져서 Insert 시키는 메서드 Call */
	    //RegistService registservice = new RegistService();
	    int intResult = registservice.doInsert(strID, strName, strAge);
	    
		/* 작업이 끝난 후 가야할 위치 지정 */
		List<People> list = new ArrayList<>();
	    
	    //PeopleService peopleService = new PeopleService();
		
		list = peopleService.doSelect();
		// 리스트의 값을 Attribute 를 통해 주고 받는다.
		request.setAttribute("people", list);
			
		System.out.println("Hi RegistPeople - Model2_Spring_War");	
		
		return "list";
	
	}

}

/src/main/java/com/model2/spring/di/controller/DeletePeople.java

package com.model2.spring.di.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.model2.spring.di.service.DeleteService;
import com.model2.spring.di.service.PeopleService;
import com.model2.spring.di.vo.People;

@Controller
public class DeletePeople {
	
	  @Autowired
	  DeleteService deleteservice;
	  
	  @Autowired
	  PeopleService peopleService;
	  
	  /*
	  @Autowired
	  public DeletePeople(PeopleService peopleService) {
			this.peopleService = peopleService;		
	  }
	  */
	
	@RequestMapping("/DeletePeople")
	public String getDeletePeople(HttpServletRequest request) throws UnsupportedEncodingException {
		
		/* ID 를 받는 부분 */
		request.setCharacterEncoding("UTF-8");
    	
	    String strID 	= request.getParameter("id");
	   	
		/* 해당 인자값을 던져서 Insert 시키는 메서드 Call */
	    // DeleteService deleteservice = new DeleteService();
	    int intResult = deleteservice.doDelete(strID);
	    
		/* 작업이 끝난 후 가야할 위치 지정 */
		List<People> list = new ArrayList<>();
	    
	    //PeopleService peopleService = new PeopleService();
		
		list = peopleService.doSelect();
		// 리스트의 값을 Attribute 를 통해 주고 받는다.
		request.setAttribute("people", list);
			
		System.out.println("Hi DeletePeople - Model2_Spring_War");	
		
		return "list";
	
	}

}

 


2. Service 소스코드 - @Component 를 사용하여 IoC 에 bean 생성

 

더보기

/src/main/java/com/model2/spring/di/service/PeopleService.java

package com.model2.spring.di.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.model2.spring.di.comm.DbConn;
import com.model2.spring.di.controller.PeopleList;
import com.model2.spring.di.vo.People;
import com.model2.spring.di.vo.People_lombok;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class PeopleService {
	
	String name;
	
	
	public List<People> doSelect(){
		
	
		Connection conn = null; // DB 에 connection 된 객체를 저장 
	    PreparedStatement ps = null;  // connection 객체에 실행문을 던지는 역할(창구)
	    ResultSet rs = null;     // select 결과값을 받아옮
	    String qry="";
		DbConn dbConn = new DbConn();	    
		conn = dbConn.getConn();
		
		List<People> list = new ArrayList<>();
		
		 try{ 
			    /* Result Set , Print */	
				qry = " select id, name, age, to_char(reg_date,'yyyy.mm.dd') as dati " 
					+" from people ";
				
				ps = conn.prepareStatement(qry);
				rs = ps.executeQuery();
				log.info(qry);
				while(rs.next()) {
					// Poeple 생성자를 이용하여 값을 입력 
					People people = new People(rs.getString("id"), rs.getString("name"), rs.getString("age"), rs.getString("dati"));
					list.add(people);	
					
				}
				
				System.out.println(list.size());
				System.out.println("Model 2");
			
		   }catch (Exception e) {
				System.out.println("Error =>"+e);			
			 }finally {
				 /* Close */ 
				try {
					if(rs != null) rs.close();
					if(ps != null) ps.close();
					if(conn != null) conn.close();			
				}catch (Exception e2) {			
				}
			}				
		
		  return list;
	}
	
	public List<People_lombok> doSelect_lombok(){
		
		
		Connection conn = null; // DB 에 connection 된 객체를 저장 
	    PreparedStatement ps = null;  // connection 객체에 실행문을 던지는 역할(창구)
	    ResultSet rs = null;     // select 결과값을 받아옮
	    String qry="";
		DbConn dbConn = new DbConn();	    
		conn = dbConn.getConn();
		
		List<People_lombok> list = new ArrayList<>();
		
		 try{ 
			    /* Result Set , Print */	
				qry = " select id, name, age, to_char(reg_date,'yyyy.mm.dd') as dati " 
					+" from people ";
				
				ps = conn.prepareStatement(qry);
				rs = ps.executeQuery();
				
				log.info(qry);
				
				while(rs.next()) {
					// Poeple 생성자를 이용하여 값을 입력 
					//People_lombok people_lombok = new People_lombok(rs.getString("id"), rs.getString("name"), rs.getString("age"), rs.getString("dati"));
					People_lombok people_lombok = People_lombok.builder()
											      .strID(rs.getString("id"))
											      .strAge(rs.getString("age"))
											      .strDati(rs.getString("dati"))
											      .strName(rs.getString("name"))
											      .build();
					
					log.info(people_lombok.toString());
					System.out.println(people_lombok.toString());
					list.add(people_lombok);
					
				}
				
				System.out.println(list.size());
				System.out.println("Model 2 , Lombok , builder");
			
		   }catch (Exception e) {
				System.out.println("Error =>"+e);			
			 }finally {
				 /* Close */ 
				try {
					if(rs != null) rs.close();
					if(ps != null) ps.close();
					if(conn != null) conn.close();			
				}catch (Exception e2) {			
				}
			}				
		
		  return list;
	}
	
	@PostConstruct
	public void init() {
	  System.out.println("PeopleService- init");
	}
	
	@PreDestroy
	public void destroy() {
	  System.out.println("PeopleService -destroy");
	}

}

/src/main/java/com/model2/spring/di/service/RegistService.java

package com.model2.spring.di.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.stereotype.Service;

import com.model2.spring.di.comm.DbConn;
import com.model2.spring.di.vo.People;

@Service
public class RegistService {
	
	
	public int doInsert(String strID, String strName, String strAge){
	
		int intI =0;
		Connection conn = null; // DB 에 connection 된 객체를 저장 
	    PreparedStatement ps = null;  // connection 객체에 실행문을 던지는 역할(창구)
	    ResultSet rs = null;     // select 결과값을 받아옮
	    String qry="";
		DbConn dbConn = new DbConn();	    
		conn = dbConn.getConn();
				
		 try{ 
			   
			 /* Result Set , Print */	
				qry = " Insert into people(id, name, age) "
					 +" values (? , ?, to_number(?))";
			     
				ps = conn.prepareStatement(qry);			
				ps.setString(1, strID);
				ps.setString(2, strName);
				ps.setString(3, strAge);			
				
				ps.executeUpdate();
				
				System.out.println("ID "+strID+" 를 등록 했습니다.");
				
				System.out.println("Model 2");
			
		   }catch (Exception e) {
			    intI = 1;
				System.out.println("Error =>"+e);			
			 }finally {
				 /* Close */ 
				try {
					if(rs != null) rs.close();
					if(ps != null) ps.close();
					if(conn != null) conn.close();			
				}catch (Exception e2) {			
				}
			}	
		 
		 return intI;
	}
	


}

/src/main/java/com/model2/spring/di/service/DeleteService.java

package com.model2.spring.di.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.model2.spring.di.comm.DbConn;
import com.model2.spring.di.vo.People;

@Service
public class DeleteService {
	
	
	public int doDelete(String strID){
	
		int intI =0;
		Connection conn = null; // DB 에 connection 된 객체를 저장 
	    PreparedStatement ps = null;  // connection 객체에 실행문을 던지는 역할(창구)
	    ResultSet rs = null;     // select 결과값을 받아옮
	    String qry="";
		DbConn dbConn = new DbConn();	    
		conn = dbConn.getConn();
				
		 try{ 
			       
			     /* Result Set , Print */	
				qry = " delete from people where id=?";
				 
				ps = conn.prepareStatement(qry);			
				ps.setString(1, strID);
				
				ps.executeUpdate();
				
				System.out.println("ID "+strID+" 를 삭제 했습니다.");				
				System.out.println("Model 2, doDelete");
			
		   }catch (Exception e) {
			    intI = 1;
				System.out.println("Error =>"+e);			
			 }finally {
				 /* Close */ 
				try {
					if(rs != null) rs.close();
					if(ps != null) ps.close();
					if(conn != null) conn.close();			
				}catch (Exception e2) {			
				}
			}	
		 
		 return intI;
		
		
	}

}

3. Vo 소스코드 

더보기

/src/main/java/com/model2/spring/di/vo/People.java

package com.model2.spring.di.vo;

/* People DB 에서 값을 받아 저장하고, View 에 던져주는 매개체 역할을 합니다. */


public class People {
	
	private String strID;
	private String strName;
	private String strAge;
	private String strDati;
	
	
	public People(String strID, String strName, String strAge, String strDati) {
		this.strID = strID;
		this.strName = strName;
		this.strAge = strAge;
		this.strDati = strDati;
	}
	
	

	public String getStrID() {
		return strID;
	}

	public void setStrID(String strID) {
		this.strID = strID;
	}

	public String getStrName() {
		return strName;
	}

	public void setStrName(String strName) {
		this.strName = strName;
	}

	public String getStrAge() {
		return strAge;
	}

	public void setStrAge(String strAge) {
		this.strAge = strAge;
	}

	public String getStrDati() {
		return strDati;
	}

	public void setStrDati(String strDati) {
		this.strDati = strDati;
	}



	@Override
	public String toString() {
		return "People [strID=" + strID + ", strName=" + strName + ", strAge="
				+ strAge + ", strDati=" + strDati + "]";
	}
	

}

/src/main/java/com/model2/spring/di/vo/People_lombok.java

package com.model2.spring.di.vo;

import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

/* People DB 에서 값을 받아 저장하고, View 에 던져주는 매개체 역할을 합니다. */

@Getter
@Setter
@ToString
public class People_lombok {
	
	private String strID;
	private String strName;
	private String strAge;
	private String strDati;
	
	@Builder
	public People_lombok(String strID, String strName, String strAge, String strDati) {
		this.strID = strID;
		this.strName = strName;
		this.strAge = strAge;
		this.strDati = strDati;
	}	
	
}

최종 테스트 진행...