Quellcode durchsuchen

병합 및 게시물 생성, 삭제

sangwonlee vor 3 Jahren
Ursprung
Commit
67e5cef3ad

+ 0 - 5
realworld/src/main/java/com/dbs/realworld/common/RealWorldSessionUtil.java

@@ -1,5 +0,0 @@
-package com.dbs.realworld.common;
-
-public class RealWorldSessionUtil {
-    
-}

+ 81 - 7
realworld/src/main/java/com/dbs/realworld/controller/ArticleController.java

@@ -15,10 +15,15 @@ import com.dbs.realworld.mapper.UserMapper;
 import com.dbs.realworld.service.ArticleService;
 
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpStatus;
 import org.springframework.http.ResponseEntity;
 import org.springframework.stereotype.Controller;
 import org.springframework.ui.ModelMap;
+import org.springframework.web.bind.annotation.DeleteMapping;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PatchMapping;
 import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
@@ -30,18 +35,21 @@ public class ArticleController {
     private final ArticleService articleService;
     private final UserMapper userMapper;
 
+
     @Autowired
     public ArticleController(ArticleService articleService, UserMapper userMapper) {
         this.articleService = articleService;
         this.userMapper = userMapper;
     }
 
-    @RequestMapping
+
+    @GetMapping
     public String initArticleForm() {
         return Views.ARTICLE_FORM;
     }
 
-    @RequestMapping(method = RequestMethod.POST)
+
+    @PostMapping
     public ResponseEntity saveArticle(HttpServletRequest request, @RequestBody ArticleDTO articleDTO) {
         Map<String, Object> data = new HashMap<>();
 
@@ -49,7 +57,7 @@ public class ArticleController {
             // 사용자 조회하여 존재하는 사용자인지 확인
             HttpSession session = request.getSession();
             String ssEmail = (String) session.getAttribute("ssEmail");
-            UserDTO finded = userMapper.selectUserByEmail(ssEmail);
+            UserDTO finded = this.userMapper.selectUserByEmail(ssEmail);
 
             if (finded != null) {
                 articleDTO.setWriterId(finded.getId());
@@ -63,20 +71,86 @@ public class ArticleController {
         return ResponseEntity.created(URI.create("/article")).body(data);
     }
 
-    @RequestMapping("/all")
+
+    @GetMapping("/{articleId}/edit")
+    public String initEditForm(HttpServletRequest request, @PathVariable("articleId") int articleId, ModelMap model) {
+        // 아티클 정보 조회
+        ArticleDTO finded = this.articleService.findByArticleId(articleId);
+
+        if (finded == null) {
+            // mvc 방식으로 모달을 띄워주는게 나을거 같음...
+            // return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
+        }
+
+        HttpSession session = request.getSession();
+        int ssUserId = (int) session.getAttribute("ssId");
+        String ssEmail = (String) session.getAttribute("ssEmail");
+
+        // 권한 확인
+        if (!(finded.getWriterId() == ssUserId && finded.getWriterEmail().equals(ssEmail))) {
+            // mvc 방식으로 모달을 띄워주는게 나을거 같음...
+            // return ResponseEntity
+            //         .status(HttpStatus.FORBIDDEN)
+            //         .body("수정할 권한이 없습니다."); // error message
+        }
+
+        model.addAttribute("article", finded);
+        return Views.ARTICLE_FORM;
+    }
+
+
+    /**
+     * https://stackoverflow.com/a/17376670
+     * HTTP PATCH Request의 경우 바디에 아무 제약도 없다
+     */
+    @PatchMapping("/{articleId}")
+    public ResponseEntity editArticle(HttpServletRequest request, @PathVariable("articleId") int articlId, @RequestBody ArticleDTO articleDTO) {
+
+
+        return null;
+    }
+
+
+    @GetMapping("/all")
     public ResponseEntity getArticles() {
-        List<ArticleDTO> articleDTOs = articleService.findAll();
+        List<ArticleDTO> articleDTOs = this.articleService.findAll();
         Map<String, Object> data = new HashMap<>();
         data.put("articles", articleDTOs);
 
         return ResponseEntity.ok().body(data);
     }
 
-    @RequestMapping("/{articleId}")
+    
+    @GetMapping("/{articleId}")
     public String getArticleById(@PathVariable("articleId") int articleId, ModelMap model) {
 
-        ArticleDTO articleDTO = articleService.findByArticleId(articleId);
+        ArticleDTO articleDTO = this.articleService.findByArticleId(articleId);
         model.put("articleDetail", articleDTO);
         return Views.ARTICLE_DETAIL;
     }
+
+
+    @DeleteMapping("/{articleId}")
+    public ResponseEntity deleteArticleById(HttpServletRequest request, @PathVariable("articleId") int articleId) {
+        
+        ArticleDTO finded = this.articleService.findByArticleId(articleId);
+
+        if (finded == null) {
+            return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
+        }
+
+        HttpSession session = request.getSession();
+        int ssUserId = (int) session.getAttribute("ssId");
+        String ssEmail = (String) session.getAttribute("ssEmail");
+
+        if (finded.getWriterId() == ssUserId && finded.getWriterEmail().equals(ssEmail)) {
+            this.articleService.remove(articleId);
+        } else {
+            return ResponseEntity
+                    .status(HttpStatus.FORBIDDEN)
+                    .body("삭제할 권한이 없습니다."); // error message
+        }
+
+        return ResponseEntity.ok().build();
+    }
 }

+ 2 - 13
realworld/src/main/java/com/dbs/realworld/controller/HomeController.java

@@ -3,23 +3,12 @@ package com.dbs.realworld.controller;
 import com.dbs.realworld.common.Views;
 
 import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.GetMapping;
 
 @Controller
 public class HomeController {
 
-    // @RequestMapping("/")
-    // public ModelAndView main(HttpServletRequest request, ModelAndView mv) {
-    //     HttpSession session = request.getSession();
-    //     session.setAttribute("name", value);
-    //     // HashMap<String, Object> data = new HashMap<>();
-    //     // data.put("isLogin", false);
-    //     // mv.addObject("data", data);
-    //     mv.setViewName("main");
-    //     return mv;
-    // }
-
-    @RequestMapping("/")
+    @GetMapping("/")
     public String main() {
         return Views.MAIN;
     }

+ 4 - 3
realworld/src/main/java/com/dbs/realworld/controller/UserController.java

@@ -12,6 +12,7 @@ import org.springframework.stereotype.Controller;
 import org.springframework.ui.ModelMap;
 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.ModelAttribute;
+import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
 
@@ -36,7 +37,7 @@ public class UserController {
     }
 
     // 회원가입 요청
-    @RequestMapping(value = "/signup", method = RequestMethod.POST)
+    @PostMapping("/signup")
     public String processSignupForm(HttpServletRequest request, @ModelAttribute("userDTO") UserDTO userDTO, ModelMap model) {
         try {
             this.userService.register(userDTO);
@@ -64,7 +65,7 @@ public class UserController {
     }
 
     // 로그인 요청
-    @RequestMapping(value = "/signin", method = RequestMethod.POST)
+    @PostMapping("/signin")
     public String processSigninForm(HttpServletRequest request, @ModelAttribute("userDTO") UserDTO userDTO, ModelMap model) {
         UserDTO finded = null;
         try {
@@ -87,7 +88,7 @@ public class UserController {
         return "redirect:/";
     }
 
-    @RequestMapping("/logout")
+    @GetMapping("/logout")
     public String processLogout(HttpServletRequest request) {
         HttpSession session = request.getSession();
         session.invalidate();

+ 1 - 0
realworld/src/main/java/com/dbs/realworld/mapper/ArticleMapper.java

@@ -13,4 +13,5 @@ public interface ArticleMapper {
     void insertArticle(ArticleDTO dto);
     List<ArticleDTO> selectAll();
     ArticleDTO selectByArticleId(int articleId);
+    void deleteByArticleId(int articleId);
 }

+ 0 - 23
realworld/src/main/java/com/dbs/realworld/runner/TestRunner.java

@@ -1,23 +0,0 @@
-// package com.dbs.realworld.runner;
-
-// import org.springframework.beans.factory.annotation.Autowired;
-// import org.springframework.boot.CommandLineRunner;
-// import org.springframework.core.env.Environment;
-// import org.springframework.stereotype.Component;
-
-// @Component
-// public class TestRunner implements CommandLineRunner {
-    
-//     @Autowired
-//     private Environment env;
-
-//     @Override
-//     public void run(String... args) throws Exception {
-//         System.out.println("DefaultProfiles ==> " + env.getDefaultProfiles()[0]);
-//         System.out.println("ActiveProfiles ==> " + env.getActiveProfiles()[0]);
-//         System.out.println("server.port ==> " + env.getProperty("server.port"));
-//         System.out.println("server.servlet.context-path ==> " + env.getProperty("server.servlet.context-path"));
-//         System.out.println("spring.mvc.view.prefix ==> " + env.getProperty("spring.mvc.view.prefix"));
-//         System.out.println("spring.mvc.view.suffix ==> " + env.getProperty("spring.mvc.view.suffix"));
-//     }
-// }

+ 3 - 0
realworld/src/main/java/com/dbs/realworld/service/ArticleService.java

@@ -35,4 +35,7 @@ public class ArticleService {
         return this.articleMapper.selectByArticleId(articleId);
     }
 
+    public void remove(int articleId) {
+        articleMapper.deleteByArticleId(articleId);
+    }
 }

+ 7 - 0
realworld/src/main/resources/mybatis/mapper/user/ArticleMapper.xml

@@ -49,6 +49,13 @@
         ON AR.user_id = USR.id
       ]]>
     </select>
+
+    <delete id="deleteByArticleId" parameterType="int">
+        <![CDATA[
+            DELETE FROM article_mst WHERE id = #{articleId}
+        ]]>
+    </delete>
+
   <!-- <select id="selectMemberPassword" resultType="com.lemon.lifecenter.dto.StaffDTO">
     <![CDATA[
       SELECT id, password

+ 16 - 1
realworld/src/main/webapp/WEB-INF/jsp/article/article.jsp

@@ -17,6 +17,19 @@
         editForm = window.document.querySelector('#editor-form');
         tagInputArea = window.document.querySelector('#tag-input-area');
         tagList = window.document.querySelector('.tag-list');
+        
+        const article = "${article}";
+
+        if (article !== "") {
+            editForm['article-title'].value = "${article.title}";
+            editForm['subtitle'].value = "${article.subtitle}";
+            editForm['article-body'].value = "${article.content}";
+
+            const strTags = "${article.tags}";
+            strTags.split(',').forEach(tag => {
+                addTag(tag);
+            });
+        }
     }
 
     function enterKeys(){
@@ -46,6 +59,9 @@
             }
 
             spanTag.append(btnDelete);
+
+            console.log(spanTag);
+
             tagList.append(spanTag);
             tagSet.add(tag);
             tagInputArea.value = "";
@@ -84,7 +100,6 @@
 
     const validateForm = () => {
         const articleTitle = editForm['article-title'].value;
-        console.log(articleTitle);
         if(articleTitle === null || articleTitle === ""){
             alert("제목을 입력해주세요.");
             return false;

+ 18 - 15
realworld/src/main/webapp/WEB-INF/jsp/article/articleDetails.jsp

@@ -31,6 +31,15 @@
         }
     }
 
+    const deleteArticle = (targetArticleId) => {
+        fetch("/article/" + targetArticleId, { method: 'delete' })
+            .then(response => {
+                console.table(response);
+                if (response.status === 200) {
+                    location.href = "/";
+                }
+            })
+        }
 
     window.onload = () => {
         const tags = document.querySelector('.tag-list');
@@ -48,6 +57,7 @@
             value.textContent = new Date(date).toLocaleString()
         )
     }
+    
 </script>
 </head>
 <body>
@@ -75,10 +85,10 @@
                         <c:choose>
                             <c:when test="${articleDetail.writerId eq ssId}">
                                 <div class="buttons">
-                                    <a href="editor.html" class="edit-article btn-sm">
+                                    <a href="/article/${articleDetail.id}/edit" class="edit-article btn-sm">
                                         <i class="fas fa-pencil-alt"> Edit Article</i>
                                     </a>
-                                    <button class="delete-article btn-sm">
+                                    <button class="delete-article btn-sm" onclick="deleteArticle('${articleDetail.id}')">
                                         <i class="fas fa-trash-alt"> Delete Article</i>
                                     </button>
                                 </div>
@@ -122,17 +132,19 @@
                             <a href="userpage-my.html" class="name">
                                 <c:out value="${articleDetail.writerName}"></c:out>
                             </a>
-                            <span class=date>
+                            <span class="date">
                                 <c:out value="${articleDetail.created}"></c:out>
                             </span>
                         </div>
-                        <c:choose>
+                        <div class="buttons">
+                            </div>
+                            <c:choose>
                             <c:when test="${articleDetail.writerId eq ssId}">
                                 <div class="buttons">
-                                    <a href="editor.html" class="edit-article btn-sm">
+                                    <a href="/article/${articleDetail.id}/edit" class="edit-article btn-sm">
                                         <i class="fas fa-pencil-alt"> Edit Article</i>
                                     </a>
-                                    <button class="delete-article btn-sm">
+                                    <button class="delete-article btn-sm" onclick="deleteArticle('${articleDetail.id}')">
                                         <i class="fas fa-trash-alt"> Delete Article</i>
                                     </button>
                                 </div>
@@ -158,15 +170,6 @@
                 <div class="col-8">
                     <div class="card comment-form">
                         <div class="card-block">
-                            -- articleDetail: <c:out value="${articleDetail}"></c:out> <br>
-                            -- title: <c:out value="${articleDetail.title}"></c:out> <br>
-                            -- subtitle: <c:out value="${articleDetail.subtitle}"></c:out>  <br>
-                            -- content: <c:out value="${articleDetail.content}"></c:out> <br>
-                            -- tags: <c:out value="${articleDetail.tags}"></c:out> <br>
-                            -- created: <c:out value="${articleDetail.created}"></c:out> <br>
-                            -- writerId: <c:out value="${articleDetail.writerId}"></c:out> <br>
-                            -- writerName: <c:out value="${articleDetail.writerName}"></c:out> <br>
-                            -- writerEmail: <c:out value="${articleDetail.writerEmail}"></c:out> <br>
                             <textarea class="form-control" placeholder="Write a comment..." rows="3"></textarea>
                         </div>
                         <div class="card-footer">