• 티스토리 홈
  • 프로필사진
    Song hyun
  • 방명록
  • 공지사항
  • 태그
  • 블로그 관리
  • 글 작성
Song hyun
  • 프로필사진
    Song hyun
    • 분류 전체보기 (780)
      • 백준 (0)
      • 영어 (2)
        • Diary (0)
        • Toast Masters (2)
      • 메모 (13)
      • 설치 메뉴얼 (30)
      • Java (178)
      • MySQL (60)
      • JSP (67)
      • Springboot (46)
      • HTML,CSS, JS (71)
        • HTML (8)
        • CSS (12)
        • JavaScript (37)
        • HTML&CSS 스터디 (13)
      • C++ (7)
      • Linux (7)
      • JPA (34)
      • Kotlin (2)
      • Flutter (42)
      • Error Note (39)
      • 디자인 패턴 (12)
      • 디지털논리회로 (4)
      • 데이터베이스 시스템 (8)
      • 알고리즘 (7)
      • 운영체제 (3)
      • 이산수학 (3)
      • 인공지능 (1)
      • 자료 구조 (14)
        • 기본 개념 (14)
        • 자료구조 스터디 (0)
      • 💡My project (76)
        • 팩맨 : Java Swing 게임 제작 프로젝트 (6)
        • 네이트톡 : Java 소켓 통신 프로젝트 (4)
        • 포켓옥션 : HikariCP&JDBC CRUD 프.. (3)
        • 이지 부산 : BDIA-Devton 2024 프로.. (20)
        • 그린 유니버시티 : JSP를 사용한 학사관리 프로.. (1)
        • 애드 포커 : 웹 소켓과 Spring을 사용한 카.. (1)
        • 셸위 : 게임 친구 매칭 사이트 (21)
        • 다모아 : 개발자 중개 플랫폼 (20)
      • 📗스터디 (13)
        • CNN : 웹개발 스터디 (10)
        • Node&React로 유튜브 사이트 만들기 (3)
      • 📙독서 및 강연 기록 (36)
        • 강연 (14)
        • 독서 (22)
  • 방문자 수
    • 전체:
    • 오늘:
    • 어제:
  • 최근 댓글
      등록된 댓글이 없습니다.
    • 최근 공지
        등록된 공지가 없습니다.
      # Home
      # 공지사항
      #
      # 태그
      # 검색결과
      # 방명록
      • [JSP] 47. <JSP와 MVC 패턴을 사용한 to-do 프로젝트> (6)
        2024년 07월 10일
        • Song hyun
        • 작성자
        • 2024.07.10.:17
        728x90
        반응형

        [JSP] 47. <JSP와 MVC 패턴을 사용한 to-do 프로젝트> (6)

         

        [F12] -> Application 창에서 JSESSIONID를 확인할 수 있다.

         

         

        1. UserController

        package com.tenco.controller;
        
        import jakarta.servlet.ServletException;
        import jakarta.servlet.annotation.WebServlet;
        import jakarta.servlet.http.HttpServlet;
        import jakarta.servlet.http.HttpServletRequest;
        import jakarta.servlet.http.HttpServletResponse;
        import jakarta.servlet.http.HttpSession;
        
        import java.io.IOException;
        
        import com.mysql.cj.Session;
        import com.tenco.model.UserDAO;
        import com.tenco.model.UserDAOImpl;
        import com.tenco.model.UserDTO;
        
        // 주소설계
        // http://localhost:8080/mvc/user/
        @WebServlet("/user/*")
        public class UserController extends HttpServlet {
        	private static final long serialVersionUID = 1L;
            private UserDAO userDAO;
        
            public UserController() {
                super();
            }
            
            @Override
            public void init() throws ServletException {
            	userDAO=new UserDAOImpl();
            }
        
            // GET 방식으로 들어올 때,
            // http://localhost:8080/mvc/user/signUp --> 회원가입 페이지
            // http://localhost:8080/mvc/user/signIn --> 로그인 페이지
        	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        		String action = request.getPathInfo();
        		System.out.println("action : "+action);
        		switch(action) {
        		case "/signIn":
        			request.getRequestDispatcher("/WEB-INF/views/signIn.jsp").forward(request, response);
        			break;
        		case "/signUp":
        			request.getRequestDispatcher("/WEB-INF/views/signUp.jsp").forward(request, response);
        			break;
        		default:
        			response.sendError(HttpServletResponse.SC_NOT_FOUND);
        			break;
        		}
        	}
        	
        	
        	// 로그인 처리 기능
        	private void signIn(HttpServletRequest request, HttpServletResponse response) throws IOException {
        		// URL, 인증 검사, 유효성 검사, 서비스 로직, DAO --> 전달, 뷰 호출
        		String username=request.getParameter("username");
        		String password=request.getParameter("password");
        		
        		// 유효성 검사
        		if(username==null || password.trim().isEmpty()) {
        			response.sendRedirect("signIn?message=invalid");
        			return;
        		}
        		
        		// 빠른 검사
        		UserDTO user= userDAO.getUserByUsername(username);
        		if(user!=null && user.getPassword().equals(password)) {
        			HttpSession session = request.getSession();
        			session.setAttribute("principal", user);
        			// 로그인 --> todoForm 화면 이동 처리
        			response.sendRedirect("/mvc/todo/todoForm");
        			System.out.println("로그인 처리 완료");
        		} else {
        			response.sendRedirect("signIn?message=invalid");
        			
        		}
        		// null <--- 회원가입 x
        		// 비밀번호 == dto.getPassword();
        	}
        	
        	
        	// 회원 가입 기능
        	private void signUp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        		// 인증 검사 필요 없는 기능
        		String username = request.getParameter("username");
        		String password=request.getParameter("password");
        		String email=request.getParameter("email");
        		
        		// 방어적 코드 작성 (username)
        		if(username==null || username.trim().isEmpty()) {
        			request.setAttribute("errorMessage", "사용자 이름을 입력하시오.");
        			request.getRequestDispatcher("/WEB-INF/views/signUp.jsp").forward(request,response);
        			return;
        		}
        		
        		// 방어적 코드 작성 (password)
        		// 방어적 코드 작성 (email)
        		
        		UserDTO userDTO = UserDTO.builder()
        				.username(username)
        				.password(password)
        				.email(email)
        				.build();
        		
        		int resultRowCount = userDAO.addUser(userDTO);
        		System.out.println("resultRowCount : "+resultRowCount);
        		if(resultRowCount==1) {
        			response.sendRedirect("/mvc/user/signIn?message=success");
        		} else {
        			response.sendRedirect("/mvc/user/signUp?message=error");
        		}
        	}
        
        	// 로그인 기능 요청 (자원의 요청 -- GET 방식, 하지만 예외 처리 -> because of 보안)
        	// POST 요청 시 - 로그인 기능 구현, 회원 가입 기능 구현
        	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        		String action = request.getPathInfo();
        		System.out.println("action : "+action);
        		switch(action) {
        		case "/signIn":
        			// 로그인 페이지로 보내는 동작 처리
        			signIn(request,response);
        			break;
        		case "/signUp":
        			// 회원가입 페이지로 보내는 동작 처리
        			signUp(request,response);
        			break;
        		default:
        			response.sendError(HttpServletResponse.SC_NOT_FOUND);
        			break;
        		}
        	}
        
        
        }

         

        2. TodoController

        package com.tenco.controller;
        
        import jakarta.servlet.ServletException;
        import jakarta.servlet.annotation.WebServlet;
        import jakarta.servlet.http.HttpServlet;
        import jakarta.servlet.http.HttpServletRequest;
        import jakarta.servlet.http.HttpServletResponse;
        import jakarta.servlet.http.HttpSession;
        
        import java.io.IOException;
        
        import com.tenco.model.UserDTO;
        
        // .../mvc/todo/xxx
        @WebServlet("/todo/*")
        public class TodoController extends HttpServlet {
        	private static final long serialVersionUID = 1L;
        
            public TodoController() {
                super();
            }
        
            // http://localhost:8080/mvc/todo/todoForm
            // http://localhost:8080/mvc/todo/form
        	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        		String action = request.getPathInfo();
        		System.out.println("action : "+action);
        		switch (action) {
        		case "/todoForm": {
        			todoFormPage(request,response);
        			break;
        		}
        		default:
        			throw new IllegalArgumentException("Unexpected value: " + action);
        		}
        	}
        
        	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        		
        	}
        	
        	private void todoFormPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        		// 로그인 한 사용자만 접근을 허용하도록 설계
        				 HttpSession session=request.getSession();
        				 UserDTO principal= (UserDTO)session.getAttribute("principal");
        				 
        				 // 인증 검사
        				 if(principal==null) {
        					 // 로그인을 안 한 상태
        					 response.sendRedirect("/mvc/user/signIn?message=invalid");
        					 return;
        				 } 
        				 
        				 request.getRequestDispatcher("/WEB-INF/views/todoForm.jsp").forward(request, response);
        	}
        
        }

         

        3. TodoForm.jsp

        <%@ page language="java" contentType="text/html; charset=UTF-8"
            pageEncoding="UTF-8"%>
        <!DOCTYPE html>
        <html>
        <head>
        <meta charset="UTF-8">
        <title>새 할 일 추가</title>
        </head>
        <body>
        	<h1> Todo Page </h1>
        	<%-- http;//localhost:8080/mvc/todo/add --%>
        	<form action="add" method="POST">
        		<label for="title"> 제목 : </label>
        		<input type="text" id="title" name="title" value="코딩연습 무한반복"> <br><br>
        		
        		<label for="description"> 설명 : </label>
        		<textarea name="description" id="description" rows="20" cols="50">
        			그래야 성공하고 높은 연봉은 기본... 아니면 워라밸
        		</textarea> <br><br>
        		
        		<label for="dueDate"> 마감기한 : </label>
        		<input type="date" id="dueDate" name="dueDate" value="2024-07-11"> <br><br>
        		
        		<label for="completed"> 완료 여부 : </label>
        		<input type="checkbox" id="completed" name="completed"> <br><br>
        		<button type="submit">추가</button>
        	</form>
        	<br><br>
        	
        	<a href="list">목록으로 돌아가기</a>
        </body>
        </html>
        728x90
        반응형

        'JSP' 카테고리의 다른 글

        [JSP] 49. <JSP와 MVC 패턴을 사용한 to-do 프로젝트> (8)  (0) 2024.07.10
        [JSP] 48. <JSP와 MVC 패턴을 사용한 to-do 프로젝트> (7)  (0) 2024.07.10
        [JSP] 46. <JSP와 MVC 패턴을 사용한 to-do 프로젝트> (5)  (0) 2024.07.09
        [JSP] 45. <JSP와 MVC 패턴을 사용한 to-do 프로젝트> (4)  (0) 2024.07.09
        [JSP] 44. <JSP와 MVC 패턴을 사용한 to-do 프로젝트> (3)  (0) 2024.07.09
        다음글
        다음 글이 없습니다.
        이전글
        이전 글이 없습니다.
        댓글
      조회된 결과가 없습니다.
      스킨 업데이트 안내
      현재 이용하고 계신 스킨의 버전보다 더 높은 최신 버전이 감지 되었습니다. 최신버전 스킨 파일을 다운로드 받을 수 있는 페이지로 이동하시겠습니까?
      ("아니오" 를 선택할 시 30일 동안 최신 버전이 감지되어도 모달 창이 표시되지 않습니다.)
      목차
      표시할 목차가 없습니다.
        • 안녕하세요
        • 감사해요
        • 잘있어요

        티스토리툴바