250x250
Notice
Recent Posts
Recent Comments
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Tags more
Archives
Today
Total
관리 메뉴

개린이 개발노트

국비지원 JAVA(자바) 프로그래밍 (jsp,param,내장객체,번들,Bundle,fmt) 본문

국비지원(국비교육) 웹 개발자 과정

국비지원 JAVA(자바) 프로그래밍 (jsp,param,내장객체,번들,Bundle,fmt)

개린이9999 2023. 1. 26. 09:43
728x90

폼에서 숫자 두개 입력해서 전송 누르면

결과부분에서 두 수의 합이 출력

예전방식+ EL 방식

 

<%@ 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>
</head>
<body>
	<form method="get" action="add.jsp">
		숫자입력 :<input type="text" name="num1"><br>
		숫자입력 : <input type="text" name="num2"><br>
		<input type="submit" value="계산">
		
	</form>

</body>
</html>
<%@ 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>
</head>
<body>
	<%
		int n1 = Integer.parseInt(request.getParameter("num1") );
		int n2 = Integer.parseInt(request.getParameter("num2") );
	%>
	<%=n1 %>+ <%=n2 %>= <%=n1+n2%>	<br>
	
	EL 방식<br>
	
	${param.num1}+${param.num2}=${param.num1+ param.num2}

</body>
</html>

표현언어(EL)로 내장객체

page

request

session

application

<%@ 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>
</head>
<body>

<%
	pageContext.setAttribute("name", "page");
	request.setAttribute("name", "request");
	session.setAttribute("name", "session");
	application.setAttribute("name", "applicaton");
%>
	페이지: <%=pageContext.getAttribute("name") %><br>
	요청: <%=request.getAttribute("name") %><br> 
	세션: <%=session.getAttribute("name") %><br>
	어플리케이션: <%=application.getAttribute("name") %><br>

</body>
</html>

 

표현언어(EL)로

EL방식<br>
	페이지: ${pageScope.name}<br>
	요청: ${requestScope.name}<br>
	세션:${sessionScope.name}<br>
	어플리케이션:${applicationScope.name} <br>

* 명시안하고 ${name} 출력하면 출력은 되나 유효범위 중 가종 좁은 것으로 출력

위 같은 경우는 page 가 출력된다. ( page<request<session<application 순)



자바 빈

<%@ 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>
</head>
<body>
	<h1>정보 입력</h1>
	<form method="post" action="info.jsp">
		아이디:<input type="text" name="id"><br>	
		비밀번호:<input type="password" name="pw"><br>	
		이름:<input type="text" name="name"><br>	
		나이:<input type="text" name="age"><br>	
		<input type ="submit" value="전송">
	</form>

</body>
</html>
package com.study.javabeans;

public class StudyBean {
	
	private String id; 
	private String pw; 
	private String name; 
	private int age;
	
	
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getPw() {
		return pw;
	}
	public void setPw(String pw) {
		this.pw = pw;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	} 

	
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%request.setCharacterEncoding("utf-8");%>
<jsp:useBean id="study" class="com.study.javabeans.StudyBean"/>
<jsp:setProperty name="study" property="*"/>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>

<body>
	<h1>정보 출력</h1>
	아이디: <jsp:getProperty name="study" property="id"/> <br>
	비밀번호: <jsp:getProperty name="study" property="pw"/> <br>
	이름: <jsp:getProperty name="study" property="name"/> <br>
	나이: <jsp:getProperty name="study" property="age"/> <br>
	
	<h1>EL로 정보출력</h1>
	아이디: ${study.id} <br>
	비밀번호: ${study.pw} <br>
	이름: ${study.name} <br>
	나이: ${study.age} <br>
</body>
</html>



JSTL 

JSP Standard Tag Library 라이브러리 

The Jakarta Site - The Apache Jakarta™ Project -- Java Related Products

 

The Jakarta Site - The Apache Jakarta™ Project -- Java Related Products

Founded in 1999, the Jakarta Project housed a diverse set of popular open source Java solutions. In 2005, as a part of creating a flatter Apache Software Foundation, Jakarta subprojects began to become full top-level Apache projects. This process has conti

jakarta.apache.org

Apache Taglibs - Apache Standard Taglib: JSP[tm] Standard Tag Library (JSTL) implementations

 

Apache Taglibs - Apache Standard Taglib: JSP[tm] Standard Tag Library (JSTL) implementations

<!-- Copyright 1999-2011 The Apache Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/

tomcat.apache.org

JSTL 

core 태그

<c:set> 태그 : 변수에 값을 설정

<c:set var ="변수명" value="값" [scope="유효범위"]/>

 

<c:set var ="변수명" value="값" [scope="유효범위"]>

</c:set>

 

유효범위 종류는

page

request

session

application

TestBean

형식

<c:set var="객체이름"  value= "<%new패키지명.클래스명()%>"/>

 

<jsp:useBean id="test" class="com.study.javabeans.TestBean"/>

<c:set var="test" value="<%= new.com.study.javabeans.TestBean()%>"/>

 

형식

<c:set target="객체이름" property="프로퍼티이름" value="값"/>

<jsp:setProperty name="test" property="id" value="qwer"/>

<c:set target="${test}" property="id" value="qwer"/>

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"  %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

