관리 메뉴

DeseoDeSeo

[Spring] mvc07 글 작성, 로그인, 로그아웃 본문

spring

[Spring] mvc07 글 작성, 로그인, 로그아웃

deseodeseo 2023. 10. 21. 15:59
list.jsp
글쓰기 버튼과 아이디를 넣는다.
<tr>
	<td colspan="5">
	<button id="regBtn" class="btn btn-xs btn-info pull-right">글쓰기</button>
	</td>
</tr>
<script type="text/javascript">
	$(document).ready(function(){
		$("#regBtn").click(function(){
				//버튼을 눌렀을 때, 함수를 작동시키겠다.
				//location.href는 페이지를 이동시킴.
				location.href="${cpath}/board/register";
	});
});

regBtn을 클릭하면 페이지를 이동한다.

src > main > webapp > web-inf > views > board> register.jsp 생성
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
	<%@ taglib prefix ="c" uri="http://java.sun.com/jsp/jstl/core" %>
	<%@ taglib prefix ="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<c:set var="cpath" value="${pageContext.request.contextPath}" />	
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet"
	href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script
	src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script
	src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
	<div class="container">
		<h2>Spring MVC07</h2>
		<div class="panel panel-default">
			<div class="panel-heading">Board</div>
			<div class="panel-body">
				<form action="${cpath}/board/register" method="post">
					<input type="hidden" name="memID" value="${mvo.memID}">
						
					<div class="form-group">
						<label>제목</label>
						<input type="text" name="title" class="form-control">
					</div>
					
					<div class="form-group">
						<label>내용</label>
						<textarea rows="10" cols="" name="content" class="form-control"></textarea>
					</div>
					
					<div class="form-group">
						<label>작성자</label>
						<input value="${mvo.memName}" readonly="readonly" type="text" name="writer" class="form-control">
					</div>
					<button type="submit" class="btn btn-default btn-sm">등록</button>
					<button type="reset" class="btn btn-default btn-sm">취소</button>
					
				</form>
			</div>
			<div class="panel-footer">스프링게시판-뇽뇽이</div>
		</div>
	</div>

<script type="text/javascript">
		
	
</script>


</body>
</html>
BoardMapper.java
public void insert(Board vo);
BoardMapper.xml
<insert id="insert" parameterType="kr.spring.entity.Board">
	INSERT INTO TBLBOARD(IDX,MEMID, TITLE, CONTENT, WRITER, BOARDGROUP, BOARDSEQUENCE, BOARDLEVEL, BOARDAVAILABLE)
	SELECT IFNULL(MAX(IDX)+1, 1),#{memID},#{title},#{content},#{writer}, IFNULL(MAX(BOARDGROUP)+1, 1), 0,0,1 FROM TBLBOARD
</insert>

 

j unit 테스트 해보기
DataSourceTest.java
@Test
   public void testInsert() {
	   Board vo = new Board();
   	   vo.setMemID("와플");
	   vo.setTitle("합병조건");
	   vo.setContent("일반집합 연산자");
  	   vo.setWriter("관계대수");
	   mapper.insertSelectKey(vo);
 }
