JSP 기초 - 태그, 싱글톤 패턴

별의개발자커비·2023년 4월 15일
0

JSP

목록 보기
3/31
post-thumbnail

1. 태그 알아보기

script 태그

선언문(declaration)

  • %!
  • 변수나 함수를 선언할 때
    		<%! int count = 3;  %>
    이걸 쓰면 자바의 문법을 쓸 수 있음
	<%! 
		int count = 3; 
		String makeItLower(String data){
			return data.toLowerCase();
		}
	%>

위는 멤버 변수와 멤버 함수로 내부에서 인식
= 얘는 클래스의 변수로 들어가게 되고

스크립틀릿(scriptlet)

  • 자바코드를 사용할 수 있게 하는 태그
	<% 
		for(int i = 0; i<count; i++){		
			out.println("java server page "+ i + "<br>");
		}
	%>
  • 얘는 함수 안으로 들어가게 된다.

표현문(expression)

  • %= : 출력한다
  • 변수나 함수의 결과를 문자열 형태로 출력
	<%=makeItLower("Hello world")%>


https://kyun2.tistory.com/47
https://codevang.tistory.com/197
*ln 안먹으니까 br

구현된 거 보기?

  • scripttag_jsp.java로 검색하면 볼 수 있음
  • 우리가 만든 scripttag 가 서블릿으로 변환된 것

새로고침해도 올라가게 하려면

%!로 전역변수로 만들어야함

<%! int count = 0 ; %>
Page Count is : 
<%
	count++;
	out.print(count);
%>

timer

	오늘은 :
	<%
	Date date = new Date();
	SimpleDateFormat formatter = new SimpleDateFormat("yyyy년 MM월 dd일 HH시 mm분 ss초");
	String formmattedDate = formatter.format(date);
	%>
	<%= formmattedDate %>

이클립스 jsp에서 js 코드 자동입력 안되니까


디렉티브 태그 '@'

  • jsp 페이지를 어떻게 처리할 것인지를 설정하는 태그
  • jsp 페이지가 서블릿 프로그램에서 서블릿 클래스로 변환할 때 jsp 페이지와 관련된 정보를 jsp 컨테이너에 지시하는 메세지

page 디렉티브 태그 @page

include 디렉티브 태그 @include

	<h1>현재 날짜를 표시하는 화면</h1>
	<h3>이 페이지에는 날짜 관련 코드가 없습니다.</h3>
	<%@ include file="./timer_js.jsp"  %>

taglib 디렉티브 태그 @taglib


액션 태그 ':'

  • 서버나 클라이언트에게 어떤 행동을 하도록 명령하는 태그
  • jsp 페이지에서 페이지와 페이지 사이를 제어
  • 다른 페이지의 실행 결과 내용을 현재 페이지에 포함

forward 액션 태그

  • 현재 jsp에서 다른 jsp로 이동하는 태그
  • 브라우저에서 요청이 오면 서버에서 페이지 정보를 읽는데.. 거기에 forward가 있으면
  • 해당 페이지를 다시 읽어서 클라이언트에 응답 즉, 서버 내부에서 페이지 이동
	<h2>forward 액션 태그</h2>
	<jsp:forward page="./timer_js.jsp"></jsp:forward>
	<p>-----------------------------------------------------
	<!-- forward를 만났기 때문에 p가 표시되지 않음: 
	클라이언트가 서버한테 foward.jsp줘 했지만
	페이지를 전환하는 forward 명령어가 있어서 timer를 주는 것
	클라이언트는 'forward 액션 태그'라는 파일을 호출했지만
	서버가 알아서 timer를 주는 것
	 -->

include 액션 태그

  • 결과를 가져와서 내장시킨다. 주로 동적페이지에 사용
	<h3>이 파일은 first.jsp입니다.</h3>
	<jsp:include page="./second.jsp"></jsp:include>
	<p>java Server Page</p>

param 액션 태그

  • 현재 페이지에서 다른 페이지에 정보를 전달하는 태그
  • 전달할 때는 forward나 include 태그 내부에 사용
  • 예제1
	<h3>이 파일은 first.jsp입니다.</h3>
	<jsp:include page="./second.jsp">
		<jsp:param value="hong gil dong" name="myname"/>
	</jsp:include>
	<p>java Server Page</p>
	<h1>이름은: <%=request.getParameter("myname")  %> </h1>
	<h3>이 파일은 second.jsp입니다.</h3>


  • 예제2
	<p>아이디 : <%=request.getParameter("id")  %>  </p>
	<p>이름 : <%=URLDecoder.decode(request.getParameter("name"))%>  </p>
	<h3>param 액션 태그</h3>
	<jsp:forward page="./param01_data.jsp">
		<jsp:param value="admin" name="id"/>
		<jsp:param value='<%=URLEncoder.encode("관리자") %>' name="name"/>
	</jsp:forward>

@@여기부터 day2@@

자바빈스 액션 태그

  • 외부에서 만든 자바 파일을 객체화해서 jsp에서 사용할 때
  • 즉... jsp 컨테이너가 미리 자바빈스들을 등록하고... 사용자는 따로 객체 생성없이 사용
  • 중요한 비즈니스 로직을 따로 분리해서 개발

만드는 방법

  • java.io.Serializable 인터페이스를 구현

  • 기본생성자가 존재해야 함

  • 모든 변수는 private

  • 변수에 대한 getter/setter가 존재

  • 시스템에서 제공하는 클래스를 빈으로 등록 사용 가능

@@ 근데 singletonedemo에서 왜 객체 생성없이 getinstance로 사용해야하는 거지?

