본문 바로가기

2023.11.21-2024.05.31

20240311 전자정부(DTO>Map 변경, 로그인 설정, 글삭제, 글수정)

dto 없애기> map 으로 바꾸기

 

 : indexMapper> freeboard,detail 두개 map타입으로 변경, 이후 controller, service, dao 수정

 

 

indexMapper

	<select id="freeboard" parameterType="int" resultType="Map">
		SELECT
		mtno, mttitle, mname, mtdate, mtip, mtdel, mtread, mtcate
		FROM
		multiboardview
		WHERE mtcate=#{cate} AND mtdel=1
		LIMIT 0, 10
	</select>

	<select id="detail" parameterType="int" resultType="Map">
		SELECT mtno,
		mttitle, mtcontent, mname, mtdate, mtip, mtdel, mtread, mtcate
		FROM
		multiboardview
		WHERE mtno=#{no}
	</select>

 

 

 

 

IndexController > detail, freeboard 수정

	// 멀티보드 20240308
	@GetMapping("/freeboard")
	public String freeboard(@RequestParam(value = "cate", defaultValue = "1") int cate, Model model) {
	      // 메뉴 불러오기
	      List<Map<String, String>> menu = indexService.menu();
	      model.addAttribute("menu", menu);
	      
	      List<Map<String,Object>> board = indexService.freeboard(cate);
	      model.addAttribute("board", board);
	      return "freeboard";
	   }
       
    // 20240307 안드로이드 앱 프로그래밍
	// 상세보기
	@GetMapping("/detail")
	public String detail(@RequestParam("no") int no, Model model) {
		// 메뉴 불러오기
		List<Map<String, String>> menu = indexService.menu();
		model.addAttribute("menu", menu);
		Map<String, Object> detail = indexService.detail(no);
		model.addAttribute("detail", detail);
		return "detail";
	
	}

 

 

 

 

 

IndexService > detail, freeboard 수정

	public Map<String, Object> detail(int no) {
		return indexDAO.detail(no);
	}

	public List<Map<String, Object>> freeboard(int cate) {
		return indexDAO.freeboard(cate);
	}

 

 

 

 

IndexDAO > detail, freeboard 수정

	Map<String, Object> detail(int no);

	List<Map<String, Object>> freeboard(int cate);

 

 

 

수정( update )만들기

 

detail.html

 

 

스윗어럴트 추가

  <!-- 스윗어럴트 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>

 

 

script > update 추가

       <th:block th:insert="~{menu.html :: head}"></th:block>
        <script type="text/javascript">
        function update(no){
      	  Swal.fire({
      		  title: "수정합니까?",
      		  text: "해당 내용을 수정합니다.",
      		  icon: "warning",
      		  showCancelButton: true,
      		  confirmButtonColor: "#3085d6",
      		  cancelButtonColor: "#d33",
      		  confirmButtonText: "수정"
      		}).then((result) => {
      		  if (result.isConfirmed) {
      		    //Swal.fire({title: "수정을 선택했습니다.",text: "수정합니다.",icon: "success"});
      			let form = document.createElement('form');
        		    form.setAttribute('method','get');
        		    form.setAttribute('action','/postUpdate');
        		    
        		    let input = document.createElement('input');
        		    input.setAttribute('type','hidden');
        		    input.setAttribute('name','no');
        		    input.setAttribute('value', no);
        		    
        		    form.appendChild(input);
        		    document.body.appendChild(form);
        		    form.submit();
      		  }
      		});
        }

 

 

하단에  onclick 추가

<i class="bi bi-pencil-fill" th:id="${detail.mtno }" onclick="update(this.id)"></i>

 

 

 

update.html 생성

<!DOCTYPE html>
<html lang="ko" xmlns:th="http://thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Freeboard</title>

<!-- 메뉴에서 헤드 가져오기(fragment:head 찾아가기) -->
<th:block th:insert="~{menu.html :: head}"></th:block>

