스프링 시큐리티를 설정하던 도중 만난 오류이다.

No grammar constraints (DTD or XML Schema) referenced in the document.라는 경고와 함께 발생하였다.

서버에서 DTD에 선언한 http://www.springframework.org/schema/beans에 접근하지 못하는 경우 생기는 에러라고 한다.

에러 발생 시 네임스페이스 

xmlns:beans="http://www.springframework.org/schema/beans"

 수정 후 네임스페이스

xmlns="http://www.springframework.org/schema/beans"

 

문제 해결에 도움이 된 글 : https://gdtbgl93.tistory.com/112

security-context.xml 설정 시 네임스페이스에서 문제가 발생하는 경우 해결법

1. 에러 메세지 (Error Message)

Multiple annotations found at this line:
	- You cannot use a spring-security-2.0.xsd or spring-security-3.0.xsd or spring-security-3.1.xsd schema or spring-security-3.2.xsd schema or spring-security-4.0.xsd schema with Spring 
	 Security 4.2. Please update your schema declarations to the 4.2 schema.
	- Configuration problem: You cannot use a spring-security-2.0.xsd or spring-security-3.0.xsd or spring-security-3.1.xsd schema or spring-security-3.2.xsd schema or spring-security-4.0.xsd 
	 schema with Spring Security 4.2. Please update your schema declarations to the 4.2 schema. Offending resource: file [C:/Users/berry/eclipse-workspace/sendAGift_202005/SendAGift_202005/src/
	 main/webapp/WEB-INF/spring/security-context.xml]

 

2. 해결 전

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:security="http://www.springframework.org/schema/security"
	xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-5.0.xsd">

xsi:schemaLocation의 주소를 변경해줍니다.

http://www.springframework.org/schema/security/spring-security-5.0.xsd

아래와 같이 5.0 버전 표기를 삭제합니다.

http://www.springframework.org/schema/security/spring-security.xsd

 

3. 해결 후

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:security="http://www.springframework.org/schema/security"
	xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">

 

참고 사이트 : https://stackoverrun.com/ko/q/10928899

 

작성중

