본문 바로가기
👨‍💻 2. 웹개발_Back end/2-4 JSP & Servlet

[JSP & Servlet] 1장 웹 애플리케이션 이해

by 달님🌙 2021. 10. 4.
반응형

 

1. 데스크톱 애플리케이션

 

예 ) 한글과 컴퓨터

특징 : 비즈니스 로직이 모두 PC로 수행됨

 

<예제> 콘솔창에 계산기 띄우기

package lesson01.exam00;

import java.util.Scanner;

public class CalculatorConsole {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		
		System.out.print("정수를 입력하세요 : ");
		int num0 = sc.nextInt();
		System.out.print("정수를 입력하세요 : ");
		int num1 = sc.nextInt();
		System.out.print("연산자를 입력하세요 : ");
		String op = sc.next();
		
		int result = 0;
		switch(op) {
		case "+" : 
			result = num0 + num1;
			break;
		case "-" : 
			result = num0 - num1;
			break;
		case "*" : 
			result = num0 * num1;
			break;
		case "/" : 
			result = num0 / num1;
			break;
		}
		
		System.out.println("결과 값은 " + result + "입니다.");
		sc.close();
		
	}

}
정수를 입력하세요 : 11
정수를 입력하세요 : 12
연산자를 입력하세요 : +
결과 값은 23입니다.

 

<예제> 자바스윙으로 계산기 띄우기

package lesson01.exam01;

import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class CalculatorFrame extends JFrame implements ActionListener {
	//자바 스윙 입력박스 및 버튼 생성 영역
	JTextField operand1 = new JTextField(4);
	JTextField operand2 = new JTextField(4);
	String[] operatorData = {"+", "-", "*", "/"};
	JComboBox<String> operator = new JComboBox<String>(operatorData);
	JButton equal = new JButton("=");
	JTextField result = new JTextField(6);
	JButton clear = new JButton("Clear");
	
	public CalculatorFrame() {
		this.setTitle("Lesson01-Exam01");
		
		Container contentPane = this.getContentPane();
		contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
		
		contentPane.add(Box.createVerticalGlue());
		contentPane.add(this.createInputForm());
		contentPane.add(this.createToolBar());
		contentPane.add(Box.createVerticalGlue());
		
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.pack();
		this.setLocationRelativeTo(null);
	}
	
	@Override
	public void actionPerformed(ActionEvent event) {
		if(event.getSource() == equal) {
			compute();
		} else {
			clearForm();
		}
	}
	
	public void compute() {
		double a = Double.parseDouble(operand1.getText());
		double b = Double.parseDouble(operand2.getText());
		double r = 0;
		
		try {
			switch(operator.getSelectedItem().toString()) {
			case "+" : r = a + b; break;
			case "-" : r = a - b; break;
			case "*" : r = a * b; break;
			case "/" : 
						if(b == 0) {
							throw new Exception("0으로 나눌 수 없습니다.");
						}
						r = a / b;
						break;
			}
			
			result.setText(Double.toString(r));
		} catch(Exception e) {
			JOptionPane.showInternalMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
		}
	}
	
	public void clearForm() {
		this.operand1.setText("");
		this.operand2.setText("");
		this.result.setText("");
	}
	
	private Box createInputForm() {
		Box box = Box.createHorizontalBox();
		box.setMaximumSize(new Dimension(300, 30));
		box.setAlignmentY(Box.CENTER_ALIGNMENT);
		box.add(operand1);
		box.add(operator);
		box.add(operand2);
		box.add(equal);
		box.add(result);
		equal.addActionListener(this);
		return box;
	}
	
	private Box createToolBar() {
		Box box = Box.createHorizontalBox();
		box.add(clear);
		clear.addActionListener(this);
		return box;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		CalculatorFrame app = new CalculatorFrame();
		app.setVisible(true);
	}

}

 

2. 클라이언트·서버 애플리케이션

 

 

 

 

 

3. 클라이언트·서버 애플리케이션

 

 

 

 

 

<예제> 클라이언트-서버 구조로 계산기 생성

CalculatorAgent.java

package lesson01.exam02.client;

import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

public class CalculatorAgent {
	Socket socket = null;
	PrintStream out = null;
	Scanner in = null;
	