</head>
<body>

   <!-- 메뉴에서 네비 가져오기(fragment:menu 찾아가기) -->
   <th:block th:insert="~{menu.html :: menu}"
   ></th:block>

   <aside class="text-center">
      <div class="container px-5">
     	<h1>글수정</h1>
          	<!-- 카테고리, 글번호, 페이지 번호 -->
			들어온 카테고리 : [[${param.cate}]]<br>
			[[${update }]]

         <form action="/postUpdate" method="post">
            <div class="p-2 rounded" style="background-color: #c0c0c0">
               <div class="input-group mb-2">
                  <span class="input-group-text" id="basic-addon1">제목</span>
  					<input type="text" name="title" class="form-control" th:value="${update.mttitle }" placeholder="제목" aria-label="제목" aria-describedby="basic-addon1">
				</div>
               <div class="input-group">
                  <span class="input-group-text">본문</span>
                  <textarea name="content" class="form-control" aria-label="With textarea" style="height : 300px">[[${update.mtcontent }]]</textarea>
               </div>
            </div>
            <div class="mt-2">
               <input type="hidden" name="mtno" th:value="${update.mtno }">
				<input type="hidden" name="mtcate" th:value="${update.mtcate }">
				
				<button type="submit" class="btn btn-info">글쓰기</button>
			</div>

         </form>

      </div>
   </aside>
 <!-- App features section-->
        
        
        <!-- Footer-->
        <th:block th:insert="~{menu.html :: footer}"></th:block>
        <!-- Feedback Modal-->
        <!-- Bootstrap core JS-->
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
        <!-- Core theme JS-->
        <script src="js/scripts.js"></script>
        <!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *-->
        <!-- * *                               SB Forms JS                               * *-->
        <!-- * * Activate your form at https://startbootstrap.com/solution/contact-forms * *-->
        <!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *-->
        <script src="https://cdn.startbootstrap.com/sb-forms-latest.js"></script>
</body>
</html>

 

 

 

 

IndexController> postUpdate(디테일로 복사해서 묻어가기)

 

@GetMapping 추가

@GetMapping("/postUpdate")
	public String postUpdate(@RequestParam("no") int no, Model model) {
		if (util.getSession().getAttribute("mid") != null) {
			// 메뉴 불러오기
			List<Map<String, String>> menu = indexService.menu();
			model.addAttribute("menu", menu);

			Map<String, Object> update2 = indexService.detail(no);
			model.addAttribute("update", update2);
			return "update";
		} else {
			return "redirect:/login";
		}
	}

 

 

 

 

@PostMapping 추가

	@PostMapping("/postUpdate")
	public String postUpdate(@RequestParam() Map<String, Object> map) {

		indexService.postUpdate(map);
		return "redirect:/detail?no=" + map.get("mtno");
	}

 

 

 

IndexService > postUpdate

	public void postUpdate(Map<String, Object> map) {
		map.put("mid", util.getSession().getAttribute("mid"));// 본인 맞는지
		indexDAO.postUpdate(map);
	}

 

 

IndexDAO> postUpdate

	void postUpdate(Map<String, Object> map);

 

 

indexMapper

	<update id="postUpdate" parameterType="Map">
		UPDATE multiboard SET
		mttitle=#{title}, mtcontent=#{content}
		WHERE mtno=#{mtno} AND mno=(SELECT mno FROM member WHERE mid=#{mid})
	</update>

 

 

 

 

삭제(del) 만들기

 

detail.html

script> del 만들기

        function del(no){
      	  Swal.fire({
      		  title: "삭제합니까?",
      		  text: "해당 내용을 삭제합니다. 복구가 불가능합니다.",
      		  icon: "warning",
      		  showCancelButton: true,
      		  confirmButtonColor: "#3085d6",
      		  cancelButtonColor: "#d33",
      		  confirmButtonText: "삭제"
      		}).then((result) => {
      		  if (result.isConfirmed) {
      		    //Swal.fire({title: "삭제를 선택했습니다.",text: "삭제합니다.",icon: "success"});
      		    //location.href="/postDel?no="+no;
      		    let form = document.createElement('form');
      		    form.setAttribute('method','post');
      		    form.setAttribute('action','/postDel');
      		    
      		    let input = document.createElement('input');
      		    input.setAttribute('type','hidden');
      		    input.setAttribute('name','no');
      		    input.setAttribute('value', no);
      		    
      		    form.appendChild(input);
      		    document.body.appendChild(form);
      		    form.submit();
      		  }
      		});
        }

 

 

 

 

 