	<c:set var="msg" value="hi jstl"/>
	${msg}<br>
	
	<c:set var="age">
	20
	</c:set>
	${age}<br> 
	
	<c:set var="test" value="<%= new com.study.javabeans.TestBean() %>"/>
	
	<c:set target="${test }" property="id" value="qwer"/>
	<c:set target="${test }" property="name" value="고길동"/>
	
	아이디: ${test.id}<br>
	이름: ${test.name}<br>
	

</body>
</html>

 

<c:remove> 변수 제거

<c:remove var="삭제할 변수명" [scope="유효범위"]/>

지울 때 scope가 일치하지 않으면 다른걸로 인식해서 안지워짐! 

 

<c:remove var="msg"/>
	삭제 후 msg : ${msg} <br>



<c:if> 자바 if랑 같은 거 인데 else가 없음

형식

<c:if test ="조건식">

조건식이 참일 때 코드

</c:if>

 

 

엘스를 만들고 싶으면 

<c:choose> else부분까지 처리가능

<c:choose> 

 <c:when test="조건식1">

  조건식1 참코드

</c:when>

 <c:when test="조건식2">

  조건식2 참코드

</c:when>

<c:otherwise>

 모두 거짓코드

<c:otherwise>

</c:choose>

 

예제

<%@ 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>
</head>
<body>

	<form method="get" action="ifResult.jsp">
		<h1>if 연습용</h1>
			<select name="colors">
				<option value="빨강">빨강</option>
				<option value="파랑">파랑</option>
				<option value="노랑">노랑</option>
			</select>
		
		<h1>choose 연습용</h1>
			<select name="grade">
				<option value="1">1학년</option>
				<option value="2">2학년</option>
				<option value="3">3학년</option>
			</select>
			
			<input type="submit" value="전송">
	</form>

</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
 
 	<h1>if 결과</h1>
		<c:if test="${param.colors =='빨강' }">
			빨강을 선택하셨습니다.<br>
		</c:if>
		<c:if test="${param.colors =='파랑' }">
			파랑을 선택하셨습니다.<br>
		</c:if>
		<c:if test="${param.colors =='노랑' }">
			노랑을 선택하셨습니다.<br>
		</c:if>
	
 	<h1>choose 결과</h1>
		<c:choose>
			<c:when test="${param.grade==1 }">
				1학년입니다.
			</c:when>
		
			<c:when test="${param.grade==2 }">
				2학년입니다.
			</c:when>
			<c:otherwise>
				3학년입니다.
			</c:otherwise>
		</c:choose>	
		
</body>
</html>

만들어보기

<%@ 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>
</head>
<body>
   <form method="get" action="ageInfo.jsp">
      나이 : <input type="text" name="age">
      <input type="submit" value="전송">
   </form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
 
 		
 	<h1>결과</h1>
		<c:choose>
			<c:when test="${param.age>=20 }">
				성인입니다.
			</c:when>
		
			<c:when test="${param.age>=17 }">
				고등학생입니다.
			</c:when>
			<c:when test="${param.age>=14 }">
				중학생입니다.
			</c:when>
			<c:when test="${param.age>=8 }">
				초등학생입니다.
			</c:when>
			<c:otherwise>
				유치원생입니다.
			</c:otherwise>
		</c:choose>	
		
</body>
</html>

<c:forEach> 반복문

형식

-> 

<c:forEach var="임시변수" items = "배열">

 반복할 코드

</c:forEach>

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
 
<%
	String[] langList ={"JAVA","HTML","CSS","JSP"};
	pageContext.setAttribute("langList", langList);	
	
%> 
  <c:forEach var="list" items="${langList}">
  	${list}<br>
  </c:forEach>

</body>
</html>

varStatus 속성

-> 반복횟수, 인덱스 등을 알려줌

