Sesac 15일차

SungMin·2022년 10월 25일
0

Sesac-Java/Spring

목록 보기
11/13

Session

  • 클라이언트에 대한 정보를 서버에 저장할 수 있는 공간
  • 접속하는 클라이언트 당 하나의 세션 생성
  • 사물함과 같은 형식으로 저장이 되며 사물함의 번호를 클라이언트로 전송
  • 번호를 분실하는 경우 새로운 세션을 생성하고 다시 클라이언트로 전송
  • 설문조사와 같이 여러단계로 입력된 정보, 로그인 정보 등
    클라이언트가 접속되어 있는 동안 내용을 기억해야 하는 경우에 활용

세션 페이지 구현

  • sessionController.java
package com.example.basic.controller;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import com.example.basic.model.User;

@Controller
public class SessionController {
    @GetMapping("sessionLogin") // sessionLogin페이지로 이동
    public String session(){
        return "sessionLogin";
    }

    @PostMapping("sessionLogin") // sessionLogin페이지에서 로그인 시도
    public String session(User user, HttpSession session) { // 세션을 이용하기 위한 매개변수 선언
        System.out.println("userId : "+user.getUserId());
        System.out.println("userPw : "+user.getUserPw());
        System.out.println("userName : "+user.getUserName());
        session.setAttribute("user", user); // 세션에 user데이터를 user라는 이름으로 저장
        return "redirect:/main"; // localhost:8080/main 으로 요청
    }

    @GetMapping("main")
    public String main(){
        return "main";
    }

    @GetMapping("logout")
    public String logout(HttpSession session){
        // session.removeAttribute("user"); // 특정 세션의 값을 지울 때 사용
        session.invalidate(); // 세션의 정보를 모두 제거
        return "redirect:/"; // localhost:8080 주소로 요청
    }
    
}
  • user.java
package com.example.basic.model;

import lombok.Data;

@Data
public class User {
    private String userId;
    private String userPw;
    private String userName;
    
}

  • sessionLogin.html
<html xmlns:th="http://www.thymeleaf.org">

<head>
</head>

<body>
    <h1> 세션 활용 예시 </h1>
    <hr/>
    <form action="/sessionLogin" method="post">
        <!-- input의 name값으로 파마리터를 줄 수도 있지만, java소스에서 model클래스 자체를 매개변수로 하고있다면, 
            model클래스의 멤버 변수와 name값을 일치시켜준다. -->
        <input type="text" placeholder="아이디" name="userId"/>
        <input type="password" placeholder="비밀번호" name="userPw"/>
        <input type="submit" value="로그인"/>
    </form>
</body>

</html>

  • home.html
<html xmlns:th="http://www.thymeleaf.org">

    <head> 
    </head>       

    <body> 
        <h1>Home 화면 입니다.</h1>
        <!-- 구구단 자동생성 링크를 지정해봅시다. 타임리프의 a태그(th:href)를 이용해서
            타임리프의 each문을 사용해서 구현해봅시다. -->
        <!-- 예시 :
            <a href="/gugudan?dan=2">구구단 자동생성 2단~2단</a> -->
        <th:block th:each="dan : ${#numbers.sequence(2, 9)}">
            <a th:href="@{/gugudan(dan=${dan})}">구구단 자동생성 2~[[${dan}]]단</a><br />
        </th:block>

        <!-- local:8080/userList 로 이동하도록 버튼을 추가해 봅시다. -->
        <a href="/userList">사용자 목록</a><br>
        <a href="/login3">로그인하기(세션이용X)</a><br>
        <th:block th:if="${session.user} == null">
            <a href="/sessionLogin">로그인하기(세션이용O)</a>
        </th:block>
        <th:block th:unless="${session.user} == null">
            <a href="/logout">로그아웃</a>
        </th:block>
    </body>

</html>

  • main.html
<html xmlns:th="http://www.thymeleaf.org">

<head>
</head>
<body>
    <h1>메인 페이지입니다.</h1>
    <hr />
    <th:block th:if="${session.user} != null">
        <p>[[${session.user.userId}]]님이 로그인 하셨습니다.</p>
    </th:block>
    <th:block th:unless="${session.user} != null">
        <p>로그인 정보가 존재하지 않습니다.</p>
    </th:block>
    <a href="/">홈으로 이동</a>
</body>

</html>

  • 출력 결과물





회원가입과 로그인

  • 회원가입 + 로그인 구현

  • HomeController.java
package com.example.sessac.first.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {
    @GetMapping("/")
    public String home(){
        return "home";
    }
}

  • UserController.java
