자바34일차

달달한스위츠·2024년 4월 1일

자바배우기

목록 보기
31/43

오늘의 코드


<%@page import="web.ch15.board.BoardBean"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>게시글 조회</title>
</head>
<body>
	<%
		// request 객체에서 getAttribute를 이용하여 board 데이터 참조
		 BoardBean board = (BoardBean) request.getAttribute("board"); // 모든 자식들의 부모는 Bean그래서 형변환함
	%>
	
	<p>번호 : <%=board.getNo() %></p>
	<p>제목 : <%=board.getTitle() %></p>
	<p>작성자 : <%=board.getWriter() %></p>
	<p>내용 : <%=board.getContent() %></p>
	<p>작성일 : <%=board.getRegDate() %></p>
	
	
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
   pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>회원 가입</title>
</head>
<body>
   <!-- url 경로가 register인 servlet으로 데이터를 전송하는 JSP -->
   <!-- 
   		action="register" :
   		현재 jsp 파일의 위치는 /ch15/member
   		register 경로는 /ch15/member/register 경로로 인식
    -->
   <form action="register" method="POST">
      <p>아이디</p>
      <!-- input name : request parameter의 name -->
      <input type="text" name="userId" placeholder="아이디 입력"
         required="required">    
      <p>패스워드</p>
      <input type="password" name="password" placeholder="비밀번호 입력"
         required="required">    
      <p>이메일</p>
      <input type="email" name="email" placeholder="이메일 입력"
         required="required">    
      <p>이메일 수신여부</p>
      <input type="radio" name="emailAgree" value="yes"><input
         type="radio" name="emailAgree" value="no" checked="checked">아니오         
      <p>자기소개</p>

      <textarea rows="4" cols="30" name="introduce" placeholder="자기소개 입력"
         required="required"></textarea><br>
         <input type="submit" value="전송">
   </form>

</body>
</html>

-------------------board Bean

package web.ch15.board;

import java.util.*;

// 게시글 데이터(번호, 제목, 작성자, 작성일)를 전송하기 위한 Bean 클래스
public class BoardBean {
	private int no; // 번호
	private String title; // 제목
	private String writer; // 작성자
	private String content; // 내용
	private Date regDate; // 작성일
	
	// 기본 생성자
	public BoardBean() {}
	
	public BoardBean(int no, String title, String writer, Date regDate) {
		super();
		this.no = no;
		this.title = title;
		this.writer = writer;
		this.regDate = regDate;
	}
	
	// getter/setter
	public int getNo() {
		return no;
	}
	public void setNo(int no) {
		this.no = no;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getWriter() {
		return writer;
	}
	public void setWriter(String writer) {
		this.writer = writer;
	}
	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public Date getRegDate() {
		return regDate;
	}
	public void setRegDate(Date regDate) {
		this.regDate = regDate;
	}
	
	
	
}

package web.ch15.board;

import java.io.IOException;
import java.util.*;

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;

// 게시글 데이터 detail.jsp 페이지로 송신하는 역할
@WebServlet("/detail")
public class DetailServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    public DetailServlet() {
       
    }

	// url 요청은 doGet() 메소드를 호출
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// register.jsp로 전송할 데이터를 BoardBean 객체에 저장
		BoardBean board = new BoardBean();
		
		board.setNo(1);
		board.setTitle("테스트 게시글 입니다.");
		board.setWriter("목진혁");
		board.setContent("임의로 데이터를 작성하고 있습니다.");
		board.setRegDate(new Date());
		
		// request attribute 방식으로 객체 데이터 전송
		request.setAttribute("board", board);
		
		// ServletContext : 애플리케이션 정보 제공
		ServletContext context = getServletContext(); //상속받은 클래스
		// ServletContext 객체를 참조
		
		// RequestDispatcher : 클라이언트로부터 발생된 요청을 다른 경로의
		// 리소스(Serclet or jsp)로 전송하는 역활
		
		RequestDispatcher dispatcher =
					context.getRequestDispatcher("/ch15/board/detail.jsp");
		
		dispatcher.forward(request, response);
		// request와 response를 포워딩(전송)
	}

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

}
package web.ch15.board;

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;

