스프링

 

Service(인터페이스), Servicelmpl(인터페이스 구현) 활용해서 Main, Swing 실습

 

스프링 설정 클래스 @Bean

package config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import dao.BoardDao;
import service.BoardServiceImpl;

@Configuration
public class AppCtx {
	
	@Bean
	public BoardDao boardDao() {
		return new BoardDao();
	}
	
	
	//@Bean // 세터방식
//	public BoardServiceImpl boardservice() {
//		BoardServiceImpl boardservice = new BoardServiceImpl();
//		boardservice.setBoardDao(boardDao());
//		return boardservice;
//	}
	
	@Bean // 생성자 방식
	public BoardServiceImpl boardservice() {
		BoardServiceImpl boardservice = new BoardServiceImpl(boardDao());
		return boardservice;
	}
	
}

 

Service ( 인터페이스 )

package service;

import java.util.ArrayList;

import dao.BoardDto;

public interface BoardService {
	ArrayList<BoardDto> findAll();
	BoardDto findOne(Long num, boolean incHits);
	void saveOne(BoardDto dto);
	void modifyOne(BoardDto dto);
	void cancelOne(Long num);
	boolean hasArticle(Long num);
}

 

ServiceImpl ( 구현 )

package service;

import java.util.ArrayList;

import dao.BoardDao;
import dao.BoardDto;

public class BoardServiceImpl implements BoardService {
	
	// 스프링 설정 클래스에서 생성자 생성했으니 생성자 생성 필요 없음
	BoardDao boardDao;
	
	
	// 세터
	public void setBoardDao(BoardDao boardDao) {
		this.boardDao = boardDao;
	}
	
	
	
	// 생성자방식 ( 의존 객체 주입 )
	public BoardServiceImpl(BoardDao boardDao) {
		super();
		// 주입 받은 객체를 필드에 할당
		this.boardDao = boardDao;
	}




	@Override
	public ArrayList<BoardDto> findAll() {
		return boardDao.selectList();
	}

	@Override
	public BoardDto findOne(Long num, boolean incHits) {
		if (incHits) {
			boardDao.updateHits(num);
		}
		return boardDao.selectOne(num, incHits);
	}

	@Override
	public void saveOne(BoardDto dto) {
		boardDao.insertOne(dto);
		
	}

	@Override
	public void modifyOne(BoardDto dto) {
		boardDao.updateOne(dto);
		
	}

	@Override
	public void cancelOne(Long num) {
		boardDao.deleteOne(num);
		
	}



	@Override
	// 게시물 번호를 매개변수로 받아서 해당 번호에 해당하는 게시물이 데이터베이스에 존재하는지 확인
	public boolean hasArticle(Long num) {
		// 주어진 게시물 번호를 가진 게시물을 데이터베이스에서 검색하고 그 결과를 Dto로 반환
		// false로 조회 시 조회수를 증가시키지않게 설정
		BoardDto dto = boardDao.selectOne(num, false);
		if(dto == null) {
			return false;
		}
		//조회 결과(Dto)가 null이 아니라면 해당 게시물이 데이터베이스에 존재하는 것을 의미
		return true;
	}



}

 

Main.java ( 실행 )

package main;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import config.AppCtx;
import dao.BoardDto;
import service.BoardService;
import service.BoardServiceImpl;


public class MainForSpring {

	private static ApplicationContext ctx = null;
	
	public static void main(String[] args) throws IOException {
		ctx = new AnnotationConfigApplicationContext(AppCtx.class);
		
		BufferedReader reader = 
				new BufferedReader(new InputStreamReader(System.in));
		while (true) {
			System.out.println("명령어를 입력하세요:");
			String command = reader.readLine();
			if (command.equalsIgnoreCase("exit")) {
				System.out.println("종료합니다.");
				break;
			}
			if (command.startsWith("new ")) {
//				String[] aaa = command.split(" ");
//				for(String ss : aaa) {
//					System.out.println(ss);
//				}
				processNewCommand(command.split(" "));
				continue;
			} else if (command.startsWith("change ")) {
				processChangeCommand(command.split(" "));
				continue;
			} else if (command.equals("list")) {
				processListCommand();
				continue;
			} else if (command.startsWith("delete ")) {
				processDeleteCommand(command.split(" "));
				continue;
			}
			
			printHelp();
		}
	}

	private static void processNewCommand(String[] arg) {
		if (arg.length != 4) {
			printHelp();
			return;
		}
		
		BoardService boardService =
				ctx.getBean("boardservice", BoardServiceImpl.class);
		boardService.saveOne(new BoardDto(0L, arg[1], arg[2], arg[3], null, 0));
		System.out.println("글 등록 완료");
		

	}

