본문 바로가기
Programming/JSP

JSP 3일차

by yoon9i 2024. 5. 22.

##########################################################################################
3일차

1. 요청처리
- request.getParameter("name값"); // retrun 타입은 String.
                                  // name 하나당 value 하나 로 리턴.
- request.getParameterValues(String name) // String[](String 배열) 로 리턴.
                                          // name 과 value가 여러개면 이 방식을 사용.
  ex> checkbox
  동작방식은 check된 값만 서버에 전달이 된다.

- 이름을 먼저 조회하고 나중에 값을 얻을 수 있다.
  request.getParameterNames(); // Enumeration<String> 타입으로 return.


  * java.util.Iterator vs java.util.Enumeration

  가. Iterator 사용방법

  while(ite.hasNext()) {
    ite.next();
  }

  나. Enumeration 사용방법

  while(enu.hasMoreElements()) {
    enu.nextElements();
  }

// memberForm.jsp

<%@ 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>1. getParameter 메서드 실습-GET 방식</h1>

	http://localhost:8090/app5/memberForm.jsp
	--->
	http://localhost:8090/app5/member : 404 error 발생
	<br>
	<br>
	절대경로로 사용할려면 아래의 방식을 사용한다.<br>
	form 의 action을 /member 으로 한다면 무조건 컨텍스트명을 명시해야함.
	<br>
	action="/member" --> action="/app5/member"
	<br>
	<br>
	상대경로로 사용할려면 아래의 방식을 사용한다.<br>
	form action="member"
	<br>
	<form action="member" method="get">
		아이디: <input type="text" name="userid"><br>
		비번: <input type="text" name="passwd"><br>
		<input type="submit" value="가입">	
	</form>
	
	<h1>1-1. getParameter 메서드 실습-POST 방식</h1>
	http://localhost:8090/app5/memberForm.jsp<br>
	http://localhost:8090/app5/member2
	
	<form action="member2" method="post">
		아이디: <input type="text" name="userid"><br>
		비번: <input type="text" name="passwd"><br>
		<input type="submit" value="가입">	
	</form>
	
	<h1>2. getParameterValues 메서드 실습</h1>
	http://localhost:8090/app5/memberForm.jsp<br>
	http://localhost:8090/app5/member3
	
	<form action="member3" method="get">
		아이디: <input type="text" name="userid"><br>
		비번: <input type="text" name="passwd"><br>
		<br>
		취미:<br>
		야구: <input type="checkbox" name="hobby" value="야구"><br>
		농구: <input type="checkbox" name="hobby" value="농구"><br>
		축구: <input type="checkbox" name="hobby" value="축구"><br>
		<input type="submit" value="가입">	
	</form>
	
	<h1>3. getParameterNames 메서드 실습-GET 방식</h1>	
	<form action="member4" method="get">
		아이디: <input type="text" name="userid"><br>
		비번: <input type="text" name="passwd"><br>
		이메일: <input type="text" name="email"><br>
		<input type="submit" value="가입">	
	</form>
</body>
</html>
package com.servlet;

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

import javax.servlet.ServletConfig;
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("/member3")
public class MemberServlet3 extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("doGet");
		
		// POST 방식의 한글처리
		request.setCharacterEncoding("utf-8");
		
		String userid = request.getParameter("userid");
		String passwd = request.getParameter("passwd");
		
		// hobby
		String [] hobbies = request.getParameterValues("hobby");
		
		System.out.println("userid: " + userid);
		System.out.println("passwd: " + passwd); 
		System.out.println("hobby: " + Arrays.toString(hobbies));
	}
}
package com.servlet;

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

import javax.servlet.ServletConfig;
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("/member4")
public class MemberServlet4 extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("doGet");
		
		Enumeration<String> enu = request.getParameterNames();
		
		while(enu.hasMoreElements()) {
			String name = enu.nextElement();
			String value = request.getParameter(name);
			System.out.println(name+"\t"+value);
		}
	}
}



2. scope(lifecycle)
- 자바의 변수에서 사용했던 scope 와 비슷
  ex> 로컬변수: 메서드호출 ~ 메서드 종료
      인스턴스 변수: 객체생성 ~ 객체소멸
      클래스 변수(static): 프로그램 실행 ~ 프로그램 종료

- 서블릿에서 사용하는 3가지 scope
0> page scope(skip)
1> request scope
- HttpServletRequest 가 실체임
- 데이터 저장기능도 포함
- setAttribute(String name, Object o) 로 저장, 
  getAttribute(String name) 로 조회, 
  removeAttribute(String name) 로 삭제
- 저장된 데이터의 scope(lifecycle)?

                1번 요청                    SetServlet(저장)
    웹브라우저 ----------------------------> doGet(HttpServletRequest request, ...) {
                                                              request.setAttribute("xxx","홍길동");
                                                             }
              <----------------------------
                응답                          

                2번 요청                    GetServlet(조회)
            ------------------------------> doGet(HttpServletRequest request, ...) {
                                                         request.getAttribute("xxx"); // null 반환
                                                    }