package com.example.sessac.first.controller;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.example.sessac.first.model.User;

// 유저 관련된 요청을 처리하는 컨트롤러
//회원가입, 로그인, 로그아웃
@Controller
@RequestMapping("user") // http://localhost:8080/user
public class UserController {
    @GetMapping("join") // http://localhost:8080/user/join
    public String join() {
        return "user/join";
    }

    @PostMapping("join")
    public String join(HttpSession session, User user){
        session.setAttribute("joinUser", user);
        return "redirect:/";
    }

    @GetMapping("login")
    public String login(){
        return "user/login";
    }

    @PostMapping("login")
    public String login(HttpSession session, User user){
        // 세션에 저장된 회원 아이디
        User userData = (User) session.getAttribute("joinUser");
        String id = user.getUserId();
        String pw = user.getUserPw();
        //로그인 시도하는 계정 정보
        if (userData.getUserId().equals(id) && userData.getUserPw().equals(pw)){
            session.setAttribute("user", userData);
        } else {
            session.setAttribute("user", null);
        }
        return "redirect:/";
    }

    // 로그아웃 기능 구현 http://localhost:8080/user/logout
    @GetMapping("logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "redirect:/";
    }
}

  • home.html
<html xmlns:th="http://www.thymeleaf.org">

<head>
</head>

<body>
    <h1>Home 화면 입니다.</h1>
    <a href="/user/join">회원가입</a>|
    <th:block th:if="${session.user} == null">
        <a href="/user/login">로그인</a>
    </th:block>
    <th:block th:unless="${session.user} == null">
        <a href="/user/logout">로그아웃</a> | <span>[[${session.user.userName}]]님 환영합니다.</span>
        <a href="/board/boardList">게시판</a>
    </th:block>
</body>

</html>

  • join.html
<html xmlns:th="http://www.thymeleaf.org">

<head>
</head>

<body>
    <h1>- 회원가입 -</h1>
    <form action="/user/join" method="post">
        <input type="text" placeholder="아이디" name="userId" />
        <input type="text" placeholder="비밀번호" name="userPw" />
        <input type="text" placeholder="이름" name="userName" />
        <input type="text" placeholder="주소" name="userAddr" />
        <input type="submit" value="회원가입" />
    </form>
</body>

</html>

  • login.html
<html xmlns:th="http://www.thymeleaf.org">

<head>
</head>

<body>
    <h1>- 로그인 -</h1>
    <form action="/user/login" method="post">
        <input type="text" placeholder="아이디" name="userId" />
        <input type="text" placeholder="비밀번호" name="userPw" />
        <input type="submit" value="로그인" />
    </form>
</body>

</html>

  • 출력 결과물





게시판

  • 회원가입과 로그인을 하면 게시판을 이용할 수 있게 구현
  • 게시글 목록과 내용, 작성, 수정 기능을 구현

  • BoardController.java
package com.example.sessac.first.controller;

import java.util.ArrayList;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.example.sessac.first.model.Board;
import com.example.sessac.first.model.User;

@Controller
@RequestMapping("board")
public class BoardController {
    @GetMapping("boardList") //게시글 목록 조회
    public String boardList(HttpSession session, Model model){
        if(session.getAttribute("boardList") != null){ 
            // 게시글 작성이 되었거나, 게시글이 존재할 때
            model.addAttribute("boardList", session.getAttribute("boardList"));
        }else{
            // 게시판에 글이 없는 상태
            model.addAttribute("boardList", null);
        }
        return "board/boardList";
    }

    @GetMapping("boardCreate") // 게시글 작성 페이지
    public String boardCreate(){
        return "board/boardCreate";
    }

    @PostMapping("boardCreate") // 게시글 작성 요청
    public String boardCreate(HttpSession session, Board board){
        ArrayList<Board> boardList = new ArrayList<>(); // 게시글을 담기 위한 리스트 생성
        board.setBoardNo("1"); //파라미터에 게시글 번호는 없었기 때문에 추가
        User user = (User) session.getAttribute("user");
        board.setBoardWriter(user.getUserName());
        boardList.add(board); // 게시글 리스트에 생성한 게시글 저장
        System.out.println(" boardList : "+boardList); // 게시글 정보 확인
        session.setAttribute("boardList", boardList); // 세션에 게시글 목록 저장
        return "redirect:/board/boardList";
    }

