JSP 기본개념

jaminyeong·2023년 11월 14일

jsp

목록 보기
3/10

참고 인강

https://www.youtube.com/watch?v=Jc9UTY_lcrY

*파싱필수 :파라미터 같은 경우에는 num을 넣어도 String과 같은 문자열로 받아들이기 때문에
paseInt 필요하다.

*try-catch 구문
: 예외사항 관련한 문구

*session은 return시 object로 받아진다 그래서 toString으로 바꿔줘야한다.

=======================

  1. DB와 HTML JSP로 연결해보기(connection 객체 사용)
    =>연결 전 content.xml//web.xml에 넣을거 넣기
    => 다른velog 글 목록에 있음
public class JDBCConnect {
==================
    public Connection conn;
<connection 객체>
1. connection의 파라미터(data url/ db id/ db pass)
2. connection은 DriveManager의 getConnection메소드
3. 주요메서드 : 
- createStatement() 
: SQL문을 DB에 전달하기위한 statement 객체생성
- preparedStatement(String sql)
: 파라미터가 포함된 SQL문을 DB에 전달 위한 preparedStatement객체 생성
- prepareCall(String sql)
:DB의 Stored Procedure 호출 위한 CallableStatement객체 생성
- close()
:현재 커넥션 객체에 할당된 시스템 리소스를 즉시반환


4. DB연결 관장 Connection 인스턴스는 사용 한 후 닫지 않으면 계속 연결 유지// 즉 커넥션 관리를 위해 커넥션 풀을 사용한다~!!!

ex> Class.forName(드라이버 이름);
	Connection con = DriverManager.getConnection(url,user,password)
==============================


    public Statement stmt;
<클래스 statement>
1. 데이터베이스로의 연결로부터 SQL문 실행해주는 클래스
2. Connection이 먼저 연결되어야한다.
3. 주요메서드 :
    public PreparedStatement pstmt;
===================================
    public ResultSet rs;
<ResultSet 인터페이스>
1. SELECT문을 사용한 쿼리 성공 시 결과물로 ResultSet반환
2. ResultSet 객체는 '커서'Cursor을 갖고 있음(마우스 커서 같은 기분)
3. 메소드 :
first(), last(),beforeFirst():마지막행이전,afterLast():마지막행다음,next()다음행,previous이전행

ex>
while(rs.next()){
}
rs.close()

   
====================================   
   
   <매서드 호출  함수 작성>
   
   public JDBCConnect() {
       try

        {
            //driver로 로드하고 커넥트
            Class.forName("com.mysql.cj.jdbc.Driver");
            =><드라이버 이름 작성>
            
            <connection 파라미터 호출 id/url/pass>
            
            String id = "lmy";
            String url = "jdbc:mysql://localhost:3306/jspdb?useSSL=false&serverTimeZone=Asia/Seoul&characterEncoding=UTF-8";
            String pwd = "1234";
           
         ☆☆☆☆  conn = DriverManager.getConnection(url, id, pwd);


            System.out.println("성공했으면 글자 호출");
        }catch(
        Exception e)

        {
            e.printStackTrace();
            System.out.println("실패시 이글자호출")
        }
    }
    
    ==============첫번째 방식 끝=========
    =============================


<2번째 방식>
        public JDBCConnect(String driver, String url, String id, String pwd){
        try{
            Class.forName(driver); //드라이브 컬렌션 파일 불러오기 로딩...
            conn = DriverManager.getConnection(url, id, pwd);
            System.out.println("JDBC2 connect!!!!!!!!!");
        }catch (Exception ex){
            ex.printStackTrace();
        }
        }

    ========================
    <3번째 방식>
        public JDBCConnect(ServletContext application){
            try{
                String driver = application.getInitParameter("MySQLDriver"); //초기생성자파라미터 삽입
                Class.forName(driver);
                String url=application.getInitParameter("MySQLURL"); //url id password필수
                String id=application.getInitParameter("MySQLId");
                String pwd=application.getInitParameter("MySQLPwd");
                conn=DriverManager.getConnection(url,id,pwd);
                System.out.println("JDBC3 success!!!!!");
            }catch (Exception ex){
                ex.printStackTrace();
            }

        }


        public void close() {
            try {
                if (rs != null)rs.close();
                if (stmt != null)stmt.close();
                if (pstmt != null)pstmt.close();
                if (conn != null)conn.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }

=================================

출처

https://m.blog.naver.com/yl95yl/222138182386

================
<jsp 기본 정의/내장 객체 함수 모음>

https://chlee21.tistory.com/149

<커넥션 풀>

https://zzang9ha.tistory.com/376

=====================

  1. 객체 생성 (DAO/DTO)개념
  • DAO(data access object) :
    데이터를 접근시켜준다/ 즉 접근 로직을 가진다/ 데이터에 직접 접근하고 삽입.삭제.조회

ex>

import java.sql.Connection
import java.sql.PreparedStatement
=><여기서 DB와의 연결을  수도 있다>
=><만약 다른 곳에서 이미 연결을 했다면 extends로 연결가능>
===================
public class BoardDAO extends JDBConnect{

#레코드 전체 개수 가져오기 DAO : ACCESS
#ArrayList 사용
# ex> List<리스트명> list = new ArrayList<리스트명>();
#선언이유 :
>https://bibi6666667.tistory.com/236


}
  • DTO : data transfer object:
    데이터 보내주는 역활이다. 보통 생성자/get/set으로 이루어져있다. 이렇게 해야
    데이터를 연결해서 보내줄 수 있다
    ex>
public class UserDTO{
	String user ID;
    
    public UserDTO(){}
    
    public userDTO(String user ID,....){
    	this.user ID = user id;
    }
    ...get/set 생성자도 있다
    }
    
    
  1. 커넥션풀 DBCP : database connection pool
  • 옵션
    1) initialSize : 최초 커넥션을 맺을 때 connection Pool에 생성되는 커넥션의 갯수
    2) maxActive/maxTotal : 동시에 사용 할 수 있는 최대 커넥션의 갯수
    3) maxIdle : connection Pool에 반납할 때 최대로 유지 될 수 있는 커넥션의 갯수
    4) midIdel : 최소한으로 유지할 커넥션의 갯수
    5) maxWait/maxWaitMillis : Pool이 예외를 throw하기 전 연결이 반환될때까지 대기하는 최대시간 or 무한 대기

https://commons.apache.org/proper/commons-dbcp/configuration.html

  1. include 지시어
    : 외부 파일을 현재 JSP 페이지에 포함시킴
    //같은 형식을 여러번 만들지 않기위한 페이지의 함수화 같은거라고 생각하면 쉽겠다

    https://myvelop.tistory.com/10

profile
주니어 개발자 잼미뇽 공부용 기록장

0개의 댓글