반응형

JSP(Java Server Page)

: JSP는 Servlet이다.

 

Test.jsp => Test_jsp.jave => Test_jsp.class

 

 

[MODEL 2 PATTERN]

Servlet의 구조를 맛봐서 알겠지만, Java Code 환경에서 응답코드를 HTML을 삽입해서 전송해주는 방법이다.

 

JSP의 구조는 HTML Code 기반에 Java Code를 삽입하여 사용한다.

 

- 결론, 최종적인 결과는 두 개다 동일하다.

 

- Java 환경으로 처리할 내용이 많다 = Servlet

- HTML 환경으로 처리할 내용이 많다 = JSP

 

 


 

 

JSP가 Servlet인 이유를 알아보자

 

 

JSP 편집한 파일 경로

D:\dev\WebStudy\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\2024_0617_2_JSPTest\org\apache\jsp

 

 

 

- JSP에서 만든 html 형식의 문서가 Test_jsp.java 프로그램 안에서 전부 Servlet 형식으로 바꿔주고 있었다.

 

- Servlet에서 일일이 하드코딩 했던 것을 JSP가 일일이 만들어주고 있었다.

 

 

 

 

JSP의 헤더

 

 

 

 

 

JSP(_jspService(request, response) 영역)의 선언부

 

★ 이 코드는 정확히 _jspService(request, response)안에 코딩되는 것이다 ★

JSP 내장 객체 : JSP -> Servlet 변환 시 내부에 존재하는 객체
request/reponse

 

- JSP의 선언부에 선언된 Java 언어들이 전부 Servlet에도 정상적으로 선언이 되어있다.

 

 

- JSP의 java 파일을 확인해보면 _jspService에 자동으로 request와 response가 만들어져있다.

 

(request/ reponse, session/application, pageContext, out 등등이 내장 되어 있기에 마음껏 사용할 수 있다)

 

 

 

HTML 파일 연동

<!DOCTYPE html>
<html>


<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

<style type="text/css">
	th{
		text-align: right;
	}
	
	textarea{
		resize: none;
	}
	
	#box {
		width: 500px;
		margin: auto;
		margin-top: 30px;
		
		border: 0.1px solid black;
	}
	
	.form-control {
		width: 200px;
	}

</style>

<script type="text/javascript">

	// 정규식
	const regular_id = /^[A-Za-z]{1}[A-Za-z0-9]{3,7}$/; // 4~8
	const regular_pwd = /^[A-Za-z]{1}[A-Za-z0-9]{3,5}$/; // 4~6
	// 첫글자는 영어로 / 대문자,소문자,숫자,4~8자리까지
	// 이것에 대한 개념은 갯수지 자릿수가 아님
	

	function send(f) {
		
		let name = f.name.value.trim(); //trim() 공백제거
		let id = f.id.value; // 정규식 체크할거라 trim()을 쓰지 않는다
		let pwd = f.pwd.value;
		let profile = f.profile.value;
		// 항상 client의 입장에서 사용자의 입장에서 생각하고 프로그램을 짜야한다.
		if(name=="") {
			alert("이름을 입력하세요!!");
			f.name.value=""; // 다시 입력해야한다면, 값 초기화
			f.name.focus();
			return;
		}
		
		if(regular_id.test(id)==false) {
			alert("아이디는 4~8자리의 영문자/숫자 조합으로 작성하세요");
			f.id.value="";
			f.id.focus();
			return;
		}
		
		if(regular_pwd.test(pwd)==false) {
			alert("비밀번호는 4~6자리의 영문자/숫자 조합으로 작성하세요");
			f.pwd.value="";
			f.pwd.focus();
			return;
		}

		if(profile=="") {
			alert("자기소개를 입력하세요!!");
			f.profile.value="";
			f.profile.focus();
			return;
		}
		
		//전송절차 form 태그 안에 적어도 된다.
		f.action = "result_input.jsp"; // jsp = Servlet
		f.method = "GET"; // 생략시 기본값 : GET
		f.submit();
		
	}

</script>


</head>

<!--
	form : 서버로 데이터 전송시 사용하는 Tag
	속성 :
	   1. action : 전송대상(누구에게..) / 생략시 자신에게 전송
	   2. method : 전송방식
                   GET : URL 주소를 통해서 전송(QueryString 방식)
                   Query 
                   POST : request body에 넣어서 전송(보안성좋다)
       cf) URL => https://www.w3schools.com/action_page.do?fname=John&Iname=Doe
                  protocol : https
                  host : www.w3shools.com(port 생략되어 있음 : https는 port를 내부로 hide처리함)
                  path : action_page.do
                  query : fname=John&Iname=Doe
                          name=value&name=value <- Query
-->

