ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Servlet-JSP MVC01 (1) - 기본 구조 만들기
    Web/Servlet-JSP 2023. 5. 23. 18:05

    사용자입력 -> 컨트롤러가 받고 -> 모델(DB 등)을 이용해 처리 -> 처리결과 view로 넘김 

    기본적으로 하나의 입력을 처리하기 위해

       ->사용자 입력받을 view -컨트롤러 ,DB모델, 출력 view가 필요 (기본골격) 여기에 살을 붙이는 것

     

    1. DB모델만들기

    데이터 베이스 연동을 위해 기본 구조를 조성하자.

    VO란

    현실에 있는 object의 값들을 표현한 객체이다. 하나의 데이터 구조를 생성한다고 보면 된다.

    기존 member.sql에 테이블에 칼럼과 동일하게 구성하고, 값을 읽거나 변경할 수 있는 메서드와, 

    DB와 연동될 생성자 (int num) , 사용자와 연동될 생성자(int num제외) 해서 두가지 생성자가 있다.

    public class MemberVO {
    	private int num; 
    	private String id;
    	private String pass;
    	private String name; 
    	private int age;
    	private String email;
    	private String phone;
    	//int num포함된건 db용 
    	public MemberVO(int num, String id, String pass, String name, int age, String email, String phone) {
    		super();
    		this.num = num;
    		this.id = id;
    		this.pass = pass;
    		this.name = name;
    		this.age = age;
    		this.email = email;
    		this.phone = phone;
    	}
    	public MemberVO(){}
    	public MemberVO(String id, String pass, String name, int age, String email, String phone) {
    		super();
    		this.id = id;
    		this.pass = pass;
    		this.name = name;
    		this.age = age;
    		this.email = email;
    		this.phone = phone;
    	}
    	@Override
    	public String toString() {
    		return "MemberVO [num=" + num + ", id=" + id + ", pass=" + pass + ", name=" + name + ", age=" + age + ", email="
    				+ email + ", phone=" + phone + "]";
    	}
    	public int getNum() {
    		return num;
    	}
    	public void setNum(int num) {
    		this.num = num;
    	}
    	public String getId() {
    		return id;
    	}
    	public void setId(String id) {
    		this.id = id;
    	}
    	public String getPass() {
    		return pass;
    	}
    	public void setPass(String pass) {
    		this.pass = pass;
    	}
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public int getAge() {
    		return age;
    	}
    	public void setAge(int age) {
    		this.age = age;
    	}
    	public String getEmail() {
    		return email;
    	}
    	public void setEmail(String email) {
    		this.email = email;
    	}
    	public String getPhone() {
    		return phone;
    	}
    	public void setPhone(String phone) {
    		this.phone = phone;
    	}
    	
    	
    }

    DAO(DATA ACCESS OBJECT)

    실제 DB데이터에 접근하기 위한 객체이다. DB와 관련된 sql드라이버 연결, sql실행 등등을 수행한다. 

    import java.sql.*;
    public class MemberDAO {
    	private Connection conn;//DB와 연결 
    	private PreparedStatement ps; //conn의 sql DB에 전송
    	private ResultSet rs; //select 실행결과 저장 //실행결과를 마치 이터레이터처럼
    	                      //한 행씩 받아올 수 있음
    }

     

    2. 사용자 입력을 위한 view 만들기 (본격적인 회원관리 전 연습) 

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
     <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    </head>
    <body>
    
    <form action="calc.do">
    <tabel class="table table-bordered">
    <tr>
    	<td>수1</td>
    	<td><input type="text" name="su1"/></td> 
    </tr>
    <tr>
    	<td>수2</td>
    	<td><input type="text" name="su2"/></td> 
    </tr>
    	<tr>
    	<td colspan="2" align="center">
          <input type ="submit" value="전송" class="btn btn-primary"/>
          <input type ="reset" value="취소"class="btn btn-warning"/>
          </td>
        </tr>
    </tabel>
    </form>
    
    </body>
    </html>

    회원관리와는 상관없지만 간단한 html만들고 흐름 파악해보자

    web에서 클라이언트가 입력하 수 있는 부분은 form이라고 한다. 

    -form안에  input 태그에 name이 사용자의 input이 저장될 파라미터이다. 

    -submit은 html의 butten형식이고, form에 작성한 사용자 데이터를 서버로 보낸다.

    -reset은 form태그 안에 사용자 입력을 모두 초기화한다.

    -form에 action이 submit한 데이터가 이동할 가상경로이다. 

    action을 통해 MAC01/calc.do로 요청을 보낸다.

     

    3. 클라이언트 요청을 처리할 컨트롤러 (su html처리)

    @WebServlet("/calc.do")
    public class CalcController extends HttpServlet {
    
    	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		// 클라리언트에서 넘어오는 폼 파라메터 받기 (su1,su2)
    		int su1 =  Integer.parseInt(request.getParameter("su1"));
    		int su2 = Integer.parseInt(request.getParameter("su2"));
    		
    		int sum =0;
    		for(int i=su1;i<=su2;i++) {
    			sum+=i;
    		}
    		PrintWriter out =response.getWriter();
    		out.println("total ="+sum);
    	}
    
    }

    calc.do요청을 처리할 컨트롤러이다. 요청에 넘어온 값을 다 더해서 클라이언트에게 보낸다.

     

    4. 전개과정 

     

    4.1  submit -> calc.do ->서블릿 동작 

     

    4.2 이때 클라이언트의 요청을 요청정보라고 부르고 패킷단위로 요청됨 

          -> 패킷은 헤더와 바디가 있는데, 헤더에는 클라이언트 정보(ip,port) 바디에는 입력정보(su 1= 10,su2=100등 파라미터정보) 등이 담긴다.

     

    4.3 이러한 패킷이 WAS에거 전달되고 WAS는 요청정보를 서버 내 특정 메모리에 저장하고 request와 response 객체를 만들어 패킷의 내용을 저장한다. 

       -> 생성된 response와 request 한쌍은 클라이언트의 정보로 클라이언트를 식별하여 한명의 클라이언트를 위한 객체이다.

     

    4.4 다시 WAS에 의해 생성된 두 객체는 매핑된 서블릿(컨트롤러)에게 전달된다. 적절한 처리 후 다시 클라이언트에게 응답한다.

     

    *클라이언트의 ip와 port를 식별할 수 있기 때문에 클라이언트-서버를 연결할 수 있는 하나의 io스트림을 연결할 수 있는것이다. request와 response는 이러한 역할을 수행하는 io객체 

    *서버가 특정 포트를 열고 클라이언트의 요청을 기다리는 것 처럼 클라이언트도 서버로 요청을 보내기 위해서 자신의 특정 포트를 개방해야한다. 

     

     

    참고자료: 나프1탄 - 박매일

Designed by Tistory.