본문 바로가기
Programming/JSP

JSP 4일차

by yoon9i 2024. 5. 23.

#######################################################################################
4일차

1. JSP 구성요소 ( 태그 형태로 구성됨 )
C:\servlet_study\apache-tomcat-9.0.89\work\Catalina\localhost\jsp\org\apache\jsp
에서 .java 를 볼수있음.

    가. html 
    # 다음 태그는 java와 관련있는 태그이다.

 

나. JSP 태그
   *종류
 - directive 태그
 - page directive 태그 :  JSP에게 정보를 알려줄 때 사용된다.
                                     정보종류? contenType, 자바의 import,...
                                     <%@ page  속성명="속성값"  속성명="속성값" ...         %>
                                      : 여러번 사용이 가능

                                   <%@ page contentType="text/html;charset=utf-8" %>
                                   ==> 서블릿의 response.setContentType("text/html;charset=utf-8") 기능.
                
                                   <%@ page import="java.util.ArrayList" %> 
                                   <%@ page import="java.util.Date" %>
                                   <%@ page import="java.util.Date,java.util.ArrayList" %>
                                    ==> 서블릿의 import java.util.ArrayList;
                                   import java.util.Date; 

<%@ page language="java" 
         contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"        
%>
<%!
int num = 10;

%>
<%
   String name="홍길동";
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p>안녕하세요</p>
<p>Hello</p>
</body>
</html>
<%!
public void aaa(){}
%>
<%
   int size=100;
%>
<%@ page language="java" 
         contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"        
%>
<%@ page import="java.util.Date" %>
<%@ page import="java.util.ArrayList" %>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p>안녕하세요</p>
<p>Hello</p>
</body>
</html>




- include directive 태그: 화면을 재사용할 때 사용.

       <%@ include  file="속성값" %>

 

- taglib directive 태그 : <%@ taglib   prefix="속성값" uri="속성값"  %>

 - declaration 태그  : - 인스턴스변수/인스턴스 메서드 ( 거의 사용 안함 )
                                   <%!  자바코드(인스턴스변수|메서드)   %>
                                - 여러번 사용 가능
                                   예>
                                    <%!
                                           int num=10;
                                           public void a(){
                                               System.out.println(num);
                                           }
                                      %>
                                      ==> 서블릿에서는        
                                      public class MyServlet extends HttpServlet{
                                                 int num=10;
                                                 public void a(){
                                                     System.out.println(num);
                                                  } 
                                                 public void doGet(){}
                                     }

<%@ page language="java" 
         contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"        
%>
<%!
	int num = 10; //인스턴스 변수