2> session scope
- HttpSession 가 실체임
- 데이터 저장기능도 포함
- setAttribute(String name, Object o) 로 저장, 
  getAttribute(String name) 로 조회, 
  removeAttribute(String name) 로 삭제

- HttpSession 얻는 방법

    HttpSession session = request.getSession();
    HttpSession session = request.getSession(true);
    # Returns the current session associated with this request, or
    if the request does not hava a session, creates one.
    세션(session)이 있으면 현재 세션(session)을 반환하고 없으면 새로 생성해서 반환.
    ---------------------------------------------------------------------------
    HttpSession session = request.getSession(false);
    # If create is false and the request has no valid HttpSession, this method returns
    null.
    세션(session)이 있으면 현재 세션(session)을 반환하고 없으면 null 반환.

- 저장된 데이터의 scope(lifecycle)?
==> 동일한 웹브라우저와 scope 가 같다.
    즉, 요청한 웹브라우저를 close 하지 않으면 session 에 저장된 정보는 계속 유지된다.
    (요청한 웹브라우저를 close 할 때까지 유지함.)

                1번 요청                             SetServlet(저장)
    웹브라우저 ----------------------------> doGet(HttpServletRequest request, ...) {
    (크롬)                                                 request.setAttribute("xxx","이순신");
                                                          }
              <----------------------------
                응답

                2번 요청                       GetServlet(조회)
            ------------------------------> doGet(HttpServletRequest request, ...) {
                                                       request.getAttribute("xxx"); // 이순신 반환
                                                   }

                2번 요청                              GetServlet(조회)
    웹브라우저 ------------------------------> doGet(HttpServletRequest request, ...) {
    (엣지)                                                   request.getAttribute("xxx"); // null 반환
                                                              }

    - tomcat 이 요청하는 웹브라우저의 정보를 알고 있다.(JSESSIONID 값을 이용)

                            id전송
                            JSESSIONID=C1B185DA85AAB0A1FCFBA3485E01E3AA
        웹브라우저(크롬) ----------------------------> Tomcat (요청한 크롬웹브라우저 id 저장함.)
                            id전송
                            JSESSIONID=2931D0F56458BB6F042D045366A71652        
        웹브라우저(엣지) ----------------------------> Tomcat (요청한 엣지웹브라우저 id 저장함.)

    - time-out 설정
    이론적으로는 요청한 웹브라우저가 close 되지 않으면 서버에 저장된 세션(HttpSession)은
    제거되지 않는다.
    하지만 보안 이슈 때문에 요청한 웹브라우저가 close되지 않아도 일정 시간이 지나면
    자동으로 세션(HttpSession)을 삭제시킨다.
    (ex) 웹사이트에서 로그인하고 일정시간동안 아무런 활동을 하지 않으면 다시 로그인해야하는 현상
         을 얘기한다.
    
    tomcat 의 기본 time-out 은 30분이다.
    (servers > Tomcat v9.0 Server at localhost-config > web.xml 에 설정되어있음.)
    <기본>

            <session-config>
                <session-timeout>30</session-timeout>
            </session-config>

    * 개발자가 명시적으로 time-out 설정 가능.
    1> web.xml 에서 설정
        <명시적>
        - 프로젝트내의 src > main > webapp > WEB-INF > web.xml

            <session-config>
                <session-timeout>60</session-timeout>
            </session-config>

            로 명시적으로 time-out 사용가능.(단위: minute)

    2> 자바코드로 설정

        session.setMaxInactiveinterval(60); (단위: seconds)
        session.setMaxInactiveinterval(60*60); // 1시간(3600초)

    - 명시적으로 세션 데이터 삭제
    가. 세션 엔트리 삭제

        session.removeAttribute("key");
        - 장바구니에 저장된 요소 삭제하는 경우

    나. 세션 전체 삭제(HttpSession)

        session.invalidate();
        - 로그아웃할 때 사용

3> application scope
- ServletContext 가 실체임
- 데이터 저장기능도 포함
- setAttribute(String name, Object o) 로 저장, 
  getAttribute(String name) 로 조회, 
  removeAttribute(String name) 로 삭제
  getParameterNames() 로 name 부터 조회

- 저장된 데이터의 scope(lifecycle)?
==> Tomcat 과 scope 가 같다.
    (정확히는 Web Module에 올라간 실행중인 Context 와 scope 가 동일)

- ServletContext 얻는 방법
==> HttpServlet(사실은 ServletConfig 에서 제공) 에서 제공되기 때문에
    doGet 메서드내에서 getServletContext() 사용하면 된다.

    ex>
        doGet(,) {
            ServletContext application = getServletContext();
            application.setAttribute(String name, Object o);
        }

        doGet(,) {
            ServletContext application = getServletContext();
            application.setAttribute("application", "유관순");
        }