예제1

	<jsp:useBean id="d" class="java.util.Date"></jsp:useBean>
	<h1>오늘의 날짜? </h1>
	<%=d %>
    
<%-- 위와 같은 의미
<% Date d = new Date(); %>
--%>

예제2

package dao;
public class Calculator {
	public int myMethod(int n) {
		return n*n*n;
	}
}
	<jsp:useBean id="ca" class="dao.Calculator"></jsp:useBean>
	<h1> 5의 3제곱? </h1>
	<%=ca.myMethod(5) %>

예제3

// usebean4

	<jsp:useBean id="person" class="dao.Person" scope="request"></jsp:useBean>
	<h4> 아이디: <%= person.getId() %> </h4>
	<h4> 이름: <%= person.getName() %>   </h4>
	<% 
	person.setId(200);
	person.setName("길복순");
	%>
	--------------
	
	<h3>include usebean3 데려온 부분 </h3>
	<jsp:include page="usebean3.jsp"></jsp:include>
	<p> * (scope="page") -> 100, 호랑이 --- 다른 jsp 페이지에서는 안바뀜 
	<p> * scope="request" -> 200, 길복순 --- 다른 jsp 페이지에서도 바뀜 
	<h4>단 (jsp:useBean id="person" ) 그 jsp 파일에서도 id가 같게 설정된 경우만</h4>
	<h4>그리고 두 jsp 파일 다 scope="request" 되어있어야 </h4>
	
	--------------
	
	<h4> set 후 아이디: <%= person.getId() %> </h4>
	<h4> set 후 이름: <%= person.getName() %>   </h4>
// usebean3

<jsp:useBean id="person" class="dao.Person" scope="request"></jsp:useBean>
<h4> 아이디: <%= person.getId() %> </h4>
<h4> 이름: <%= person.getName() %></h4>

@@ 여기까지 정리

예제4

// 

package dao;
import java.io.Serializable;

public class Product implements Serializable{
	private static final long serialVersionUID = 1L;
	
	private String productId;		// 상품아이디
	private String pname; 			// 상품명
	private Integer unitPrice;		// 상품 가격
	private String description;		// 상품 설명
	private String manufacturer;	// 제조사
	private String category;		// 분류
	private long unitInStock;		// 재고수
	private String condition;		// 신품, 중고품, 재생품
	
	public Product() {};
	public Product(String productId, String pname, Integer unitPrice, String description, String manufacturer,
			String category, long unitInStock, String condition) {
		this.productId = productId;
		this.pname = pname;
		this.unitPrice = unitPrice;
		this.description = description;
		this.manufacturer = manufacturer;
		this.category = category;
		this.unitInStock = unitInStock;
		this.condition = condition;
	}
	public String getProductId() {
		return productId;
	}
	public void setProductId(String productId) {
		this.productId = productId;
	}
	public String getPname() {
		return pname;
	}
	public void setPname(String pname) {
		this.pname = pname;
	}
	public Integer getUnitPrice() {
		return unitPrice;
	}
	public void setUnitPrice(Integer 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 getUnitInStock() {
		return unitInStock;
	}
	public void setUnitInStock(long unitInStock) {
		this.unitInStock = unitInStock;
	}
	public String getCondition() {
		return condition;
	}
	public void setCondition(String condition) {
		this.condition = condition;
	}
	public static long getSerialversionuid() {
		return serialVersionUID;
	}
	
	
}

싱글톤 패턴(Singleton Pattern)

// 5
public class SingleToneDemo {

	public static void main(String[] args) {
		SingleTone s1 = SingleTone.getInstance();
		s1.setId(100);
		System.out.println("s1:"+ s1.getId());
		
		SingleTone s2 = SingleTone.getInstance();
		s2.setId(200);
		System.out.printf("s1 id = %d s2 id = %d\n", s1.getId(), s2.getId());
		
		SingleTone s3 = SingleTone.getInstance();
		System.out.println("s3:"+ s3.getId());
		
		SingleTone s4 = new SingleTone();
		s4.setId(300);
		System.out.println("s4:"+ s4.getId());
		
		SingleTone s5 = new SingleTone();
		s4.setId(400);
		System.out.printf("s4 id = %d s5 id = %d\n", s4.getId(), s5.getId());
	}

실행결과
s1:100
s1 id = 200 s2 id = 200
s3:200ㅇ
s4:300
s4 id = 400 s5 id = 0

	1) SingleTone s1 = SingleTone.getInstance();
    
	2) s1 = new singletone();
  • 위 두개의 차이점

    • 1) s4를 바꾸면 s5도 바뀜

    • 2) s2를 바꿔도 s1은 안바뀜

    • (?) bean은 동일 객체다
      // scope = request이면 같은 범위이다.

      		//  자바빈을 만들 때는 그냥 클래스명 만으로 할 ㅜㅅ 있는데
      		// 기존 걸 그대로 쓰는 것이 ??@@

https://sky17777.tistory.com/93
https://code4.tistory.com/category/JSP

중간에 자바 만들 때는

여기에 other - class로

  • 앗 패키지 만들고: 타이핑으로 할 수도 있음

    	package dao;


https://getbootstrap.kr/docs/5.2/components/popovers/#%EC%98%88%EC%8B%9C-container-%EC%98%B5%EC%85%98-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0

https://velog.io/@nawhes_joo/JSP-%EA%B5%90%EC%9C%A1-day.1

profile
비전공자 독학러. 일단 쌔린다. 개발 공부👊

0개의 댓글