[필기정리]Day75 - Servlet 생명주기, session 등

Web/JSP

2020. 10. 13. 10:56

# Servlet 생명주기

 

[JSP/Servlet] Servlet 생명주기 ( Life Cycle )

1. Servlet 생명 주기 ( Life Cycle ) 클라이언트가 Servlet에 요청을 하면, Servlet은 바로 호출이 되지 않습니다. Servlet은 객체를 생성하고 초기화 작업을 거친 후, 요청을 처리하는 생명 주기를 갖고 있

victorydntmd.tistory.com

- 실행순서 : Constructor → @PostConstructinit(한번만 실행) → Service(새로고침 시 계속 추가됨)

                → destroy(서버 종료 시) → @PreDestroy

ex)

package com.superman.ex;

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

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
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("/ServletLifeCycle")
public class ServletLifeCycle extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

    public ServletLifeCycle() {
        super();
        System.out.println("Constructor");
    }
    
	@PostConstruct // constructor 후에 실행
	private void initPostConstruct() {
		System.out.println("initPostConstruct");
	}

	public void init(ServletConfig config) throws ServletException {
		System.out.println("init");
	}

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("service");
		response.setContentType("text/html; charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE html>");
		out.println("<html>");
		out.println("<head>");
		out.println("<title>service</title>");
		out.println("</head>");
		out.println("<body>");
		out.println("service");
		out.println("</body>");
		out.println("</html>");
	}
	
	public void destroy() {
		System.out.println("destroy");
	}
	
	@PreDestroy
	private void destoryPreDestory() {
		System.out.println("destoryPreDestory");
	}
}

 

- JSP 저장 영역 종류

영역 영역객체 설명
page pageContext 한 번의 요청에 대해 하나의 JSP 페이지가 호출되고
객체를 하나의 JSP 페이지 내에서만 공유
request request 한 번의 요청에 대해 같은 요청을 공유하는 페이지가 대응
ex) 페이지 모듈화
session session 하나의 웹 브라우저 당 1개의 세션 객체 생성
같은 웹 브라우저 내 페이지들은 같은 객체 공유
ex) 로그인
application application 하나의 어플리케이션 당 1개의 어플리케이션 객체가 생성
같은 어플리케이션 내 페이지들은 같은 객체 공유

 

- 내장객체의 속성

메소드 반환형 설명
setAttribute
(String name, Object value)
void 이름이 name인 속성 값을 value로 지정
객체만 저장 가능
getAttribute(String name) Object 이름이 name인 속성 값을 구하는 것
존재하지 않는 경우 null값 반환
removeAttribute(String name) void 이름이 name인 속성 삭제
getAttributeNames() Enumeration 속성의 이름 목록 구하기
(pageContext 제외)


# session(세션) : JSP 내장객체 중 하나

 

[JSP] 웹에서 세션(session)의 사용

웹에서 세션(session)의 사용 1. 세션(session)의 개요 쿠키가 웹 브라우저에 사용자의 상태를 유지하기 위한 정보를 저장했다면, 세션(session)은 웹 서버 쪽의 웹 컨테이너에 상태를 유지하기 위한 정�

hyeonstorage.tistory.com

- 세션 속성

① 속성 값은 객체 형태만 올 수 있다.

② 세션 객체는 웹 브라우저와 매핑되므로 해당 웹 브라우저를 닫지 않는 한 모두 같은 세션 객체를 공유한다.

메소드 설명 예시
setAttribute() 속성 설정 session.setAttribute("id", "value");
getAttribute() 속성 사용 String id = (String)session.getAttribute("id");
removeAttribute() 특정 속성 삭제 session.removeAttribute("id");
invalidate() 모든 속성 삭제 session.invalidate();

Q1.

 아이디와 비밀번호를 입력받아 아이디랑 비밀번호가 일치하면 id라는 이름으로 입력받아 id의 세션을 만들자.

    로그아웃도 구현하자.

    위 내용을 구성하는데,

    login.jsp 한페이지에 세션이 없으면 아이디와 비밀번호를 입력받는 폼이 보이도록 하고,

    세션이 있으면 아이디(아이디의 값)님 환영합니다. 라는 문구와 로그아웃을 구현하자.

 번을 Servlet으로 구현하자.

 번 폼에서 세션유효시간을 10초로 주고 그 값을 출력해보자.

 번에서 세션유효시간이 끝나면 자동으로 로그인 페이지로 이동하게 하자.

 세션이 없으면 접근하지 못하는 페이지를 만들자.

