기존에 작성한 bbs_detail 페이지의 삭제 버튼에 대한 기능구현을 하려합니다.

먼저 삭제를 위해 BDao, BbsDao에 삭제관련된 인터페이스를 추가해주고 mapper/BDao.xml 에서는 삭제 쿼리문 작성 이들을 이용해 컨트롤로에서 삭제 수행 메소드를 작성하는 순서로 쓰겠습니다.


Dao/BDao.java 와 BbsDao.java의 수정


BDao.java

아래 메소드를 추가해줍니다.

public void Delete(String bbs_id);

BbsDao.java

	@Override
	public void Delete(String bbs_id) {
	}

mapper/BDao.xml의 수정


BDao.xml에 아래 쿼리문을 등록해줍니다.

	<delete id="Delete">
	DELETE
	FROM bbs
	WHERE bbs_id = #{bbs_id}
	</delete>

BbsController 의 수정


BbsController 의 하단에 아래 메소드를 추가해줍니다

	@ResponseBody
	@RequestMapping("/Delete")
	public String bbs_delete(HttpServletRequest request, Model model) {
		BDao dao = sqlSession.getMapper(BDao.class);
		dao.Delete(request.getParameter("bbs_id"));
		String str="<script>";
		str+="location.href='/app/bbs/';";
		str+="</script>";
		return str;
	}

위와 같이 작성하면 삭제가 잘 수행되는 것을 볼 수있다

'WEB > Spring' 카테고리의 다른 글

11) Spring - 게시글 수정  (0) 2019.11.18
10) Spring - 게시글 보기 구현  (0) 2019.11.01
9) Spring - 게시글 목록 구현  (0) 2019.11.01
8) Spring - 게시판 글쓰기 구현  (0) 2019.10.12
7) Spring - 로그아웃  (0) 2019.10.12

bbs_detail.jsp 수정


게시글 수정을 위해 게시글 상세 페이지에 버튼을 추가합니다.

기존 테이블 하단에 새로운 행을 생성하고 버튼을 추가해줍니다

<table width=80% height=500px border=1 align=center>
	<tr height=30px>
	<td align="center" colspan="1">제목</td>
	<td align="center" colspan="3"><c:out value="${detail.bbs_title}"/></td>
	</tr>
	<tr>
	<td align="center" width=25%>작성자</td>
	<td align="center" width=25%><c:out value="${detail.author}"/></td>
	<td align="center" width=25%>작성일</td>
	<td align="center" width=25%><c:out value="${detail.date}"/></td>
	</tr>
	<tr>
	<td align="center" colspan="4">내 용</td>
	</tr>
	<tr height = 500px>
	<td colspan="4"><c:out value="${detail.bbs_content}"/></td>
	</tr>
	<tr>
	<td colspan="2">
	<button onclick="location.href='/app/bbs/edit/${detail.bbs_id}';">수정</button>
	</td>
	<td colspan="2">
	<button>삭제</button>
	</td>
	</tr>
</table>

수정을 위한 bbs_edit.jsp 작성


<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
	
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form method="post" action="/app/EditAct">
		<table>
			<tr>
				<td>
					<table width="100%" cellpadding="0" cellspacing="0" border="0">
						<tr>
							<td>글쓰기</td>
						</tr>
					</table>
					<table>
						<tr>
							<td>&nbsp;</td>
							<td align="center">제목</td>
							<td><input name="bbs_title" size="50" maxlength="100" value="<c:out value="${detail.bbs_title}"/>"></td>
							<td>&nbsp;</td>
						</tr>
						<tr height="1">
							<td colspan="4"></td>
						</tr>
						<tr>
							<td>&nbsp;</td>
							<td align="center">내용</td>
							<td><textarea name="bbs_content" cols="50" rows="13"><c:out value="${detail.bbs_content}"/></textarea></td>
							<td>&nbsp;</td>
						</tr>
						<tr height="1">
							<td colspan="4"></td>
						</tr>
						<tr height="1">
							<td colspan="4"></td>
						</tr>
						<tr align="center">
							<td>&nbsp;</td>
							<td colspan="2"><input type="submit" value="수정">
							<td>&nbsp;</td>
						</tr>
						<input type="hidden" name="bbs_id" value="<c:out value="${detail.bbs_id}"/>">
					</table>
				</td>
			</tr>
		</table>
	</form>
