Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

7주차 미션 / 서버 4조 김재윤 #17

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 52 additions & 2 deletions src/main/java/kuit/springbasic/controller/HomeController.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,62 @@
package kuit.springbasic.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import kuit.springbasic.db.QuestionRepository;
import kuit.springbasic.domain.Question;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.Collection;

@Slf4j //logger 객체 생성하지 않아도 바로 logging 할 수 있도록 해줌
@Controller
@RequiredArgsConstructor
public class HomeController {
private final QuestionRepository questionRepository;

// public HomeController(QuestionRepository questionRepository){
// this.questionRepository = questionRepository;
// }

/**
* TODO: showHome
* showHomeV1 : parameter - HttpServletRequest, HttpServletResponse / return - ModelAndView
* showHomeV2 : parameter - none / return - ModelAndView
* showHomeV3 : parameter - Model / return - String
*/

}
@RequestMapping("/homeV1")
public ModelAndView showHomeV1(HttpServletRequest request, HttpServletResponse response){
log.info("showHomeV1");
ModelAndView mav = new ModelAndView("home");

Collection<Question> questions = questionRepository.findAll();
// mav.getModel().put("questions", questions);
mav.addObject("questions", questions);
return mav;
}

@RequestMapping("/homeV2")
public ModelAndView showHomeV2(){
log.info("showHomeV2");
ModelAndView mav = new ModelAndView("home");

Collection<Question> questions = questionRepository.findAll();
mav.addObject("questions", questions);
return mav;
}

@RequestMapping("/")
public String showHomeV3(Model model){
log.info("showHomeV3");

Collection<Question> questions = questionRepository.findAll();
model.addAttribute("questions", questions);
return "home"; //String 을 해당 이름의 view 를 반환한 식으로 자동으로 해석해서 사용함
}

}
25 changes: 0 additions & 25 deletions src/main/java/kuit/springbasic/controller/LoginController.java

This file was deleted.

29 changes: 0 additions & 29 deletions src/main/java/kuit/springbasic/controller/UserController.java

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,13 +1,92 @@
package kuit.springbasic.controller.qna;

