교육 52일차

권재현·2021년 6월 3일
0

교육

목록 보기
37/49
post-thumbnail

글쓰기

게시판 글쓰기 동작 순서에 대한 그림 쉽지않다.
글쓰기에 대해 부분은 DB이후 추가됐다

코드
TestController

ackage com.spring.sample.web.test.controller;

import java.util.HashMap;
import java.util.List;

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

import com.spring.sample.web.test.service.ITestService;

@Controller
public class TestController {

	//객체주입 받겠다.
	@Autowired
	public ITestService iTestService;
	
	@RequestMapping(value="/test1")
	
	public ModelAndView test1(ModelAndView mav) throws Throwable {
		
		List<HashMap<String, String>>list
					= iTestService.getBList();
		
		mav.addObject("list", list);
		
		mav.setViewName("test/test1");
	
		return mav;
		
	}
	
	
//	@RequestMapping(value="/testMList")
//	public ModelAndView testMList(ModelAndView mav) throws Throwable{
//		
//		List<HashMap<String, String>>list1
//							= iTestService.getMList();
//		
//		mav.addObject("list", list1);
//		
//		mav.setViewName("test/testMList");
//		
//		return mav;
//	}
	
	@RequestMapping(value="/test2")
	public ModelAndView tes2(
			@RequestParam HashMap<String, String> params,
			ModelAndView mav) throws Throwable{
		if(params.get("bNo") !=null) {
			//단일 컬럼은 해쉬맵으로 갖고온다
			HashMap<String, String> data
			=iTestService.getB(params);
			
			mav.addObject("data", data);
			
			mav.setViewName("test/test2");
			
		} else {
			//redirect: 주소 => 해당주소로 이동. 즉, 컨트롤러에서 컨트롤러로 이동
			//					get방식만 적용됨
			mav.setViewName("redirect:test1");
		}
		
		return mav;
	}

	@RequestMapping(value="/ajaxTest")
	public  ModelAndView ajaxtest(ModelAndView mav) {
		
		mav.setViewName("test/ajaxTest");
		return mav;
	}
	
	@RequestMapping(value="/test3")
	public ModelAndView test3(ModelAndView mav) {
		mav.setViewName("test/test3");
		
		return mav;
	}
	
	@RequestMapping(value="/test3s")
	public ModelAndView test3s(
			@RequestParam HashMap<String, String> params,
			ModelAndView mav) {
		/*
		 * int cnt = iTestService.addB(params);
		 * 
		 * if(cnt > 0) {
		 *  mav.setViewName("redirect:test1"); 
		 *  } else {
		 * mav.addObject("msg", "등록실패"); 
		 * mav.setViewName("redirect:test3");  
		 * }
		 */
		
			try {
				int cnt = iTestService.addB(params);
				
				if(cnt > 0 ) {
					 mav.setViewName("redirect:test1");
				} else {
					 mav.addObject("msg", "등록실패");
					 mav.setViewName("test/test3s");
				}
				
			} catch (Throwable e) {
				e.printStackTrace();
				 mav.addObject("msg", "오류발생");
				 mav.setViewName("test/test3s");
			}
			
		
		return mav;
	}
}

ITestService

package com.spring.sample.web.test.service;

import java.util.HashMap;
import java.util.List;

public interface ITestService {

	public List<HashMap<String, String>> getBList() throws Throwable;

	/* public List<HashMap<String, String>> getMList() throws Throwable; */

	public HashMap<String, String> getB(HashMap<String, String> params) throws Throwable;

	public int addB(HashMap<String, String> params) throws Throwable;
}

TestService

package com.spring.sample.web.test.service;

import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.spring.sample.web.test.dao.ITestDao;

@Service
public class TestService implements ITestService {

	//객체 주입 받겠다.
	@Autowired
	public ITestDao iTestDao;
	
	@Override
	public List<HashMap<String, String>> getBList() throws Throwable {
		
		return iTestDao.getBList();
	}

	/*
	 * @Override public List<HashMap<String, String>> getMList() throws Throwable {
	 * 
	 * return iTestDao.getMList(); }
	 */

	@Override
	public HashMap<String, String> getB(HashMap<String, String> params) throws Throwable {
		
		return iTestDao.getB(params);
	}

	@Override
	public int addB(HashMap<String, String> params) throws Throwable {
		
		return iTestDao.addB(params);
	}

}

ITestDao

package com.spring.sample.web.test.dao;

import java.util.HashMap;
import java.util.List;