A.

 

 세션설정

-loginTest.jsp

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

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="HTML Study">
<meta name="keywords" content="HTML,CSS,XML,JavaScript">
<meta name="author" content="coderbear">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert title here</title>
</head>
<body>
<%
	String id = (String)session.getAttribute("id"); // 반환형이 Object이므로 String으로 형변환
	if(id != null)
	{
%>
		<%=id %>님 안녕하십니까?
<%
	}
	else
	{	
%>
		로그인 되어있지 않습니다.
<%
	}
%>
</body>
</html>

- login.jsp

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

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="HTML Study">
<meta name="keywords" content="HTML,CSS,XML,JavaScript">
<meta name="author" content="coderbear">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="loginChk.jsp">
<%
	String id = (String)session.getAttribute("id");
	if(id == null)
	{
%>
아이디 : <input type="text" name="id">
비밀번호 : <input type="password" name="password">
<input type="submit" value="로그인">
<a href="memberRegister.jsp">회원가입</a><br>
<%
	}
	else{
%>
	<%=id %>님 환영합니다.<br>
	<a href="logout.jsp">로그아웃</a>&nbsp;<a href="memberModify.jsp">회원정보수정</a><br>
<%		
	}
%>
<a href="loginTest.jsp">loginTest</a>
</form>
</body>
</html>

- loginChk.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	session.setAttribute("id", request.getParameter("id"));
	response.sendRedirect("login.jsp");
%>

- logout.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	session.invalidate();	// 세션 무효화(지금 세션에 있는 내용을 모두 지움)
	//session.removeAttribute("id");	// 특정 속성의 세션을 무효화
	response.sendRedirect("login.jsp");
%>

// invalidate( ) : 지금 세션에 있는 모든 내용을 지움

   removeAttribute( ) : ( )안에 있는 특정 속성의 세션 내용만 지움

 

 Servlet 세션설정

      서블릿은 세션이 기본객체가 아니기 때문에 request.getSession() 사용하여 불러와야 한다.

- Login.java

package com.superman.ex;

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

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("/Login")
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public Login() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession(); // 세션 객체를 가지고 옴
		out.println("<!DOCTYPE html>");
		out.println("<html>");
		out.println("<head>");
		out.println("<meta charset='UTF-8'>");
		out.println("<meta name='description' content='HTML Study'>");
		out.println("<meta name='keywords' content='HTML,CSS,XML,JavaScript'>");
		out.println("<meta name='author' content='coderbear'>");
		out.println("<meta name='viewport' content='width=device-width, initial-scale=1.0'>");
		out.println("<title>Insert title here</title>");
		out.println("</head>");
		out.println("<body>");
		out.println("<form method='post' action='LoginChk'>");
		String id = (String)session.getAttribute("id");
		if(id == null)
		{
			out.println("아이디 : <input type='text' name='id'>");
			out.println("비밀번호 : <input type='password' name='password'>");
			out.println("<input type='submit' value='로그인'>");
			out.println("<a href='memberRegister.jsp'>회원가입</a>");
		}
		else{
			out.println(id + "님 환영합니다.<br>");
			out.println("<a href='Logout'>로그아웃</a>&nbsp;<a href='memberModify.jsp'>회원정보수정</a>");
		}
		out.println("</form>");
		out.println("</body>");
		out.println("</html>");		
	}
}

- LoginChk.java

package com.superman.ex;

import java.io.IOException;

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("/LoginChk")
public class LoginChk extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public LoginChk() {
        super();
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		session.setAttribute("id", request.getParameter("id"));
		response.sendRedirect("Login");
	}

}

- Logout.java

package com.superman.ex;

import java.io.IOException;
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("/Logout")
public class Logout extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public Logout() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		session.invalidate();
		//session.removeAttribute("id");
		response.sendRedirect("Login");
	}

}

 

③ 세션 유효시간