	public CalculatorAgent(String ip, int port) throws Exception {
		socket = new Socket(ip, port);
		out = new PrintStream(socket.getOutputStream());
		in = new Scanner(socket.getInputStream());
	}
	
	public double compute(String operator, double a, double b) throws Exception {
		try {
			out.println(operator);
			out.println(a);
			out.println(b);
			out.flush();
			
			String state = in.nextLine();
			if(state.equals("success")) {
				return Double.parseDouble(in.nextLine());
			} else {
				throw new Exception(in.nextLine());
			}
		} catch(Exception e) {
			throw e;
		}
	}
	
	public void close() {
		try {
			out.println("goodbye");
			System.out.println(in.nextLine());
		} catch(Exception e) {
			
		}
		
		try {out.close();} catch(Exception e) {}
		try {in.close();} catch(Exception e) {}
		try {socket.close();} catch(Exception e) {}
	}
}

 

CalculatorFrame.java

package lesson01.exam02.client;

import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class CalculatorFrame extends JFrame implements ActionListener {
	//자바 스윙 입력박스 및 버튼 생성 영역
	CalculatorAgent calcAgent;
	JTextField operand1 = new JTextField(4);
	JTextField operand2 = new JTextField(4);
	String[] operatorData = {"+", "-", "*", "/"};
	JComboBox<String> operator = new JComboBox<String>(operatorData);
	JButton equal = new JButton("=");
	JTextField result = new JTextField(6);
	JButton clear = new JButton("Clear");
	
	public CalculatorFrame() {
		try {
			calcAgent = new CalculatorAgent("localhost", 8888);
		} catch(Exception e) {
			JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
			System.exit(0);
		}
		
		this.setTitle("Lesson01-Exam01");
		
		Container contentPane = this.getContentPane();
		contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
		
		contentPane.add(Box.createVerticalGlue());
		contentPane.add(this.createInputForm());
		contentPane.add(this.createToolBar());
		contentPane.add(Box.createVerticalGlue());
		
		this.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				calcAgent.close();
				System.exit(0);
			}
		});
		this.pack();
		this.setLocationRelativeTo(null);
	}
	
	@Override
	public void actionPerformed(ActionEvent event) {
		if(event.getSource() == equal) {
			compute();
		} else {
			clearForm();
		}
	}
	
	public void compute() {
		double a = Double.parseDouble(operand1.getText());
		double b = Double.parseDouble(operand2.getText());
		double r = 0;
		
		try {
			switch(operator.getSelectedItem().toString()) {
			case "+" : r = a + b; break;
			case "-" : r = a - b; break;
			case "*" : r = a * b; break;
			case "/" : 
						if(b == 0) {
							throw new Exception("0으로 나눌 수 없습니다.");
						}
						r = a / b;
						break;
			}
			
			result.setText(Double.toString(r));
		} catch(Exception e) {
			JOptionPane.showInternalMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
		}
	}
	
	public void clearForm() {
		this.operand1.setText("");
		this.operand2.setText("");
		this.result.setText("");
	}
	
	private Box createInputForm() {
		Box box = Box.createHorizontalBox();
		box.setMaximumSize(new Dimension(300, 30));
		box.setAlignmentY(Box.CENTER_ALIGNMENT);
		box.add(operand1);
		box.add(operator);
		box.add(operand2);
		box.add(equal);
		box.add(result);
		equal.addActionListener(this);
		return box;
	}
	
	private Box createToolBar() {
		Box box = Box.createHorizontalBox();
		box.add(clear);
		clear.addActionListener(this);
		return box;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		CalculatorFrame app = new CalculatorFrame();
		app.setVisible(true);
	}

}

 

CalculatorServer.java

package lesson01.exam02.client;