public interface ITestDao {
	
	public List<HashMap<String, String>> getBList() throws Throwable;

	/* public List<HashMap<String, String>> getMList() throws Throwable; */

	public HashMap<String, String> getB(HashMap<String, String> params) throws Throwable;

	public int addB(HashMap<String, String> params) throws Throwable;
}

TestDao

package com.spring.sample.web.test.dao;

import java.util.HashMap;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

//저장소에 접근한다.
@Repository
public class TestDao implements ITestDao {

	@Autowired
	public SqlSession sqlSession;

	@Override
	public List<HashMap<String, String>> getBList() throws Throwable {
		
		return sqlSession.selectList("B.getBList");
	}
	/*
	 * @Override public List<HashMap<String, String>> getMList() throws Throwable {
	 * 
	 * return sqlSession.selectList("M.getMList"); }
	 */

	@Override
	public HashMap<String, String> getB(HashMap<String, String> params) throws Throwable {
		//단일row selectOne
		return sqlSession.selectOne("B.getB",params);
	}

	@Override
	public int addB(HashMap<String, String> params) throws Throwable {
		
		return sqlSession.insert("B.addB",params);
	}
	
}

DB

INSERT INTO B(B_NO, B_TITLE,B_WRITER, B_CON)
VALUES(B_SEQ.NEXTVAL, 'TEST중', '홍길동', '테스트용')
;

SELECT *
FROM B
;

B_SQL

<?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="B"><!-- namespace: 클래스명과동일 -->
	<!-- id: 메소드명과 동일 -->
	<!-- resultType: row 1줄의 형태를 지정 -->
	<!-- 쿼리 작성 시 ; 이 들어가면 실행 되지 않음 -->
	<select id="getBList" resultType="hashmap">
	SELECT B_NO, B_TITLE, B_WRITER, TO_CHAR(B_DT, 'YYYY-MM-DD')AS B_DT
	FROM B
	ORDER BY B_NO DESC
	</select>
	<!-- parameterType은 받는 값타입에 대한 것 resultType: 쿼리결과타입에 대한 것 -->
	<select id="getB" parameterType="hashmap" resultType="hashmap">
	SELECT B_NO, B_TITLE, B_WRITER, B_CON, TO_CHAR(B_DT, 'YYYY--MM--DD') AS B_DT
	FROM B
	WHERE B_NO = #{bNo}
	</select>
	<!-- 값만 넣어주면 되기 때문에 resultType이 필요없음  -->
	<insert id="addB" parameterType="hashmap">
		INSERT INTO B(B_NO, B_TITLE,B_WRITER, B_CON)
		VALUES(B_SEQ.NEXTVAL, #{bTitle}, #{bWriter}, #{bCon})
	</insert>
</mapper>

VALUES에 넣을 때 주의사항 ID 정확하게 입력, 그리고 따옴표 지우기 !!

Test1

<%@ 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>
<style type="text/css">
thead{
	background-color: orange;
}
</style>
<script type="text/javascript"
		src="resources/script/jquery/jquery-1.12.4.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
	$("tbody").on("click", "tr", function(){
		$("#bNo").val($(this).attr("name")); //여기서 this는 클릭한 tr
		$("#goForm").submit();
	}); //tbody end
	
	$("#addBtn").on("click", function(){
		location.href = "test3";
	});//addBtn end
	
}); //ready end
</script>
</head>
<body>
<form action="test2" id="goForm" method="post">
	<input type="hidden" id="bNo" name="bNo"/>
</form>
<input type="button" value="작성" id="addBtn"/>
<table>
	<thead>
		<tr>
			<th>번호</th>
			<th>제목</th>
			<th>작성자</th>
			<th>작성일</th>
		</tr>
	</thead>
	<tbody>
		<c:forEach var="data" items="${list}">
			<tr name="${data.B_NO}">
				<td>${data.B_NO}</td>
				<td>${data.B_TITLE}</td>
				<td>${data.B_WRITER}</td>
				<td>${data.B_DT}</td>
			</tr>
		</c:forEach>
	</tbody>
</table>
</body>
</html>

form 태그와 제이쿼리 부분이 추가 됐다.

Test3

<%@ 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>
<script type="text/javascript"
		src="resources/script/jquery/jquery-1.12.4.min.js"></script>