	private static void processChangeCommand(String[] arg) {
		if (arg.length != 5) {
			printHelp();
			return;
			
		}
		
		BoardService boardService =
				ctx.getBean("boardservice", BoardService.class);
		
        long num = (arg[1].length() > 0) ? Long.parseLong(arg[1])
                : 0;
        if(num != 0 && boardService.hasArticle(num)) {
            BoardDto dto = new BoardDto(num, arg[2], arg[3], arg[4], null, 0);
            
            
    		boardService.modifyOne(dto);
    		System.out.println("글 수정 완료");
        }else {
			System.out.println("글 번호가 오류입니다.");
		}

//		ChangePasswordService changePwdSvc = 
//				ctx.getBean("changePwdSvc", ChangePasswordService.class);
//		try {
//			changePwdSvc.changePassword(arg[1], arg[2], arg[3]);
//			System.out.println("암호를 변경했습니다.\n");
//		} catch (MemberNotFoundException e) {
//			System.out.println("존재하지 않는 이메일입니다.\n");
//		} catch (WrongIdPasswordException e) {
//			System.out.println("이메일과 암호가 일치하지 않습니다.\n");
//		}
	}

	private static void printHelp() {
		System.out.println();
		System.out.println("잘못된 명령입니다. 아래 명령어 사용법을 확인하세요.");
		System.out.println("명령어 사용법:");
		System.out.println("new 이메일 이름 암호 암호확인");
		System.out.println("change 이메일 현재비번 변경비번");
		System.out.println();
	}

	private static void processListCommand() {
		BoardService listprint =
				ctx.getBean("boardservice", BoardService.class);
							// "boardservice" @Bean 사용 할 메서드변수
		List<BoardDto> list = listprint.findAll();
		for(BoardDto dto : list) {
			System.out.println(dto);
		}
		

	}
	
	private static void processDeleteCommand(String[] arg) {
		if (arg.length != 2) {
			printHelp();
			return;
			
		}
		
		BoardService boardService =
				ctx.getBean("boardservice", BoardService.class);
		
		// arg 배열의 두 번째 요소(arg[1])가 비어있지 않은 경우(길이가 0보다 큰 경우), 
		// 해당 값을 long 타입으로 변환하여 변수 num에 저장
		// 예외적인 상황에서 비어있는 경우 0으로 초기화하여 기본값으로 사용하기 위함
        long num = (arg[1].length() > 0) ? Long.parseLong(arg[1]) : 0;
        
        // 변수 num의 값이 0이 아니고, boardService의 hasArticle 메서드를 호출하여 해당 
        // 게시물 번호(num)의 게시물이 데이터베이스에 존재하는지 여부를 확인
        if(num != 0 && boardService.hasArticle(num)) {
            
            
            
    		boardService.cancelOne(num);
    		
    		System.out.println("글 삭제 완료");
        }else {
			System.out.println("글 번호가 오류입니다.");
		}
		

	}

	

}

 

Swing ( 실행 ) 

package swing;

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import config.AppCtx;
import dao.BoardDto;
import service.BoardService;
import service.BoardServiceImpl;

public class Win1 extends JFrame {
	
	private static ApplicationContext ctx = new AnnotationConfigApplicationContext(AppCtx.class);
	
	// 알럿
	private JFrame frame = this;
	