- SessionForm.jsp

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

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="HTML Study">
<meta name="keywords" content="HTML,CSS,XML,JavaScript">
<meta name="author" content="coderbear">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert title here</title>
</head>
<body>
<%
	String id = (String)session.getAttribute("id");
	if(id==null)
	{
%>
<form method="post" action="SessionFormOK.jsp">
아이디 : <input type="text" name="id"><br>
비밀번호 : <input type="password" name="password"><br>
<input type="submit" value="로그인">
<%
	}
	else{
%>
<%=id %>님 환영합니다.<br>
<%= session.getMaxInactiveInterval() %>
<!-- 세션의 유효시간을 얻어오기 리턴된 단위는 초-->
<%
	}
%>
</form>
</body>
</html>

- SessionFormOK.jsp

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

<%
	session.setMaxInactiveInterval(10); // 어떠한 요청도 없는 경우 10초 후 세션 만료하겠다는 의미
	// 세션 최대시간 설정 단위는 초 (서버 기본 설정은 30분)
	session.setAttribute("id", request.getParameter("id"));
	response.sendRedirect("SessionForm.jsp");
%>

 

④ 세션 유효시간 후 자동이동

- SessionForm.jsp

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

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="HTML Study">
<meta name="keywords" content="HTML,CSS,XML,JavaScript">
<meta name="author" content="coderbear">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert title here</title>
</head>
<body>
<%
	String id = (String)session.getAttribute("id");
	if(id==null)
	{
%>
<form method="post" action="SessionFormOK.jsp">
아이디 : <input type="text" name="id"><br>
비밀번호 : <input type="password" name="password"><br>
<input type="submit" value="로그인">
<%
	}
	else{
%>
<%=id %>님 환영합니다.<br>
<%= session.getMaxInactiveInterval() %>
<!-- 세션의 유효시간을 얻어오기 리턴된 단위는 초-->
<%
	}
%>
</form>
</body>
</html>

- SessionTest.jsp

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

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="HTML Study">
<meta name="keywords" content="HTML,CSS,XML,JavaScript">
<meta name="author" content="coderbear">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert title here</title>
</head>
<body>
<h3>SessionTest 페이지 입니다.</h3>
<script>
function expireSession()
{
  location.href = "SessionForm.jsp";
}
setTimeout(expireSession, <%= request.getSession().getMaxInactiveInterval() * 1000 %>);
</script>
</body>
</html>

- SessionTest.jsp

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

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="HTML Study">
<meta name="keywords" content="HTML,CSS,XML,JavaScript">
<meta name="author" content="coderbear">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert title here</title>
</head>
<body>
<h3>SessionTest 페이지 입니다.</h3>
<script>
function expireSession()
{
  location.href = "SessionForm.jsp";
}
setTimeout(expireSession, <%= request.getSession().getMaxInactiveInterval() * 1000 %>); // 유효시간을 가져옴
</script>
</body>
</html>

// Tip - 1000을 곱하는 이유 : 기준이 ms이기 때문에 5초를 만들기 위해 1000을 곱해주는 것이다

// Tip : setTimeout을 이용해 애니메이션 등을 만들어 응용도 가능하다.

 

⑤ 세션이 없는 경우 접근 불가 예시

- login.jsp

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

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="HTML Study">
<meta name="keywords" content="HTML,CSS,XML,JavaScript">
<meta name="author" content="coderbear">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="loginChk.jsp">
<%
	String id = (String)session.getAttribute("id");
	if(id == null)
	{
%>
아이디 : <input type="text" name="id">
비밀번호 : <input type="password" name="password">
<input type="submit" value="로그인">
<a href="memberRegister.jsp">회원가입</a><br>
<%
	}
	else{
%>
	<%=id %>님 환영합니다.<br>
	<a href="logout.jsp">로그아웃</a>&nbsp;<a href="memberModify.jsp">회원정보수정</a><br>
<%		
	}
%>
<a href="loginTest.jsp">loginTest</a>
</form>
</body>
</html>

- loginChk.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	session.setAttribute("id", request.getParameter("id"));
	response.sendRedirect("login.jsp");
%>