<script type="text/javascript"
		src="resources/script/ckeditor/ckeditor.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
	CKEDITOR.replace("bCon", {
		resize_enabled : false,
		languague : "ko",
		enterMode : "2",
		width : "600",
		height: "300"
	});
	
	$("#listBtn").on("click", function(){
		history.back();
	});
	//form에서 작성하다 엔터누를 시 실행 방지 
	$("#addForm").on("keypress", "input", function(event){
		if(event.keyCode ==13 ){
			return false;
		}
	});
	
	$("#addBtn").on("click",function(){
		$("#bCon").val(CKEDITOR.instances['bCon'].getData());
		//입력된게 없는 경우
		if($.trim($("#bTitle").val()) == ""){
			alert("제목을 입력해주세요");
			$("#bTitle").focus();
		} else if($.trim($("#bWriter").val()) == ""){
			alert("작성자를 입력해주세요");
			$("#bWriter").focus();
		} else if($.trim($("#bCon").val()) == ""){
			alert("내용을 입력해 주세요");
			$("#bCon").focus();
		} else{
			$("#addForm").submit();
		}
	}); //addBtn end
}); //ready end
</script>
</head>
<body>
<form action="test3s" id="addForm" method="post">
제목<input type="text" id="bTitle" name="bTitle"/><br/>
작성자<input type="text" id="bWriter" name="bWriter" /><br/>
내용<br/>
<textarea rows="20" cols="50" id="bCon" name="bCon"></textarea><br/>
</form>
<input type="button" value="등록" id="addBtn"/>
<input type="button" value="목록으로" id="listBtn"/>
</body>
</html>

Test3s

<%@ 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>
<script type="text/javascript">
// el tag를 script에서 사용 시 ""로  묵어야 함
// alert(오류발생);  <- 따옴표 없을 시 오류난다
// alert("오류발생");  <- 따옴표 있을 시
alert("${msg}");
history.back();
</script>
</head>
<body>

</body>
</html>

실습 결과



회원등록 실습

TestDController

package com.spring.sample.web.test.controller;

import java.util.HashMap;
import java.util.List;

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

import com.spring.sample.web.test.service.ITestDService;

@Controller
public class TestDController {

	@Autowired
	public ITestDService iTestDService;
	
	@RequestMapping(value="/testDList")
	public ModelAndView testDList(ModelAndView mav) throws Throwable {
		
		List<HashMap<String, String>>list
					= iTestDService.getDList();
		
		mav.addObject("list",list);
		
		mav.setViewName("test/testDList");
		
		return mav;
	}
	
	@RequestMapping(value="/testDDetail")
	public ModelAndView tesD2(
			@RequestParam HashMap<String, String> params,
			ModelAndView mav) throws Throwable{
		if(params.get("dNo") !=null) {
			HashMap<String, String> data
					=iTestDService.getD(params);
			
			mav.addObject("data", data);
			
			mav.setViewName("test/testDDetail");
			
			
		} else {
			mav.setViewName("redirect:testDList");
		}
		
		return mav;
		
	}
	@RequestMapping(value="/testDAdd")
	public ModelAndView testDAdd(ModelAndView mav) {
		
		mav.setViewName("test/testDAdd");
		
		return mav;
		
	}
	
	@RequestMapping(value="/testDAdds")
	public ModelAndView testDAdds(
			@RequestParam HashMap<String, String> params,
			ModelAndView mav) throws Throwable {
			
			int cnt = iTestDService.addD(params);
			
			if(cnt > 0) {
				mav.setViewName("redirect: testDList");
			} else {
				mav.addObject("msg", "등록실패");
				mav.setViewName("redirect: testDAdd");
			}
		
		return mav;
		
	}
	

ITestDService

package com.spring.sample.web.test.service;

import java.util.HashMap;
import java.util.List;

public interface ITestDService {

	public List<HashMap<String, String>> getDList() throws Throwable;

	public HashMap<String, String> getD(HashMap<String, String> params) throws Throwable;

	public int addD(HashMap<String, String> params) throws Throwable;

}

TestDService

package com.spring.sample.web.test.service;

import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.spring.sample.web.test.dao.ITestDDao;

@Service
public class TestDService implements ITestDService {
	
	@Autowired
	public ITestDDao iTestDDao;

	@Override
	public List<HashMap<String, String>> getDList() throws Throwable {
		
		return iTestDDao.getDList();
	}

	@Override
	public HashMap<String, String> getD(HashMap<String, String> params) throws Throwable {
		return iTestDDao.getD(params);
	}

	@Override
	public int addD(HashMap<String, String> params) throws Throwable {
		
		return iTestDDao.addD(params);
	}

}

ITestDDao

package com.spring.sample.web.test.dao;

import java.util.HashMap;
import java.util.List;

public interface ITestDDao {