%>
<%!
	public void a() {
		System.out.println(num);
	} // 인스턴스 메서드로 만들어짐.
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p>안녕하세요</p>
<p>Hello</p>
</body>
</html>

 

 - scriptlet 태그    : -서비스 메서드(doGet/doPost)내에서 코드 ( 매우 많이 사용됨 )
                               <%   자바코드   %>  
                              - 여러번 사용 가능

 

                               예>
                               서블릿의 doGet() 구현 코드예-1
                               pulic void doGet(HttpServletRequest x,
                                                          HttpServletResponse y){
  
                                              int n = 10;
                                              int [] arr = {10,20};
                                              for(int k: arr){
                                                     System.out.println(k);
                                               }

                                  }

                                  JSP에서는 다음과 같이 표현한다.- 1 
                                  <%
                                           int n = 10;
                                           int [] arr = {10,20};
                                    %>
                                     <%
                                                 for(int k: arr){
                                                         System.out.println(k);
                                                   }
                                    %>


                                    서블릿의 doGet() 구현 코드예-2
                                    pulic void doGet(HttpServletRequest x,
                                                               HttpServletResponse y){
  
                                              String userid = x.getParamter("userid");
 
                                              HttpSession session= x.getSession();

                                              x.setCharacterEncoding("utf-8");

                                              y.setContentType("text/html;charset=utf-8");
                                              PrintWriter out = y.getWriter();  
                                              out.print("<html>");
                                        }

                                        JSP 표현-2
                                         =>변환하면 항상 _jspService(HttpServletRequest request,
                                                                                         HttpServletResponse response){
                                                                              String userid = request.getParamter("userid");
                                                                       }
                                           <%
                                                      String userid = request.getParamter("userid");
                                                      HttpSession session= request.getSession();

                                                      request.setCharacterEncoding("utf-8");
                                              %>
   

                                               서블릿의 doGet() 구현 코드예-3
                                               pulic void doGet(HttpServletRequest request,
                                                                          HttpServletResponse response){
                                                                 String userid = request.getParamter("userid");

                                                                 request.setAttribute("xxx","이순신");
 
                                                                  HttpSession session= request.getSession();
                                                                  session.setAttribute("xxx","홍길동");

                                                                  request.setCharacterEncoding("utf-8");

                                                                   ServletContext application = getServletContext();
                                                                   application.setAttribute("xxx","유관순");

                                                                   response.setContentType("text/html;charset=utf-8");
                                                                   PrintWriter out = response.getWriter();  
                                                                   out.print("<html>");
                                                   }

                                                    JSP 표현-3
                                                     =>변환하면 항상 _jspService(HttpServletRequest request,
                                                     HttpServletResponse response)가 자동생성됨.
                                                      => 항상 자동으로 선언되는 변수가 있음.
                                                     HttpSession session;
                                                     ServletContext application; 
                                                     ServletConfig config;
                                                     JspWriter out;  // PrintWrtier 동일 기능
                                                  <%
                                                         // 내장변수(내장객체) 라고 부른다.
                                                           request.메서드
                                                           response.메서드
                                                           session.메서드
                                                           application.메서드
                                                           config.메서드
                                                           out.print("값");
                                                     %>

package com.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/xxx")
public class MainServlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
       throws ServletException, IOException {

		List<String> list = Arrays.asList("홍길동","이순신");
		
		// 응답처리
		response.setContentType("text/html;charset=utf-8");
		
		PrintWriter out = response.getWriter();
		out.print("<html>");
		out.print("<head>");
		out.print("<title>JSP 변경해보기</title>");
		out.print("</head<");
		out.print("<body>");
		for(String name: list) {
			out.print("이름: " + name + "<br>");
		}
		out.print("</body>");
		out.print("</html>");
	}
}
<%@ page language="java" 
         contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"        
%>
<% 
    // 로컬변수선언
    int n = 10;

    // 반복문
    int [] arr = {10,20};               
%>
<% 
    for(int k: arr) {
        System.out.println(k);
    }        
%> 
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p>안녕하세요</p>
<p>Hello</p>
</body>
</html>
<%@ page language="java" 
         contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"        
%>
<% 
	// 변수선언 없이 사용가능한 내장 변수가 제공됨(내장변수)
	request.setAttribute("request", "홍길동");
	session.setAttribute("session", "이순신");
	application.setAttribute("application", "유관순");
	
	String request_scope = (String)request.getAttribute("request");
	String session_scope = (String)session.getAttribute("session");
	String application_scope = (String)application.getAttribute("application");
%> 
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
	out.print("request_scope: " + request_scope);
	out.print("session_scope: " + session_scope);
%>
<%
	out.print("application_scope: " + application_scope);
%>
</body>
</html>
<%@page import="java.util.Arrays"%>
<%@page import="java.util.List"%>
<%@ page language="java" 
         contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"        
%>
<%
	List<String> list = Arrays.asList("홍길동","이순신");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
방법1:<br>
<%
	for(String name: list) {
		out.print("이름: " + name + "<br>");
	}	
%>
<br>
<br>
방법2:<br>
<%
for(String name: list) {
%>
이름: <%= name %><br>
<%
}
%>
</body>
</html>