- loginTest.jsp

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

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="HTML Study">
<meta name="keywords" content="HTML,CSS,XML,JavaScript">
<meta name="author" content="Bruce">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert title here</title>
</head>
<body>
<%
	String id = (String)session.getAttribute("id");
	if(id != null)
	{
%>
		<%=id %>님 안녕하십니까?
<%
	}
	else
	{	
%>
<script>
	alert("잘못된 접근입니다.");
	location.href="login.jsp";
</script>
<%
	}
%>
</body>
</html>

-logout.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	session.invalidate();	// 세션 무효화
	//session.removeAttribute("id");	// 특정 속성의 세션을 무효화
	response.sendRedirect("login.jsp");
%>

 

// 세션 vs 쿠키

 

[web] 쿠키(cookie)와 세션(session)의 개념/차이/용도/작동방식

[web] 쿠키(cookie)와 세션(session)의 개념/차이/용도/작동 쿠키와 세션을 이해하기 위해서는 먼저 http의 특징에 대해 이해하면 도움이 됩니다. 비연결성(Connectionless) HTTP(Hypertext Transfer Protocol..

devuna.tistory.com

  세션 : 웹 서버 쪽의 웹 컨테이너에 상태를 유지하기 위한 정보 저장

          사용자 정보 유지를 위해 javax.servlet.http 패키지의 HttpSession 인터페이스 구현해 사용

  쿠키 : 웹 브라우저에 사용자의 상태를 유지하기 위한 정보 저장

          웹 서버가 쿠키 정보를 읽어서 사용, 개인 정보 및 보안 이슈로 인해 쿠키 허용 여부를 사용자에게 물어봄   

          ∴ 세션을 사용한 웹 브라우저와 웹 서버의 상태를 유지하는 것이 안정적이며, 보안문제도 해결된다

구분 세션 쿠키
저장위치 server client
저장형식 Object text
종료시점 정확한 시점을 알 수 없음 쿠키 저장 시 설정
(브라우저 종료)
자원 서버 자원 클라이언트 자원
용량제한 제한없음 총 300개

 

- 세션 설정 방법

① 특정 경우에 타임아웃 설정

ex) 클라이언트가 20분동안 요청이 없으면 세션 제거

<%
session.setMaxInactiveInterval(20*60); // 초 단위
%>

② DD(Deployment Descriptor)에서 전체 세션 타임아웃을 설정

ex) 클라이언트가 15분동안 요청이 없으면 세션 제거 (파일위치 : web-inf/web.xml)

<web-app>
<session-config>
<session-timeout>15</session-timeout> // 분 단위
</session-config>
</web-app>

설정하지 않으면 WAS 기본 디폴트 값으로 적용

ex) Tomcat(conf/web.xml)30분입니다.

만약 1번과 2번이 적용되어 있다면 1번 방법으로 설정한 값으로 적용된다.

, 어플리케이션에서 10분으로 설정을 했다면

컨테이너나 웹서버에서 20 - 30분으로 설정을 해도 소용없다.

(우선순위 : 어플리케이션 > 컨테이너 > 웹서버)

 

// 세션 유지시간은 해당 세션을 생성한 사용자의 브라우저 요청이 있을 때마다 갱신됩니다.

ex) 따릉이 2시간 → 반납 후 다시 빌린 경우 2시간으로 다시 리셋

 

// 서버는 원본 파일을 따로 백업을 먼저하고 수정해야 한다

 

# 유효성 검사

ex)

- validation1.html

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Can Validate Input</h1>

<p>Please input a number between 1 and 10:</p>

<input id="numb">

<button type="button" onclick="myFunction()">Submit</button>

<p id="demo"></p>

<script>
function myFunction() {
    var x, text;

    // Get the value of the input field with id="numb"
    x = document.getElementById("numb").value;

    // If x is Not a Number or less than one or greater than 10
    if (isNaN(x) || x < 1 || x > 10) { // isNaN : 숫자가 아니면 true, 숫자면 false 반환 
        text = "Input not valid";
    } else {
        text = "Input OK";
    }
    document.getElementById("demo").innerHTML = text;
}
</script>

</body>
</html>

- validation2.html

