web 기초/jsp 액션태그 - 자바 빈스

Algo rhythm·2022년 6월 13일
0

web 기초

목록 보기
14/15
post-thumbnail

액션 태그

액션 태그의 기능

  • 서버나 클라이언트에게 어떤 행동을 하도록 명령하는 태그
  • JSP 페이지에서 페이지와 페이지 사이 제어
  • 다른 페이지의 실행 결과 내용을 현재 페이지에 포함
  • 자바 빈즈(JavaBeans) 등의 다양한 기능 제공
  • XML 형식 <jsp: … /> 사용

액션 태그의 종류

액션 태그 예시(자바 빈즈 중심)

<%@page import="java.text.SimpleDateFormat"%>
<%@ page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Insert title here</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</head>

<body>
  <jsp:include page="menu.jsp"></jsp:include>

  <div class="p-5 bg-primary text-white">
    <div class="container">
      <h1 class="display-3">
        Welcome to Web Shopping Mall
      </h1>
    </div>
  </div>

  <div class="container">
    <div class="text-center">
      <h3>Welcome to Web Market!</h3>
      <%
      Date now = new Date();
      SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss a");
      %>
      현재 접속 시각: <%= format.format(now) %>
    </div>
  </div>

  <jsp:include page="footer.jsp"></jsp:include>

</body>
</html>

<jsp:include page="footer.jsp"></jsp:include>

  • footer.jsp 파일을 불로오고 실행

footer.jsp 파일

<footer class="container">
  <p>&copy; WebMarket</p>
</footer>

<jsp:include page="menu.jsp"></jsp:include>

  • 외부에서 jsp 파일을 불러오고 동작하도록 함

<nav class="navbar navbar-expand navbar-dark bg-dark">
  <div class="container">
    <div class="navbar-header">
      <a href="./welcome.jsp" class="navbar-brand">Home</a>
      <a href="./products.jsp" class="navbar-brand">Products</a>
    </div>
  </div>
</nav>
  • div 웹 페이지 화면의 일부를 구성하는 곳

products.jsp

<%@page import="com.survivalcoding.data.ProductRepository"%>
<%@page import="com.survivalcoding.domain.model.Product"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<jsp:useBean id="repository"
	class="com.survivalcoding.data.ProductRepository" scope="session"></jsp:useBean>
<html>

<head>
<meta charset="UTF-8">
<title>상품 목록</title>
<link
	href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
	rel="stylesheet">
<script	src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</head>

<body>
	<jsp:include page="menu.jsp"></jsp:include>

	<div class="p-5 bg-primary text-white">
		<div class="container">
			<h1 class="display-3">상품 목록</h1>
		</div>
	</div>

	<div class="container">
		<div class="row" align="center">
            <%
            List<Product> products = repository.getAllProducts();
            for (int i = 0; i < products.size(); i++) {
                Product product = products.get(i);
            %>
				<div class="col-md-4">
					<h3><%= product.getName() %></h3>
					<p><%= product.getDescription() %></p>
					<p><%= product.getUnitPrice() %>원</p>
					<p><a href="product.jsp?id=<%= product.getId() %>" class="btn btn-secondary">상세 정보 &raquo;</a></p>
				</div>
			<%
            }
			%>
		</div>
	</div>

	<jsp:include page="footer.jsp"></jsp:include>
</body>

</html>



핵심 코드 해설

자바빈즈

<jsp:useBean id="repository"
	class="com.survivalcoding.data.ProductRepository" scope="session"></jsp:useBean>
  • 동적 콘텐츠 개발을 위해 자바 코드를 사용하여 자바 클래스로 로직을 작성하는 방법
  • JSP 페이지에서 화면을 표현하기 위한 계산식이나 자료의 처리를 담당하는 자바코드를 따로 분리하여 작성하는 것
  • JSP 페이지가 HTML과 같이 쉽고 간단한 코드만으로 구성