<!-- Quote/testimonial aside--> 안에 onclick 넣어주기

<i class="bi bi-trash2-fill" th:id="${detail.mtno }" onclick="del(this.id)"></i>

 

 

 

 

 

IndexController > postDel

	@PostMapping("/postDel")
	public String postDel(@RequestParam("no") int no) {
		// System.out.println(no);
		int result = indexService.postDel(no);
		return "redirect:/freeboard";
	}

 

 

IndexService > postDel

	public int postDel(int no) {
		return indexDAO.postDel(no);
	}

 

 

IndexDAO > postDel

int postDel(int no);

 

 

indexMapper

	<update id="postDel" parameterType="int">
		UPDATE multiboard SET mtdel=0
		WHERE mtno=#{no}
	</update>

 

 

 

 

 

 

로그인 설정하기

MemberController

 

@Autowired 추가

	@Autowired
	private IndexService indexService;

 

 

 

 

@GetMapping("/login")  수정

	@GetMapping("/login")
	public String login(Model model) {
		// 메뉴 불러오기
		List<Map<String, String>> menu = indexService.menu();
		model.addAttribute("menu", menu);
		return "login";
	}

 

 

 

 

 

@PostMapping("/login") 수정 > result 추가한 부분 잘 보기

@PostMapping("/login")
	public String login2(@RequestParam Map<String, Object> map) {
		System.out.println(map);// {id=poseidon, pw=01234567}
		Map<String, Object> result = memberService.login(map);
		System.out.println(result);// {count=1, mname=포세이돈}

		if (util.str2Int(result.get("count")) == 1) {
			// 정상 - 세션 -> board로 이동
			HttpSession session = util.getSession();
			session.setAttribute("mid", map.get("id"));
			session.setAttribute("mname", result.get("mname"));
			return "redirect:/freeboard";
		} else {
			// 로그인 불가 -> 화면이동 다시 로그인으로
			return "redirect:/login";
		}
	}

 

 

 

 

데이터베이스에 mtip 추가해서 null값 없애기

UPDATE `c23c_22`.`multiboard` SET `mtip`='127.0.0.1' WHERE  `mtno`;

 

 

 

AOP사용하기

 

build.gradle  > aop추가 > 리프레쉬

	implementation 'org.springframework.boot:spring-boot-starter-aop'

 

 

 

 

 

util(패키지)> AOPConfig(클래스) 생성

 

 

 

@Component, @Aspect 설정하기

@Aspect
@Component
public class AOPConfig {

}

 

 

 

 

 

 

package com.mask.web.util;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class AOPConfig {

	@Pointcut("execution(* com.mask.web.controller.*.*(..))")
	public void cut() {
		
	}
	
	@Before("cut()")
	public void before() {
		System.out.println("시작할 때");
	}


}

 

 

 

JoinPoint 추가

	@Before("cut()")
	public void before(JoinPoint joinPoint) {
		System.out.println("시작할 때"+joinPoint.getSignature());
		System.out.println("시작할 때"+joinPoint.getArgs());
		System.out.println("시작할 때"+joinPoint.getSourceLocation());
	}

 

 

 

 

 

methodSignature 출력하기

   
   @Before("cut()")
   public void before(JoinPoint joinPoint) {
   
   	  //실해되는 함수 이름을 가져오고 출력 
      MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
      System.out.println("시작할 때 : " + methodSignature.getName());
      System.out.println("시작할 때 : " + methodSignature.getMethod());
   }

 

 

      //파라미터
      Object[] args = joinPoint.getArgs();
      System.out.println(Arrays.toString(args));

 

      //파라미터 배열의 종류 값
      for (Object object : args) {
    	  System.out.println("파라미터 타입 : " + object.getClass().getSimpleName());
    	  System.out.println("파라미터 값 : " + object);
    	  ;

 

 

 

 

@After 어노테이션 설정

   @After("cut()")
   public void after(JoinPoint joinPoint) {
	   MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
	   //실행되는 함수 이름을 가져오고 출력
	  System.out.println(methodSignature.getName() + "메소드가 종료되었습니다.");
   }