JX405기_비트/Spring Framework

Day45-3 스프링 프레임워크 게시판 만들기 ShowAll 페이지 만들기

_하루살이_ 2023. 3. 15. 22:00

index.jsp 설정하기

로그인 화면 만들기

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>인덱스</title>
</head>
<body>
    <form method="post" action="/user/auth">
        아이디 : <input type="text" name="username">
        비밀 번호 : <input type="password" name="password">
        <button type="submit">로그인</button>
    </form>
    <a href="/user/register">회원가입 하기</a>
</body>
</html>

 

 

 

UserDTO 추가하기

package com.bit.spring.model;

import lombok.Data;

@Data
public class UserDTO {
    private int id;
    private String username;
    private String password;
    private String nickname;
}

 

 

 

UserService에 auth 생성

package com.bit.spring.service;

import com.bit.spring.connector.MySqlConnector;
import com.bit.spring.model.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Service
public class UserService {
    private MySqlConnector connector;
    private Connection connection;
    @Autowired
    public UserService(MySqlConnector connector){
        this.connector = connector;
        connection = this.connector.makeConnection();

    }

    public UserDTO auth(UserDTO attempt){
        String query = "SELECT * FROM `user` WHERE `username` = ? AND `password` = ?";
        UserDTO userDTO = null;

        try {
            PreparedStatement preparedStatement = connection.prepareStatement(query);
            preparedStatement.setString(1, attempt.getUsername());
            preparedStatement.setString(2, attempt.getPassword());

            ResultSet resultSet = preparedStatement.executeQuery();

            if (resultSet.next()){
                userDTO = new UserDTO();
                userDTO.setId(resultSet.getInt("id"));
                userDTO.setUsername(resultSet.getString("username"));
                userDTO.setNickname(resultSet.getString("nickname"));

            }

            resultSet.close();
            preparedStatement.close();

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return userDTO;
    }
    
}

 

 

Servlet 추가 pom.xml

https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api/4.0.1

<dependency>
     <groupId>javax.servlet</groupId>
     <artifactId>javax.servlet-api</artifactId>
     <version>4.0.1</version>
     <scope>provided</scope>
</dependency>

 

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.bit</groupId>
    <artifactId>spring</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>16</maven.compiler.source>
        <maven.compiler.target>16</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.25</version>
        </dependency>
        
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.26</version>
            <scope>provided</scope>
        </dependency>
        
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <version>8.0.32</version>
        </dependency>
        
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

</project>

 

 

 

controller폴더에 UserController 생성하기

package com.bit.spring.controller;

import com.bit.spring.model.UserDTO;
import com.bit.spring.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user/")
public class UserController {
    private UserService userService;
    @Autowired
    public UserController(UserService userService){
        this.userService = userService;
    }

    // 로그인
    @PostMapping("auth")
    public String auth(HttpSession session, Model model, UserDTO attempt){
        UserDTO result = userService.auth(attempt);

        if (result != null) {
            session.setAttribute("logIn", result);
            return "/board/showAll";
        }
        else {
            model.addAttribute("message", "로그인 정보를 다시 확인해주세요.");
            return "index";
        }
        

    }

}

 

board/showAll로 왔지만 URL은 변하지 않음

 

 

 

 

redirect : /board/showAll로 변경

@PostMapping("auth")
    public String auth(HttpSession session, Model model, UserDTO attempt){
        UserDTO result = userService.auth(attempt);

        if (result != null) {
            session.setAttribute("logIn", result);
            return "redirect:/board/showAll";
        }
        else {
            model.addAttribute("message", "로그인 정보를 다시 확인해주세요.");
            return "index";
        }
        

    }

 

 

 

controller에 BoardController 생성

package com.bit.spring.controller;

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

@Controller
@RequestMapping("/board/")
public class BoardController {
    @GetMapping("showAll")
    public String showAll(){
        return "/board/showAll";
    }
}

URL 정상적으로 변경

 

 

 

 

BoardDTO 생성

package com.bit.spring.model;

import lombok.Data;

import java.sql.Date;

@Data
public class BoardDTO {
    private int id;
    private int writerId;
    private String title;
    private String content;
    private Date entryDate;
    private Date modifyDate;
}

 

 

 

 

BoardService 생성

package com.bit.spring.service;

import com.bit.spring.connector.MySqlConnector;
import com.bit.spring.model.BoardDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.*;
import java.util.ArrayList;

@Service
public class BoardService {
    private final int PAGE_SIZE = 15;
    private Connection connection;
    @Autowired
    public BoardService(MySqlConnector mySqlConnector){
        connection = mySqlConnector.makeConnection();
    }