- expression 태그   : <%=  변수(값)  %>
                                  <%  out.print("값"); %> 동일한 기능.

 

  * 서블릿 코드
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response){

             List<String> list = Arrays.asList("홍길동","이순신");

             out.print
     }

 

<%@ page language="java" 
         contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"        
%>
<% 
	// 변수선언 없이 사용가능한 내장 변수가 제공됨(내장변수)
	request.setAttribute("request", "홍길동");
	session.setAttribute("session", "이순신");
	application.setAttribute("application", "유관순");
	
	String request_scope = (String)request.getAttribute("request");
	String session_scope = (String)session.getAttribute("session");
	String application_scope = (String)application.getAttribute("application");
%> 
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

request_scope: <%= request_scope %><br>
session_scope: <%= session_scope %><br>
application_scope: <%= application_scope %>
</body>
</html>

 

    다. EL 태그
    라. JSTL 태그
      - taglib directive 태그 : <%@ taglib   prefix="속성값" uri="속성값"  %> 사용

 

 

2. 화면 재사용

 1> include 디렉티브 이용한 방법. ( 정적인 방법 )

    jsp05_화면재사용1_include디렉티브.jsp               copyright.jsp

   <body>
            내용
            <hr>
            <!-- copyright 위치 -->
            <%@ include file="copyright.jsp"%>
  </body>

 
 2> jsp include 액션 태그 이용한 방법. ( 동적인 방법 )

   <body>
             내용
             <hr>
             <!-- copyright 위치 -->
             <jsp:incldue  page="copyright.jsp"  flush="true" />
  </body>

<%@ 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>
내용
<hr>
	<!-- copyright 위치 -->
	<%@ include file="copyright.jsp" %>
</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>
내용
<hr>
	<!-- copyright 위치 -->
	<jsp:include page="copyright.jsp" flush="true" />
</body>
</html>

 

3. 서블릿에서 JSP로 위임 (*********************)
1> 개요
- 서블릿: - 대부분이 자바코드이고 일부분이 html 로 구성되어있다.
           일부분의 html 작업조차도 매우 번거로운 작업이다.
         - 비즈니스 로직처리를 잘함.

- JSP: - 대부분이 html 이고 일부분이 java 코드이다.
         일부분의 java 코드 작업은 <% %> JSP 태그를 사용해야된다.
       - 화면처리를 잘함.

 

2> 구조
가. 현재방식

                        요청(잘함.)
    웹브라우저 -----------------------------> 서블릿
                       <-----------------------------
                        응답(매우 힘들게 처리함.)



                        요청(자바처리가 번거로움)
    웹브라우저 -----------------------------> jsp
                       <-----------------------------
                        응답(잘함.)

나. 적용할 방식

                        요청(잘함.)
    웹브라우저 -----------------------------> 서블릿
                                                                |
                                                                | 위임처리
                                                                |
                        <----------------------------    jsp
                                응답(잘함.)

 

 

3> 위임처리 방법 2가지
가. 리다이렉트(redirect)
- HttpServletResponse 이용
- 문법:

    public void doGet(HttpServletRequest request, HttpServletResponse response) {
        response.sendRedirect("타켓");
    }

                    1> 요청(/xxx)
     웹브라우저 ------------------>    MainServlet("/xxx") 2> doGet실행
                                                 HttpServletRequest request(100번지) 생성
                                                request(100번지).setAttribute("xxx","홍길동")

                                                  3>
                                                 response.sendRedirect(" a.jsp");
                         <-------------------
                           4>응답(서블릿이 응답)

                           5> 재요청(a.jsp)
                           ------------------>  a.jsp   HttpServletRequest request(200번지)
                           <------------------          request.getAttribute("xxx"); null 반환
                           6> 응답

   - url이 변경됨. ( /xxx  --> a.jsp )
  - 서블릿에서 request scope에 저장된 데이터는
    리다이렉트된 jsp에서 참조 불가 (null 반환)
    따라서 session scope 또는 application scope를 사용해야 된다.