<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
    var x = document.forms["myForm"]["fname"].value;
    if (x == "") {
        alert("Name must be filled out");
        return false; // false가 되면 submit 되지 않는다
    }
}
</script>
</head>
<body>

<form name="myForm" action="hello.htm"
onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

</body>
</html>

- hello.html

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

 

Q2.

숫자를 1 부터 10 사이의 값을 입력받을 수 있도록 input을 만들자. 입력필수. (유효성 검사를 html5로 한다.)
번 문제의 input type="text"로 하고 유효성 검사를 javascript로 한다. 입력필수.
 비밀번호와 비밀번호확인을 만들고 두 값이 다르면 submit을 하지 않도록 javascript로 유효성 검사를 한다.

A. 강사님의 답

- test1.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test1</title>
</head>
<body>
<form method="post" action="hello.htm">
	<input type="number" min="2" max="10" step="2" required>
	<input type="submit" value="전송">
</form>
</body>
</html>

- test2.html

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

</head>
<body>
<form name="myForm" method="post" action="hello.htm" onsubmit="return validation()">
	<input type="text" name="number">
	<input type="submit" value="전송">
</form>
<script>
	function validation()
	{
	    var x = document.forms["myForm"]["number"].value;

	    if (isNaN(x) || x < 1 || x > 10 || x=="") {
	       alert("Input not valid");
	       return false;
	    } else {
	        alert("Input OK");
	        return true;
	    }
	}
</script>
</body>
</html>

- test3.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form name="myForm" method="post" action="hello.htm" onsubmit="return validation()">
	비밀번호 : <input type="password" name="password"><br>
	비밀번호확인 : <input type="password" name="passwordChk"><br>
	<input type="submit" value="전송">
</form>
<script>
	function validation()
	{
	    var password = document.forms["myForm"]["password"].value;
	    var passwordChk = document.forms["myForm"]["passwordChk"].value;

	    if (password != passwordChk) {
	       alert("비밀번호가 일치하지 않습니다.");
	       return false;
	    } 
	}
</script>
</body>
</html>

- hello.html

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

A. 내가 생각한 답

- inputNumber.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>input Number</title>
</head>
<body>
	<p>1부터 10 사이의 원하는 숫자를 입력해주세요.</p>
	<form>
    	<input type="text" id="number" required>
    </form>
	<button type="button" onclick="myFuntion()">submit</button>
	<p id="contents"></p>
	
	<script type="text/javascript">
		function myFuntion() {
			var x, text;
			x = document.getElementById("number").value;
			if(isNaN(x) || x < 1 || x > 10) {
				text = "유효하지 않은 입력입니다.";
			} else {
				text = "입력이 완료되었습니다.";
			}
			document.getElementById("contents").innerHTML = text;
		}	
	</script>
</body>
</html>

- checkPassword.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Check Password</title>
</head>
<body>
	<form onSubmit="return checkPassword()">
	<input type="password" id="password" required>
	<input type="password" id="checkPassword" required>
	<input type="submit" value="submit">
    </form>
	<p id="contents"></p>
	
	<script type="text/javascript">
		function checkPassword() {
			var pw, checkPw;
			pw = document.getElementById("password").value;
            checkPw = document.getElementById("checkPassword").value;
			if(pw != checkPw) {
				alert("비밀번호가 일치하지 않습니다.");
				return false;
			} 
		}	
	</script>
</body>
</html>

 

Q3.

main.jsp 로그인화면.png3.main.jsp로그인된 화면.png를 참고하여 main.jsp를 만든다.

    로그인 처리는 LoginOK라는 서블릿으로 처리한다.

    로그아웃은 Logout이라는 서블릿으로 처리한다.

 memberRegister.htm 회원가입화면.png을 참고하여 회원가입을 만든다.

    회원가입처리는 MemberRegisterOK라는 서블릿으로 처리한다.

 memberModify.jsp 회원정보 수정화면.png를 참고하여 회원정보 수정페이지를 만든다.

   회원정보처리는 MemberRegisterOK 서블릿에서 처리한다.

④ error를 처리하는 error.jsp페이지를 만든다.

main.jsp 로그인 화면
memberRegister.html 회원가입 화면
main.jsp 로그인된 화면
memberModify.jsp 회원정보 수정 화면

A. 내가 생각한 답

