2022.10.12 Spring

sofia·2022년 11월 16일
0

Spring

목록 보기
7/11
post-thumbnail
  • 저번시간에 이어서

BContentCommand의 약 19번째 줄

24번째 줄

--- 최종 정리본

com.javalec.spring_mvc_board.command

BCommand.java

package com.javalec.spring_mvc_board.command;

import org.springframework.ui.Model;

public interface BCommand {//인터페이스
	public void execute(Model model); //선언
}

BContentCommand.java

package com.javalec.spring_mvc_board.command;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.ui.Model;

import com.javalec.spring_mvc_board.dao.BDao;
import com.javalec.spring_mvc_board.dto.BDto;

//게시글 목록에서 제목 클릭시 해당 글을 보여주는 작업
public class BContentCommand implements BCommand {

	@Override
	public void execute(Model model) {
		//MAP 선언 후에 이  map 안에다가 모델 객체를 담음(요청처리
		Map<String, Object> map = model.asMap();
		//get으로 꺼냄
		HttpServletRequest request =(HttpServletRequest) map.get("request");
		
		//글번호를 가지고 옴
		//list.jsp의 bId로 가지고 와야함
		String bId = request.getParameter("bId");
		//list.jsp에서 제목 클릭시 글내용을 조회할 수있는 <a href></a>에서의 쿼리스트링에서 받은 bId를 가지고 와야함
		
		//BDao 호출하여 데이터 처리
		BDao dao =new BDao();
		//BAO에서 처리한 데이터를 객체화?
		BDto dto = dao.contentView(bId);//내용을 보여줌
		//dao의 contentView메소드의 리턴값을 받아옴
		
		//결과값을 넘겨줘야하므로 model에 집어넣음
		model.addAttribute("content_view",dto);
	}

}

BDeleteCommand.java

package com.javalec.spring_mvc_board.command;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.ui.Model;

import com.javalec.spring_mvc_board.dao.BDao;

public class BDeleteCommand implements BCommand{

	@Override
	public void execute(Model model) {
		Map<String, Object> map = model.asMap();
		
		HttpServletRequest request =(HttpServletRequest) map.get("request");
		String bId = request.getParameter("bId");
		//동일하게 content_view의 삭제 쿼리스트링의 bid를 가지고 와야함
		
		BDao dao = new BDao();
		dao.delete(bId);//18번 줄의 String bId
	}

}

BListCommand.java

package com.javalec.spring_mvc_board.command;

import java.util.ArrayList;

import org.springframework.ui.Model;

import com.javalec.spring_mvc_board.dao.BDao;
import com.javalec.spring_mvc_board.dto.BDto;

public class BListCommand implements BCommand {

	@Override
	public void execute(Model model) {
		//DAO 단 호출(패키치 DAO쪽 호출)
		
		BDao dao = new BDao();
		ArrayList<BDto> dtos = dao.list();//list 호출
		//모델 객체에 삽입
		model.addAttribute("list",dtos);
	}

}

BModifyCommand.java

package com.javalec.spring_mvc_board.command;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.ui.Model;

import com.javalec.spring_mvc_board.dao.BDao;

public class BModifyCommand implements BCommand{

	@Override
	public void execute(Model model) {
		Map<String, Object> map = model.asMap();
		HttpServletRequest request =(HttpServletRequest) map.get("request");
		
		//request.getParameter로 데이터 값들을 받아옴
		String bId = request.getParameter("bId");
		String bName = request.getParameter("bName");
		String bTitle = request.getParameter("bTitle");
		String bContent = request.getParameter("bContent");
		
		//DAO객체 생성하여 COMMAND와 연결
		BDao dao =new BDao();
		dao.modify(bId, bName, bTitle, bContent);
	}

}

BWriteCommand.java

package com.javalec.spring_mvc_board.command;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.ui.Model;

import com.javalec.spring_mvc_board.dao.BDao;

public class BWriteCommand implements BCommand{

