01. Java
02. git
03. Database
04. Jsp [Server] (v)
05. 미니프로젝트 (3W)
06. HTML,CSS
07. JS
08. SpringFramework , SrpingBoot
09. React JS [Front-end]
10. 중간프로젝트 (1M)
11. Linux 명령어
12. AWS 클라우드
13. DevOps - Docker
14. App - Android
15. 최종프로젝트 (1M)
- JSP페이지 내에서 어떤 동작을 하도록 지시하는 태그
종류 기능 forward 현재의 페이지에서 다른 특정 페이지로 전환할 때 사용 include 현재 페이지에 다른 페이지를 삽입할 때 사용 param forward 및 include 태그에 데이터를 전달할 목적으로 사용되는 태그로 name과 value속성으로 이루어져 있음 userBean(자바빈) JAVA언어의 데이터와 기능으로 이루어진 클래스 setProperty Setter getProperty Getter
forward
- 요청받은 요청객체를 위임하는 컴포넌트에 요청 객체값을 동일하게 전달할 수 있음
- 요청을 처리함과 동시에 해당 결과를 바로 보여줘야 하는 경우
<% request.setCharacterEncoding("utf-8"); String id = request.getParameter("id"); String name = request.getParameter("name"); %> # jsp 액션태그 사용시 <jsp:forward page="forward03.jsp" />
sendRedirect
- 요청 받은 요청객체를 위임하는 컴포넌트에 전달하는 것이 아닌, 새로운 요청객체 생성
- 요청을 처리한 다음 새로운 요청으로 작업을 해야할 경우 사용
<% //리퀘스트에 값을 강제로 저장하는 방법 request.setAttribute("date", new Date()); response.sendRedirect("send03.jsp"); %> # id, name, date는 sendRedirect를 통해 보내졌기 떄문에 null값을 받음 <% String id = request.getParameter("id"); String name = request.getParameter("name"); //setAttribute저장했던 값은 getAttribute로 얻음 Date date = (Date)request.getAttribute("date"); %>
JAVA언어의 데이터(변수)와 기능(메서드)로 이루어진 클래스
데이터를 저장하는 변수, 데이터를 읽어오는 메서드(Getter), 데이터를 저장할 때 사용되는 메서드(Setter)로 이루어짐
데이터베이스와의 반복적인 작업을 효율적으로 처리하기 위해 사용
JSP 액션태그로 자바빈 사용하는 방법
<jsp:useBean id="1.객체이름" class = "2.실제 경로" scope="3. 범위 "/>
- id : JSP 페이지에서 자바빈 객체에 접근할 때 사용할 이름
- class : 패키지 이름을 포함한 자바빈 클래스의 완전한 경로 입력
- scope : 자바빈 객체를 저장할 영역 지정
- page : 하나의 JSP페이지를 처리할 때 사용되는 영역
- request : 하나의 요청을 처리할 떄 사용
- session : 하나의 웹 브라우저와 관련된 영역
- application : 하나의 웹 어플리케이션과 관련된 영역
- Setter
<jsp:getProperty property="변수명" name="자바빈id"/>
- Getter
<jsp:setProperty property="변수명" name="자바빈id" value="값"/>
1. DAO(Data Access Object) 클래스
- 데이터베이스에 접속해서 데이터의 추가, 삭제, 수정 등의 작업(CRUD)을 하는 클래스
- 일반적으로 JSP 혹은 Servlet에서 위의 로직을 함께 기술할 수도 있지만, 유지보수 및 코드의 모듈화를 위해 별도의 DAO클래스를 만들어 사용
- 보통 한개의 테이블마다 한개의 DAO클래스 작성(싱글톤 클래스)
- 싱글톤클래스는 객체를 단 하나만 생성하도록 보장하는 디자인 패턴
- 싱글톤클래스는 하나의 인스턴스만 생성되며, 그 인스턴스를 전역적으로 공유
- DAO클래스는 테이블로부터 데이터를 읽어와 자바 객체로 변환하거나 자바 객체의 값을 테이블에 저장
- DAO를 구현하면 테이블의 컬럼과 매핑되는 값을 갖는 자바빈 클래스(VO 클래스)를 항상 작성해야함.
public class DepartmentDAO { /* * DAO는 클래스는 여러개 만들필요 없이, 객체가 한개만 생성되도록 * singleton클래스로 생성 */ //1. 나자신의 객체를 1개 생성한다. private static DepartmentDAO instance = new DepartmentDAO(); //2. 외부에서 생성자를 호출할수 없도록 private막는다 private DepartmentDAO() { try { InitialContext context = new InitialContext(); dataSource = (DataSource)context.lookup("java:comp/env/jdbc/oracle"); } catch (Exception e) { e.printStackTrace(); } } //3. 외부에서 객체를 요구할 때, instance를 반환합니다. public static DepartmentDAO getInstance() { return instance; } //커넥션풀을 사용할 dataSource클래스 private DataSource dataSource; private String url = "jdbc:oracle:thin:@localhost:1521:xe"; private String uid = "HR"; private String upw = "HR"; //메서드로 Database에 접근해서 값을 처리. //부서아이디를 받아서, 부서정보를 반환하는 메서드 public DepartmentDTO getDepartmentInfo(String departmentId) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = "SELECT * FROM DEPARTMENTS WHERE DEPARTMENT_ID = ?"; //반환할 DTO생성 DepartmentDTO dto = new DepartmentDTO(); try { //1.드라이버 클래스 로드 //Class.forName("oracle.jdbc.driver.OracleDriver"); //2.conn //conn = DriverManager.getConnection(url, uid, upw); conn = dataSource.getConnection(); //3.pstmt pstmt = conn.prepareStatement(sql); pstmt.setString(1, departmentId); //3.실행 rs = pstmt.executeQuery(); if(rs.next()) { //1행에 대한 처리 String departmentName = rs.getString("department_name"); int managerId = rs.getInt("manager_id"); int locationId = rs.getInt("location_id"); dto.setDepartmentId( Integer.parseInt(departmentId) ); dto.setDepartmentName(departmentName); dto.setManagerId(managerId); dto.setLocationId(locationId); } } catch (Exception e) { e.printStackTrace(); } finally { try { if(conn != null) conn.close(); if(pstmt != null) pstmt.close(); if(rs != null) rs.close(); } catch (Exception e2) { } } return dto; } }
2. VO(Value Object) 클래스 / DTO(Data Transfer Object) 클래스
- DAO클래스를 이용해 데이터베이스에서 데이터를 관리할 떄 데이터를 일반적인 변수에 할당하여 작업할 수도 있지만, 별도의 VO클래스를 작성하여 데이터베이스와 관련된 변수들의 모음 역할을 함
- VO클래스는 자바빈 클래스로 생성
public class DepartmentDTO { //DTO클래스는 데이터베이스에 전달될, 전달할 데이터를 운반하는 클래스입니다 //멤버변수를 테이블의 컬럼과 동일하게 생성합니다. //1. 은닉클래스로 생성합니다. //2. 생성자는 기본 생성자와, 모든 멤버변수를 전달받는 생성자 private int departmentId; private String departmentName; private int managerId; private int locationId; public DepartmentDTO() { } public DepartmentDTO(int departmentId, String departmentName, int managerId, int locationId) { super(); this.departmentId = departmentId; this.departmentName = departmentName; this.managerId = managerId; this.locationId = locationId; } public int getDepartmentId() { return departmentId; } public void setDepartmentId(int departmentId) { this.departmentId = departmentId; } public String getDepartmentName() { return departmentName; } public void setDepartmentName(String departmentName) { this.departmentName = departmentName; } public int getManagerId() { return managerId; } public void setManagerId(int managerId) { this.managerId = managerId; } public int getLocationId() { return locationId; } public void setLocationId(int locationId) { this.locationId = locationId; } }
<% //vc역할을 하고있음 String departmentId = request.getParameter("departmentId"); //model로 연결 //DAO객체 생성 DepartmentDAO dao = DepartmentDAO.getInstance(); //부서정보 DepartmentDTO dto = dao.getDepartmentInfo(departmentId); //dto를 request에 저장함 request.setAttribute("dto", dto); //dto에 값이 있으면, 부서정보페이지로 이동, 없으면 다시 원본페이지로 이동 if(dto.getDepartmentName() == null) { %> <script> alert("부서정보가 없습니다"); history.back(); //뒤로가기 </script> <% } else { request.getRequestDispatcher("index01_result.jsp").forward(request, response); } %>