2022.10.11 Spring

sofia·2022년 11월 16일
0

Spring

목록 보기
6/11
post-thumbnail
  • 저번 시간에서 넘어옴

예제 7


ltaewonclass.java

package com.javalec.spring_ex_12_3;

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

@Controller
public class ltaewonclass {
		@RequestMapping("/actor") //url 인식하기 위해서 사용
		public String actor(Model model) {
			model.addAttribute("name","박새로이");
			
			return "actor/actor";
		}
		
		@RequestMapping("/actress")
		public String actress(Model model) {
			model.addAttribute("name","조이서");
			
			return "actress/actress";
		}
		
}

actor.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>
	남자배우  : ${name}
</body>
</html>

actress.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>
	여자배우  : ${name}"
</body>
</html>

예제 8

HomeController.java

package com.javalec.spring_ex_12_4;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		return "home";
	}
	
	@RequestMapping("/portpolio/airbnb") //url 인식하기 위해서 사용
	public String airbnb(Model model) {
		model.addAttribute("title","숙소예약");
		
		return "/portpolio/airbnb";
	}
	@RequestMapping("/portpolio/universityManager") //url 인식하기 위해서 사용
	public String universityManager(Model model) {
		model.addAttribute("title","학사관리");
		
		return "/portpolio/universityManager";
	}
	@RequestMapping("/portpolio/bookManager") //url 인식하기 위해서 사용
	public String bookManager(Model model) {
		model.addAttribute("title","도서관리");
		
		return "/portpolio/bookManager";
	}
	
}

airbnb.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>
	1,2: ${title}
</body>
</html>

universityManager.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>
	3: ${title}
</body>
</html>

bookManager.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>
	4: ${title}
</body>
</html>

Char.13

HttpServletRequest 클래스

예제 1

HomeController. java

package com.javalec.spring_13_1;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		return "home";
	}
	
	@RequestMapping("board/confirmId")
	public String confirmId(HttpServletRequest httpServletRequest, Model model) {
		String id = httpServletRequest.getParameter("id");
		String pw = httpServletRequest.getParameter("pw");
		
		model.addAttribute("id",id);
		model.addAttribute("pw",pw);
		
		return "board/confirmId";
	}
	
}

confirmId.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>
	ID : ${id}<br>
	PW : ${pw}<br>
</body>
</html>


@RequestParam 어노테이션

예제 2

파라미터가 없으면 오류 페이지 출력(위의 예제에서는 값이 아예 안나왔지만 여기는 페이지부터 걍 안뜸)

HomeController.java

package com.javalec.spring_13_2;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		return "home";
	}
	
	@RequestMapping("board/checkId")
	public String checkId(@RequestParam("id") String id, @RequestParam("pw") int pw, Model model) {
		model.addAttribute("identify", id);
		model.addAttribute("password", pw);
		
		return "board/checkId";
	}
	
}

checkId.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>
	ID : ${identify}<br>
	PW : ${password}
</body>
</html>

데이터(커맨드) 객체

  • 예제 보면 확인 가능(spring_13_3)

  • 기존 방법의 경우 : 다소 코드 양이 많음.

  • 개선한 방법의 경우 : 코드 양이 적음

예제 3


HomeController.java

package com.javalec.spring_13_3;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		return "home";
	}
	
//	@RequestMapping("member/join")
//	public String joinData(@RequestParam("name") String name
//								,@RequestParam("id") String id
//								,@RequestParam("pw") String pw
//								,@RequestParam("email") String email
//								,Model model
//								) {
//		Member member = new Member();
//		member.setName(name);
//		member.setId(id);
//		member.setPw(pw);
//		member.setEmail(email);
//		
//		model.addAttribute("member",member);
//		
//		return "member/join";
//		
//	}
	//위의 방법도 가능하지만 밑의 방법으로 하면 간단하게 할 수있음
	@RequestMapping("member/join")
	public String joinData(Member member) {
		
		return "member/join";
	}
}

@PathVariable

  • 예제로 확인 가능 (spring_13_4)

예제 4

HomeController .java

package com.javalec.spring_13_4;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		return "home";
	}
	
	@RequestMapping("student/{studentId777}")
	public String getStudent(@PathVariable String studentId777, Model model) {
		model.addAttribute("studentId", studentId777);
		
		return "student/studentView";
	}
}

student.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>
	student : ${studentId}
</body>
</html>


Char14.@RequestMapping 파라미터