package com.servlet;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@WebServlet("/main")
public class MainServlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("doGet");
		
		//복잡한 로직 처리
		List<String> list = Arrays.asList("홍길동","이순신","유관순");
		
		// scope에 저장.
		//1. request scope에 저장
		request.setAttribute("req_list", list);
		
		
		//2. session scope에 저장
		HttpSession session = request.getSession();
		session.setAttribute("session_list", list);
		
		//3. application scope에 저장
		ServletContext application = getServletContext();
		application.setAttribute("application_list", list);
		
		
		//결과물 응답처리 ==> list.jsp 위임
		//리다이렉트 방식이용.
		response.sendRedirect("list.jsp");
	}
}
<%@page import="java.util.List"%>
<%@ 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>list.jsp</h1>
<%
      List<String> list =
        (List<String>) request.getAttribute("req_list");

		List<String> list2 =
		(List<String>) session.getAttribute("session_list");
		
		List<String> list3 =
		(List<String>) application.getAttribute("application_list");
%>
<h2>1. request scope 처리</h2>
<table border="1">
  <tr>
   <th>이름</th>
  </tr>
<%
 if(list!=null)
   for(String name: list){
%>  
  <tr>
    <td><%= name %></td>
  </tr>
<%
   }//end for
%>  
</table>
<h2>2. session scope 처리</h2>
<table border="1">
  <tr>
   <th>이름</th>
  </tr>
<%
if(list2!=null)
   for(String name: list2){
%>  
  <tr>
    <td><%= name %></td>
  </tr>
<%
   }//end for
%>  
</table>
<h2>3. application scope 처리</h2>
<table border="1">
  <tr>
   <th>이름</th>
  </tr>
<%
if(list3!=null)
   for(String name: list3){
%>  
  <tr>
    <td><%= name %></td>
  </tr>
<%
   }//end for
%>  
</table>
</body>
</html>

나. 포워드(forward)
- HttpServletRequest 이용
- 문법:

    public class MainServlet extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response) {
            RequestDispatcher dis = request.getRequestDispatcher("타켓");
            dis.forward(request, response);
        }
    }

    public class MainServlet extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response) {
            RequestDispatcher dis = request.getRequestDispatcher("a.jsp");
            dis.forward(request, response);
        }
    }

 

                1> 요청                   서버
    웹브라우저 --------------------------------> MainServlet("/xxx")     2> doGet 실행
                                                                       |                                HttpServletRequest request 생성
                                                                       |                                 request.setAttribute("xxx", "홍길동");
                                                                       |
                                                                       | 3> 포워드 위임(요청) - 1번에서 만든 request 를 재사용.
                                                                       |    request.getRequestDispatcher("a.jsp");
                                                                       |    dis.forward(request, response);
              <----------------------------------- a.jsp
    
==> forward 방식은 서블릿을 요청할 때 생성했던 request 를 jsp 로 위임(요청)할 때도 재사용한다.
        따라서, 하나의 request로 서블릿도 요청하고 jsp 도 요청하는 방식으로서 request를 
        확장시킬수 있는 개념이다.
==> 서블릿에서 request.setAttribute(key,value) 로 저장된 데이터를
        JSP 에서 request.getAttribute(key) 하면 value 를 얻을 수 있다.
==> 브라우저 url 변경 안됨
    서블릿맵핑값으로 계속 유지됨.