// register.jsp에서 전송된 데이터를 수신하는 역할
@WebServlet("/ch15/member/register") // register.jsp form 요청 url과 매칭
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    
    public RegisterServlet() {
    	
    }

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

	// register.jsp의 form method="post"이므로 doPost()호출
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// form에서 보낸 Form Data는 request 객체에 저장되어 있음
		// request parameter로 데이터 참조
		
		// getParameter name : input name과 동일
		String userId = request.getParameter("userId");
		String password = request.getParameter("password");
		String email = request.getParameter("email");
		String emailAgree = request.getParameter("emailAgree");
		String introduce = request.getParameter("introduce");
		
		// DB 연결 생략
		System.out.println("userId = " + userId);
		System.out.println("password = " + password);
		System.out.println("email = " + email);
		System.out.println("emailAgree = " + emailAgree);
		System.out.println("introduce = " + introduce);
		
		
		
		
	}

}

------------------------------쿠키

<%@ 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>
	<form action="setCookie.jsp">
		성 : <input type="text" name="firstName"><br>
		이름 : <input type="text" name="lastName"><br>
		<br>
		<input type="submit" value="전송">
		
	</form>
	
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>쿠키 가져오기(GET)</title>
</head>
<body>
	<%
		Cookie[] cookies = request.getCookies();
	
		if(cookies != null) { // 쿠키가 존재하는 경우
			out.println("<h2>모든 쿠키의 이름과 값 찾기</h2>");
			for(Cookie cookie : cookies) {
				out.print("name : " + cookie.getName() + "<br>");
				out.print("value : " + cookie.getValue() + "<br>");
				out.print(cookie.getComment() + "<br>");
			}
		} else {
			out.println("<h2>쿠키를 찾지 못했습ㄴ디ㅏ.</h2>");
		}
		
				
	%>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>로그인</title>
</head>
<body>
	<%
	// 저장된 id, pw 쿠키를 꺼내서
	// input 태그(id, pw)에 값 보여주기
	String Id = "";
	String Pw = "";
	Cookie[] cookies = request.getCookies();

	if(cookies != null) { // 쿠키가 존재하는 경우
		out.println("<h2>모든 쿠키의 이름과 값 찾기</h2>");
		for(Cookie cookie : cookies) {
			String name = cookie.getName();
			String value = cookie.getValue();
			if(name.equals("id")) {
				Id = value;
			} else if (name.equals("pw")){
				Pw = value;
			}
		}
	} else {
		out.println("<h2>쿠키를 찾지 못했습ㄴ디ㅏ.</h2>");
	}
	%>
	<form action="practiceResult.jsp" method="post">
		아이디<br>
		<input type="text" name="id" value="<%= Id %>"><br>
		비밀번호<br>
		<input type="password" name="pw" value="<%= Pw %>"><br>
		<input type="checkbox" name="saveAgreed" value="agreed">
		아이디 저장<br><br>
		<input type="submit" value="로그인">
	</form>
	
</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>
	<%
	request.setCharacterEncoding("UTF-8");
	// practiceLogin.jsp에서 saveAgreed가 체크가 되어 있으면
	// id, pw에 대한 쿠키를 생성한다.
	// 쿠키 만료 시간은 10분으로 설정
	String agreed = request.getParameter("saveAgreed");
	if (agreed != null) {
		String id = request.getParameter("id");
		String pw = request.getParameter("pw");

		// 파라미터 값으로 쿠키 생성
		Cookie idCookie = new Cookie("id", id);
		Cookie pwCookie = new Cookie("pw", pw);

		// 만료 시간 설정(초단위) : 24시간
		idCookie.setMaxAge(60 * 10);
		pwCookie.setMaxAge(60 * 10);

		// response.header에 쿠키추가
		response.addCookie(idCookie);
		response.addCookie(pwCookie);
		// Context Root에서 생성된 쿠키는
		// 이프로젝트에서만 사용됨
	}
	%>

	<h2>로그인 결과 화면</h2>
	<p><%=request.getParameter("id")%>님, 환영합니다.
	</p>


</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSP cookie</title>
</head>
<body>
	<%
		request.setCharacterEncoding("UTF-8");
		String firstName = request.getParameter("firstName");
		String lastName = request.getParameter("lastName");
		
		// 파라미터 값으로 쿠키 생성
		Cookie firstNameCookie = new Cookie("firstName", firstName);
		Cookie lastNameCookie = new Cookie("lasrName", lastName);
		
		// 만료 시간 설정(초단위) : 24시간
		firstNameCookie.setMaxAge(60 * 60 * 24);
		lastNameCookie.setMaxAge(60 * 60 * 24);
		
		// response.header에 쿠키추가
		response.addCookie(firstNameCookie);
		response.addCookie(lastNameCookie);
		// Context Root에서 생성된 쿠키는
		// 이프로젝트에서만 사용됨
	%>
	
	
</body>
</html>

0개의 댓글