	@Override
	//이 메소드는 BController의 public String write(HttpServletRequest request, Model model) 로 보냄
	public void execute(Model model) {
		//Model에서 끌어와서 dao로 끌어보내야함
		Map<String, Object> map = model.asMap();
		HttpServletRequest request = (HttpServletRequest) map.get("request");
		//모델에 리퀘스트를 담아서 커맨드로 보내면 됨
		
		//꺼내서 변수로 담음
		String bName = request.getParameter("bName");
		String bTitle = request.getParameter("bTitle");
		String bContent = request.getParameter("bContent");
		
		//그후 BDao로 받게 함
		BDao dao = new BDao();
		dao.write(bName, bTitle, bContent);
		
	}

}

com.javalec.spring_mvc_board.controller

BController.java

package com.javalec.spring_mvc_board.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.javalec.spring_mvc_board.command.BCommand;
import com.javalec.spring_mvc_board.command.BContentCommand;
import com.javalec.spring_mvc_board.command.BDeleteCommand;
import com.javalec.spring_mvc_board.command.BListCommand;
import com.javalec.spring_mvc_board.command.BModifyCommand;
import com.javalec.spring_mvc_board.command.BWriteCommand;

@Controller //어노테이션 -> 컨트롤러  생성
public class BController {
	BCommand command;//인터페이스? 생성?
	
	//목록 조회
	@RequestMapping("/list")//url 받음
	public String list(Model model) {
		System.out.println("@@@### list()");

		//command 단 호출(패키지 command 쪽 호출)
		
		command = new BListCommand();
		//command로(인터페이스) 수정 삭제 삽입등을 받으면 됨. 왜냐 인터페이스로 상속 받을 예정이기 때문
		command.execute(model);//호출
		
		return "list";//결과값 받아서 화면 출력해야하기 때문에 list생성해야함
		
	}
	
	//글작성 페이지
	@RequestMapping("/write_view")//url 받음
	public String write_view() {
		System.out.println("@@@### write_view()");

		return "write_view";//글쓰기 폼으로 이동
		
	}
	
	//글작성
	@RequestMapping("/write")//url 받음
	public String write(HttpServletRequest request, Model model) {
		System.out.println("@@@### write()");
		
		//Model에 데이터 삽입
		model.addAttribute("request",request);
		
		command = new BWriteCommand();
		command.execute(model);
		
		return "redirect:list";//글 목록 폼으로 이동
	}
	
	//글 조회
	@RequestMapping("/content_view")//url 받음
	public String content_view(HttpServletRequest request, Model model) {
		System.out.println("@@@### content_view()");
		
		//Model에 데이터(request)를 담아서 보냄.(BContentCommand로)
		model.addAttribute("request",request);
		//"request"는 BContentCommand.java의 20번째 줄의 "request"(글번호 가지고 오는 부분)
		//뒤의 request는 content_view 메소드의 매개변수인 HttpServletRequest request부분
		
		
		command = new BContentCommand();
		command.execute(model);
		//커맨드 호출필요
		
		return "content_view";//내용보는 페이지로 이동
	}
	
	
	//글수정
	@RequestMapping("/modify")//url 받음
	public String modify(HttpServletRequest request, Model model) {
		System.out.println("@@@### modify()");
		
		model.addAttribute("request",request);
		//command단 호출
		//Interface command 사용
		command = new BModifyCommand();
		command.execute(model);//호출
		
		return "redirect:list";//글 목록 폼으로 이동
	}
	
	
	
	//글 삭제
	@RequestMapping("/delete")//url 받음
	public String delete(HttpServletRequest request, Model model) {
		//여기 매개변수의 request는 bId가 들어있음
		System.out.println("@@@### delete()");
		
		model.addAttribute("request",request);
		
		command = new BDeleteCommand();
		command.execute(model);//호출
		
		return "redirect:list";//글 목록 폼으로 이동
	}
}

com.javalec.spring_mvc_board.dao

BDao.java

package com.javalec.spring_mvc_board.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.ArrayList;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import com.javalec.spring_mvc_board.dto.BDto;

public class BDao {
	DataSource dataSource;
	
