My Trace/T아카데미

[T아카데미] 모바일 서버 프로그래밍 기본 - 3일차

Junhong Kim 2016. 6. 29. 17:55
728x90
반응형

● Java와 MySQL 연동

 

- JDBC의 연동 과정

1) JDBC 드라이버 이름 및 접속할 JDBC URL을 설정한다.

2) JDBC 드라이버를 로드한다.

3) JDBC URL과 계정 정보를 이용해 Connection 객체를 얻는다.

4) JDBC 이용해 데이터베이스를 사용한다.

5) Connection을 종료한다.

 

※ 확인사항

- MySQL에 '데이터베이스'와 '테이블'을 만들어 둬야 함

- mysql-connector-java-5.1.22-bin.jar 파일을 WebContent/WEB-INF/lib 아래에 넣어야 함

- import 할 때는 import java.sql.* 아래에 있는 것을 import 해야 함

 

 

public class DBTest {

 public DBTest() {
  // 1. 대표 클래스 동적 로딩
  
  try {
   Class.forName("com.mysql.jdbc.Driver");
   System.out.println("로딩 성공");
  } catch (ClassNotFoundException e) {
   System.out.println("로딩 오류 : " +e );
   return;
  }
  
  String jdbcURL = "jdbc:mysql://192.168.201.187:3306/db_tacademy";
  String jdbcId = "root";
  String jdbcPw = "1234";
//  String sql = "insert into tbl_account(account, password, address, phoneNo)"
//  + " values("zzz", "zzzz", "울산", "888-0000-0000")";
  
//  String sql = "insert into tbl_account(account, password, address, phoneNo)"
//    + " values(?,?,?,?)";
  
  String sql = "select uid, account, phoneNo from tbl_account where uid > 0";
  
  Connection con = null;
  //Statement stmt = null;
  PreparedStatement stmt = null;
  //CallableStatement stmt = null;
  
  ResultSet rst = null;
  try {
   con = DriverManager.getConnection(jdbcURL, jdbcId, jdbcPw);
   System.out.println("접속 성공");
//   ----------------------------------
//   stmt = con.createStatement();
//   int cnt = stmt.executeUpdate(sql);
   
//   ----------------------------------
//   stmt = con.prepareStatement(sql);
//   stmt.setString(1, "rrr"); // 위치는 1부터 시작
//   stmt.setString(2, "rrrr");
//   stmt.setString(3, "전주");
//   stmt.setString(4, "32323-23-232323");
//   int cnt = stmt.executeUpdate();
   
//   ----------------------------------
   stmt = con.prepareStatement(sql);
   
   rst = stmt.executeQuery();
   while(rst.next()){ // 다음에 있는지 없는지 검사
    int uid = rst.getInt(1); // 컬럼 인덱스로 가져오기
    String account = rst.getString("account"); // 컬럼명으로 가져오기
    String phoneNo = rst.getString(3);
    System.out.println(String.format("번호 %d 이름 %s 전화 %s", uid, account, phoneNo));
   }
//   System.out.println(cnt == 0 ? "fail" : "success");
   
  } catch(SQLException e) {
   System.out.println("e : " +e);
   
  } finally {
   if(rst != null){
    try {
     rst.close();
    } catch (SQLException e) {}
   }
   
   if(stmt != null){
    try {
     stmt.close();
    } catch (SQLException e) {}
   }
   
   if(con != null){
    try {
     con.close();
    } catch (SQLException e) {}
   }
  }
 }

 public static void main(String[] args) {
  new DBTest();
 }

}

 

 

 

※ 웹에서 출력하고 싶으면 위 코드를 복사하여 jsp 파일에 복사한다.

   System.out.println을 out.println으로 바꾸면 client 쪽에서 출력된다.

 

● Database Connection Pool(DBCP)

 : 데이터베이스에 대한 여러 개의 연결을 미리 맺은 후 그것을 한곳에 모아놓고 웹 어플리케이션들이 필요할 때마다 가져가 사용한 후

   반환 할 수 있도록 만들어 놓은 장소.

 

● 웹 Error Page 보여주기

 

 

/* 에러시 보여 줄 페이지 설정*/

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" errorPage="e2.jsp"%>

 


 

/* 에러 페이지 설정 */

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" isErrorPage="true"%>
<%
 response.setStatus(200); // 익스플로에서는 제대로 안보이기 때문에 응답 코드 바꿔서 보내야 함
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
접속자가 많습니다.<br>
오류 <%= exception %> // isErrorPage="true" 를 해줘야 exceoption을 사용할 수 있다
</body>
</html>

 

 

 

/* 에러가 나오면 보여줄 페이지 설정 web.xml */

 

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" metadata-complete="true" version="3.1">
  <display-name>Welcome to Tomcat</display-name>
  <description>
     Welcome to Tomcat
  </description>
   <error-page>
    <exception-type>java.lang.NullPointerException</exception-type>
    <location>/e5.jsp</location>
   </error-page>
   <error-page>
    <error-code>404</error-code> <!-- 404 오류가 나면 e3.jsp 보여준다 -->
    <location>/e3.jsp</location>
   </error-page>
</web-app>

 

 

● 이벤트 리스너(event listener)

 : 웹 컨테이너 안에서 어떤 사건(event)이 일어났을 때 자동으로 호출되는 프로그램.

 

[web.xml] 에 추가

 

  <listener>
   <listener-class>com.tacademy.test.controller.MySessionListener</listener-class>
  </listener>

 

 

 

[MySessionListener.java]

 

@WebListener
public class MySessionListener implements HttpSessionListener {