RequestMapping에서 Get방식과 Post방식

예제 5

HomeController .java

package com.javalec.spring_14_1_2;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		return "home";
	}
	
	@RequestMapping("/index")
	public String goIndex() {
		
		return "index";
	}
	
	
	@RequestMapping(method = RequestMethod.GET, value = "/student")//전송방식get으로 지정
	public String goStudent(HttpServletRequest httpServletRequest, Model model) {
		System.out.println("@@@### RequestMethod.GET");
		
		String id = httpServletRequest.getParameter("id");
		model.addAttribute("studentId",id);

		return "student/studentId";
	}
	
	
	@RequestMapping(method = RequestMethod.POST, value = "/student")//전송방식 post으로 지정
	public ModelAndView goStudent(HttpServletRequest httpServletRequest) {
		System.out.println("@@@### RequestMethod.POST");
		
		String id = httpServletRequest.getParameter("id");
		ModelAndView mv = new ModelAndView();
		mv.addObject("studentId",id);
		mv.setViewName("student/studentId");
		
//		return "student/studentId";
		return mv;
	}
	
}

student.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="student.jsp">-->
	
	
	 <form method="post" action="student">
	<!--<form method="get" action="student">-->
		student id : <input type="text" name="id"><br>
		<input type="submit" value="전송"> 
	</form>
</body>
</html>

index,jsp의 form method가 Get 인 경우 출력 됨

index,jsp의 form method가 post 인 경우 출력 됨

ModelAttribute

예제 6

HomeController.java

package com.javalec.spring_14_2;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		return "home";
	}
	
	@RequestMapping("/index")
	public String index() {
		
		return "index";
	}
	
	@RequestMapping("/studentView")
	public String studentView(StudentInfomation studentInfomation) {
		
		return "studentView";
	}
	
	
}

또는

package com.javalec.spring_14_2;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		return "home";
	}
	
	@RequestMapping("/index")
	public String index() {
		
		return "index";
	}
	
	@RequestMapping("/studentView")
//	public String studentView(StudentInfomation studentInfomation) {
		public String studentView(StudentInfomation studentInfo) {
		
		return "studentView";
	}
	
	
}

index.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="get" action="studentView">
		이름 :<input type="text" name="name"><br>
		나이 :<input type="text" name="age"><br>
		학년 :<input type="text" name="gradeNum"><br>:<input type="text" name="classNum"><br>
		<input type="submit" name="전송"><br>
	</form>
</body>
</html>

StudentInfomation.java

package com.javalec.spring_14_2;

public class StudentInfomation {
	private String name;
	private String age;
	private String gradeNum;
	private String classNum;
	
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	public String getGradeNum() {
		return gradeNum;
	}
	public void setGradeNum(String gradeNum) {
		this.gradeNum = gradeNum;
	}
	public String getClassNum() {
		return classNum;
	}
	public void setClassNum(String classNum) {
		this.classNum = classNum;
	}
	
	
}

studentView.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>
	studentView.jsp입니다.
	이름 : ${studentInfomation.name}
	나이 : ${studentInfomation.age}
	학년 : ${studentInfomation.gradeNum}: ${studentInfomation.classNum}
	
</body>
</html>

만약에

<%@ 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>
	<!--이름 : ${studentInfomation.name}<br>
	나이 : ${studentInfomation.age}<br>
	학년 : ${studentInfomation.gradeNum}<br>: ${studentInfomation.classNum}<br>  -->

	이름 : ${studentInfo.name}<br>
	나이 : ${studentInfo.age}<br>
	학년 : ${studentInfo.gradeNum}<br>: ${studentInfo.classNum}<br>
	
</body>
</html>

으로 수정시 값이 출력되지 않음

HomeController.java의 이름을 바꿔서 하고싶으면 @ModelAttribute를 사용

예제 7

HomeController .java

package com.javalec.spring_14_2;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		return "home";
	}
	
	@RequestMapping("/index")
	public String index() {
		
		return "index";
	}
	
	@RequestMapping("/studentView")
//	public String studentView(StudentInfomation studentInfomation) {
	
//	public String studentView(StudentInfomation studentInfo) {
//	참조변수를 바꿔도 StudentInfomation를 따라간다.
		
	public String studentView(@ModelAttribute("studentInfo") StudentInfomation studentInfo) {
		return "studentView";
	}
	
	
}