import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class CalculatorFrame extends JFrame implements ActionListener {
	//자바 스윙 입력박스 및 버튼 생성 영역
	CalculatorAgent calcAgent;
	JTextField operand1 = new JTextField(4);
	JTextField operand2 = new JTextField(4);
	String[] operatorData = {"+", "-", "*", "/"};
	JComboBox<String> operator = new JComboBox<String>(operatorData);
	JButton equal = new JButton("=");
	JTextField result = new JTextField(6);
	JButton clear = new JButton("Clear");
	
	public CalculatorFrame() {
		try {
			calcAgent = new CalculatorAgent("localhost", 8888);
		} catch(Exception e) {
			JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
			System.exit(0);
		}
		
		this.setTitle("Lesson01-Exam01");
		
		Container contentPane = this.getContentPane();
		contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
		
		contentPane.add(Box.createVerticalGlue());
		contentPane.add(this.createInputForm());
		contentPane.add(this.createToolBar());
		contentPane.add(Box.createVerticalGlue());
		
		this.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				calcAgent.close();
				System.exit(0);
			}
		});
		this.pack();
		this.setLocationRelativeTo(null);
	}
	
	@Override
	public void actionPerformed(ActionEvent event) {
		if(event.getSource() == equal) {
			compute();
		} else {
			clearForm();
		}
	}
	
	public void compute() {
		double a = Double.parseDouble(operand1.getText());
		double b = Double.parseDouble(operand2.getText());
		double r = 0;
		
		try {
			switch(operator.getSelectedItem().toString()) {
			case "+" : r = a + b; break;
			case "-" : r = a - b; break;
			case "*" : r = a * b; break;
			case "/" : 
						if(b == 0) {
							throw new Exception("0으로 나눌 수 없습니다.");
						}
						r = a / b;
						break;
			}
			
			result.setText(Double.toString(r));
		} catch(Exception e) {
			JOptionPane.showInternalMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
		}
	}
	
	public void clearForm() {
		this.operand1.setText("");
		this.operand2.setText("");
		this.result.setText("");
	}
	
	private Box createInputForm() {
		Box box = Box.createHorizontalBox();
		box.setMaximumSize(new Dimension(300, 30));
		box.setAlignmentY(Box.CENTER_ALIGNMENT);
		box.add(operand1);
		box.add(operator);
		box.add(operand2);
		box.add(equal);
		box.add(result);
		equal.addActionListener(this);
		return box;
	}
	
	private Box createToolBar() {
		Box box = Box.createHorizontalBox();
		box.add(clear);
		clear.addActionListener(this);
		return box;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		CalculatorFrame app = new CalculatorFrame();
		app.setVisible(true);
	}

}

 

 

 

4. 웹 애플리케이션 아키텍처 특징

 

표기오류 (1.5절이 아닌 1.4절임) 

 

표기오류 (1.5절이 아닌 1.4절임) 

 

 

5. 클라이언트·서버 아키텍처의 진화

 

표기오류 (1.4절이 아니라 1.5절임) 

 

표기오류 (1.4절이 아니라 1.5절임) 

 

 

<예제> Servlet 이용하여 계산기 생성

- 서버 뷰 키기

- 톰캣 8.5 서버 불러오기

- 실행하려는 프로젝트 Add

 

- Dynamic Web Project 생성

- server.xml 파일에서 port번호 바꾸기, Context path를 "/"로 변경하기

- servlet 패키지 생성 -> servlet 파일 생성

- WebContent 폴더에 html 파일 생성

 

CalculatorServlet

package lesson01.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;

/**
 * Servlet implementation class CalculatorServlet
 */
@WebServlet("/calc")
public class CalculatorServlet extends GenericServlet {
	
	@Override
	public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
		String op = req.getParameter("op");
		int v1 = Integer.parseInt(req.getParameter("v1"));
		int v2 = Integer.parseInt(req.getParameter("v2"));
		int result = 0;
		
		res.setContentType("text/html;charset=UTF-8");
		PrintWriter out = res.getWriter();
		
		switch(op) {
		case "+" : result = v1 + v2; break;
		case "-" : result = v1 - v2; break;
		case "*" : result = v1 * v2; break;
		case "/" : 
					if(v2 == 0) {
						out.println("0으로 나눌 수 없습니다.");
						return;
					}
					result = v1 / v2;
					break;
		}
		out.println(v1 + " " + op + " " + v2 + " = " + result);
	}
}

 

calculator.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>계산기</title>
</head>
<body>
	<h1>계산기</h1>
	<form action="calc" method="post">
		<input type="text" name="v1" style="width:50px;">
		<select name="op">
			<option value="+">+</option>
			<option value="-">-</option>
			<option value="*">*</option>
			<option value="/">/</option>
		</select>
		<input type="text" name="v2" style="width:50px;">
		<input type="submit" value="=">
	</form>
</body>
</html>

 

 

 

반응형

댓글