- main.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login main</title>
</head>
<body>
	<form method="get" action="/LoginOK">
		<table>
			<tr>
				<td>아이디:</td>
				<td><input type="text" name="id" id="id" required></td>
			</tr>
			<tr>
				<td>비밀번호:</td>
				<td><input type="password" name="pw" id="pw" required></td>
			</tr>
			<tr>
				<td>
					<input type="submit" name="login" value="로그인">
					<a href="memberRegister.html">회원가입</a>
				</td>
			</tr>
		</table>
	</form>
</body>
</html>

- LoginOK.java

package com.tistory.coderbear;

import java.io.IOException;

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("/LoginOK")
public class LoginOK extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public LoginOK() {
        super();
    }

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE html>");
		out.println("<html>");
		out.println("<head>");
		out.println("<title>LoginOk</title>");
		out.println("</head>");
		out.println("<body>");
		out.println("<p>"+request.getParameter("id")+"님 환영합니다"+"</p>");
		out.println("<br>");
		out.println("<a href='/Logout'>로그아웃</a>");
		out.println("<a href='memberModify.jsp'>개인정보수정</a>");
		out.println("</body>");
		out.println("</html>");
	}
}

- Logout.java

package com.tistory.coderbear;

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

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("/Logout")
public class Logout extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public Logout() {
        super();
    }

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE html>");
		out.println("<html>");
		out.println("<head>");
		out.println("<title>Logout</title>");
		out.println("</head>");
		out.println("<body>");
		out.println("<p>로그아웃이 완료되었습니다.</p>");
		out.println("<a href='main.jsp'>로그인하기</a>");
		out.println("</body>");
		out.println("</html>");
	}
}

- memberResister.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Join Board</title>
</head>
<body>
	<h2>회원가입</h2>
	<form method="post" action="/MemberRegisterOK">
    	<input type="hidden" name="mode" value="1">
		<table>
			<tr>
				<td>이름</td>
				<td><input type="text" name="name" id="name" required></td>	
			</tr>
			<tr>
				<td>아이디</td>
				<td><input type="text" name="id" id="id" required></td>	
			</tr>
			<tr>
				<td>비밀번호</td>
				<td><input type="password" name="password" id="password" required></td>	
			</tr>
			<tr>
				<td>비밀번호확인</td>
				<td><input type="password" name="password2" id="password2" required></td>	
			</tr>
			<tr>
				<td>성별</td>
				<td>
					<input type="radio" name="gender" id="male" value="male">
					<label for="male">남</label>
					<input type="radio" name="gender" id="female" value="female">
					<label for="female">여</label>
				</td>	
			</tr>
			<tr>
				<td>이메일</td>
				<td><input type="email" name="email" id="email" required></td>	
			</tr>
			<tr>
				<td>취미</td>
				<td>
					<input type="checkbox" name="hobby" id="swimming" value="swimming">
					<label for="swimming">수영</label>
					<input type="checkbox" name="hobby" id="baseball" value="baseball">
					<label for="baseball">야구</label>
					<input type="checkbox" name="hobby" id="watchingMovie" value="watchingMovie">
					<label for="watchingMovie">영화감상</label>
					<input type="checkbox" name="hobby" id="listeningMusic" value="listeningMusic">
					<label for="listeningMusic">음악감상</label>
				</td>	
			</tr>
			<tr>
				<td>핸드폰</td>
				<td>
					<select name="phoneCompany">
						<option selected>010</option>
						<option>011</option>
						<option>016</option>
					</select>
					<input type="text" name="phoneNumber" id="phoneNumber">
				</td>	
			</tr>
			<tr>
				<td>
					<input type="submit" name="join">회원가입</button>
					<input type="reset" value="초기화">
				</td>	
			</tr>
		</table>
	</form>
</body>
</html>

- MemberResisterOK.java