    //특정 페이지 출력하기
    public ArrayList<BoardDTO> selectAll(int pageNo){
        ArrayList<BoardDTO> list = new ArrayList<>();
        String query = "SELECT * FROM `board` ORDER BY `id` DESC LIMIT ?, ?";
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(query);
            preparedStatement.setInt(1, (pageNo - 1) * PAGE_SIZE);
            preparedStatement.setInt(2, PAGE_SIZE);

            ResultSet resultSet = preparedStatement.executeQuery();

            while (resultSet.next()){
                BoardDTO boardDTO = new BoardDTO();
                boardDTO.setId(resultSet.getInt("id"));
                boardDTO.setTitle(resultSet.getString("title"));
                boardDTO.setContent(resultSet.getString("content"));
                boardDTO.setWriterId(resultSet.getInt("writerId"));
                boardDTO.setEntryDate(new Date(resultSet.getTimestamp("entry_date").getTime()));
                boardDTO.setModifyDate(new Date(resultSet.getTimestamp("modify_date").getTime()));

                list.add(boardDTO);
            }

            resultSet.close();
            preparedStatement.close();

        } catch (SQLException e) {
            e.printStackTrace();
        }


        return list;
    }
}

 

 

 

BoardController 수정

package com.bit.spring.controller;

import com.bit.spring.service.BoardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/board/")
public class BoardController {
    BoardService boardService;
    @Autowired
    public BoardController(BoardService boardService){
        this.boardService = boardService;
    }
    @GetMapping("showAll/{pageNo}")
    public String showAll(HttpSession session, Model model, @PathVariable int pageNo){
        if (session.getAttribute("logIn") == null){
            model.addAttribute("message", "다시 로그인해주세요.");
            return "redirect:/";
        }
        return "/board/showAll";
    }
}

 

 

 

HomeController 수정

package com.bit.spring.controller;

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

@Controller
public class HomeController {
    @RequestMapping("/")
    public String showIndex(Model model){
        System.out.println(model.getAttribute("message"));
        return  "index";
    }

}

URL창에 localhost:8080/board/showAll/3 치면 오류남

 

 

 

 

BoardController 수정

package com.bit.spring.controller;

import com.bit.spring.service.BoardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/board/")
public class BoardController {
    BoardService boardService;
    @Autowired
    public BoardController(BoardService boardService){
        this.boardService = boardService;
    }
    @GetMapping("showAll/{pageNo}")
    public String showAll(HttpSession session, RedirectAttributes redirectAttributes, Model model, @PathVariable int pageNo){
        if (session.getAttribute("logIn") == null){
            redirectAttributes.addFlashAttribute("message", "다시 로그인해주세요.");
            return "redirect:/";
        }
        return "/board/showAll";
    }
}

 

 

 

 

UserController 변경

package com.bit.spring.controller;

import com.bit.spring.model.UserDTO;
import com.bit.spring.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user/")
public class UserController {
    private UserService userService;
    @Autowired
    public UserController(UserService userService){
        this.userService = userService;
    }

    // 로그인
    @PostMapping("auth")
    public String auth(HttpSession session, Model model, UserDTO attempt){
        UserDTO result = userService.auth(attempt);

        if (result != null) {
            session.setAttribute("logIn", result);
            return "redirect:/board/showAll/1";
        }
        else {
            model.addAttribute("message", "로그인 정보를 다시 확인해주세요.");
            return "index";
        }
        

    }

}

 

 

 

 

BoardController

package com.bit.spring.controller;

import com.bit.spring.model.BoardDTO;
import com.bit.spring.service.BoardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;

@Controller
@RequestMapping("/board/")
public class BoardController {
    BoardService boardService;
    @Autowired
    public BoardController(BoardService boardService){
        this.boardService = boardService;
    }
    @GetMapping("showAll/{pageNo}")
    public String showAll(HttpSession session, RedirectAttributes redirectAttributes, Model model, @PathVariable int pageNo){
        if (session.getAttribute("logIn") == null){
            redirectAttributes.addFlashAttribute("message", "다시 로그인해주세요.");
            return "redirect:/";
        }

        ArrayList<BoardDTO> list = boardService.selectAll(pageNo);

        model.addAttribute("list", list);

        return "/board/showAll";
    }
}

 

 

 

showAll.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <c:forEach items="${list}" var="item">
        ${item.id} ${item.title} ${item.entryDate} <br>
    </c:forEach>
</body>
</html>