package com.servlet;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@WebServlet("/main")
public class MainServlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("doGet");
		
		//복잡한 로직 처리
		List<String> list = Arrays.asList("홍길동","이순신","유관순");
		
		// scope에 저장.
		//1. request scope에 저장
		request.setAttribute("req_list", list);
		
		
		//2. session scope에 저장
		HttpSession session = request.getSession();
		session.setAttribute("session_list", list);
		
		//3. application scope에 저장
		ServletContext application = getServletContext();
		application.setAttribute("application_list", list);
		
		
		//결과물 응답처리 ==> list.jsp 위임
		//포워드방식이용
		RequestDispatcher dis = request.getRequestDispatcher("list.jsp");
		dis.forward(request, response);
	}
}
<%@page import="java.util.List"%>
<%@ 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>list.jsp</h1>
<%
      List<String> list =
        (List<String>) request.getAttribute("req_list");

		List<String> list2 =
		(List<String>) session.getAttribute("session_list");
		
		List<String> list3 =
		(List<String>) application.getAttribute("application_list");
%>
<h2>1. request scope 처리</h2>
<table border="1">
  <tr>
   <th>이름</th>
  </tr>
<%
 if(list!=null)
   for(String name: list){
%>  
  <tr>
    <td><%= name %></td>
  </tr>
<%
   }//end for
%>  
</table>
<h2>2. session scope 처리</h2>
<table border="1">
  <tr>
   <th>이름</th>
  </tr>
<%
if(list2!=null)
   for(String name: list2){
%>  
  <tr>
    <td><%= name %></td>
  </tr>
<%
   }//end for
%>  
</table>
<h2>3. application scope 처리</h2>
<table border="1">
  <tr>
   <th>이름</th>
  </tr>
<%
if(list3!=null)
   for(String name: list3){
%>  
  <tr>
    <td><%= name %></td>
  </tr>
<%
   }//end for
%>  
</table>
</body>
</html>
<%@page import="java.util.List"%>
<%@ 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>list.jsp</h1>
<%
      List<String> list =
        (List<String>) request.getAttribute("req_list");

		List<String> list2 =
		(List<String>) session.getAttribute("session_list");
		
		List<String> list3 =
		(List<String>) application.getAttribute("application_list");
%>
<h2>1. request scope 처리</h2>
<table border="1">
  <tr>
   <th>이름</th>
  </tr>
<%
 if(list!=null)
   for(String name: list){
%>  
  <tr>
    <td><%= name %></td>
  </tr>
<%
   }//end for
%>  
</table>
<h2>2. session scope 처리</h2>
<table border="1">
  <tr>
   <th>이름</th>
  </tr>
<%
if(list2!=null)
   for(String name: list2){
%>  
  <tr>
    <td><%= name %></td>
  </tr>
<%
   }//end for
%>  
</table>
<h2>3. application scope 처리</h2>
<table border="1">
  <tr>
   <th>이름</th>
  </tr>
<%
if(list3!=null)
   for(String name: list3){
%>  
  <tr>
    <td><%= name %></td>
  </tr>
<%
   }//end for
%>  
</table>
</body>
</html>

####################################################################
4. MyBatis 연동

1> SE 버전 아키텍쳐

    (main 메서드)                         Empservice(인터페이스)
    JComponent04_JTextField  ----------> EmpServiceImpl ----------> EmpDAO ----------> MySQL
                                                 <----------                             <----------                 <----------

    - 2개의 jar 파일을 build path 로 설정.

2> EE 버전 아키텍쳐

    (main메서드역할)             Empservice(인터페이스)
    EmpListServlet  ----------> EmpServiceImpl ----------> EmpDAO ----------> MySQL
         |                     <----------                            <----------                 <----------
         |
         |
     list.jsp

    - 2개의 jar 파일을 build path 로 설정하지 않고 WEB-INF/lib 폴더에 jar 복사한다.
      자동으로 build path 됨.

'Programming > JSP' 카테고리의 다른 글

JSP 5일차 - MyBatis 연동  (0) 2024.05.24
JSP 5일차  (0) 2024.05.24
JSP 3일차  (0) 2024.05.22
JSP - 2일차  (0) 2024.05.21
JSP 1일차  (0) 2024.05.20