package com.tistory.coderbear;

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

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("/MemberResisterOK")
public class MemberResisterOK extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public MemberResisterOK() {
        super();
    }

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
        String mode = request.getParameter("mode");
        if(mode.equals("1")) {
          out.println("<!DOCTYPE html>");
          out.println("<html>");
          out.println("<head>");
          out.println("<title>MemberResisterOK</title>");
          out.println("</head>");
          out.println("<body>");
          out.println("<p>회원가입이 완료되었습니다.</p>");
          out.println("<p>다시 로그인 해주세요.</p>");
          out.println("<br>");
          out.println("<a href='main.jsp'>로그인</a>");
          out.println("</body>");
          out.println("</html>");
          HttpSession session = request.session();
          session.setAttribute("name",request.getParameter("name"));
          session.setAttribute("id",request.getParameter("id"));
          session.setAttribute("password",request.getParameter("password"));
          session.setAttribute("gender",request.getParameter("gender"));
          session.setAttribute("email",request.getParameter("email"));
          session.setAttribute("hobby",request.getParameter("hobby"));
          session.setAttribute("phoneNumber",request.getParameter("phoneNumber"));
        } else if(mode.equals("2")) {
          out.println("<!DOCTYPE html>");
          out.println("<html>");
          out.println("<head>");
          out.println("<title>MemberResisterOK</title>");
          out.println("</head>");
          out.println("<body>");
          out.println("<p>회원정보 수정이 완료되었습니다.</p>");
          out.println("<br>");
          out.println("<a href='main.jsp'>로그인</a>");
          out.println("</body>");
          out.println("</html>");
        }

	}
}

- memberModify.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Member Modify</title>
</head>
<body>
<%
	String name = session.getAttribute("name");
    String id = session.getAttribute("id");
    String gender = session.getAttribute("gender");
    String email = session.getAttribute("email");
    String phoneCompany = session.getAttribute("phoneCompany");
    String phoneNumber = session.getAttribute("phoneNumber");
    
%>
	<h2>회원정보수정</h2>
	<form method="post" action="MemberRegisterOK">
   		<input type="hidden" name="mode" value="2">
		<table>
			<tr>
				<td>이름</td>
				<td><input type="text" name="name" value="<%= name%>" readonly></td>	
			</tr>
			<tr>
				<td>아이디</td>
				<td><input type="text" name="id" value="<%= id%>"></td>	
			</tr>
			<tr>
				<td>비밀번호</td>
				<td><input type="password" name="password" id="password" required></td>	
			</tr>
			<tr>
				<td>비밀번호확인</td>
				<td><input type="password" name="password2" id="password2" required></td>	
			</tr>
			<tr>
				<td>성별</td>
				<td>
                	<%
                    	if(gender.equals("male")) {
                    %>
					<input type="radio" name="gender" id="male" value="male" checked>
					<label for="male">남</label>
					<input type="radio" name="gender" id="female" value="female">
					<label for="female">여</label>
                    <%
                    	} else {
                    %>
                    <input type="radio" name="gender" id="male" value="male">
					<label for="male">남</label>
					<input type="radio" name="gender" id="female" value="female" checked>
					<label for="female">여</label>
                    <%
                    	}
                    %>
				</td>	
			</tr>
			<tr>
				<td>이메일</td>
				<td><input type="email" name="email" id="email" required></td>	
			</tr>
			<tr>
				<td>취미</td>
				<td>
					<input type="checkbox" name="hobby" id="swimming" value="swimming">
					<label for="swimming">수영</label>
					<input type="checkbox" name="hobby" id="baseball" value="baseball">
					<label for="baseball">야구</label>
					<input type="checkbox" name="hobby" id="watchingMovie" value="watchingMovie">
					<label for="watchingMovie">영화감상</label>
					<input type="checkbox" name="hobby" id="listeningMusic" value="listeningMusic">
					<label for="listeningMusic">음악감상</label>
				</td>	
			</tr>
			<tr>
				<td>핸드폰</td>
				<td>
					<select>
						<option selected>010</option>
						<option>011</option>
						<option>016</option>
					</select>
					<input type="text" name="phoneNumber" id="phoneNumber">
				</td>	
			</tr>
			<tr>
				<td>
					<button type="button" onclick="MemberRegisterOK.java" name="modify">정보수정</button>
					<input type="reset" value="초기화">
				</td>	
			</tr>
		</table>
	</form>
</body>
</html>

- error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Error</title>
</head>
<body>
	<p>에러가 발생했습니다.</p>
</body>
</html>
728x90