    /**
     * Default constructor.
     */
    public MySessionListener() {
        // TODO Auto-generated constructor stub
    }

 /**
     * @see HttpSessionListener#sessionCreated(HttpSessionEvent)
     */
    public void sessionCreated(HttpSessionEvent event)  {
         HttpSession session = event.getSession();
         System.out.println("create id : " + session.getId());
    }

 /**
     * @see HttpSessionListener#sessionDestroyed(HttpSessionEvent)
     */
    public void sessionDestroyed(HttpSessionEvent event)  {
        HttpSession session = event.getSession();
        System.out.println("Destroy id : " + session.getId());
    }

 

 

 

● 필터(filter)

 : 여러 웹 자원(servlet/JSP 등) 에 대해 동일한 사전작업이나 사후작업이 필요한 경우

   클라이언트와 웹 컨테이너 사이에 개입하여 이를 처리할 수 있는 방법

 

[web.xml] 에 추가

 

  <filter>
   <filter-name>aFilter</filter-name>
   <filter-class>com.tacademy.test.controller.AFilter</filter-class>
  </filter>
 
  <filter-mapping>
   <filter-name>aFilter</filter-name>
   <url-pattern>/f.jsp</url-pattern>
  </filter-mapping>

 

 

[AFilter.java]

 

 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  // TODO Auto-generated method stub
  // place your code here

  System.out.println("A Filter 사전작업");
  chain.doFilter(request, response);
  
  System.out.println("A Filter 사후작업");
 }

 

 

 

● 래퍼(wrapper)

 : 클라이언트와 웹 자원 사이를 오가는 요청 객체와 응답 객체를 변경할 수 있는 방법. 필터와 함께 사용된다.

 

[AFilter.java]

 

 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  // TODO Auto-generated method stub
  // place your code here
  
  response.setContentType("text/html;charset=utf-8");
  PrintWriter out = response.getWriter();
  
  System.out.println("A Filter 사전작업");
  
  MyWrapperRequest mRequest = new MyWrapperRequest((HttpServletRequest)request);
  chain.doFilter(mRequest, response);
  
  System.out.println("A Filter 사후작업");
  
  out.println("<!-- 이곳은 복사 금지-->");
 }

 

 

[MyWrapperRequest.java]

 

public class MyWrapperRequest extends HttpServletRequestWrapper {

 public MyWrapperRequest(HttpServletRequest request) {
  super(request);
  // TODO Auto-generated constructor stub
 }

 @Override
 public String getParameter(String name) {
  String data = super.getParameter(name);
  if("check".equals(name)) {
   return "Y"; // 악용이 가능함 파라미터가 무엇이든 무시하고 무조건 'Y'
  }
  
  if(data != null) {
   data = data.toUpperCase();
  } else {
   if("tel".equals(name)) {
    data = "000-0000-0000"; // 원하는 데이터가 없으면 해당 데이터로
   }
  }
  return data;
 }
}

 

 

[g.jsp]

<body>
name : <%= request.getParameter("name") %><br>
tel : <%= request.getParameter("tel") %><br>
check : <%= request.getParameter("check") %><br>
</body>

 

 

 

● 배포

 

프로젝트 오른쪽 버튼 → export → WAR file → Destination(위치 설정) → finish

 

WebContent 아래에 있는것만 배포, wara 파일로 됨.

java 파일은 배포 되지 않는다. 즉, build 된것(class)만 배포 됨

 

이제 배포버전 달라고 하면 이 war 파일을 복사해서 실제 톰캣이 설치되어 있는

C:\Program Files\Apache Software Foundation\Tomcat 8.0\webapps 아래에 넣는다

 

되는지 확인하려면

C:\Program Files\Apache Software Foundation\Tomcat 8.0\bin\Tomcat8 실행

 

아까 그 war 파일이 압축해제 됨.

그 다음 브라우저로 가서 해당 서버(ip) 주소를 치고 들어가서 하면된다.

이 컴퓨터를 끄지 않으면 이제 서버운영 구축이 된 것임. 컴퓨터를 끄지말자~ 그러면 내 서버가 돌아가는 중!!

 

 

● 설계 모델

 

1) 모델1

- 화면에 보여지는 부분과 DB 연결 부분이 모두 JSP에서 구현된 모델

- 비교적 간단한 웹 어플리케이션에 적합

- JSP 내에서 동적인 부분은 스크립트릿으로  처리하고, 나머지 부분은 템플릿으로 처리

* 자바빈 (Java Bean) : 자바로 작성되어진 컴포넌트들을 일컫는 말

 

2) 모델2 (MVC 디자인 패턴)

- 화면에 보여지는 부분(view) 과 데이터를 관리하는 부분(model) 그리고 이를 제어 및 분기 (controller) 해주는 부분을 구성된 모델

- 비교적 복잡한 웹 어플리케이션에 적합한 모델

- 모델 2 구조는 RequestDispatcher.forward() 메소드를 통해서 구현될 수 있음

- 쪼개서 하는 것

 

클라이언트에서 요청하는것을 서블릿이 처리, 서블릿은 데이터베이스로부터 읽기/쓰기를 함, controller & model

보여주는건 JSP가 함. JSP는 view 출력을 함

고쳐야하는 것이 있으면 해당하는 것만 고치면 됨.

 

servlet은 웹 응용프로그램임 → web.xml에서 수정해야 함 → 서버를 껏다 다시켜야 함 → 서버 껏다 키는건 심각한 것 임

 

MVC 디자인 패턴으로 하는것이 좋음!!

728x90
반응형