	public List<HashMap<String, String>> getDList() throws Throwable;

	public HashMap<String, String> getD(HashMap<String, String> params)throws Throwable;

	public int addD(HashMap<String, String> params) throws Throwable;

}

TestDDao

package com.spring.sample.web.test.dao;

import java.util.HashMap;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class TestDDao implements ITestDDao {

	@Autowired
	public SqlSession sqlSession;
	
	@Override
	public List<HashMap<String, String>> getDList() throws Throwable {

		return sqlSession.selectList("D.getDList");
	}

	@Override
	public HashMap<String, String> getD(HashMap<String, String> params) throws Throwable {
		
		return sqlSession.selectOne("D.getD", params);
	}

	@Override
	public int addD(HashMap<String, String> params) throws Throwable {
		
		return sqlSession.insert("D.addD", params);
	}

}

testDList

<%@ 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>
<style type="text/css">
thead{
	background-color: auqa;
}
</style>
<script type="text/javascript"
		src="resources/script/jquery/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
	$("tbody").on("click", "tr", function(){
		$("#dNo").val($(this).attr("name"));
		$("#goForm").submit();
	});
	
	$("#addBtn").on("click",function(){
		location.href = "testDAdd";
	});
}); //ready end
</script>
</head>
<body>
<form action="testDDetail" id="goForm" method="post">
	<input type="hidden" id="dNo" name="dNo"/>
</form>
<input type="button" value="작성" id="addBtn"/>
<table border="2" cellspacing="0">
	<thead>
		<tr>
			<th>회원번호</th>
			<th>아이디</th>
			<th>이름</th>
			<th>입사일</th>
		</tr>
	</thead>
	<tbody>
		<%-- items는 키값을 적어야한다 벨류값이 아니고 ㅋㅋ --%>	
		<c:forEach var="data" items="${list}">
			<tr  name="${data.D_NO}">
				<td>${data.D_NO}</td>
				<td>${data.D_ID}</td>
				<td>${data.D_NM}</td>
				<td>${data.D_JOINDT}</td>
			</tr>
		</c:forEach>
	</tbody>
</table>
</body>
</html>

testDAdd

<%@ 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>
<script type="text/javascript"
		src="resources/script/jquery/jquery-1.12.4.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
	$("#listDBtn").on("click",function(){
		history.back();
	}); //listBtn end
	
	$("#addDBtn").on("click",function(){
		
		if($.trim($("#dId").val())== ""){
			alert("아이디를 입력해주세요");
			$("#dId").focus();
		} else if($.trim($("#dNm").val())== ""){
			alert("이름을 입력해주세요");
			$("#dNm").focus();
		} else{
			$("#addForm").submit();
		}
	});
	
}); //ready end
</script>
</head>
<body>
<form action="testDAdds" id="addForm" method="post">
아이디<input type="text" id="dId" name="dId"/><br/>
이름<input type="text" id="dNm" name="dNm"/><br/>
</form>
<input type="button" value="등록" id="addDBtn"/>
<input type="button" value="목록으로" id="listDBtn"/>
</body>
</html>

D_SQL

<?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="D"><!-- namespace: 클래스명과동일 -->
	<!-- id: 메소드명과 동일 -->
	<!-- resultType: row 1줄의 형태를 지정 -->
	<!-- 쿼리 작성 시 ; 이 들어가면 실행 되지 않음 -->
	<select id="getDList" resultType="hashmap">
	SELECT D_NO,D_ID,D_NM,D_JOINDT
	FROM D
	</select>
	<!-- parameterType은 받는 값타입에 대한 것 resultType: 쿼리결과타입에 대한 것 -->
	<select id="getD" parameterType="hashmap" resultType="hashmap">
	SELECT D_NO, D_ID, D_NM, D_JOINDT
	FROM D
	WHERE D_NO = #{dNo}
	</select>
	<select id="addD" parameterType="hashmap">
	INSERT INTO D(D_NO, D_ID, D_NM, D_JOINDT)
	VALUES(D_SEQ.NEXTVAL, #{dId}, #{dNm}, SYSDATE)
	</select>
</mapper>

실습결과


확실히 여러번 반복하다보니 익숙해지고 있다. 확실히 오류도 덜나기 시작하고 오류도 금방찾고있다. 좋은느낌이다. 꾸준히가자

profile
호텔리어 출신 비전공자

0개의 댓글