</body>
</html>

위 코드는 게시글 보기 페이지 구현을 할때 사용한 jstl을 이용하여 구성하였습니다.

컨트롤러에서 model Attribute로 심어준 데이터를 html상에서 뿌려주는 역할을 합니다.


Dao/BbsDao.java 와 BDao.java 수정


BbsDao와 BDao에 수정을 위한 메소드 Edit을 추가해줍니다.

BDao

public interface BDao {
	public void Write(Map map);
	public ArrayList<BbsDto> list();
	public BbsDto detail(String bbs_id);
	public void Edit(Map map);
}

BbsDao

	public void Edit(Map map) {
		// TODO Auto-generated method stub
		
	}

mapper/BDao.xml 수정


BDao.xml에 UPDATE 쿼리를 등록합니다.

	<update id="Edit">
	UPDATE bbs
	SET
		bbs_title = #{bbs_title},
		bbs_content = #{bbs_content}
	WHERE bbs_id = #{bbs_id}
	</update>

 

BbsController 수정


bbsController에 이전 포스트에서 사용했던 PathVariable을 이용하여 수정 페이지에 접속하는 매핑 메소드를 생성해줍니다.

	@RequestMapping("/bbs/edit/{bbs_id}")
	public String bbs_edit(@PathVariable String bbs_id, Model model) {
		BDao dao = sqlSession.getMapper(BDao.class);
		BbsDto detail = dao.detail(bbs_id);
		model.addAttribute("detail", detail);
		return "bbs_edit";
	}

게시글의 수정이 이루어지는 메소드 입니다

	@ResponseBody
	@RequestMapping("/EditAct")
	public String EditAct(HttpSession session, HttpServletRequest request) throws UnsupportedEncodingException {
		request.setCharacterEncoding("utf-8");
		Map map = new HashMap();
		map.put("bbs_title", request.getParameter("bbs_title"));
		map.put("bbs_content", request.getParameter("bbs_content"));
		map.put("bbs_id", request.getParameter("bbs_id"));
		BDao dao = sqlSession.getMapper(BDao.class);
		dao.Edit(map);
		String str="<script>";
		str+="location.href='/app/bbs/';";
		str+="</script>";
		return str;
	}

위와 같이 작성하고 직접 접속하여 확인해보면 잘 수정되는 것을 볼 수 있습니다.

'WEB > Spring' 카테고리의 다른 글

12) Spring - 게시글 삭제  (0) 2019.11.19
10) Spring - 게시글 보기 구현  (0) 2019.11.01
9) Spring - 게시글 목록 구현  (0) 2019.11.01
8) Spring - 게시판 글쓰기 구현  (0) 2019.10.12
7) Spring - 로그아웃  (0) 2019.10.12

이전 글에서 게시글 목록까지 구현하였고, 이제 게시글 목록에서 게시글을 클릭하여 내용을 볼 수 있는 페이지를 만드려고한다.

먼저 게시글을 보기위한 jsp 부터 작성해주도록 한다.


bbs_detail.jsp 작성


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>bbs_detail</title>
</head>
<body>

<table width=80% height=500px border=1 align=center>
	<tr height=30px>
	<td align="center" colspan="1">제목</td>
	<td align="center" colspan="3"><c:out value="${detail.bbs_title}"/></td>
	</tr>
	<tr>
	<td align="center" width=25%>작성자</td>
	<td align="center" width=25%><c:out value="${detail.author}"/></td>
	<td align="center" width=25%>작성일</td>
	<td align="center" width=25%><c:out value="${detail.date}"/></td>
	</tr>
	<tr>
	<td align="center" colspan="4">내 용</td>
	</tr>
	<tr height = 500px>
	<td colspan="4"><c:out value="${detail.bbs_content}"/></td>
	</tr>
</table>
</body>
</html>

BbsDao, BDao 수정


BbsDao와 BDao에 아래 메소드를 추가해준다.

public BbsDto detail(String bbs_id);

mapper/BDao.xml 수정


아래 쿼리문을 추가해준다.

<select id="detail" resultType="com.app.app.Dto.BbsDto">
	SELECT *
		FROM bbs
		WHERE bbs_id = #{bbs_id}
</select>