public class AnswerController {
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletResponse;
import kuit.springbasic.db.AnswerRepository;
import kuit.springbasic.db.QuestionRepository;
import kuit.springbasic.domain.Answer;
import kuit.springbasic.domain.Question;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequiredArgsConstructor
@RequestMapping("/api/qna")
public class AnswerController {
/**
* TODO: addAnswer - @PostMapping
* addAnswerV0 : @RequestParam, HttpServletResponse
* addAnswerV1 : @RequestParam, Model
* addAnswerV2 : @RequestParam, @ResponseBody
* addAnswerV3 : @ModelAttribute, @ResponseBody
*/
private final AnswerRepository answerRepository;
private final QuestionRepository questionRepository;
// @PostMapping("/addAnswer")
public void addAnswerV0(@RequestParam int questionId,
@RequestParam String writer,
@RequestParam String contents,
HttpServletResponse response) throws SQLException, IOException {

Answer answer = new Answer(questionId, writer, contents);
Answer savedAnswer = answerRepository.insert(answer);

Question question = questionRepository.findByQuestionId(questionId);
question.increaseCountOfAnswer();

Map<String, Object> model = new HashMap<>();
model.put("answer", savedAnswer);

//JSON 응답을 보내기 위한 부분(기존의 jsonView() 에서 처리해주던 부분
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(new ObjectMapper().writeValueAsString(model));
}

// @PostMapping("/addAnswer")
public String addAnswerV1(@RequestParam int questionId,
@RequestParam String writer,
@RequestParam String contents,
Model model){

Answer answer = new Answer(questionId, writer, contents);
Answer savedAnswer = answerRepository.insert(answer);

Question question = questionRepository.findByQuestionId(questionId);
question.increaseCountOfAnswer();

model.addAttribute("answer", savedAnswer);

return "jsonView"; //해당 View가 없는거 아닌가? 모르겠는데
}

// @PostMapping("/addAnswer")
@ResponseBody
public Answer addAnswerV2(@RequestParam int questionId,
@RequestParam String writer,
@RequestParam String contents) {

Answer answer = new Answer(questionId, writer, contents);

Question question = questionRepository.findByQuestionId(questionId);
question.increaseCountOfAnswer();

return answerRepository.insert(answer);
//answers 라는 Map을 반환해줌 >> 해당 HashMap 이 JSON으로 변환되고, HTTP 응답 본문에 포함
}

@PostMapping("/addAnswer")
@ResponseBody
public Answer addAnswerV3(@ModelAttribute Answer answer) {
Question question = questionRepository.findByQuestionId(answer.getQuestionId());
question.increaseCountOfAnswer();

return answerRepository.insert(answer);
}
}
29 changes: 27 additions & 2 deletions src/main/java/kuit/springbasic/controller/qna/QnaController.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,34 @@
package kuit.springbasic.controller.qna;

public class QnaController {
import kuit.springbasic.db.AnswerRepository;
import kuit.springbasic.db.QuestionRepository;
import kuit.springbasic.domain.Answer;
import kuit.springbasic.domain.Question;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequiredArgsConstructor
public class QnaController {
/**
* TODO: showQnA
* showQnA
*/
private final QuestionRepository questionRepository;
private final AnswerRepository answerRepository;

@GetMapping("/qna/show")
public String showQna(@RequestParam("questionId") String questionId, Model model){
Question question = questionRepository.findByQuestionId(Integer.parseInt(questionId));
List<Answer> answers = (List<Answer>)answerRepository.findAllByQuestionId(question.getQuestionId());

model.addAttribute("question", question);
model.addAttribute("answers", answers);

return "/qna/show";
}
}
111 changes: 102 additions & 9 deletions src/main/java/kuit/springbasic/controller/qna/QuestionController.java
Original file line number Diff line number Diff line change
@@ -1,25 +1,118 @@
package kuit.springbasic.controller.qna;

public class QuestionController {
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import kuit.springbasic.db.QuestionRepository;
import kuit.springbasic.domain.Question;
import kuit.springbasic.domain.User;
import kuit.springbasic.util.UserSessionUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

/**
* TODO: showQuestionForm
*/
import static kuit.springbasic.util.UserSessionUtils.USER_SESSION_KEY;

@Controller
@RequiredArgsConstructor
@RequestMapping("/qna")
public class QuestionController { //컨트롤러 인자 관련해서? >ModelAndView > defaultModel
private final QuestionRepository questionRepository;

@GetMapping("/form")
public String showQuestionForm(HttpServletRequest req){
HttpSession session = req.getSession();
if (UserSessionUtils.isLoggedIn(session)) { // 회원만 질문 등록 가능
return "/qna/form";
}

return "redirect:/user/loginForm";
}
/**
* TODO: createQuestion
* createQuestionV1 : @RequestParam
* createQuestionV2 : @ModelAttribute
*/
// @PostMapping("/create")
public String createQuestionV1(@RequestParam("writer") String writer,
@RequestParam("title") String title,
@RequestParam("contents") String contents){
Question question = new Question(writer, title, contents, 0);
questionRepository.insert(question);

return "redirect:/";
}

@PostMapping("/create")
public String createQuestionV2(@ModelAttribute Question question){
questionRepository.insert(question);

return "redirect:/";
}


/**
* TODO: showUpdateQuestionForm
* showUpdateQuestionFormV1 : @RequestParam, HttpServletRequest, Model
* showUpdateQuestionFormV2 : @RequestParam, @SessionAttribute, Model
*/
// @GetMapping("/updateForm")
public String showUpdateQuestionFormV1(@RequestParam("questionId") String questionId,
HttpServletRequest req, Model model){ //todo model?

/**
* TODO: updateQuestion
*/
HttpSession session = req.getSession();
if (!UserSessionUtils.isLoggedIn(session)) { // 회원만 질문 등록 가능
return "redirect:/user/loginForm";
}

Question question = questionRepository.findByQuestionId(Integer.parseInt(questionId));
User user = UserSessionUtils.getUserFromSession(session);
if (!question.isSameUser(user)) {
throw new IllegalArgumentException();
}

model.addAttribute("question", question);
return "/qna/updateForm"; //컨트롤러에서 데이터를 Model에 추가하거나, HttpServletRequest에 직접 값을 설정하면 '뷰'로 자동으로 전달
}

@GetMapping("/updateForm")
public String showUpdateQuestionFormV2(@RequestParam("questionId") String questionId,
@SessionAttribute(USER_SESSION_KEY) User user,
Model model){
// @SessionAttribute -> session 객체에 담겨져있는 값을 읽어올 수 있는 어노테이션
if(user == null){
return "redirect:/";
}

Question question = questionRepository.findByQuestionId(Integer.parseInt(questionId));
if (!question.isSameUser(user)) {
throw new IllegalArgumentException();
}

model.addAttribute("question", question);
return "/qna/updateForm";
}



@PostMapping("/update")
public String updateQuestion(@RequestParam("questionId") String questionId,
@RequestParam("title") String title,
@RequestParam("contents") String contents,
@SessionAttribute(USER_SESSION_KEY) User user,
Model model){

if(user == null){
return "redirect:/users/loginForm";
}

Question question = questionRepository.findByQuestionId(Integer.parseInt(questionId));
if (!question.isSameUser(user)) {
throw new IllegalArgumentException("로그인된 유저와 질문 작성자가 다르면 질문을 수정할 수 없습니다.");
}

question.updateTitleAndContents(title, contents);
questionRepository.update(question);

return "redirect:/";
}

}
Loading