BoardMapper.xml
selectKey : pk값을 미리(before) SQL을 통해서 처리해 두고 특정한 이름으로 결과를 보관.
- id, boardGroup만 가져와서 board타입에 넣는다.
<insert id="insertSelectKey" parameterType="kr.spring.entity.Board">
	       <!-- id,boardGroup만 가져와서 board타입에 넣고 befor= 이전에 실행하겠다. -->
	<selectKey keyProperty ="idx,boardGroup" resultType="kr.spring.entity.Board" order="BEFORE">
			SELECT IFNULL(MAX(IDX)+1, 1) as  idx,
				   IFNULL(MAX(BOARDGROUP)+1, 1) as boardGroup
				   FROM TBLBOARD
	</selectKey>
	INSERT INTO TBLBOARD(IDX, MEMID, TITLE, CONTENT, WRITER, BOARDGROUP, BOARDSEQUENCE, BOARDLEVEL, BOARDAVAILABLE)
	VALUES(#{idx},#{memID},#{title},#{content},#{writer},#{boardGroup},0,0,1)
		
</insert>

 

BoardMapper.java
@Mapper
public void insertSelectKey(Board vo);
DataSourceTest.java
 @Test
public void testInsert() {
   Board vo = new Board();
   vo.setMemID("와플");
   vo.setTitle("합병조건");
   vo.setContent("일반집합 연산자");
   vo.setWriter("관계대수");
   mapper.insertSelectKey(vo);
 }
list.jsp
<div class="panel panel-default">
	<div class="panel-heading">
		<form class="form-inline" action="${cpath}/login/loginProcess" method="post">
			<div class="form-group">
	 	  	<!-- 라벨태그를 사용하면 글자를 클릭하면 활성화됨, -->
				<label for="id">ID: </label>
				<input type="text" class="form-control" id="id" name="memID">
			</div>
			<div class="form-group">
	 	     <!-- 라벨태그를 사용하면 글자를 클릭하면 활성화됨, -->
					<label for="pwd">Password: </label>
					<input type="password" class="form-control" id="pwd" name="memPwd">
		   </div>
			<button type="submit" class="btn btn-default">로그인</button>
		</form>
kr.spring.controller > LoginController.java 생성
package kr.spring.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import kr.spring.entity.Member;
import kr.spring.service.BoardService;

@Controller
@RequestMapping("/login/*")
public class LoginController {
	
	@Autowired
	private BoardService service;
	
	@RequestMapping("/loginProcess")
	//login정보는 member에 있음.
	//로그인 하고 나서는 session에 저장,
	public String login(Member vo, HttpSession session) {
		
		//로그인 성공하면 member타입으로 받아옴.
		Member mvo =service.login(vo);
		
		if(mvo != null) {
			session.setAttribute("mvo", mvo);
		}
		return "redirect:/board/list";
BoardService.java
public Member login(Member vo);
BoardServiceImpl.java
@Override
public Member login(Member vo) {
	Member mvo = mapper.login(vo);
	return mvo;
}
BoardMapper.java
public Member login(Member vo);
BoardMapper.xml
<select id="login" resultType="kr.spring.entity.Member" parameterType="kr.spring.entity.Member">
	SELECT * FROM TBLMEMBER WHERE MEMID=#{memID} AND MEMPWD = #{memPwd} 
</select>
list.jsp
 : 로그인을 했을 때, 안 했을 때
  <c:if test="${empty mvo}"> 
	<form class="form-inline" action="${cpath}/login/loginProcess" method="post">
			<div class="form-group">
	 	       <!-- 라벨태그를 사용하면 글자를 클릭하면 활성화됨, -->
				<label for="id">ID: </label>
				<input type="text" class="form-control" id="id" name="memID">
			</div>
			<div class="form-group">
	 	   	<!-- 라벨태그를 사용하면 글자를 클릭하면 활성화됨, -->
					<label for="pwd">Password: </label>
					<input type="password" class="form-control" id="pwd" name="memPwd">
			</div>
					<button type="submit" class="btn btn-default">로그인</button>
	</form>
					
				</c:if>
	<c:if test="${not empty mvo}">
	<!-- login: loginController로 감. 그리고 logoutProcess 는 @requestmapping으로 함. -->
		   <form  class="form-inline" action="${cpath}/login/logoutProcess" method="post">
		    	<div class="form-group">
		    		<lable> ${mvo.memName}님 방문을 환영합니다. </lable>	
		    	</div>
		    	<button type="submit" class="btn btn-default"> 로그아웃 </button>
		   </form>
		    
</c:if>

 

로그아웃 기능
LoginController.java
@RequestMapping("/logoutProcess")
public String logout(HttpSession session) {
	session.invalidate();
	return "redirect:/board/list";
}

 

게시글 작성
register.jsp
게시글 등록할 때 아이디를 넘기고 작성자 부분에 로그인한 사람의 이름을 띄워준다.
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
	<%@ taglib prefix ="c" uri="http://java.sun.com/jsp/jstl/core" %>
	<%@ taglib prefix ="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<c:set var="cpath" value="${pageContext.request.contextPath}" />	
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet"
	href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script
	src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script
	src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
	<div class="container">
		<h2>Spring MVC07</h2>
		<div class="panel panel-default">
			<div class="panel-heading">Board</div>
			<div class="panel-body">
				<form action="${cpath}/board/register" method="post">
					<input type="hidden" name="memID" value="${mvo.memID}">
						
					<div class="form-group">
						<label>제목</label>
						<input type="text" name="title" class="form-control">
					</div>
					
					<div class="form-group">
						<label>내용</label>
						<textarea rows="10" cols="" name="content" class="form-control"></textarea>
					</div>
					
					<div class="form-group">
						<label>작성자</label>
						<input value="${mvo.memName}" readonly="readonly" type="text" name="writer" class="form-control">
					</div>
					<button type="submit" class="btn btn-default btn-sm">등록</button>
					<button type="reset" class="btn btn-default btn-sm">취소</button>
					
				</form>
			</div>
			<div class="panel-footer">스프링게시판-뇽뇽이</div>
		</div>
	</div>

	<script type="text/javascript">
		
	
	</script>


</body>
</html>
BoardService.java
public void register(Board vo);
BoardServiceImpl.java
	@Override
	public void register(Board vo) {
		mapper.insertSelectKey(vo);
	}
BoardController.java
모달 띄우기 위해서  RedirectAttributes
@PostMapping("/register")
	public String register(Board vo, RedirectAttributes rttr) {
	// System.out.println(vo.toString());
	  service.register(vo);
	// System.out.println(vo.toString()); idx,boardGroup이 채워져서 print된다.
	 //result라는 이름으로 
		rttr.addFlashAttribute("result", vo.getIdx());
		return "redirect:/board/list";
	}
web.xml
인코딩 위해서
<!-- post방식 인코딩  -->
	    <filter> 
	    <filter-name>encodingFilter</filter-name> 
	    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 
	    <init-param> 
	       <param-name>encoding</param-name> 
	       <param-value>UTF-8</param-value> 
	    </init-param> 
	    <init-param> 
	       <param-name>forceEncoding</param-name> 
	       <param-value>true</param-value> 
	    </init-param> 
	 </filter> 
	 <filter-mapping> 
	    <filter-name>encodingFilter</filter-name> 
	    <url-pattern>/*</url-pattern> 
	 </filter-mapping>
list.jsp
list.jsp가장 하단, java script 위에 추가
<!-- 모달 창!  -->
<div class="modal fade" id="myMessage" role="dialog">
	<div class="modal-dialog">
		    
		      <!-- Modal content-->
	 <div id="messageType" class="modal-content">
		<div class="modal-header panel-heading">
		     <button type="button" class="close" data-dismiss="modal">&times;</button>
		          <h4 class="modal-title">Modal Header</h4>
		        </div>
		        <div class="modal-body">
		          
		        </div>
		        <div class="modal-footer">
		          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
		        </div>
		      </div>
		      
    </div>
  </div>
$(document).ready(function(){
		
			var result="${result}";
			checkModal(result);
			
			$("#regBtn").click(function(){
				//버튼을 눌렀을 때, 함수를 작동시키겠다.
				//location.href는 페이지를 이동시킴.
				location.href="${cpath}/board/register";
			});
		});
		
		function checkModal(result){
			if(result == ''){
				return;
			}
			if(parseInt(result)> 0){
				$(".modal-body").text("게시글 " + result+"번이 등록되었습니다.");
				$("#myMessage").modal("show");
			}
		}
<c:forEach items="${list}" var="vo" varStatus="i">
<tr>
<td><a href="${cpath}/board/get?idx=${vo.idx}">${vo.title}</a></td>
<td>${vo.writer}</td>
<td><fmt:formatDate value="${vo.indate}" pattern="yyyy-MM-dd"/></td>
<td>${vo.count}</td>
BoardController.java
@GetMapping("/get")
	// 게시글 상세보기
	// 하나만 받아올 떄는 requestparam사용. idx를 받아와서 idx안에 넣겠다.
	public String get(@RequestParam("idx") int idx, Model model) {
		// 받아오는 자료는 board자료형태이고 이름은 vo이다.
		Board vo =service.get(idx);
		model.addAttribute("vo", vo);
		return "board/get";
	}
BoardService.java
public Board get(int idx);
BoardServiceImpl.java
	@Override
	public Board get(int idx) {
		// TODO Auto-generated method stub
		Board vo = mapper.read(idx);
		return vo;
	}
BoardMapper.java
public Board read(int idx);
BoardMapper.xml
	<select id="read" parameterType="int" resultType="kr.spring.entity.Board">
		SELECT * FROM TBLBOARD WHERE IDX= #{idx}
	</select>

 

get.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
	<%@ taglib prefix ="c" uri="http://java.sun.com/jsp/jstl/core" %>
	<%@ taglib prefix ="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<c:set var="cpath" value="${pageContext.request.contextPath}" />	
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet"
	href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script
	src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script
	src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
	<div class="container">
		<h2>Spring MVC07</h2>
		<div class="panel panel-default">
			<div class="panel-heading">Board</div>
			<div class="panel-body">
				<table class="table table-bordered table-hover">
						<tr>
							<td>번호</td>
							<td>${vo.idx}</td>
						</tr>
						<tr>
							<td>제목</td>
							<td><c:out value="${vo.title}"/></td>
						</tr>
						<tr>
							<td>내용</td>
							<td>
								<textarea class="form-control" readonly = "readonly" rows="10" cols=""><c:out value="${vo.content}"/></textarea>
							</td>
						</tr>
						<tr>
							<td>작성자</td>
							<td>${vo.writer}</td>
						</tr>
						
						<tr>
							<td colspan="2" style="text-align:center;" >
								<c:if test="${not empty mvo}">   
									<button data-btn="reply" class="btn btn-sm btn-primary">답글</button>
									<button data-btn="modify" class="btn btn-sm btn-success">수정</button>
								</c:if>
								<!--  -->
								<c:if test="${empty mvo}">   
									<button disabled="disabled" class="btn btn-sm btn-primary">답글</button>
									<button disabled="disabled" class="btn btn-sm btn-success">수정</button>
								</c:if>
								
								<button data-btn="list" class="btn btn-sm btn-warning">목록</button>
							</td>
						</tr>
									
				</table>
				<!--10/11 button에 location href없앰. -->
				<form id="frm" method="get" action="">
					<input id="idx" type="hidden" name="idx" value="${vo.idx}">
				</form>
				
			</div>
			<div class="panel-footer">스프링게시판-뇽뇽이</div>
		</div>
	</div>

	<script type="text/javascript">
		//10.11 링크처리(가독성, 보안(url노출 안됨.),유지보수 편리)//e:클릭했을 때, 요소를 감지하겠다.
		$(document).ready(function(){
			$("button").on("click",function(e){ 
				var formData=$("#frm");
				var btn =$(this).data("btn");
				
				//버튼이 reply이면 action을 아래 경로로 바꿔줌.
				if(btn=="reply"){
					formData.attr("action","${cpath}/board/reply");
				}else if(btn=="modify"){
					formData.attr("action","${cpath}/board/modify");
				}else if(btn=="list"){
					formData.attr("action","${cpath}/board/list");
					formData.find("#idx").remove();
					//list는 idx가 필요 없으니까 찾아서 없애줌.
				}
				
				formData.submit();
			}); //버튼 눌렀을 떄
			
		});
		
	
	</script>


</body>
</html>
⛤ 글 수정하기
get.jsp
<button onclick = "Location.href='${cpath}/board/list'" class="btn btn-sm btn-info">목록</button>
BoardController.java
	@GetMapping("/modify")
	//location.href는 get방식임.
	public String modify(@RequestParam("idx") int idx, Model model) {
		//model에 idx를 담아서 board/modify로 이동함.
		Board vo = service.get(idx);
		model.addAttribute("vo", vo);
		return "board/modify";
	}
modify.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
	<%@ taglib prefix ="c" uri="http://java.sun.com/jsp/jstl/core" %>
	<%@ taglib prefix ="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<c:set var="cpath" value="${pageContext.request.contextPath}" />	
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet"
	href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script
	src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script
	src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
	<div class="container">
		<h2>Spring MVC07</h2>
		<div class="panel panel-default">
			<div class="panel-heading">Board</div>
			<div class="panel-body">
			<!--이건 수정해서 post방식으로 보내는 거임.   -->
				<form action="${cpath}/board/modify" method="post">   
					<table class="table table-bordered table-hover">
							<tr>
								<td>번호</td>
								<td><input readonly="readonly" value="${vo.idx}" name="idx" type="text" class="form-control"></td>
							</tr>
							<tr>
								<td>제목</td>
								<td><input value="<c:out value='${vo.title}'/>" name="title" type="text" class="form-control"></td>
							</tr>
							<tr>
								<td>내용</td>
								<td>
									<textarea class="form-control" name="content" rows="10" cols=""><c:out value="${vo.content}"/></textarea>
								</td>
							</tr>
							<tr>
								<td>작성자</td>
								<td><input readonly="readonly" value="${vo.writer}" name="writer" type="text" class="form-control"></td>
							</tr>
							
							<tr>
								<td colspan="2" style="text-align:center;" >
									<c:if test="${not empty mvo && mvo.memID eq vo.memID }">
										<button type="submit" class="btn btn-sm btn-primary">수정완료</button>
										<button data-btn="remove" type="button" class="btn btn-sm btn-success">삭제</button>
									</c:if>
									<c:if test="${empty mvo or mvo.memID ne vo.memID }">
										<button disabled="disabled" type="submit" class="btn btn-sm btn-primary">수정완료</button>
										<button disabled="disabled" type="button" class="btn btn-sm btn-success">삭제</button>
									</c:if>
										<button data-btn="list" type="button"  class="btn btn-sm btn-warning">목록</button>
										<!-- cpath는 절대경로임. -->
								</td>
							</tr>					
					</table>
				</form>
				
				<!--10/11 button에 location href없앰. -->
				<form id="frm" method="get" action="">
					<input id="idx" type="hidden" name="idx" value="${vo.idx}">
				</form>
				
				
			</div>
			<div class="panel-footer">스프링게시판-뇽뇽이</div>
		</div>
	</div>

	<script type="text/javascript">
	//10.11 링크처리(가독성, 보안(url노출 안됨.),유지보수 편리)//e:클릭했을 때, 요소를 감지하겠다.
	$(document).ready(function(){
		$("button").on("click",function(e){ 
			var formData=$("#frm");
			var btn =$(this).data("btn");
			
			//버튼이 reply이면 action을 아래 경로로 바꿔줌.
			if(btn=="list"){
				formData.attr("action","${cpath}/board/list");
				formData.find("#idx").remove();
				//list는 idx가 필요 없으니까 찾아서 없애줌.
			}else if(btn=="remove"){
				formData.attr("action","${cpath}/board/remove");

			}
			
			formData.submit();
		}); //버튼 눌렀을 떄
		
	});
	
	
	</script>


</body>
</html>
BoardController.java
	@PostMapping("/modify")
	public String modify(Board vo) {
		service.modify(vo);
		return "redirect:/board/list";
	}
BoardService.java
public void modify(Board vo);
BoardServiceImpl.java
	@Override
	public void modify(Board vo) {
		mapper.update(vo);
	}
BoardMapper.java
public void update(Board vo);
BoardMapper.xml
	<update id="update" parameterType="kr.spring.entity.Board">
		UPDATE TBLBOARD 
		SET TITLE = #{title}, CONTENT = #{content}
		WHERE IDX = #{idx}
	</update>
글 삭제
BoardController.java
	
	@GetMapping("/remove")
	public String remove(@RequestParam("idx") int idx) {
		service.remove(idx);
		return"redirect:/board/list";
	}
BoardService.java
public void remove(int idx);
BoardServiceImpl.java
	@Override
	public void remove(int idx) {
		mapper.delete(idx);
	}
BoardMapper.java
	public void delete(int idx);
BoardMapper.xml
	<delete id="delete" parameterType="int">
		UPDATE TBLBOARD
		SET BOARDAVAILABLE=0 
		WHERE IDX=#{idx}
	</delete>