1. UTF-8 / 한글 인코딩 설정 추가

	<!-- UTF-8 / 한글 인코딩 설정 -->
	<filter>
	    <filter-name>encoding-filter</filter-name>
	    <filter-class>
	        org.springframework.web.filter.CharacterEncodingFilter
	    </filter-class>
	    <init-param>
	        <param-name>encoding</param-name>
	        <param-value>UTF-8</param-value>
	    </init-param>
	    <init-param>
	        <param-name>forceEncoding</param-name>
	        <param-value>true</param-value>
	    </init-param>
	</filter>
	<filter-mapping>
	    <filter-name>encoding-filter</filter-name>
	    <url-pattern>/*</url-pattern>
	</filter-mapping>

 

2. 스프링 웹 시큐리티(Spring Web Security) 설정

 

1) 상단 contextConfigLocation에 작성한 security-context.xml을 로딩하도록 설정

	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>
			/WEB-INF/spring/appServlet/servlet-context.xml 
			/WEB-INF/spring/security-context.xml
			</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

2) 필터 추가

	<!-- 스프링 웹 시큐리티 관련 설정 -->
	<filter>
		<filter-name>springSecurityFilterChain</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
	</filter>

	<filter-mapping>
		<filter-name>springSecurityFilterChain</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

 

 

 

 




Unsatisfied dependency expressed through field 'dao'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.violet.persistence.ItemDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@javax.inject.Inject()}



DAOImpl 구현 시 클래스 위에  @Repository 어노테이션을 빼먹어서 발생한 오류였다.

어노테이션을 제대로 작성하였는지 확인할 것!





${org.springframework-version}에는 pom.xml 상단의 <properties>항목에 정의된 <org.springframework-version>버전의 값이 들어가게 된다.

이 경우에는 5.0.7.RELEASE이 된다.

기상청 날씨 정보가 들어있는 XML 문서를 로딩하고 분석 후 결과 출력하는 예제


- 기상청 RSS http://www.kma.go.kr/weather/lifenindustry/sevice_rss.jsp 
- 기상청 육상 중기예보 http://www.kma.go.kr/weather/forecast/mid-term-rss3.jsp?stnId=109 

stnId=108(전국) 
stnId=109 (서울, 경기) 
stnId=105 (강원) 
stnId=131 (충청북도)
stnId=133 (충청남도) 
stnId=146 (전라북도) 
stnId=156 (전라남도) 
stnId=143 (경상북도) 
stnId=159 (경상남도) 
stnId=184 (제주특별자치도)


코드

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" trimDirectiveWhitespaces="true"%>
<%@ page import="java.net.URL"%>
<%@ page import="javax.xml.parsers.*"%>
<%@ page import="org.w3c.dom.*"%>
<%@page import="javax.xml.xpath.*"%>
<%@ page import="org.xml.sax.InputSource"%>
<%
    //weather.jsp -> 지역 선택. 서브밋 액션. 날씨 정보 확인 및 출력.
    //절대경로 확인
    String path = request.getContextPath();
 
    String stnId = request.getParameter("stnId");
    if (stnId == null) {
        stnId = "108";
    }
 
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = null;
 
    String str = String.format("http://www.kma.go.kr/weather/forecast/mid-term-rss3.jsp?stnId=%s", stnId);
    System.out.println(str);
    URL url = new URL(str);
    InputSource is = new InputSource(url.openStream());
    doc = builder.parse(is);
 
    // XPath에 의한 XML 엘리먼트 탐색
    XPath xpath = XPathFactory.newInstance().newXPath();
 
    // 루트 엘리먼트 접근
    //Node rootNode = (Node) xpath.compile("/rss").evaluate(doc, XPathConstants.NODE);
    // System.out.println(rootNode.getNodeName()); //rss
 
    //특정 엘리먼트의 텍스트 접근  rss/channel/item/title 뽑아오기
    String title = xpath.compile("/rss/channel/item/title").evaluate(doc);
    
    // rss/channel/item/description/header/wf
    String headerWf = xpath.compile("/rss/channel/item/description/header/wf").evaluate(doc);
    
    // rss/channel/item/description/body/location -> 복수개 존재하므로 NodeList로 받아온다.
    NodeList locationList = (NodeList)xpath.compile("/rss/channel/item/description/body/location").evaluate(doc, XPathConstants.NODESET);
 
    StringBuilder sb = new StringBuilder();
    
    for (int i=0; i < locationList.getLength(); i++) {
        Node location = (Node)xpath.compile(String.format("/rss/channel/item/description/body/location[%s]", i+1)).evaluate(doc, XPathConstants.NODE);
        
        String city = xpath.compile("city").evaluate(location);
        
        sb.append(String.format("<h3>%s</h3>", city));
        sb.append(String.format("<table class=\"table\">"));
        sb.append(String.format("<thead><tr><th>날짜</th><th>날씨</th><th>최저/최고 기온</th><th>신뢰도</th></tr></thead>"));
        sb.append(String.format("<tbody>"));
        
        NodeList dataList = (NodeList)xpath.compile("data").evaluate(location, XPathConstants.NODESET);
        for (int k=0; k < dataList.getLength(); k++) {                                   //부모 -> 하나밖에 없어야 된다?(->Node)
            Node dataNode = (Node)xpath.compile(String.format("data[%s]", k+1)).evaluate(location, XPathConstants.NODE);
            
            // // -> 자손 탐색
            // / -> 루트
            String tmEf = xpath.compile(String.format("tmEf", k+1)).evaluate(dataNode);
            String wf = xpath.compile(String.format("wf", k+1)).evaluate(dataNode);
            String tmn = xpath.compile(String.format("tmn", k+1)).evaluate(dataNode);
            String tmx = xpath.compile(String.format("tmx", k+1)).evaluate(dataNode);
            String reliability = xpath.compile(String.format("reliability", k+1)).evaluate(dataNode);
            
            sb.append(String.format("<tr>"));
            sb.append(String.format("<td>%s</td>", tmEf));
            String img = "";
            switch(wf){
            case "흐림": img = "W_DB04.png"break;
            case "비": img = "W_DB05.png"break;
            case "비,눈": img = "W_DB06.png"break;
            case "눈": img = "W_DB08.png"break;
            case "구름조금": img = "W_NB02.png"break;
            case "구름많음": img = "W_NB03.png"break;
            case "흐리고 비": img = "W_NB08.png"break;
            case "구름많고 비": img = "W_NB20.png"break;
            }
            sb.append(String.format("<img src=\""+ path +"/resources/img/%s\">", img));
            sb.append(String.format("<td>%s / %s</td>", tmn, tmx));
            sb.append(String.format("<td>%s</td>", reliability));
            sb.append(String.format("</tr>"));
        }            
        sb.append(String.format("</tbody>"));
        
    }
%>
<!DOCTYPE html>
<html>
<head>
<title>쌍용교육센터</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
 
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 
<!-- jQuery library -->
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 
<!-- Latest compiled JavaScript -->
<script
    src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 
<script>
    $(document).ready(function() {
        $("input[value='<%=stnId%>']").attr("checked""checked");
    });
</script>
 
</head>
<body>
 
    <div class="container">
        <h1>
            기상청 육상 중기예보 <small>v1.0 by XML</small>
        </h1>
        <div class="panel-group">
            <div class="panel panel-default">
                <div class="panel-heading">지역 선택</div>
                <div class="panel-body">
                    <form role="form" method="POST">
                        <input type="radio" name="stnId" value="108" checked="checked">
                        전국 <input type="radio" name="stnId" value="109"> 서울,경기 <input
                            type="radio" name="stnId" value="105"> 강원 <input
                            type="radio" name="stnId" value="131"> 충청북도 <input
                            type="radio" name="stnId" value="133"> 충청남도 <input
                            type="radio" name="stnId" value="146"> 전라북도 <input
                            type="radio" name="stnId" value="156"> 전라남도 <input
                            type="radio" name="stnId" value="143"> 경상북도 <input
                            type="radio" name="stnId" value="159"> 경상남도 <input
                            type="radio" name="stnId" value="184"> 제주특별자치도
 
                        <button type="submit" class="btn btn-default">Submit</button>
                    </form>
                </div>
            </div>
            <div class="panel panel-default">
                <div class="panel-heading">기상 정보 출력</div>
                <div class="panel-body">
 
                    <p>
                        <b><%=title%></b>
                    </p>
 
                    <p>
                        <%=headerWf%>
                    </p>
                    
                    <%=sb.toString()%>
 
 
                </div>
            </div>
        </div>
 
    </div>
 
</body>
</html>
 
 
 
</div>
 
</body>
</html>
cs


1. 클래스


 정의

클래스란 사물을 객체화시키는 프로그램 작성 방법이다. 

객체(Object) 프로그램의 대상이   있는 현실세상에 있는 모든 것을 말한다.

 


사물 ---------- 객체화 ---------- > 클래스


 

현실 세계의 객체(Object / ex)자동차...) 속성(statement) 동작(behavior) 추려내어 소프트웨어 객체의 필드(field) 메소드(method) 정의하여 코드로 표현한 것이라고 할 수 있다.

클래스는 사용자 정의 자료형이기 때문에, 원하는 자료형을  마음대로 구성할  있다.

 

 선언 형식

클래스를 구성하는 멤버로는 필드(Field) 생성자(Constructor),메소드(Method) 있다.

 

public class ClassName {

 

//필드 field : 객체의 데이터가 저장되는 

//클래스의 객체(instance) 상태(state) 저장할  사용한다.

int fieldName;

 

//생성자 constructor : 객체 생성  초기화 역할 담당

ClassName (매개변수) {

//객체의 초기화 코드

}

 

//메소드 method : 객체의 동작에 해당하는 실행 블록

//클래스의 기능(behavior) 구현할  사용한다.

publicvoid methodName () {

}

 }

 

 특징

  • 클래스 이름은 식별자 작성 규칙을 따라야하며,  글자를 대문자로 작성한다.

  • 물리적 파일명(.java) 같은 이름을 가진클래스가 존재해야 하고,  클래스 선언에만 public 접근지정자가 붙어야 한다.

  • 클래스의 범위는 { } (중괄호) 정해진다.

  • 클래스는 필드(field 멤버변수라고도 한다) 메소드(method / 생성자, 일반, getter, setter) 구성되며, 내부에 멤버를 자유롭게 구성할  있다.

    • 필드는 클래스의 객체 상태를 저장할  사용한다.

    • 메소드는 클래스의 기능을 구현할  사용한다. 객체 간의 데이터 전달의 수단으로 사용된다. 메소드는 외부로부터 매개값을 받을 수도 있고, 실행  어떤 값을 리턴(결과  반환) 수도 있다. 메소드를 호출함으로써 클래스  필드() 조작할  있다.

    • 생성자는 클래스를 초기화하기 위해 사용한다. 특별히 생성자를 적지 않아도 자동으로 기본 생성자를 호출한다.

  • 클래스에 접근지정자(접근제어자->p256참고) 주로 public  사용하거나, 생략한다.파일 이름과 동일한 이름의 클래스에만 public 접근 제한자를 붙일  있다. public 사용하는 경우는 독립적인 물리적 저장이 가능한 상태이고, 외부에서 해당 클래스를 접근할  있다는 의미이다. 생략하는 경우는 독립적인 물리적 저장은 가능하지만, 외부( 패키지)에서 접근이 제한된다.

 

  • 선언된 클래스는 메모리 적재가 되어야 활동이 가능하다.

-> new 연산자로 클래스에 대한 객체(instance) 생성이 가능

  • 멤버 구성이 전혀 없어도 기본 제공되는 멤버가 있다. (Object 클래스 상속에 의한 공유 멤버 제공 /p457 Object클래스, p288 상속개념 참고)

 

  • 클래스는 서로독립적인 상태이므로 필요시 다른 클래스의 객체를 생성해서 사용할 수 있다.(동일한 클래스를 이용해서 여러개의 객체 생성 가능  blueprint(설계도) 특성)

  • 클래스의 객체가생성된 후에는 해당 클래스의 접근 가능한 멤버를 사용할 수 있다.

 

-실행 클래스 : main() 메소드가 포함된 클래스

-라이브러리 클래스 : main() 메소드가 포함되지 않은 클래스. 단독 실행이 불가능하다.

 

-JAVA에서 기본 제공하는 클래스의 물리적 모음(라이브러리) API(Application Program Interface)라고한다.

 

-다른 패키지 내에 있는 클래스의 멤버 접근 방법

1)**import 구문 사용 (단축키 : ctrl+shift+O)

2)패키지명.클래스명 형태로 작성 (: com.test.Sample)

 

-접근제한자

-public키워드가 없는 클래스 : 같은 패키지 내라면 접근이 가능!

-public 키워드가 있는 클래스 : 다른 패키지에서도 접근 가능

 

 

2. 필드

필드(field) 클래스의 구성멤버  하나로, 객체(instance) 상태 정보가 저장되는 곳이다.

객체 모델링에서 객체(Object) state field 표현한다.

 

형식

-[접근제한자] 자료형 변수명;

-[접근제한자] 자료형 변수명 = 초기값;

-접근 제한자는 private 권장

-필드는 Global 변수로써, 메소드 블록 내부에서 선언된 Local 변수와 구분된다.

 

예시) 자동차 객체의 필드

고유데이터) 제작회사, 모델, 색깔, 최고 속도

상태) 현재 속도, 엔진 회전수

 

//자동차 클래스

public classCar {

 

//<필드(field)>  -Global Variables

//->자동차의 state 분석 -> 모델명, 회사, 색상, ...

//Car 객체(instance)의상태가 고정된 상태

//->private 접근 제한자 생략된 상태 (p189 캡슐화 참고)-> 외부 직접 접근 가능

String model = "그랜저";

String company = "현대자동차";

String color = "검정";


public void method() {

//<Local Variables 로컬 변수>

//->메소드(블럭) 내부에서 선언된 변수

//->메소드 실행이 끝나면 활동 불가

//->메소드(블럭) 영역을 벗어나면 활동 불가

//->주의!) 글로벌 변수와 로컬 변수가 동일한 식별자인 경우 로컬 변수를 우선한다.(영역이 작은 쪽을 우선)

//->   변수명이 다르면 해결. 같을 경우 글로벌 변수에 this 키워드 사용.

//-> 자동 초기화 X

int a = 0; // 명시적 초기화 필요


System.out.println(this.a); //this-> 글로벌 변수

}

}

 

  • 글로벌 변수(필드) 로컬 변수의 차이점?

필드는 클래스 내부에서 선언된 변수로, 클래스 내부 영역 전체에서 사용이 가능하며 객체(instance)메모리에 활동하는 동안 사용하다. 자동초기화가 지원되고 접근 제한자도 사용할  있다.

로컬 변수(Local Variable) 메소드(블록) 내부에서 선언된 변수로, 메소드 실행이 끝나거나 메소드 블록영역을 벗어나면 활동이 불가한 변수이다.

! 주의 ) 글로벌 변수와 로컬 변수가 동일한 식별자인 경우 로컬 변수를 우선한다. (변수명을 다르게 설정해주자) 같을 경우 글로벌 변수에 this 키워드를 사용한다.

자동초기화가 지원되지 않아 명시적 초기화가 필요하다.

 

필드 초기화 방법 네가지 (->p206 추가 참고 : p265. Getter/Setter 메소드)

자동 초기화

String color; //자동초기화  : null

int age;  //자동초기화  : 0

명시적 초기화

String company = "현대자동차";

 


----추가 참고----

p31. p192. 식별자 작성 규칙

클래스의 접근 제한 (->p257 ~264p)

캡슐화 개념(p189 참고) -> 방법 : 접근 제한자 사용



// 추가 참고한 책 : <이것이 자바다> 1권

'Java > 노트' 카테고리의 다른 글

[Java] 생성자(Constructor)에 대해서  (0) 2018.07.13

생성자란?

생성자는 특수한 목적을 가지는 메소드로객체가 생성될  자동으로 호출되어 필드를 초기화하는 역할을 한다.

 

생성자가 필요한 이유

-필드를 선언할  초기값을 주게 되면 동일한 클래스로부터 생성되는 객체들은 모두 같은 데이터를 갖게된다.

->객체 생성 시점부터 원하는 초기값을 설정하기 위해 생성자를 사용한다.

 

생성자 작성 형식

접근제한자 메소드이름 ([매개변수]) {

//실행 코드

}



 

특징

-객체 생성  생성자가 호출되지 않으면 예외(에러) 발생한다.

-없으면 컴파일러에서 기본 생성자를 자동으로 제공

-클래스 이름과 동일하고 반환자료형(return type) 없다void표기 조차도 필요 없음

-일반적으로 접근제한자는 public 사용하나private 생성자를 사용하는 경우도 있다. (->private 생성자)

 

기본 생성자

-사용자가 생성자 선언을 하지 않는 경우에만 자동 제공되는 생성자

-객체 생성  자동 호출되는 메소드이므로기본 생성자가 없으면 컴파일러에서 기본 생성자를 자동으로 제공해준다.

-자동으로 생성되는 기본 생성자의 접근 제한은 클래스의 접근 제한과 동일하다. (p260 참고)


매개변수가 있는 생성자 Parameterized Constructor

-생성자에 매개변수를 쓰는 이유 : 외부 전달 받아서 필드를 초기화하기 위한 목적

->기본 생성자 추가로 명시적 선언이 필요  - 매개변수가 있는 생성자 선언  기본 생성자는 자동 제공되지않으므로 기본 생성자와 함께 쓰는 것을 권장한다.


private 생성자 (p260, p243 참고)

->외부에서 객체(instance) 생성하는 과정을 통제하는 수단.

-private 접근제한자는 동일 패키지이건 다른 패키지이건 상관없이 생성자를 호출하지 못하도록 제한하여클래스 외부에서 new 연산자로 객체를 만들  없다.

-클래스 내부에서 정적(static) 메소드를 사용해 객체 생성  제공하도록  

 예Math 클래스 - Math클래스 메소드는 객체(instance)를 선언하지 않아도 사용이 가능하다.

 Math m = new Math(); 라고 선언해보면 The constructor Math() is not visible이라는 메시지

 ->Math클래스의 생성자의 접근제한자는 private인 것을 알 수 있다.

 

 

[참고]생성자와 setter - 생성자와 setter 역할은 비슷하지만 호출 시점이 다르다.

-생성자는 객체 생성  필드 초기화 역할을 수행 - 객체 생성    번만 호출된다.

-setter 객체 생성 이후에 호출이 가능 - 필드 초기화가 아니라 기존값 덮어쓰기객체 생성 이후라면 원하는 때에 언제라도 호출할  있다.

'Java > 노트' 카테고리의 다른 글

[Java] 클래스(Class)의 특징  (0) 2018.07.19

[문제] 여러명의 회원 정보를 전달받고, 출력하는 메소드 선언하기

실행예) 

------------ 

HONG 

010-1234-1234 

20세 

------------ 

PARK 

010-1111-2222 

25세

------------ 

CHOI 

010-5432-4321

22세 


 1. main() 메소드가 있는 실행 클래스

 2. 사용자 정의 자료형 Member 클래스

 3. 출력용 클래스 세 클래스로 나눠서 작성


package com.exam002;

public class Main {
	public static void main(String[] args) {
		//실행 클래스
		//Member 클래스를 사용하기 위해 new연산자를 이용해 객체(instance) 생성
		Member m1 = new Member();
		
		//setter 메소드를 이용해 해당 인스턴스 변수(필드)에 값을 넣어준다.
		m1.setName("고길동");
		m1.setAge(45);
		m1.setPhoneNum("010-0000-0000");

		//마찬가지로 다른 Member 객체(instance)를 생성해서 값을 넣어주자
		Member m2 = new Member();
		Member m3 = new Member();
		
		m2.setName("김둘리");
		m2.setAge(100);
		m2.setPhoneNum("010-1234-5678");
		
		m3.setName("고희동");
		m3.setAge(3);
		m3.setPhoneNum("010-9999-9999");
		
		//Member배열에 각각의 객체(instance) m1, m2, m3를 넣어준다.
		Member[] members = new Member[3]; //크기가 3인 Member자료형(사용자정의자료형) 배열을 선언한다.
		members[0] = m1;
		members[1] = m2;
		members[2] = m3;
		
		//출력
		Test t = new Test();
		t.printMembers(members); //매개변수로 사용자정의자료형인 Member배열을 넘겨준다.
		
	}
}
package com.exam002;

public class Member {
	//자료형 클래스 : 자료를 저장하는 Member 클래스
	
	//필드 field
	private String name;
	private int age;
	private String phoneNum;
	
	//getter, setter 메소드 - 다른 클래스에서도 접근할 수 있도록 접근제한자는 public
        //getName 메소드를 다른 곳에서 호출하면 이 클래스의 필드의 name변수에 저장된 값을 돌려준다.
	public String getName() {
		return this.name; 
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public int getAge() {
		return this.age;
	}
	
	public void setAge(int age) {
		this.age = age;
	}
	
	public String getPhoneNum() {
		return this.phoneNum;
	}
	
	public void setPhoneNum(String phoneNum) {
		this.phoneNum = phoneNum;
	}
	
}
package com.exam002;

public class Test {
	//액션 클래스 - 출력용 메서드 작성
	
	//매개변수로 배열을 받아서 출력하는 형태로 작성
	public void printMembers(Member[] members) {
		
		//향상된 for문(Enhanced for loop) 사용
		//배열 members에 들어있는 값을 처음부터 끝까지 차례차례 하나씩 꺼내서 선언된 변수에 m에 담아서 출력한다.
		//주의 : 배열에서 사용. 요소를 참조할 때만 사용하는 것이 좋으며, 요소의 값을 변경하는 작업에는 적합하지 않다.
		for(Member m : members) {
			System.out.println("------------");
			System.out.println(m.getName());
			System.out.println(m.getAge()+"세");
			System.out.println(m.getPhoneNum());
		}
	}
	
	
}

실행 결과

------------
고길동
45세
010-0000-0000
------------
김둘리
100세
010-1234-5678
------------
고희동
3세
010-9999-9999


+ Recent posts