위 쿼리문은 BbsController가 넘겨운 bbs_id를 통해 DB의 bbs테이블에서 해당 아이디를 가진 게시글을 BbsDto로 리턴해준다.


BbsController - bbs_detail 메소드 추가


	@RequestMapping("/bbs/{bbs_id}")
	public String bbs_detail(@PathVariable String bbs_id, Model model) {
		BDao dao = sqlSession.getMapper(BDao.class);
		BbsDto detail = dao.detail(bbs_id);
		model.addAttribute("detail", detail);
		return "bbs_detail";
	}

위의 코드에서

	@RequestMapping("/bbs/{bbs_id}")
	public String bbs_detail(@PathVariable String bbs_id, Model model) {

위 부분은 url /bbs/뒤에 들어오는 게시글 번호를 변수로 사용할 수 있게 해준다.

ex) http://~/app/bbs/5 -> 게시글 번호가 5번인 게시글 조회

PathVariable로 지정된 {bbs_id}는 DB에서 게시글 조회를 위한 키 넘버로 쓰인다.


 위와 같이 다 작성한 후 게시글 조회를 시도해보자.

위와 같이 나온다면 제대로 한 것이다.

'WEB > Spring' 카테고리의 다른 글

12) Spring - 게시글 삭제  (0) 2019.11.19
11) Spring - 게시글 수정  (0) 2019.11.18
9) Spring - 게시글 목록 구현  (0) 2019.11.01
8) Spring - 게시판 글쓰기 구현  (0) 2019.10.12
7) Spring - 로그아웃  (0) 2019.10.12

이전 글에서 글쓰기 까지 구현 하였고, 이번 게시글에서는 글 목록 구현을 하겠습니다.

먼저 목록에 접근하기위한 링크를 메인화면에 삽입하겠습니다


index.jsp의 수정


<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">

<title>Index</title>
</head>
<body>
Login ID:
<c:out value="${sessionScope.user_id }" default="null"/>
<table border="1" align="center" width="500" height="400">
	<tr>
		<td colspan="4" height="100" align="center">Main page</td>
	</tr>
	<tr>
		<td colspan="4" height="100" align="center"><a href="write">글 쓰기</a></td>
	</tr>
	<tr>
		<td colspan="4" height="100" align="center"><a href="bbs">글 목록</a></td>
	</tr>
	<tr>
	<c:if test="${empty sessionScope.user_id}">
		<td colspan="2" align="center" width="250"><a href="Login">로그인</a></td>
	</c:if>
	
	<c:if test="${!empty sessionScope.user_id}">
		<td colspan="2" align="center" width="250"><a href="Logout">로그아웃</a></td>
	</c:if>
		<td colspan="2" align="center" width="250"><a href="Register">회원가입</a></td>
	</tr>
</table>
</body>
</html>

Controller/BbsController - bbs 메소드 작성


게시글 목록 조회에 대한 처리를 해주는 메소드 bbs를 작성합니다.

	@RequestMapping("/bbs")
	public String bbs(Model model) {
		
		BDao dao = sqlSession.getMapper(BDao.class);
		ArrayList<BbsDto> list = dao.list();
		model.addAttribute("list",list);
		return "bbs";
	}

model.addAttribute("list", list) 는 DB조회를 통해 생성된 list 객체 배열을 jsp에서 쓰기위해 속성으로 추가해주는 과정입니다.


Dao/BDao, BbsDao - DB 조회를 위한 list 메소드 추가


BDao에 list 메소드를 추가합니다.

package com.app.app.Dao;

import java.util.ArrayList;
import com.app.app.Dto.BbsDto;
import java.util.Map;
import com.app.app.Dto.UserDto;

public interface BDao {
	public void Write(Map map);
	public ArrayList<BbsDto> list();
}

mapper/Bdao.xml 수정


게시글 조회를 위한 쿼리를 추가해줍니다.

	<select id="list" resultType="com.app.app.Dto.BbsDto">
	SELECT *
		FROM bbs
	</select>
	