<body>

	<form>
		<div id="box">
			<table class="table">
				<!-- 1번째줄 required:반드시입력(이 input안에 정보를 입력해야 넘어간다) -->
				<tr>
					<th>이름</th>
					<td><input class="form-control" type="text" name="name" autofocus placeholder="이름을 입력하세요" required="required"></td>
				</tr>
				
				<!-- 2번째줄 -->
				<tr>
					<th>아이디</th>
					<td><input class="form-control" type="text" size="30" name="id" autofocus placeholder="아이디는 4~8자리 영숫자 조합" required="required"></td>
				</tr>
				
				<!-- 3번째줄 -->
				<tr>
					<th>비밀번호</th>
					<td><input class="form-control" type="password" size="30" name="pwd" autofocus placeholder="비밀번호 4~6자리 영숫자 조합" required="required"></td>
				</tr>
				
				<!-- 4번째줄 checked:기본으로 체크되어 있음 name이 같아야 그룹으로 잡혀서 체크 해제가 된다. -->
				<tr>
					<th>성별</th>
					<td>
					<input type="radio" name="gender" value="남자" checked="checked">남자
					<input type="radio" name="gender" value="여자">여자
					</td>
				</tr>
				
				<!-- 5번째줄 -->
				<tr>
					<th>취미</th>
					<td>
					<!-- check된 항목만 전송된다 -->
					<input type="checkbox" name="hobby" value="여행">여행
					<input type="checkbox" name="hobby" value="보드게임">보드게임
					<input type="checkbox" name="hobby" value="독서">독서
					<input type="checkbox" name="hobby" value="프로그래밍">프로그래밍
					</td>
				</tr>
				
				<!-- 6번째줄 -->
				<tr>
					<th>친구</th>
					<td>
						<input class="form-control" name="friend"><br>
						<input class="form-control" name="friend"><br>
						<input class="form-control" name="friend"><br>
					</td>
				</tr>
				
				<!-- 7번째줄 -->
				<tr>
					<th>혈액형</th>
					<td>
					<select name="blood">
						<option value="A형">A형</option>
						<option value="B형">B형</option>
						<option value="O형">O형</option>
						<option value="AB형">AB형</option>
					</select>
					</td>
				</tr>
				
				<!-- 8번째줄 -->
				<tr>
					<th>자기소개</th>
					<td>
						<textarea name="profile" rows="5" cols="40"></textarea>
					</td>
				</tr>
				
				<!-- 버튼 -->
				<tr>
					<td colspan="2" align="center">
						<input type="button" value="전송" onclick="send(this.form);">
						<input type="reset" value="취소">
					</td>
				</tr>
			</table>
		</div>
	</form>

</body>


</html>

 

 

 

JSP 파일 생성(Bootstrap 적용)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<%
	//ScriptLet : Java Code 영역
	// ★ 이 코드는 정확히 _jspService(request, response)안에 코딩되는 것이다 ★
	
	// JSP 내장 객체 : JSP -> Servlet 변환 시 내부에 존재하는 객체
	//                 request/reponse
	//                 session/application
	//                 pageContext
	//                 out
	
	//0.수신인코딩 설정(기본적으로 설정해주지 않으면 깨진다)
	request.setCharacterEncoding("utf-8");
	
	//1.parameter 받기
	// html 내부의 name이 넘어가는 것이다.
	String name = request.getParameter("name");
	String id = request.getParameter("id");
	String pwd = request.getParameter("pwd");
	String gender = request.getParameter("gender");
	String blood = request.getParameter("blood");
	String profile = request.getParameter("profile");
	
	// parameter 이름이 동일한 이름으로 들어온 경우에는 배열로 받는다.
	// checkbox : 체크된 목록만 넘어온다(체크항목이 없으면 null)
	String [] hobby_array = request.getParameterValues("hobby");
	//                         hobby=독서&hobby=영화&hobbyy=프로그래밍
	//                             0        1          2
	// String [] hobby_array = { "독서", "영화" , "프로그래밍" };
	// 취미목록
	String hobby_list = "취미없음";
	if(hobby_array != null) {
		StringBuffer sb = new StringBuffer();
		for(String hobby : hobby_array) {
		// 메모리 낭비가 심한 방식이다.
		// hobby_list += hobby + " "; // hobby_list = "독서 " + "영화 " + "프로그래밍 "
			sb.append(hobby);
			sb.append(" ");
		}
		// trim()은 중간공백 제거가 아닌 양쪽 공백제거이다.
		hobby_list = sb.toString().trim();
	}
	
	// input : 모든값이 다 넘어온다
	String [] friend_array = request.getParameterValues("friend");
	//                       friend=철수&friend=&friend=
	//String [] friend_array = { "철수", "", "" };
	String friend_list = "";
	
	StringBuilder sb = new StringBuilder();
	for(String friend : friend_array) {
		sb.append(friend);
		sb.append(" ");
	}
	friend_list = sb.toString().trim();
	
	if(friend_list.isEmpty()) {
		friend_list = "친구없음";
	}
%>
    
<!-- 결과전송 -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

<style type="text/css">
#box {
	width: 500px;
	margin: auto;
	margin-top: 50px;
	box-shadow: 1px 1px 2px black;
	
	text-shadow: 1px 1px 2px black;
}

th {
	background: #333333;
	color: white;
}
</style>
</head>
<body>
	<div id="box">
		<table class="table table-hover table-bordered">
			<tr>
				<th>이름</th>
				<!-- 변수안에 있는 값 출력 -->
				<td><%= name %></td>
			</tr>
			<tr>
				<th>아이디</th>
				<td><% out.print(id); %></td>
			</tr>
			<tr>
				<th>비밀번호</th>
				<td><%= pwd %></td>
			</tr>
			<tr>
				<th>성별</th>
				<td><%= gender %></td>
			</tr>
			<tr>
				<th>혈액형</th>
				<td><%= blood %></td>
			</tr>
			<tr>
				<th>취미</th>
				<td><%= hobby_list %></td>
			</tr>
			<tr>
				<th>친구</th>
				<td><%= friend_list %></td>
			</tr>
			<tr>
				<th>자기소개</th>
				<td><%= profile %></td>
			</tr>
			<tr>
				<td colspan= "2" align="center">
				<button class="btn btn-info" onclick="location.href='input.html'">다시하기</button>
			</tr>
			
		</table>
	</div>

</body>
</html>

 

 

 

 

 

 

 

 

 

반응형