studentView.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>
	<!--이름 : ${studentInfomation.name}<br>
	나이 : ${studentInfomation.age}<br>
	학년 : ${studentInfomation.gradeNum}<br>: ${studentInfomation.classNum}<br>  -->

	이름 : ${studentInfo.name}<br>
	나이 : ${studentInfo.age}<br>
	학년 : ${studentInfo.gradeNum}<br>: ${studentInfo.classNum}<br>
	
</body>
</html>

Redirect : 키워드

예제 8

RedirectController.java

package com.javalec.spring_14_3;

import javax.servlet.http.HttpServletRequest;

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

@Controller
public class RedirectController {
	@RequestMapping("/studentConfirm")
	public String studentRedirect(HttpServletRequest httpServletRequest) {
		String id = httpServletRequest.getParameter("id");
		
		if (id.equals("abc")) {
			return "redirect:studentOk";
		}
		
		return "redirect:studentNg";
	}
	
	@RequestMapping("/studentOk")
	public String studentOk() {
			return "student/studentOk";
	}
	
	@RequestMapping("/studentNg")
	public String studentNg() {
		return "student/studentNg";
	}
}

studentOk.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>
	studentOk.jsp 입니다.
</body>
</html>

studentNg.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>
	studentNg.jsp 입니다.
</body>
</html>


Char15. 스프링MVC 게시판

예제 9

  1. SQL
SELECT * FROM MVC_BOARD;

DELETE from MVC_BOARD;

SELECT * FROM MVC_BOARD_SEQ;
SELECT bId, bName, bTitle, bContent, bDate, bHit FROM MVC_BOARD;
INSERT INTO MVC_BOARD(bId, bName, bTitle, bContent, bDate, bHit)
VALUES (1,'aaa','a1','abcd',sysdate,0);
COMMIT;

-- 글번호를 SEQUENCE로 처리
INSERT INTO MVC_BOARD(bId, bName, bTitle, bContent, bDate, bHit) 
VALUES(MVC_BOARD_SEQ.NEXTVAL,?,?,?,sysdate,0);

DROP TABLE MVC_BOARD;
DROP SEQUENCE MVC_BOARD_SEQ;

--테이블 생성
CREATE TABLE MVC_BOARD
(bId NUMBER(4) PRIMARY KEY--글번호
,bName VARCHAR2(20) -- 작성자
,bTitle  VARCHAR2(100) -- 글제목
,bContent  VARCHAR2(300) -- 글 내용
,bDate Date DEFAULT SYSDATE -- 작성일
,bHit NUMBER(4) DEFAULT 0 -- 조회수
);

-- 시퀀스 생성 
-- 1부터 증가하여 반복 없이 1씩 증가
CREATE SEQUENCE MVC_BOARD_SEQ
MINVALUE 1
MAXVALUE 9999
INCREMENT BY 1 START WITH 1 NOCYCLE;

--테이블 생성
CREATE TABLE MVC_BOARD
(bId NUMBER(4) PRIMARY KEY--글번호
,bName VARCHAR2(20) -- 작성자
,bTitle  VARCHAR2(100) -- 글제목
,bContent  VARCHAR2(300) -- 글 내용
,bDate Date DEFAULT SYSDATE -- 작성일
,bHit NUMBER(4) DEFAULT 0 -- 조회수
);

-- 시퀀스 생성 
-- 1부터 증가하여 반복 없이 1씩 증가
CREATE SEQUENCE MVC_BOARD_SEQ
MINVALUE 1
MAXVALUE 9999
INCREMENT BY 1 START WITH 1 NOCYCLE;

INSERT INTO MVC_BOARD(bId, bName, bTitle, bContent, bDate, bHit) 
VALUES(MVC_BOARD_SEQ.NEXTVAL,?,?,?,sysdate,0);

COMMIT;

<Resource auth="Container" driverClassName="oracle.jdbc.driver.OracleDriver"
 maxActive="100" maxIdle="30" maxWait="10000" name="jdbc/oracle" 
password="-----" type="javax.sql.DataSource" 
url="jdbc:oracle:thin:@localhost:1521:xe" username="-----"/>

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.BListCommand;
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";//글 목록 폼으로 이동
		
	}
	
}

BCommand.java

package com.javalec.spring_mvc_board.command;

import org.springframework.ui.Model;

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

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);
	}

}

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);
		
	}

}

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();
				}
			}
		}
		
}

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;
	}
	
	
}

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.bTitle}</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>

0개의 댓글