JSTL 을 이용한 bbs.jsp 작성


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<table width=80% height=70% border=1 align=center>
	<tr>
	<th width=10% align="">글 번호</th>
	<th width=20%>작성자</th>
	<th width=40%>글 제목</th>
	<th width=30%>작성일</th>
	</tr>
	<c:forEach var="bbs" items="${list }">
	<tr align="center">
	<td> <c:out value="${bbs.bbs_id }"/></td>
	<td> <c:out value="${bbs.author }"/></td>
	<td align="left"><a href='bbs/<c:out value="${bbs.bbs_id }"/>'> <c:out value="${bbs.bbs_title }"/></a></td>
	<td> <c:out value="${bbs.date }"/></td>
	</tr>
	</c:forEach>
	<tr>
	</tr>
</table>
</body>
</html>

 

위의 <c:forEach var="bbs" items="${list}"> ~ 의 코드는 JSTL tag로서 forEach는 for 문이라고 생각하면 된다.

bbsController에서 게시글 목록조회하여 속성으로 심어준 ArrayList<BbsDto> list 객체를 화면에 순서대로 뿌려주는 역할을 한다.

JSTL을 잘 이용하면 코드 가독성이 높아지고 간결화된다.

예를 들면 위의 코드를 스크립트릿을 이용하여 작성하면 이렇게 된다.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="com.app.app.Dto.BbsDto" %>
<%@ page import="java.util.ArrayList" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<table width=80% height=70% border=1 align=center>
	<tr>
	<th width=10% align="">글 번호</th>
	<th width=20%>작성자</th>
	<th width=40%>글 제목</th>
	<th width=30%>작성일</th>
	</tr>
	<%
	ArrayList<BbsDto> bbs = new ArrayList<BbsDto>();
	bbs = (ArrayList<BbsDto>)request.getAttribute("list");
	for(int i=0; i<bbs.size(); i++){
	%>
	<tr align="center">
	<td> <%=bbs.get(i).getBbs_id() %>
	<td> <%=bbs.get(i).getAuthor() %>
	<td align="left"><a href='bbs/<%=bbs.get(i).getBbs_id()%>'> <%=bbs.get(i).getBbs_title() %></a></td>
	<td> <%=bbs.get(i).getDate() %></td>
	</tr>
	<%
	}
	%>
    <tr>
	</tr>
</table>
</body>
</html>

java.util.ArrayList 와 com.app.app.Dto.BbsDto를 따로 import 해주어야 하고 같은 기능을 하는 코드인데 더 많은 코드를 요구로한다.


이제 게시글을 작성하고 확인해보자.

위와 같이 나온다면 제대로 한것이다.

 

'WEB > Spring' 카테고리의 다른 글

11) Spring - 게시글 수정  (0) 2019.11.18
10) Spring - 게시글 보기 구현  (0) 2019.11.01
8) Spring - 게시판 글쓰기 구현  (0) 2019.10.12
7) Spring - 로그아웃  (0) 2019.10.12
6) Spring - 로그인(Session 이용)  (0) 2019.10.08

게시판 Table 생성


mysql command를 키고 아래 코드를 입력합니다.

USE BBS;
 
CREATE TABLE IF NOT EXISTS bbs(
    bbs_id INT(10) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    bbs_title VARCHAR(32) NOT NULL,
    bbs_content VARCHAR(1000) NOT NULL,
    author VARCHAR(32) NOT NULL,
    date DATETIME DEFAULT CURRENT_TIMESTAMP
    );


BbsDto 생성


Dto 패키지 아래에 BbsDto를 생성해줍니다.

package com.app.app.Dto;

public class BbsDto {
	private String bbs_id;
	private String bbs_title;
	private String bbs_content;
	private String author;
	private String date;
	public String getBbs_id() {
		return bbs_id;
	}
	public void setBbs_id(String bbs_id) {
		this.bbs_id = bbs_id;
	}
	public String getBbs_title() {
		return bbs_title;
	}
	public void setBbs_title(String bbs_title) {
		this.bbs_title = bbs_title;
	}
	public String getBbs_content() {
		return bbs_content;
	}
	public void setBbs_content(String bbs_content) {
		this.bbs_content = bbs_content;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	public String getDate() {
		return date;
	}
	public void setDate(String date) {
		this.date = date;
	}
}

index.jsp 수정


<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">

<title>Index</title>
</head>
<body>
Login ID:
<c:out value="${sessionScope.user_id }" default="null"/>
<table border="1" align="center" width="500" height="300">
	<tr>
		<td colspan="4" height="100" align="center">Main page</td>
	</tr>
	<tr>
		<td colspan="4" height="100" align="center"><a href="write">글 쓰기</a></td>
	</tr>
	<tr>
	<c:if test="${empty sessionScope.user_id}">
		<td colspan="2" align="center" width="250"><a href="Login">로그인</a></td>
	</c:if>
	