	public BDao() {//기본 생성자 생성
		
		try {
			Context contex = new InitialContext();
			dataSource = (DataSource) contex.lookup("java:comp/env/jdbc/oracle");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
		
		//list.jsp 조회하는 메소드
		public ArrayList<BDto> list(){
			ArrayList<BDto> dtos = new ArrayList<BDto>();
			
			Connection conn = null;
			PreparedStatement pstmt = null;
			ResultSet rs = null;
			
			try {
				conn = dataSource.getConnection();
				String sql = "SELECT bId, bName, bTitle, bContent, bDate, bHit FROM MVC_BOARD";
				pstmt = conn.prepareStatement(sql);
				rs = pstmt.executeQuery();
				
				
				while (rs.next()) {//결과값받기
					int bId = rs.getInt("bId");
					String bName = rs.getString("bName");
					String bTitle = rs.getString("bTitle");
					String bContent = rs.getString("bContent");
					Timestamp bDate = rs.getTimestamp("bDate");
					int bHit = rs.getInt("bHit");
					
					BDto dto = new BDto(bId, bName, bTitle, bContent, bDate, bHit);
					dtos.add(dto);//arraylist에 추가

				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {//자원 반납
					if (rs != null) rs.close();
					if (pstmt != null) pstmt.close();
					if (conn != null) conn.close();
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
			return dtos;//command쪽의  execute메소드로로 이동
		}
		
		//글작성 write 메소드?
		public void write(String bName, String bTitle,String bContent) {
			Connection conn = null;
			PreparedStatement pstmt = null;
			
			try {
				conn = dataSource.getConnection();
				//글 삽입 쿼리문
//				String sql = "INSERT INTO MVC_BOARD(bId, bName, bTitle, bContent, bDate, bHit) \r\n" + 
//						" VALUES(MVC_BOARD_SEQ.NEXTVAL,?,?,?,0)";
				
				String sql = "INSERT INTO MVC_BOARD(bId, bName, bTitle, bContent, bHit)\r\n" + 
			               " VALUES(MVC_BOARD_SEQ.NEXTVAL,?,?,?,0)";
				
				
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, bName);
				pstmt.setString(2, bTitle);
				pstmt.setString(3, bContent);
				pstmt.executeUpdate();
				//wirte.jsp에서 삽입되는 데이터들 세팅
				
				
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {//자원 반납
					if (pstmt != null) pstmt.close();
					if (conn != null) conn.close();
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}
		
		//글 내용을 보는 메소드
		//글번호를 매개변수로 받음
		public BDto contentView(String strID) {
			upHit(strID);
			//조회할때 strID를 넘기면 조회수가 증가함(upHit메소드)
			
			BDto dto = null;
			//초기값 설정
			
			Connection conn = null;
			PreparedStatement pstmt = null;
			ResultSet rs = null;
			
			try {
				conn = dataSource.getConnection();
				String sql = "SELECT bId, bName, bTitle, bContent, bDate, bHit FROM MVC_BOARD where bId=?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setInt(1, Integer.parseInt(strID));//캐스팅 + ?에 데이터 삽입
				rs = pstmt.executeQuery();
				
				
				while (rs.next()) {//결과값받기
					int bId = rs.getInt("bId");
					String bName = rs.getString("bName");
					String bTitle = rs.getString("bTitle");
					String bContent = rs.getString("bContent");
					Timestamp bDate = rs.getTimestamp("bDate");
					int bHit = rs.getInt("bHit");
					
					dto = new BDto(bId, bName, bTitle, bContent, bDate, bHit);
					//위에서 만든 dto를 리턴

				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {//자원 반납
					if (rs != null) rs.close();
					if (pstmt != null) pstmt.close();
					if (conn != null) conn.close();
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
			return dto;//command쪽의  execute메소드로로 이동
		}
		
		//조회수 증가 메소드
		//어짜피 내부에서만 돌아가면 되는거라서 private로 메소드 생성함
		private void upHit(String bId) {
			Connection conn = null;
			PreparedStatement pstmt = null;
			
			try {
				conn = dataSource.getConnection();
				//업데이트문사용하여 조회수 증가
				String sql = "update MVC_BOARD set bHit = bHit + 1 where bId=?";
				
				pstmt = conn.prepareStatement(sql);
				pstmt.setInt(1, Integer.parseInt(bId));//글번호 세팅, 캐스팅
				pstmt.executeUpdate();
				
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {//자원 반납
					if (pstmt != null) pstmt.close();
					if (conn != null) conn.close();
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}
		
		//수정 메소드
		//매개변수로 content_view에서 보낸 데이터들을 다 받는다.
		public void modify(String bId, String bName, String bTitle, String bContent) {
			Connection conn = null;
			PreparedStatement pstmt = null;
			
			try {
				conn = dataSource.getConnection();
				//업데이트문사용하여 수정문 생성
				String sql = "update MVC_BOARD set bName = ?, bTitle = ?, bContent = ? where bId=?";
				
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, bName);//작성자 세팅
				pstmt.setString(2, bTitle);//글제목 세팅
				pstmt.setString(3, bContent);//글내용 세팅
				pstmt.setInt(4, Integer.parseInt(bId));//글번호 세팅, 캐스팅
				pstmt.executeUpdate();
				
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {//자원 반납
					if (pstmt != null) pstmt.close();
					if (conn != null) conn.close();
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}
		
		
		public void delete(String strID) {
			Connection conn = null;
			PreparedStatement pstmt = null;
			
			try {
				conn = dataSource.getConnection();
				String sql = "delete from MVC_BOARD where bId=?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setInt(1, Integer.parseInt(strID));//글번호 세팅, 캐스팅
				pstmt.executeUpdate();
				
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {//자원 반납
					if (pstmt != null) pstmt.close();
					if (conn != null) conn.close();
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}
}

com.javalec.spring_mvc_board.dto

BDto.java

package com.javalec.spring_mvc_board.dto;

import java.sql.Timestamp;

public class BDto {
	int bId;
	String bName;
	String bTitle;
	String bContent;
	Timestamp bDate;
	int bHit;
	
	
	public BDto() {//기본 생성자
		
	}
	
	//필드를 사용한 생성자
	public BDto(int bId, String bName, String bTitle, String bContent, Timestamp bDate, int bHit) {
		super();
		this.bId = bId;
		this.bName = bName;
		this.bTitle = bTitle;
		this.bContent = bContent;
		this.bDate = bDate;
		this.bHit = bHit;
	}

	public int getbId() {
		return bId;
	}
	public void setbId(int bId) {
		this.bId = bId;
	}
	public String getbName() {
		return bName;
	}
	public void setbName(String bName) {
		this.bName = bName;
	}
	public String getbTitle() {
		return bTitle;
	}
	public void setbTitle(String bTitle) {
		this.bTitle = bTitle;
	}
	public String getbContent() {
		return bContent;
	}
	public void setbContent(String bContent) {
		this.bContent = bContent;
	}
	public Timestamp getbDate() {
		return bDate;
	}
	public void setbDate(Timestamp bDate) {
		this.bDate = bDate;
	}
	public int getbHit() {
		return bHit;
	}
	public void setbHit(int bHit) {
		this.bHit = bHit;
	}
	
	
}

content_view.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
	<table width="500" border="1">
			<form method="post" action="modify">
				<input type="hidden" name="bId" value="${content_view.bId}">
				<!-- 글번호 데이터도 가지고 가야하지만 수정되면 안되므로(PK) hidden을 사용하여 안보이게 함 -->
				<tr>
					<td>번호</td>
					<!-- 쿼리 결과값을 BContentCommand의 리턴 값에 받았음 --><!--  31번째 줄-->
					<td>${content_view.bId}</td>
				</tr>
				<tr>
					<td>히트</td>
					<!-- 쿼리 결과값을 BContentCommand의 리턴 값에 받았음 -->
					<td>${content_view.bHit}</td>
				</tr>
				<tr>
					<td>이름</td>
					<!-- 쿼리 결과값을 BContentCommand의 리턴 값에 받았음 -->
					<td>
						<input type="text" name="bName" value="${content_view.bName}">
						<!-- bName를 가지고 가야하므로 -->
					</td>
				</tr>
				<tr>
					<td>제목</td>
					<!-- 쿼리 결과값을 BContentCommand의 리턴 값에 받았음 -->
					<td>
						<input type="text" name="bTitle" value="${content_view.bTitle}">
						<!-- bTitle를 가지고 가야하므로 -->
					</td>
				</tr>
				<tr>
					<td>내용</td>
					<!-- 쿼리 결과값을 BContentCommand의 리턴 값에 받았음 -->
					<td>
						<input type="text" name="bContent" value="${content_view.bContent}">
						<!-- bContent를 가지고 가야하므로 -->
					</td>
				</tr>
				<tr>
					<td colspan="2">
						<input type="submit" value="수정">
						&nbsp;&nbsp;<a href="list">목록 보기</a>
						&nbsp;&nbsp;<a href="delete?bId=${content_view.bId}">삭제</a>
					</td>
				</tr>
			</form>
	</table>
</body>
</html>

list.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<!-- MODEL에서 참조값으로 결과값을 꺼내면 됨 -->
	<table width="500" border="1">
		<tr>
			<td>번호</td>
			<td>이름</td>
			<td>제목</td>
			<td>날짜</td>
			<td>히트</td>
		</tr>
		
		<c:forEach items="${list}" var="dto"><!--Model의 list로 가지고옴-->
			<tr><!-- 결과 출력 -->
				<td>${dto.bId}</td>
				<td>${dto.bName}</td>
				<td><!-- 글번호를 넘겨줘야함으로 쿼리스트링 사용, 글번호는 ${dto.bId}으로 표현 -->
					<a href="content_view?bId=${dto.bId}">${dto.bTitle}</a>
				</td>
				<td>${dto.bDate}</td>
				<td>${dto.bHit}</td>
			</tr>
		</c:forEach>
		
		<tr>
			<td colspan="5">
				<a href="write_view">글작성</a><!-- BController의 write_view로 이동  -->
			</td>
		</tr>
	</table>
</body>
</html>

write_view.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
	<table width="500" border="1">
		<form method="post" action="write"><!-- BController에서 write로 호출 해야함 -->
			<tr>
				<td>이름</td>
				<td>
					<input type="text" name="bName" size="50">
				</td>
			</tr>
			<tr>
				<td>제목</td>
				<td>
					<input type="text" name="bTitle" size="50">
				</td>
			</tr>
			<tr>
				<td>내용</td>
				<td>
					<textarea rows="10" name="bContent"></textarea>
				</td>
			</tr>
			<tr>
				<td colspan="2">
					<input type="submit" value="입력">
				</td>
			</tr>
		</form>
	</table>
</body>
</html>

예제 1

CREATE TABLE item
(name VARCHAR2(20)
,price NUMBER(8)
,description VARCHAR2(100)
);

com.javalec.spring_test_item.controller

ItemController.java

package com.javalec.spring_test_item.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.javalec.spring_test_item.service.ItemContentService;
import com.javalec.spring_test_item.service.ItemService;
import com.javalec.spring_test_item.service.ItemWriteService;

@Controller
public class ItemController {
	ItemService service;
	
	@RequestMapping("/write")
	public String write() {
		System.out.println("@@@### write()");
		
		return "itemWrite";
	}
	
	@RequestMapping("/writeResult")
	public String writeResult(HttpServletRequest request, Model model) {
		System.out.println("@@@### writeResult()");
		
		model.addAttribute("request", request);
		service = new ItemWriteService();
		service.execute(model);
		
		return "writeResult";
	}
	
	@RequestMapping("/content_view")
	public String content_view(Model model) {
		System.out.println("@@@### content_view()");

		service = new ItemContentService();
		service.execute(model);
		
		return "content_view";
	}
	
}

com.javalec.spring_test_item.dao

ItemDao.java

package com.javalec.spring_test_item.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.ArrayList;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import com.javalec.spring_test_item.dto.ItemDto;

public class ItemDao {
	DataSource dataSource;
	
	public ItemDao() {
		try {
			Context context = new InitialContext();
			dataSource = (DataSource) context.lookup("java:comp/env/jdbc/oracle");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void write(String name, int price, String description) {
		Connection conn=null;
		PreparedStatement pstmt=null;
		
		try {
			conn = dataSource.getConnection();
			String sql="insert into item(name, price, description) values(?,?,?)";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, name);
			pstmt.setInt(2, price);
			pstmt.setString(3, description);
			pstmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	public ArrayList<ItemDto> contentView(){
		ArrayList<ItemDto> dtos=new ArrayList<ItemDto>();
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		
		try {
			conn = dataSource.getConnection();
			String sql="select name, price, description from item";
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			
			while (rs.next()) {
				String name = rs.getString("name");
				int price = rs.getInt("price");
				String description = rs.getString("description");
				
				ItemDto dto = new ItemDto(name, price, description);
				dtos.add(dto);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if(rs != null) rs.close();
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		
		return dtos;
	}
}

com.javalec.spring_test_item.dto

ItemDto.java

package com.javalec.spring_test_item.dto;

public class ItemDto {
	String name;
	int price;
	String description;
	
	public ItemDto() {
		// TODO Auto-generated constructor stub
	}
	
	public ItemDto(String name, int price, String description) {
		this.name = name;
		this.price = price;
		this.description = description;
	}

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getPrice() {
		return price;
	}
	public void setPrice(int price) {
		this.price = price;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	
}

com.javalec.spring_test_item.service

ItemService.java

package com.javalec.spring_test_item.service;

import org.springframework.ui.Model;

public interface ItemService {
	public void execute(Model model);
}

ItemContentService.java

package com.javalec.spring_test_item.service;

import java.util.ArrayList;

import org.springframework.ui.Model;

import com.javalec.spring_test_item.dao.ItemDao;
import com.javalec.spring_test_item.dto.ItemDto;

public class ItemContentService implements ItemService{

	@Override
	public void execute(Model model) {
		ItemDao dao = new ItemDao();
		ArrayList<ItemDto> dtos = dao.contentView();
		model.addAttribute("content_view", dtos);
	}

}

ItemWriteService.java

package com.javalec.spring_test_item.service;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.ui.Model;

import com.javalec.spring_test_item.dao.ItemDao;

public class ItemWriteService implements ItemService{

	@Override
	public void execute(Model model) {
		Map<String, Object> map = model.asMap();
		HttpServletRequest request = (HttpServletRequest) map.get("request");
		
		String name = request.getParameter("name");
		int price = Integer.parseInt(request.getParameter("price"));
		String description = request.getParameter("description");
		
		ItemDao dao = new ItemDao();
		dao.write(name, price, description);
	}

}

content_view.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
	<table width="500" border="1">
		<tr>
			<td>상품명</td>
			<td>가격</td>
			<td>설명</td>
		</tr>
		<c:forEach items="${content_view}" var="dto">
			<tr>
				<td>${dto.name}</td>
				<td>${dto.price}</td>
				<td>${dto.description}</td>
			</tr>
		</c:forEach>
	</table>
</body>
</html>

itemWrite.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
	<form method="post" action="writeResult">
		<table>
			<tr>
				<td>상품명</td>
				<td>
					<input type="text" name="name">
				</td>
			</tr>
			<tr>
				<td>가격</td>
				<td>
					<input type="text" name="price">
				</td>
			</tr>
			<tr>
				<td>설명</td>
				<td>
					<input type="text" name="description">
				</td>
			</tr>
			<tr>
				<td colspan="2" align="center">
					<input type="submit" value="전송">
					<input type="reset" value="취소">
				</td>
			</tr>
		</table>
	</form>
</body>
</html>

writeResult.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
	<a href="content_view">결과 보기</a>
</body>
</html>

예제 2

OMMIT;
CREATE TABLE MVC_MEMBER
(MEM_UID VARCHAR2(15)
,MEM_PWD VARCHAR2(15)
,MEM_NAME VARCHAR2(10)
);

SELECT MEM_UID, MEM_PWD, MEM_NAME FROM MVC_MEMBER;
insert into MVC_MEMBER(MEM_UID, MEM_PWD, MEM_NAME) values('aaa','1234','abc');


com.javalec.spring_test_member.controller

MemController.java

package com.javalec.spring_test_member.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.javalec.spring_test_member.service.MemLoginService;
import com.javalec.spring_test_member.service.MemService;

@Controller
public class MemController {
	MemService service;
	
	@RequestMapping("/login")
	public String login() {
		System.out.println("###@@@ login()");
		
		return "login";
	}
	
	@RequestMapping("/login_yn")
	public String login_yn(HttpServletRequest request, Model model) {
		System.out.println("###@@@ login_yn()");
		
		model.addAttribute("request",request);
		service =  new MemLoginService();
		int result = service.execute(model);
		
		//분기처리
		if (result == 1) {
			return "redirect:login_ok";//로그인 성공시 이동
		}
		return "redirect:login";//로그인 실패시 그자리에 그대로 있음
	}
	
	@RequestMapping("/login_ok")
	public String login_ok() {
		System.out.println("###@@@ login_ok()");
		
		return "login_ok";
	}
		
	
}

com.javalec.spring_test_member.dao

MemDao.java

package com.javalec.spring_test_member.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class MemDao {
	DataSource dataSource;
	
	public MemDao() {
		try {
			Context context = new InitialContext();
			dataSource = (DataSource) context.lookup("java:comp/env/jdbc/oracle");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	public int loginYn(String id, String pw) {
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		int re = -1;
		String db_mem_pwd;//DB에서 받는 PW
		try {
			conn = dataSource.getConnection();
//			String sql="selete mem_pwd from MVC_MEMBER where mem_uid=?";
			String sql = "SELECT mem_pwd FROM MVC_MEMBER WHERE mem_uid=?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, id);
			rs = pstmt.executeQuery();
			
			if (rs.next()) {//아이디가 존재한다면
				db_mem_pwd = rs.getString("mem_pwd");
				
				if (db_mem_pwd.equals(pw)) {//패스워드도  일치
					re = 1;
				}else {//패스워드가 불일치
					re=0  ;
				}
			}else {//해당 아이디가 존재하지 않음
				re = -1;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if(rs != null) rs.close();
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		
		return re;
	}
	
	
	
}

com.javalec.spring_test_member.dto

MemDto.java

package com.javalec.spring_test_member.dto;

public class MemDto {
	String MEM_UID;
	String MEM_PWD;
	String MEM_NAME;
	public String getMEM_UID() {
		return MEM_UID;
	}
	public void setMEM_UID(String mEM_UID) {
		MEM_UID = mEM_UID;
	}
	public String getMEM_PWD() {
		return MEM_PWD;
	}
	public void setMEM_PWD(String mEM_PWD) {
		MEM_PWD = mEM_PWD;
	}
	public String getMEM_NAME() {
		return MEM_NAME;
	}
	public void setMEM_NAME(String mEM_NAME) {
		MEM_NAME = mEM_NAME;
	}
	
	public MemDto(String mEM_UID, String mEM_PWD, String mEM_NAME) {
		super();
		MEM_UID = mEM_UID;
		MEM_PWD = mEM_PWD;
		MEM_NAME = mEM_NAME;
	}
	public MemDto() {
		
	}
	
	
}

com.javalec.spring_test_member.service

MemService.java

package com.javalec.spring_test_member.service;

import org.springframework.ui.Model;

public interface MemService {
	public int execute(Model model);
}

MemLoginService.java

package com.javalec.spring_test_member.service;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.ui.Model;

import com.javalec.spring_test_member.dao.MemDao;

public class MemLoginService implements MemService {

	@Override
	public int execute(Model model) {
		Map<String, Object> map = model.asMap();
		HttpServletRequest request = (HttpServletRequest) map.get("request");
		
		String mId = request.getParameter("mem_uid");
		String mPw = request.getParameter("mem_pwd");
		
		MemDao dao = new MemDao();//객체 생성
		int re = dao.loginYn(mId, mPw);
		
		return re;
	}

}

login_ok,jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
	<h1>login ok~~!!!</h1>
</body>
</html>

login.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
	<table border="1"  align="center">
		<form method="post" action="login_yn" >
			<tr height="30">
         		<td width="100">
         			사용자 ID 
         		</td>
         		<td width="100">
         			<input type="text" name="mem_uid">
         		</td>
     		</tr>
     		<tr>
         		<td width="100">
         		 	비밀번호 
         		</td>
         		<td width="100">
         			 <input type="text" name="mem_pwd" >
         		</td>
     		</tr>
     		<tr>
     			<td colspan = "2" align="center">
         			<input type="submit" value="로그인">
         			 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
         			 <input type="button" value="회원가입">
         		</td>
     		</tr>
		</form>
	</table>
</body>
</html>

0개의 댓글