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주차 미션 / 서버 3조 이윤희 #14

Open
wants to merge 5 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
6 changes: 3 additions & 3 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ group = 'kuit'
version = '0.0.1-SNAPSHOT'

java {
toolchain {
languageVersion = JavaLanguageVersion.of(17)
}
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}


configurations {
compileOnly {
extendsFrom annotationProcessor
Expand Down
52 changes: 52 additions & 0 deletions src/main/java/kuit/springbasic/controller/HomeController.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,64 @@
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.beans.factory.annotation.Autowired;
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
@Controller
@RequiredArgsConstructor // -> 생성자 생략
public class HomeController {

private final QuestionRepository questionRepository;

// @Autowired -> spring container : 자동으로 repository 주입 (생성자가 1개라면 필요 없음)
// 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);
// addObject : mav 반환 => method chaining 가능
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);

// RequestMapping : HandlerAdapter 역할도 수행 -> String을 return 하여도 ModelAndView로 변환됨
return "home";
}
}
81 changes: 81 additions & 0 deletions src/main/java/kuit/springbasic/controller/LoginController.java
Original file line number Diff line number Diff line change
@@ -1,14 +1,41 @@
package kuit.springbasic.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import kuit.springbasic.db.UserRepository;
import kuit.springbasic.domain.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import static kuit.springbasic.util.UserSessionUtils.USER_SESSION_KEY;

@Slf4j
@Controller
@RequiredArgsConstructor
@RequestMapping("/user")
public class LoginController {

private final UserRepository userRepository;
/**
* TODO: showLoginForm
*/
// @RequestMapping(value = "/loginForm", method = RequestMethod.GET)
@GetMapping("/loginForm" )
public String showLoginForm(){
log.info("showLoginForm");
return "user/login";
}

/**
* TODO: showLoginFailed
*/
@RequestMapping("/loginFailed")
public String showLoginFailed(){
log.info("showLoginFailed");
return "user/loginFailed";
}

/**
* TODO: login
Expand All @@ -18,8 +45,62 @@ public class LoginController {
* loginV4 : @ModelAttribute
*/

// @RequestMapping("/login")
public String loginV1(@RequestParam("userId") String userId,
@RequestParam("password") String password,
HttpServletRequest request){
log.info("loginV1");
User loggedInUser = new User(userId, password);
User user = userRepository.findByUserId(userId);

if(user != null && user.isSameUser(loggedInUser)){
HttpSession session = request.getSession();
session.setAttribute(USER_SESSION_KEY, loggedInUser);
return "redirect:/";
}
return "redirect:/user/loginFailed";
}

// @RequestMapping("/login")
public String loginV2(@RequestParam String userId,
@RequestParam String password,
HttpServletRequest request){
log.info("loginV2");
User loggedInUser = new User(userId, password);
User user = userRepository.findByUserId(userId);

if(user != null && user.isSameUser(loggedInUser)){
HttpSession session = request.getSession();
session.setAttribute(USER_SESSION_KEY, loggedInUser);
return "redirect:/";
}
return "redirect:/user/loginFailed";
}

// @RequestMapping(value = "/login", method = RequestMethod.POST)
@PostMapping("/login")
public String loginV4(@ModelAttribute User loggedInUser,
HttpServletRequest request){
log.info("loginV4");
User user = userRepository.findByUserId(loggedInUser.getUserId());

if(user != null && user.isSameUser(loggedInUser)){
HttpSession session = request.getSession();
session.setAttribute(USER_SESSION_KEY, user);
return "redirect:/";
}
return "redirect:/user/loginFailed";
}

/**
* TODO: logout
*/
@GetMapping("/logout")
public String logout(HttpServletRequest request) {
log.info("logout");
HttpSession session = request.getSession();
session.removeAttribute(USER_SESSION_KEY);

return "redirect:/";
}
}
94 changes: 93 additions & 1 deletion src/main/java/kuit/springbasic/controller/UserController.java
Original file line number Diff line number Diff line change
@@ -1,29 +1,121 @@
package kuit.springbasic.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import kuit.springbasic.db.UserRepository;
import kuit.springbasic.domain.User;
import kuit.springbasic.util.UserSessionUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;
import java.util.Collection;
import java.util.Map;

import static kuit.springbasic.util.UserSessionUtils.USER_SESSION_KEY;