	<c:if test="${!empty sessionScope.user_id}">
		<td colspan="2" align="center" width="250"><a href="Logout">로그아웃</a></td>
	</c:if>
		<td colspan="2" align="center" width="250"><a href="Register">회원가입</a></td>
	</tr>
</table>
</body>
</html>


wirte.jsp 작성


<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form method="post" action="WriteAct">
		<table>
			<tr>
				<td>
					<table width="100%" cellpadding="0" cellspacing="0" border="0">
						<tr>
							<td>글쓰기</td>
						</tr>
					</table>
					<table>
						<tr>
							<td>&nbsp;</td>
							<td align="center">제목</td>
							<td><input name="bbs_title" size="50" maxlength="100"></td>
							<td>&nbsp;</td>
						</tr>
						<tr height="1">
							<td colspan="4"></td>
						</tr>
						<tr>
							<td>&nbsp;</td>
							<td align="center">내용</td>
							<td><textarea name="bbs_content" cols="50" rows="13"></textarea></td>
							<td>&nbsp;</td>
						</tr>
						<tr height="1">
							<td colspan="4"></td>
						</tr>
						<tr height="1">
							<td colspan="4"></td>
						</tr>
						<tr align="center">
							<td>&nbsp;</td>
							<td colspan="2"><input type=button value="등록">
							<td>&nbsp;</td>
						</tr>
					</table>
				</td>
			</tr>
		</table>
	</form>
</body>
</html>

BDao , BbsDao 생성


Dao 패키지 아래에 BDao를 생성합니다.

package com.app.app.Dao;

import java.util.ArrayList;
import java.util.Map;
import com.app.app.Dto.UserDto;

public interface Bdao {
	public void Write(Map map);
}

BbsDao 도 생성해줍니다

package com.app.app.Dao;

import java.util.Map;

public class BbsDao implements BDao{

	@Override
	public void Write(Map map) {
	}

}

BDao.xml 생성


mapper 패키지 아래에 BDao.xml을 생성해줍니다.

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.app.app.Dao.BDao">