   <c:forEach var="list" items="${langList}" varStatus="status">
  	값출력: ${list}<br>
  	반복횟수 출력: ${status.count}<br>
  	인덱스 출력:  ${status.index}<br>
 	<hr>
  </c:forEach>

	first? : ${status.first }<br>
  	last? : ${status.last }<br>

first->첫번째 반복이면 true 아니면 false

last-> 마지막 반복이면 true 아니면 false

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
   
   <c:forEach var="cnt" begin="1" end="10" step="2">
   	${cnt}<br>
   </c:forEach>

</body>
</html>

 

 

 

 

<c:redirect> response.sendRedirect("이동할페이지")랑 같은거

 

<c:redirect url="이동할페이지/>

 

 

<c:out>출력

${} 이게 더 편함

 

<c:out value="값" [default="기본값"]/>

 

<c:out value="hi jstl"/>

 

<c:catch> try~catch랑 같음

 

<c:catch var="변수이름">

 예외 발생이 될 수 도 있는 코드

</c:catch>

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
   
	<c:set var="name" value="고길동"/>
	이름(EL) : ${name} <br>
	이름(out) : <c:out value="${name}"/><br>
	
	<h1>name삭제</h1>
	<c:remove var="name"/>
	이름(EL) : ${name} <br>
	이름(out) : <c:out value="${name}" default="이름없음"/><br>
	
	
</body>
</html>

<h1>catch 구경</h1>
	<c:catch var="errmsg">
	에러 발생전 <br>
	<%=10/5 %><br>
	에러 발생 후<br>
	</c:catch>
	
	${errmsg}<br>
	<c:out value="${errmsg}" default="정상작동"/>

 



fmt태그

<fmt:formatNumber> 

 

<fmt:formatNumber value="값(숫자)" 

              [type="number|currency|percent"]

              [pattern="패턴"]#,##0

              [currencySymbol="화폐단위"]

              [groupingUsed="true|false"]// 천단위 구분기호 true(기본값)

              [var="변수명"]      

              [scope="유효범위"]/>

 

실습예제

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
   
   	<fmt:formatNumber value="123456.78"/><br>
   	<fmt:formatNumber value="123456.78" groupingUsed="false"/><br>
   	<fmt:formatNumber value="0.5" type="percent"/><br>
   	<fmt:formatNumber value="123456" type="currency"/><br>
   	<fmt:formatNumber value="123456" type="currency" currencySymbol="$"/><br>
   	<fmt:formatNumber value="123456.789" pattern="#,##0.0"/><br>
   	<fmt:formatNumber value="123456.789" pattern="#,##0.00" var="num"/><br>
   	${num}
	
</body>
</html>

fmt태그

<fmt:formatdate>

<fmt:formatDate value="날짜/시간"

 [type="time|date|both|"] // 시간 날짜 둘다

 [dateStyle="defalut|short|medium|long|full"]

 [timeStyle="defalut|short|medium|long|full"]

 [pattern="패턴"]

 [timeZone="타임존"]

 [var="변수명"]      

 [scope="유효범위"]/>

 

<%@page import="java.util.Date"%>
<%@page import="javax.xml.crypto.Data"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
   	
   	<c:set var="now" value="<%= new Date() %>"/>
   	now: ${now}<br>
   	date: <fmt:formatDate value="${now}" type="date"/><br>
   	date: <fmt:formatDate value="${now}" type="time"/><br>
   	date: <fmt:formatDate value="${now}" type="both"/><br>
	<br>
	default : <fmt:formatDate value="${now}" type="both" dateStyle="default" timeStyle="default"/><br>
	short : <fmt:formatDate value="${now}" type="both" dateStyle="short" timeStyle="short"/><br>
	medium : <fmt:formatDate value="${now}" type="both" dateStyle="medium" timeStyle="medium"/><br>
	long : <fmt:formatDate value="${now}" type="both" dateStyle="long" timeStyle="long"/><br>
	full : <fmt:formatDate value="${now}" type="both" dateStyle="full" timeStyle="full"/><br>
	<br>
	pattern: <fmt:formatDate value="${now}" type="both" pattern="yyyy년MM월dd일 hh시 mm분 ss초"/>
   	
</body>
</html>

 

<fmt:setTimeZone>

형식

<fmt:setTimeZone value="timezone"

[var="변수명"]

[scope="유효범위"]/>

 

 

<fmt:timeZone value="timezone">

 

</fmt:timeZone>

Time Zone Map (timeanddate.com)

 

Time Zone Map

Current local times around the world, including (DST) changes.

www.timeanddate.com