    @GetMapping("boardDetail") //게시글 상세보기
    public String boardDetail(HttpSession session, Model model, @RequestParam("boardNo") String boardNo){
        ArrayList<Board> boardList = (ArrayList<Board>) session.getAttribute("boardList");
        for(Board board : boardList){
            if (board.getBoardNo().equals(boardNo)){
                model.addAttribute("board", board);
            }
        }

        return "board/boardDetail";
    }

    @GetMapping("boardUpdate")
    public String boardupdate(HttpSession session, @RequestParam("boardNo") String boardNo, Model model){
        // 수정하고자 하는 페이지의 글 정보를 가져온다.
        // boardCreate페이지를 참고하는데
        // textArea 태그 안에 글 정보가 있어야 한다.
        ArrayList<Board> boardList = (ArrayList<Board>) session.getAttribute("boardList");
        for(Board board : boardList){
            if (board.getBoardNo().equals(boardNo)){
                model.addAttribute("board", board);
            }
        }
        return "board/boardUpdate";
    }

    @PostMapping("boardUpdate")
    public String boardUpdate(HttpSession session, Board board){
        ArrayList<Board> boardList = new ArrayList<>(); // 게시글을 담기 위한 리스트 생성
        boardList.add(board); // 게시글 리스트에 생성한 게시글 저장
        System.out.println(" boardList : "+boardList); // 게시글 정보 확인
        session.setAttribute("boardList", boardList); // 세션에 게시글 목록 저장
        return "redirect:/board/boardList";
    }
}

  • boardList.html
<html xmlns:th="http://www.thymeleaf.org">

<head>
</head>
<!-- th:each를 사용해서 게시글의 정보를 나타내는 페이지로 수정-->

<body>
    <table border="1">
        <tr>
            <td>게시글번호</td>
            <td>게시글제목</td>
            <td>작성자</td>
        </tr>
        <th:block th:if="${boardList} !=null">
            <tr th:each="board : ${boardList}">
                <td th:text="${board.boardNo}"></td>
                <td>
                    <a th:href="@{/board/boardDetail(boardNo=${board.boardNo})}">[[${board.boardTitle}]]</a>
                </td>
                <td th:text="${board.boardWriter}"></td>
            </tr>
        </th:block>
        <th:block th:unless="${boardList} != null">
            <tr>
                <td colspan="3">게시글이 존재하지 않습니다.</td>
            </tr>
        </th:block>
    </table>
    <a href="/board/boardCreate">글쓰기</a>
</body>

</html>

  • boardDetail.html
<html xmlns:th="http://www.thymeleaf.org">

<head>
</head>

<body>
    <h1>- 게시글 상세보기 -</h1>
    <h3>작성자 : [[${board.boardWriter}]]</h3>
    <h3>글 제목</h3>
    <textarea name="boardTitle" style="width:100%;"  readonly>[[${board.boardTitle}]]</textarea>
    <h3>글 내용</h3>
    <textarea name="boardContent" style="width:100%; height:200px;" readonly>[[${board.boardContent}]]</textarea>
    <a href="/board/boardList">목록으로</a> <a th:href="@{/board/boardUpdate(boardNo=${board.boardNo})}">글수정</a>
</body>

</html>

  • boardCreate.html
<html xmlns:th="http://www.thymeleaf.org">

<head>
</head>

<body>
    <h1>- 게시글 작성 -</h1>
    <form action="/board/boardCreate" method="post">
        <h3>작성자 : [[${session.user.userName}]]</h3>
        <h3>글 제목</h3>
        <textarea name="boardTitle" style="width:100%;"></textarea>
        <h3>글 내용</h3>
        <textarea name="boardContent" style="width:100%; height:200px;"></textarea>
        <input type="submit" value="게시글작성"/>
    </form>
</body>

</html>

  • boardUpdate.html
<html xmlns:th="http://www.thymeleaf.org">

<head>
</head>

<body>
    <h1>- 게시글 수정 -</h1>
    <form action="/board/boardUpdate" method="post">
        <input type="hidden" name="boardNo" value="@{board.boardNo}"/>
        작성자 : <input type="text" name="boardWriter" th:value="${session.user.userName}"/>
        <h3>글 제목</h3>
        <textarea name="boardTitle" style="width:100%;">[[${board.boardTitle}]]</textarea>
        <h3>글 내용</h3>
        <textarea name="boardContent" style="width:100%; height:200px;">[[${board.boardContent}]]</textarea>
        <input type="submit" value="게시글수정"/>
    </form>
</body>

</html>

  • 출력 결과물







profile
초보 개발자의 학습 저장용 블로그

0개의 댓글