	<insert parameterType="Map" id="Write">
	INSERT INTO
		BBS (bbs_title, bbs_content, author)
		VALUES(#{bbs_title}, #{bbs_content}, #{author}) 
	</insert>
</mapper>

BbsController 수정


package com.app.app.Controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.app.app.Dao.BDao;
import com.app.app.Dao.BbsDao;
import com.app.app.Dto.BbsDto;

import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.json.simple.JSONObject;




@Controller
public class BbsController {
	@Autowired
	private SqlSession sqlSession;
	
	private static final Logger logger = LoggerFactory.getLogger(AppController.class);
	
	
	@RequestMapping("/write")
	public String Write(Model model, HttpSession session, HttpServletResponse response) throws IOException {
		if(session.getAttribute("user_id") == null) {
			System.out.println("로그인세션 없음");
			response.setContentType("text/html; charset=UTF-8");
			PrintWriter out = response.getWriter();
			out.println("<script>alert('잘못된 접근'); history.back();</script>");
			out.flush();
		}
			
	return "write";	
	}
	@RequestMapping("/WriteAct")
	public String Write(HttpSession session, HttpServletRequest request) {
		Map map = new HashMap();
		map.put("bbs_title", request.getParameter("bbs_title"));
		map.put("bbs_content", request.getParameter("bbs_content"));
		map.put("author", session.getAttribute("user_id"));
		BDao dao = sqlSession.getMapper(BDao.class);
		dao.Write(map);
		return "index";
	}
}

이제 글쓰기를 해보자

mysql command에서 

use bbs;

select * from bbs; 를 입력하여 확인해보자

위와 같이 나오면 성공한것이다

index.jsp 수정


페이지 상단에 jstl 사용을 위한 taglib를 추가해줍니다.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

세션을 체크하여 로그인된 상태에서는 로그아웃이 나오게 하고,

로그인이 필요한 상태에서는 로그인이 나오게 코드를 작성합니다 아래 코드는 jstl문법으로 작성된 코드입니다.

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">

<title>Index</title>
</head>
<body>
<table border="1" align="center" width="500" height="200">
	<tr>
		<td colspan="4" height="100" align="center">Main page</td>
	</tr>
	<tr>
	<c:if test="${empty sessionScope.user_id}">
		<td colspan="2" align="center" width="250"><a href="Login">로그인</a></td>
	</c:if>
	
	<c:if test="${!empty sessionScope.user_id}">
		<td colspan="2" align="center" width="250"><a href="Logout">로그아웃</a></td>
	</c:if>
		<td colspan="2" align="center" width="250"><a href="Register">회원가입</a></td>
	</tr>
</table>
Login ID:
<c:out value="${sessionScope.user_id }" default="null"/>
</body>
</html>

AppController 수정


AppController에 로그아웃을 위한 메소드 Logout을 새로 만들어줍니다.

	@ResponseBody
	@RequestMapping("/Logout")
	public String Logout(HttpSession session) {
		session.invalidate();
		String str = "<script>";
		str+="alert('Logout success');";
		str+="window.location.href = '/app';";
		str+="</script>";
		return str;
	}

AppController 수정


Login을 처리해줄 LoginAct 메소드 생성

	@RequestMapping("/LoginAct")
	public String LoginAct(HttpSession session, HttpServletRequest request) {
		String id = request.getParameter("id");
		String password = request.getParameter("password");
		System.out.println("로그인 시도\nID:"+id+"\npassword:"+password);
		
		return null;
	}

위와 같이 입력하고 Login페이지에서 값을 전송해 본다.

로그인 버튼을 누르면 서버 Log에 

로그인 시도
ID:test
password:test

위와 같이 찍힌다 이제 추출한 값을 가지고 DB조회를 하여 입력된 id와 password가 일치하는지 확인한다


UDao와 UserDao 수정


UDao에 아래 코드를 추가해준다

	public UserDto Login(Map map);

UserDao에도 아래 코드를 추가한다

	@Override
	public UserDto Login(Map map) {
		return null;
	}

로그인을 위한 SQL 작성


UDao.xml에 아래 코드를 추가해준다

	<select parameterType="Map" id="Login" resultType="com.app.app.Dto.UserDto">
	SELECT user_id FROM user WHERE user_id = #{id} AND password = #{password}
	</select> 

위 SQL문은 id와 password 를 이용하여 두 값이 모두 일치하는 user_id를 뽑아낸다.

만약 id나 password 둘중 하나라도 틀리면 결과 값이 반환되지 않는다.


AppController - LoginAct 수정


	@ResponseBody
	@RequestMapping("/LoginAct")
	public String LoginAct(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException {
		//PrintWriter out = response.getWriter();
		String id = request.getParameter("id");
		String password = request.getParameter("password");
		System.out.println("로그인 시도\nID:"+id+"\npassword:"+password);
		Map map = new HashMap();
		map.put("id", id);
		map.put("password", password);
		UDao dao = sqlSession.getMapper(UDao.class);
		UserDto dto = dao.Login(map);
		if(dto != null) {
			session.setAttribute("user_id", id);
			String str = "<script>";
			str+="alert('Login success');";
			str+="window.location.href = '/app';";
			str+="</script>";
			return str;
		}
		else {
			session.setAttribute("user_id", id);
			String str = "<script>";
			str+="alert('Login fail');";
			str+="history.back();";
			str+="</script>";
			return str;
		}	
	}

로그인을 시도해보자

성공한 경우

실패한 경우

json을 이용하기 위한 lib 추가

pom.xml에 아래 코드를 추가해 줍니다.

<!-- json parser -->
<dependency>
	<groupId>com.googlecode.json-simple</groupId>
	<artifactId>json-simple</artifactId>
	<version>1.1</version>
</dependency>
<!-- jackson -->
<dependency>
	<groupId>org.codehaus.jackson</groupId>
	<artifactId>jackson-mapper-asl</artifactId>
	<version>1.9.13</version>
</dependency>

Register.jsp 수정

ajax를 이용하기위해 jquery를 추가해주고 버튼을 만들어 줍니다.

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>회원가입</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
	<form name="Register" method="post" action="RegisterAct">
		<table border="1" align="center" width="500" height="500">
			<tr>
				<td colspan="4" height="100" align="center">회원가입</td>
			</tr>
			<tr>
				<td colspan="1" height="100" align="center">ID</td>
				<td colspan="2" height="100" align="center">
				<input type="text" name="user_id" id="user_id">
				</td>
				<td align="center">
				<button id="duplicate_check" type="button" onclick="check();">중복체크</button>
				</td>
			</tr>
			<tr>
				<td colspan="1" height="100" align="center">Password</td>
				<td colspan="3" height="100" align="center">
				<input type="text" name="password">
				</td>
			</tr>
			<tr>
				<td colspan="1" height="100" align="center">NickName</td>
				<td colspan="3" height="100" align="center">
				<input type="text" name="nickname">
				</td>
			</tr>
			<tr>
				<td colspan="1" height="100" align="center">Name</td>
				<td colspan="3" height="100" align="center">
				<input type="text" name="name">
				</td>
			</tr>
			<tr>
				<td colspan="4" height="100" align="center"><input type = "submit" value="가입하기"></td>
			</tr>
		</table>
		
	</form>
</body>
</html>

</body>아래 function check를 만들어 줍니다.

<script>
function check(){
	id = $("#user_id").val();
	
	$.ajax({
	    url: 'ID_Check',
	    type: 'POST',
	    dataType: 'text', //서버로부터 내가 받는 데이터의 타입
	    contentType : 'text/plain; charset=utf-8;',//내가 서버로 보내는 데이터의 타입
	    data: id ,

	    success: function(data){
	         if(data == 0){
	         console.log("아이디 없음");
	         alert("사용하실 수 있는 아이디입니다.");
	         }else{
	         	console.log("아이디 있음");
	         	alert("중복된 아이디가 존재합니다.");
	         }
	    },
	    error: function (){        
	                      
	    }
	  });


}
</script>

UDao와 UserDao 수정

interface UDao에 아이디 중복 체크와 관련된 새로운 메소드를 생성해 줍니다.

package com.app.app.Dao;

import java.util.ArrayList;
import java.util.Map;
import com.app.app.Dto.UserDto;

public interface UDao {
	public void Register(Map map);
	public UserDto Id_Check(String id);
}

UDao의 구현클래스 UserDao에서 추가된 메소드를 재정의 해줍니다.

package com.app.app.Dao;
import java.util.ArrayList;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

import com.app.app.Dto.UserDto;
public class UserDao implements UDao{

	JdbcTemplate template;
	
	@Autowired
	public void setTemplate(JdbcTemplate template) {
		this.template = template;
	}
	
	@Override
	public void Register(Map map) {	}
	@Override
	public UserDto Id_Check(String id) { 
		return null;
	}
	

}

mapper 수정

com.app.app.mapper에 있는 UDao.xml에 아래 구문을 추가해줍니다.

	<select parameterType="String" id="Id_Check" resultType="com.app.app.Dto.UserDto">
	SELECT user_id FROM user where user_id = #{id}
	</select>

AppController 수정

Register페이지에서 /ID_Check 로 보낸 아이디값을 DB에서 조회하고 중복 여부를 알려주는 메소드 ID_Check를 만들어 줍니다.

	@ResponseBody
	@RequestMapping(value = "/ID_Check", produces="text/plane")
	public String ID_Check(@RequestBody String paramData) throws ParseException {
		//클라이언트가 보낸 ID값
		String ID = paramData.trim();
		System.out.println(ID);
		UDao dao = sqlSession.getMapper(UDao.class);
		UserDto dto = dao.Id_Check(ID);
		
		if(dto != null) {//결과 값이 있으면 아이디 존재	
			return "-1";
		} else {		//없으면 아이디 존재 X
			System.out.println("null");
			return "0";
		}
	}

Register 페이지에 접속하여 확인해봅시다.

'WEB > Spring' 카테고리의 다른 글

7) Spring - 로그아웃  (0) 2019.10.12
6) Spring - 로그인(Session 이용)  (0) 2019.10.08
4) Spring - 회원가입 처리하기.  (0) 2019.09.26
3) Spring - RequestMapping 하기  (0) 2019.09.25
2) Spring - 기본설정(MyBatis)  (0) 2019.09.25

+ Recent posts