자바빈즈 규칙

  • 인수가 없는 기본 생성자 필수
  • 모든 멤버 변수인 프로퍼티는 private 접근 지정자로 설정
  • 모든 멤버 변수인 프로퍼티는 getter/setter( ) 메소드가 존재
    캡슐화 : https://velog.io/@watervottle/%EC%9E%90%EB%B0%94%EC%BA%A1%EC%8A%90%ED%99%94
  • getter( ) 메소드는 멤버 변수에 저장된 값을 가져올 수 있는 메소드이고, setter( ) 메소드는 멤버 변수에 값을 저 장할 수 있는 메소드임

자비빈즈 예시

package com.survivalcoding.data;

import java.util.ArrayList;
import java.util.List;
import com.survivalcoding.domain.model.Product;

// 다형성
public class ProductRepository {
    private List<Product> products = new ArrayList<>();

    public ProductRepository() {
        Product phone = new Product("P1234", "iPhone 6s", 800000);
        phone.setDescription("4.7-inch, 1334x750 Retina HD display");
        phone.setCategory("Smart Phone");
        phone.setManufacturer("Apple");
        phone.setUnitsInStock(1000);
        phone.setCondition("New");

        Product notebook = new Product("P1235", "LG PC 그램", 1500000);
        notebook.setDescription("!4.7-inch, 1334x750 Retina HD display");
        notebook.setCategory("!Smart Phone");
        notebook.setManufacturer("!Apple");
        notebook.setUnitsInStock(1000);
        notebook.setCondition("Refubished");

        Product tablet = new Product("P1236", "Galaxy Tab S", 900000);
        tablet.setDescription("?4.7-inch, 1334x750 Retina HD display");
        tablet.setCategory("?Smart Phone");
        tablet.setManufacturer("?Apple");
        tablet.setUnitsInStock(1000);
        tablet.setCondition("Old");

        products.add(phone);
        products.add(notebook);
        products.add(tablet);
    }

    public List<Product> getAllProducts() {
        return products;
    }

}

자바 빈즈로 불러오려는 자바 파일

package com.survivalcoding.domain.model;

import java.util.Objects;

// 1. 무지성 private 멤버 변수
// 2. 필요하면 생성자 추가
// 3. 무지성 getter / setter 읽기 전용, 쓰기 전용
// 4. 무지성 toString()
// 5. 필요하면 equals / hashCode 재정의 (오버라이드)
public class Product {
    private String id;
    private String name;
    private int unitPrice;
    private String description;
    private String manufacturer;
    private String category;
    private long unitsInStock;
    private String condition;

    public Product(String id, String name, int unitPrice) {
        this.id = id;
        this.name = name;
        this.unitPrice = unitPrice;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getUnitPrice() {
        return unitPrice;
    }

    public void setUnitPrice(int unitPrice) {
        this.unitPrice = unitPrice;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getManufacturer() {
        return manufacturer;
    }

    public void setManufacturer(String manufacturer) {
        this.manufacturer = manufacturer;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public long getUnitsInStock() {
        return unitsInStock;
    }

    public void setUnitsInStock(long unitsInStock) {
        this.unitsInStock = unitsInStock;
    }

    public String getCondition() {
        return condition;
    }

    public void setCondition(String condition) {
        this.condition = condition;
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Product other = (Product) obj;
        return Objects.equals(id, other.id);
    }

    @Override
    public String toString() {
        return "Product [id=" + id + ", name=" + name + ", unitPrice=" + unitPrice
                + ", description=" + description + ", manufacturer=" + manufacturer + ", category="
                + category + ", unitsInStock=" + unitsInStock + ", condition=" + condition + "]";
    }
}

리스트 클래스의 인스턴스 생성 부분 이해하기

List<Product> products = repository.getAllProducts();

Product 클래스를 List의 데이터 타입으로 하여 products라는 인스턴스를 생성
더 자세한 설명 -> https://velog.io/@watervottle/%EC%9E%90%EB%B0%94list

profile
배운 건 써 먹자

0개의 댓글