 	<h1>timezone</h1>
   	한국: <fmt:formatDate value="${now}" type="both"/><br>
   	
   		<fmt:timeZone value="GMT">
   			런던: <fmt:formatDate value="${now}" type="both"/><br>
   		</fmt:timeZone>
   	
   		<fmt:timeZone value="CET">
   			파리: <fmt:formatDate value="${now}" type="both"/><br>
   		</fmt:timeZone>

지역으로 시간지정

 

<fmt:setLocale>

 

<fmt:setLocale value="언어코드_국가코드/>

  	<h1>로케일 설정</h1>
   	톰캣 서버 로케일 : <%=response.getLocale() %><br>
   	통화: <fmt:formatNumber value="10000" type="currency"/> <br>
   	날짜: <fmt:formatDate value="${now}"/> <br>
   	
   	<br>
   	<fmt:setLocale value="ja_jp"/>
   	변경후 : <%=response.getLocale() %><br>
   	통화: <fmt:formatNumber value="10000" type="currency"/> <br>
   	날짜: <fmt:formatDate value="${now}"/> <br>
   	<br>
   	
   	<fmt:setLocale value="en_us"/>
   	변경후 : <%=response.getLocale() %><br>
   	통화: <fmt:formatNumber value="10000" type="currency"/> <br>
   	날짜: <fmt:formatDate value="${now}"/> <br>
   	<br>

<fmt:requestEncoding value="utf-8"/>

 

request.setChractorEncoding("utf-8")

 

<fmt:bundle>

리소스 번들.properties 

 

한국어 페이지/영어페이지 

 

이름-> 유니코드로 작성

https://osdn.net/projects/propedit/storage/eclipse/updates/

 

Downloading File /eclipse/updates - Properties Editor - OSDN

Free download page for Project Properties Editor's updates.This editor can directly edit property files written in Unicode reference characters, eliminating the need to convert to Unicode. In a...

osdn.net

중간에 이표시가 나와도 당황하지 말고 인스톨 애니웨이

리스타트 나우 눌러주면 끝~~

 

<fmt:bundle basename="번들경로.파일명"

 [prefix="key앞에 반복되는 문자">

출력할 코드

</fmt:bundle> "키이름" [bundle =" setBundle 이름"]

                                     [var="변수명"]

                                     [scope="유효범위"]/>

 

name = 테스트
title = 확인
user_id = 아이디
user_pw = 비밀번호
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
 	<fmt:bundle basename="bundle.test">
 		<fmt:message key="name"/> <br>
 		<fmt:message key="title"/> <br>
 	</fmt:bundle>
 	 	
 	 	<h1>새로 추가한 내용</h1>
 	 <fmt:bundle basename="bundle.test" prefix="user_">
 	 	<fmt:message key="id"/> <br>
 	 	<fmt:message key="pw" var="pw"/>
 		${pw}
 	 </fmt:bundle>
 	 <h1>번들태그 밖</h1>
 	 <fmt:message key="id"/><br>
 	 ${pw} 
	
</body>
</html>

<fmt:setbundle basename="번들경로.파일명"

                      var="변수명"

                       [scope="유효범위"]/>

</fmt:bundle> "키이름" [bundle =" setBundle 이름"]

                                     [var="변수명"]

                                     [scope="유효범위"]/>

set번들

<h1>setBundle</h1>
	  <fmt:setBundle basename="bundle.test" var="test"/>	  
	  
	  <fmt:message key="name" bundle="${test}"/><br>
	  <fmt:message key="title" bundle="${test}"/><br>

test.properties: 기본메세지

test_ko.properties : 한글

test_en.properties: 영어 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
 	
 	<h1>기본 로케일</h1>
 	<fmt:setLocale value="ko"/>
 	<fmt:bundle basename="bundle.sampleBundle">
 		<fmt:message key="id"/> <br>
 		<fmt:message key="pw"/> <br>
 		<fmt:message key="name"/> <br>
 		<fmt:message key="email"/> <br>
 	</fmt:bundle>
 	 	
 	<h1>영문 로케일</h1>
 	<fmt:setLocale value="en"/>
	<fmt:bundle basename="bundle.sampleBundle">
 		<fmt:message key="id"/> <br>
 		<fmt:message key="pw"/> <br>
 		<fmt:message key="name"/> <br>
 		<fmt:message key="email"/> <br>
 	</fmt:bundle>
		  
	  

	
	
</body>
</html>


 

처음엔 한국어페이지로 나오고 영어 누르면 영어로 바뀌게끔 

 

728x90