	Win1() {
		JButton bt1 = new JButton("검색");
		JButton bt2 = new JButton("입력");
		JButton bt3 = new JButton("수정");
		JButton bt4 = new JButton("삭제");
		
		JTextArea ta = new JTextArea();

		JTextField tf1 = new JTextField();
		JTextField tf2 = new JTextField();
		JTextField tf3 = new JTextField();
		JTextField tf4 = new JTextField();
		
		JLabel lb1 = new JLabel("num");
		JLabel lb2 = new JLabel("writer");
		JLabel lb3 = new JLabel("title");
		JLabel lb4 = new JLabel("content");
		
		Container c = this.getContentPane();
		this.setLayout(null);
		this.setTitle("person");
		this.setSize(430, 300);
		this.setLocation(500, 500);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		bt1.setSize(70,  30);              // 폭과 높이 조절
		bt1.setLocation(20, 230);          // 위치 조정
		c.add(bt1);
		bt2.setSize(70,  30);              // 폭과 높이 조절
		bt2.setLocation(120, 230);          // 위치 조정
		c.add(bt2);
		bt3.setSize(70,  30);              // 폭과 높이 조절
		bt3.setLocation(220, 230);          // 위치 조정
		c.add(bt3);
		bt4.setSize(70,  30);              // 폭과 높이 조절
		bt4.setLocation(320, 230);          // 위치 조정
		c.add(bt4);
		
		tf1.setSize(70,  30);              // 폭과 높이 조절
		tf1.setLocation(20, 30);          // 위치 조정
		c.add(tf1);
		tf2.setSize(70,  30);              // 폭과 높이 조절
		tf2.setLocation(120, 30);          // 위치 조정
		c.add(tf2);
		tf3.setSize(70,  30);              // 폭과 높이 조절
		tf3.setLocation(220, 30);          // 위치 조정
		c.add(tf3);
		tf4.setSize(70,  30);              // 폭과 높이 조절
		tf4.setLocation(320, 30);          // 위치 조정
		c.add(tf4);
		
		lb1.setSize(70,  30);              // 폭과 높이 조절
		lb1.setLocation(20, 5);          // 위치 조정
		c.add(lb1);
		lb2.setSize(70,  30);              // 폭과 높이 조절
		lb2.setLocation(120, 5);          // 위치 조정
		c.add(lb2);
		lb3.setSize(70,  30);              // 폭과 높이 조절
		lb3.setLocation(220, 5);          // 위치 조정
		c.add(lb3);
		lb4.setSize(70,  30);              // 폭과 높이 조절
		lb4.setLocation(320, 5);          // 위치 조정
		c.add(lb4);
		
		JScrollPane scrollPane = new JScrollPane(ta);
		ta.setCaretPosition(ta.getDocument().getLength());
		scrollPane.setSize(350,  80);
		scrollPane.setLocation(30,  100);
		c.add(scrollPane);
		
		this.setVisible(true);
		
		bt1.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				
				ta.setText("");
				BoardService listprint =
						ctx.getBean("boardservice", BoardService.class);
									// "boardservice" @Bean 사용 할 메서드변수
				List<BoardDto> list = listprint.findAll();
				for(BoardDto dto : list) {
					ta.append(dto.toString()+"\n");
				}
				
				
				
//				List<BoardDto> list = listprint.findAll();
//				for(BoardDto dto : list) {
//					
//				}
				
				//System.out.println("클릭!");
				
			}
		});
		
		bt2.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				
				if(
						"".equals(tf2.getText())||
						"".equals(tf3.getText())||
						"".equals(tf4.getText())) {
					JOptionPane.showMessageDialog
					(frame, "num입력칸 빼고 모두 입력하세요.");
					return;
				}
				
				BoardService boardService =
						ctx.getBean("boardservice", BoardServiceImpl.class);
				BoardDto dto = new BoardDto();
				
				
				
				boardService.saveOne(new BoardDto(0L, tf2.getText(), tf3.getText(), tf4.getText(), null, 0));
				JOptionPane.showMessageDialog(frame, "입력을 완료 했습니다.");
				
			}
		});
		
		bt3.addActionListener(new ActionListener() {
			
			
			
			@Override
			public void actionPerformed(ActionEvent e) {
				
				if("".equals(tf1.getText())||
						"".equals(tf2.getText())||
						"".equals(tf3.getText())||
						"".equals(tf4.getText())) {
					JOptionPane.showMessageDialog
					(frame, "num값은 수정 할 num값, 나머지는 변경 할 내용을 입력하세요.\n");
					return;
				}
				
				
				BoardService boardService =
						ctx.getBean("boardservice", BoardService.class);
				
				long num = (Long.parseLong(tf1.getText())  > 0) ? Long.parseLong(tf1.getText()) : 0;
		        if(num != 0 && boardService.hasArticle(num)) {
		            BoardDto dto = new BoardDto(num, tf2.getText(), tf3.getText(), tf4.getText(), null, 0);
		            
		            
		    		boardService.modifyOne(dto);
		    		JOptionPane.showMessageDialog(frame, "글 수정 완료");
		        }else {
//		        	JOptionPane.showMessageDialog(frame, "글을 수정 완료");
				}
				
			}
		});
		
		bt4.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				
				if("".equals(tf1.getText())){
					JOptionPane.showMessageDialog
					(frame, "삭제 할 num값을 입력 해주세요.");
					return;
				}
				
				BoardService boardService =
						ctx.getBean("boardservice", BoardServiceImpl.class);
				
				
				boardService.cancelOne(Long.parseLong(tf1.getText()));
				JOptionPane.showMessageDialog(frame, "삭제를 완료 했습니다.");
				
			}
		});
		

		
		
	}

	public static void main(String[] args) {
		Win1 win = new Win1();

	}

}

 

 

 

'프로젝트 기반 자바(JAVA) 응용 SW개발자 취업과정' 카테고리의 다른 글

2023-07-28 51일차  (0) 2023.07.28
2023-07-27 50일차  (0) 2023.07.27
2023-07-25 48일차  (0) 2023.07.25
2023-07-24 47일차  (0) 2023.07.24
2023-07-21 46일차  (0) 2023.07.21

+ Recent posts