package com.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
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("/SetServlet")
public class SetServlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("SetServlet.doGet");
		
		// 3가지 scope 에 데이터 저장
		// 1. request scope 에 저장(HttpServletRequest request)
		request.setAttribute("request", "홍길동");
				
		// set 한것을 get 해서 응답처리
		String request_scope = (String)request.getAttribute("request");
		
		// 2. session scope 에 저장
		HttpSession session = request.getSession();
		// isNew(): 처음만든것이면 true , 이미 생성되어있다면 false
		System.out.println(session.isNew());
		
		session.setAttribute("session", "이순신");
		String session_scope = (String)session.getAttribute("session");
		
		// 3. application scope 에 저장
		ServletContext application = getServletContext();
		application.setAttribute("application", "유관순");
		String application_scope = (String)application.getAttribute("application");
		
		
		// 응답처리
		response.setContentType("text/html;charset=utf-8");
		
		PrintWriter out = response.getWriter();
		out.print("<html>");
		out.print("<head>");
		out.print("<title>Set</title>");
		out.print("</head<");
		out.print("<body>");
		out.print("request scope: " + request_scope);
		out.print("session scope: " + session_scope);
		out.print("session scope: " + application_scope);
		out.print("</body>");
		out.print("</html>");
	}
}
package com.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
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("/GetServlet")
public class GetServlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("GetServlet.doGet");
		
		// 3가지 scope 에서 데이터 조회
		
		// 1. request scope 에서 조회
		String request_scope = (String)request.getAttribute("request");
		
		// 2. session scope 에서 조회
		HttpSession session = request.getSession();
		String session_scope = (String)session.getAttribute("session");
		System.out.println(session.isNew());
		
		// 3. application scope 에서 조회
		ServletContext application = getServletContext();
		String application_scope = (String)application.getAttribute("application");
		
		// 응답처리
		response.setContentType("text/html;charset=utf-8");
		
		PrintWriter out = response.getWriter();
		out.print("<html>");
		out.print("<head>");
		out.print("<title>Set</title>");
		out.print("</head<");
		out.print("<body>");
		out.print("request scope: " + request_scope);
		out.print("session scope: " + session_scope);
		out.print("session scope: " + application_scope);
		out.print("</body>");
		out.print("</html>");
	}
}



3. JSP(Java Server Page)
1> 특징
- 동적 컴포넌트(서버에서 실행되어 동적으로 결과를 만듬.)
- *.jsp 확장자를 가짐.
- 서블릿은 요청하면 doGet|doPost 같은 서비스 메서드가 실행됨.
  JSP 는 요청하면 3단계를 거쳐서 실행됨.

  가. 변환단계
  jsp ----> .java (서블릿과 매우 유사한 코드임.)

  나. 컴파일단계
  *.java ------> *.class

  다. 실행단계
  *.class ------> 결과반환(결과는 html로 반환됨.)

  - JSP 내의 대부분의 코드는 html 이다.
    약간씩 자바코드가 포함된다.

    Servlet 의 대부분의 코드는 java 코드이다.
    약간씩 html가 포함된다.
    따라서 비즈니스 로직처리는 Servlet 이 더 잘함.


2> JSP 구성요소

가. html

# 다음 태그는 java 와 관련있는 태그이다.
나. JSP 태그
    * 종류
    - directive 태그
        -> page directive 태그: <%@ page 속성명="속성값" 속성명="속성값" ... %>
           JSP 에게 정보를 알려줄 때 사용된다.
           정보종류? contenType, 자바의 import, ....
        -> include directive 태그 <%@ include file="속성값" %>
        -> taglib directive 태그 <%@ taglib prefix="속성값" uri="속성값" %>

    - declaration 태그: <%! 자바코드 %>
        인스턴스변수/인스턴스 메서드(거의 사용안함.)
    - scriptlet 태그: <% 자바코드 %>
        서비스 메서드내에서 코드(사용빈도높음.)
    - expression 태그: <%= 변수(값) %>

<%@ 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;
%>
// jsp01_jsp.java 로 변경 ( 서블릿 )

package ~

import ~

public class 클래스명 extends ~{

    int num = 10; //인스턴스변수
    public void aaa(){} //인스턴스 메서드

	public void 서비스메서드명(HttpServletRequest request,
	                       HttpServletResponse response ){
	
	     String name="홍길동"; // 로컬변수
	
	     response.setContentType("text/html; charset=UTF-8");
	
		  ....
		  
		 out.print("<!DOCTYPE html>");
		 out.print("<html>");
		 out.print("안녕하세요");
	
	}


}



다. EL 태그
라. JSTL 태그

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

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