@Slf4j
@Controller
@RequiredArgsConstructor
@RequestMapping("/user")
public class UserController {

private final UserRepository userRepository;

/**
* TODO: showUserForm
*/

@GetMapping("/form" )
public String showUserForm(){
log.info("showUserForm");
return "user/form";
}
/**
* TODO: createUser
* createUserV1 : @RequestParam
* createUserV2 : @ModelAttribute
*/

@PostMapping("/signup")
public String createUserV1(@RequestParam String userId,
@RequestParam String password,
@RequestParam String name,
@RequestParam String email
){
User user = new User(userId, password, name, email);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

userId가 일치하는 회원이 존재하는지 확인하는 절차가 추가하면 좋을 것 같아요. 실제 서비스에서는 동일한 id를 갖는 회원이 존재하면 안되니까요.

userRepository.insert(user);
log.info("createUserV1 done");
return "redirect:/user/list";
}

// @PostMapping("/signup")
public String createUserV2(@ModelAttribute User user){
userRepository.insert(user);
log.info("createUserV2 done");
return "redirect:/user/list";
}
/**
* TODO: showUserList
*/
@GetMapping("/list" )
public String showUserList(HttpServletRequest request, Model model){
log.info("showUserList");
HttpSession session = request.getSession();
if(UserSessionUtils.isLoggedIn(session)){
Collection<User> users = userRepository.findAll();
model.addAttribute("users", users);
return "user/list";
}
return "redirect:/user/loginForm";
}

/**
* TODO: showUserUpdateForm
*/
@GetMapping("/updateForm")
public String showUserUpdateForm(@RequestParam String userId, HttpServletRequest request, Model model) {
log.info("showUserUpdateForm");
HttpSession session = request.getSession();

if (UserSessionUtils.isLoggedIn(session)) {
User sessionUser = (User) session.getAttribute(USER_SESSION_KEY);
if (sessionUser != null && sessionUser.getUserId().equals(userId)) {
Comment on lines +83 to +85

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

83번 줄에서 UserSessionUtils의 isLoggedIn()으로 로그인되어 있는지 여부를 확인했기 때문에 여기서 인가가 끝납니다. 그래서 이후에 조건식 2줄은 중복되는 내용이라 없어도 될 것 같네요!

User user = userRepository.findByUserId(userId);

if (user != null) {
model.addAttribute("user", user);
return "user/updateForm";
}
Comment on lines +88 to +91

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

정말 예외적인 상황이지만 repository로 조회해보니 user가 삭제되어서 없을 수도 있을 것 같네요. 만약 user가 존재하지 않아서 null이라면, 이 코드상으로는 /user/list로 redirect하는데 실제 서비스에서는 어떻게 동작하는 게 좋을지 고민해보는 것도 좋을 것 같아요

}
}
return "redirect:/user/list";
}

/**
* TODO: updateUser
* updateUserV1 : @RequestParam
* updateUserV2 : @ModelAttribute
*/

// @PostMapping("/update")
public String updateUserV1(@RequestParam String userId,
@RequestParam String password,
@RequestParam String name,
@RequestParam String email
){
User modifiedUser = new User(userId, password, name, email);
userRepository.update(modifiedUser);
log.info("updateUserV1 done");
return "redirect:/user/list";
Comment on lines +109 to +112

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

수정 시에도 인가가 필요하지 않을까요?

}

@PostMapping("/update")
public String updateUserV2(@ModelAttribute User modifiedUser){
userRepository.update(modifiedUser);
log.info("updateUserV2 done");
return "redirect:/user/list";
}
}
Original file line number Diff line number Diff line change
@@ -1,13 +1,60 @@
package kuit.springbasic.controller.qna;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletResponse;
import kuit.springbasic.db.AnswerRepository;
import kuit.springbasic.db.QuestionRepository;
import kuit.springbasic.db.UserRepository;
import kuit.springbasic.domain.Answer;
import kuit.springbasic.domain.Question;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

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

@Slf4j
@Controller
@RequiredArgsConstructor
public class AnswerController {

/**
* TODO: addAnswer - @PostMapping
* addAnswerV0 : @RequestParam, HttpServletResponse
* addAnswerV1 : @RequestParam, Model
* addAnswerV2 : @RequestParam, @ResponseBody
* addAnswerV3 : @ModelAttribute, @ResponseBody
*/
private final QuestionRepository questionRepository;
private final AnswerRepository answerRepository;

// * TODO: addAnswer - @PostMapping
// addAnswerV0 : @RequestParam, HttpServletResponse

@PostMapping("/api/qna/addAnswer")
public void addAnswerV0(@RequestParam int questionId,
@RequestParam String writer,
@RequestParam String contents,
HttpServletResponse response) throws SQLException, IOException {
log.info("AnswerController.addAnswerV0");

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

Question question = questionRepository.findByQuestionId(answer.getQuestionId());
question.increaseCountOfAnswer();
questionRepository.update(question);

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

response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(new ObjectMapper().writeValueAsString(model));
}

// addAnswerV1 : @RequestParam, Model
// addAnswerV2 : @RequestParam, @ResponseBody
// addAnswerV3 : @ModelAttribute, @ResponseBody


}
Loading