Spring(2023-04-10)

권단비·2023년 4월 10일
0

IT

목록 보기
118/139

[@ 어노테이션]

@어노테이션 : 한 개의 함수 역할을 한다
Component : new 객체생성(Component + 의미)

@Controller : @Component + controller
@Service : @Component + 객체
@Repository : + @Component + dao
@Autowired : 주입 / 객체에 주소를 줌

@Autowired // 주입
private BoardDAO dao; // BoardDAO dao = new BoardDAO();
[계산 GradeVO.java]
package edu.global.ex.vo;

import lombok.*;

//Grade grade = new Grade();
//System.out.print(grade) >> 주소값이 나옴 | toString 함수 오버라이딩을 사용하면 값이 나온다.

@Getter // : 컴파일 될 때 getter함수가 자동으로 생성
@Setter // : 컴파일 될 때 setter함수가 자동으로 생성
@NoArgsConstructor // : 컴파일 될 때 비어있는 생성자 자동으로 생성
@AllArgsConstructor // : 컴파일 될 때 생성자 자동으로 생성
@ToString // : 주소값이 아닌 데이터 멤버 값이 나오도록 변경
//@Data // : 상기 모든 것을 포함한 어노테이션
public class GradeVO {
	private int kor;
	private int eng;
	private int math;
	public int getTotal() {
		return kor + eng + math;
	}
	public double getAvg() {
		return (kor + eng + math) / 3.0;
	}
	public String getGrade() {
		String grade = "가";
		double avg = getAvg();
		if (avg >= 90) {
			grade = "수";
		} else if (avg >= 80) {
			grade = "우";
		} else if (avg >= 70) {
			grade = "미";
		} else if (avg >= 60) {
			grade = "양";
		} else {
			grade = "가";
		}
		return grade;
	}
}
---------------------------------------------------------------------
[계산 GradeController.java]
package edu.global.ex.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.*;
import org.springframework.ui.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import edu.global.ex.vo.GradeVO;

//1.URL과 페이지 매핑 방법
//2.뷰(jsp)에 데이터 전달
@RequestMapping("/grade") // http://localhost:8282/grade
@Controller
public class GradeController {

	@GetMapping("/") // http://localhost:8282/grade/
	public String grade_form() {
		return "grade_form";
	}

	@PostMapping("/total") // http://localhost:8282/grade/total
	public String grade_form(HttpServletRequest request, Model model) {
		int kor = Integer.valueOf(request.getParameter("kor"));
		int eng = Integer.valueOf(request.getParameter("eng"));
		int math = Integer.valueOf(request.getParameter("math"));
//		int total = kor + eng + math;
//		double avg = total / 3.0;

		GradeVO grade = new GradeVO(kor, eng, math); // lombok으로 만든 생성자에 객체로 넘긴다
		model.addAttribute("grade", grade);

		return "grade";
	}

	@PostMapping("/total2") // http://localhost:8282/grade/total2
	public String grade_form2(GradeVO gradeVO) { // 커맨드 객체 : GradeVO gradeVO
//		grade_form2(GradeVO gradeVO) == GradeVO gradeVO = new gradeVO(); 의 역할을 함
//		gradeVO.setkor(70); 를 호출한다.
//		gradeVO.setEng(70); 를 호출한다.

//		model.addAttribute("grade", gradeVO);
		return "grade";
	}
}
---------------------------------------------------------------------
[계산 grade_form.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>list</title>
</head>
<body>
	<!-- submit을 누르면 total로 이동 -->
  	<form action="/grade/total" method = "post">
		<!-- name은 반드시 소문자! -->
		국어 : <input type="text" name="kor"><br>
 		영어 : <input type="text" name="eng"><br>
 		수학 : <input type="text" name="math"><br>
 		<button type="submit">입력</button>
 		<button type="reset">취소</button>
 	</form><br><hr>

	<!-- submit을 누르면 total2로 이동 -->
 	<form action="/grade/total2" method = "post">
		국어 : <input type="text" name="kor"><br>
 		영어 : <input type="text" name="eng"><br>
 		수학 : <input type="text" name="math"><br>
 		<button type="submit">입력</button>
 		<button type="reset">취소</button>
 	</form>
</body>
</html>
---------------------------------------------------------------------
[계산 grade.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>list</title>
</head>
<body>
	합계 : ${gradeVO.getTotal()}
	<br> 평균 : ${gradeVO.getAvg()}
	<br> 성적 : ${gradeVO.getGrade()}
	<br>
	<br> 또는
	<br>
	<br> 합계 : ${gradeVO.total}
	<br> 평균 : ${gradeVO.avg}
	<br> 성적 : ${gradeVO.grade}
	<br> toString : ${gradeVO.toString()}
	<br>
</body>
</html>
[결과값]


[계산 pom.xml]
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.6.3</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<groupId>edu.global</groupId>
	<artifactId>ex</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>spring_boot_kdb_board</name>
	<description>Board project for Spring Boot</description>

	<properties>
		<java.version>11</java.version>
	</properties>
	<repositories>
		<repository>
			<id>oracle</id>
			<url>http://www.datanucleus.org/downloads/maven2/</url>
		</repository>
	</repositories>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<!-- spring-boot-devtools는 클래스 수정시 웹서버를 재시작하여 결과를 바로 반영 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-tomcat</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<!-- 오라클 JDBC 드라이버 -->
		<dependency>
			<groupId>oracle</groupId>
			<artifactId>ojdbc6</artifactId>
			<version>11.2.0.3</version>
		</dependency>

		<!-- MyBatis 라이브러리 -->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.1.4</version>
		</dependency>

		<!-- MyBatis sql pretty -->
		<dependency>
			<groupId>org.bgee.log4jdbc-log4j2</groupId>
			<artifactId>log4jdbc-log4j2-jdbc4.1</artifactId>
			<version>1.16</version>
		</dependency>

		<!-- JSP를 사용하기 위한 라이브러리 -->
		<!-- 톰캣 파서 -->
		<dependency>
			<groupId>org.apache.tomcat.embed</groupId>
			<artifactId>tomcat-embed-jasper</artifactId>
		</dependency>

		<!-- jstl 라이브러리 -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
		</dependency>
	</dependencies>

	<build><!-- 컴파일~배포까지 -->
		<plugins>
			<plugin>
				<groupId>org.apache.tomcat.maven</groupId>
				<artifactId>tomcat7-maven-plugin</artifactId>
				<version>2.2</version>
				<configuration>
					<url>http://146.56.137.240:8282/manager/text</url>
					<username>admin</username>
					<password>1234</password>
				</configuration>
			</plugin>
			<!-- cmd에 입력 ( 배포 ) : mvnw.cmd tomcat7:redeploy -->
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<excludes>
						<exclude>
							<groupId>org.projectlombok</groupId>
							<artifactId>lombok</artifactId>
						</exclude>
					</excludes>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>
---------------------------------------------------------------------
[계산 application.properties]
#server port number
server.port = 8282

#datasource (oracle)
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521/xe
#spring.datasource.driver-class-name=net.sf.log4jdbc.sql.jdbcapi.DriverSpy
#spring.datasource.url=jdbc:log4jdbc:oracle:thin:@localhost:1521/xe
spring.datasource.username=scott
spring.datasource.password=tiger

#xml location
#mybatis.mapper-locations=classpath:mappers/`**/*.xml

#### jsp 
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
---------------------------------------------------------------------
[계산 BoardVO.java]
package edu.global.ex.VO;

import java.sql.Timestamp;
import lombok.*;

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class BoardVO {
	   private int bid;
	   private String bname;
	   private String btitle;
	   private String bcontent;
	   private Timestamp bdate;
	   private int bhit;
	   private int bgroup;
	   private int bstep;
	   private int bindent;
}
---------------------------------------------------------------------
[계산 BoardController.java]
package edu.global.ex.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.*;
import org.springframework.ui.*;
import org.springframework.web.bind.annotation.*;

import edu.global.ex.BoardService;
import lombok.extern.slf4j.Slf4j;

@Slf4j // 로그를 사용하기 위한 어노테이션 : log.info("view_list()..");
@Controller
@RequestMapping("/jboard/*") // jboard로 들어오는 모든 것들은 BoardController를 생성해라
public class BoardController {

	@Autowired
	private BoardService boardService;

	@GetMapping("/list")
	public String view_list(Model model) {
		log.info("view_list().."); // 디버그
		model.addAttribute("boards", boardService.getList());
		return "/board/list";
	}
}
---------------------------------------------------------------------
[계산 list.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="500" cellpadding="0" cellspacing="0" border="1">
		<tr>
			<td>번호</td>
			<td>이름</td>
			<td>제목</td>
			<td>날짜</td>
			<td>히트</td>
		</tr>
		<c:forEach var="board" items="${boards}">
			<tr>
				<td>${board.bid}</td>
				<td>${board.bname}</td>
				<td><c:forEach begin="1" end="${board.bindent}">-</c:forEach> <a href="${pageContext.request.contextPath}/jboard/content_view?bid=${board.bid}">${board.btitle}</a></td>
				<td>${board.bdate}</td>
				<td>${board.bhit}</td>
			</tr>
		</c:forEach>
		<tr>
			<td colspan="5"><a href="write_view">글작성</a></td>
		</tr>
	</table>
</body>
</html>
---------------------------------------------------------------------
[계산 BoardService.java]
package edu.global.ex;
import java.util.List;
import edu.global.ex.VO.BoardVO;

public interface BoardService {
	public List<BoardVO> getList();
}
---------------------------------------------------------------------
[계산 BoardServiceImpl.java]
package edu.global.ex;

import java.util.List;

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

import edu.global.ex.VO.*;
import edu.global.ex.repository.BoardDAO;
import lombok.*;
import lombok.extern.slf4j.Slf4j;

@Slf4j // 로그를 사용하기 위한 어노테이션 : log.info("view_list()..");
@Service
@AllArgsConstructor
@NoArgsConstructor
public class BoardServiceImpl implements BoardService {
	@Autowired // 주입
	private BoardDAO dao; // BoardDAO dao = new BoardDAO();

	@Override
	public List<BoardVO> getList() {
		return dao.boardSelect();
	}
}
---------------------------------------------------------------------
[계산 BoardDAO.java]
package edu.global.ex.repository;

import java.sql.*;
import java.util.*;

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

import org.springframework.stereotype.Repository;

import edu.global.ex.VO.*;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Repository
public class BoardDAO {
//	private DataSource dataSource;
	private String url = "jdbc:oracle:thin:@localhost:1521:xe";
	private String uid = "scott";
	private String upw = "tiger";

	public BoardDAO() {
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public List<BoardVO> boardSelect() {
		List<BoardVO> boards = new ArrayList<BoardVO>();

		Connection con = null;
		Statement stmt = null;
		ResultSet resultSet = null;

		try {
			String sql = "Select * from mvc_board";

			con = DriverManager.getConnection(url, uid, upw);
			stmt = con.createStatement();
			resultSet = stmt.executeQuery(sql);

			while (resultSet.next()) {
				int bid = resultSet.getInt("bid");

				String bname = resultSet.getString("bname");
				String btitle = resultSet.getString("btitle");
				String bcontent = resultSet.getString("bcontent");

				Timestamp bdate = resultSet.getTimestamp("bdate");

				int bhit = resultSet.getInt("bhit");
				int bgroup = resultSet.getInt("bgroup");
				int bstep = resultSet.getInt("bstep");
				int bindent = resultSet.getInt("bindent");

				BoardVO vo = new BoardVO(bid, bname, btitle, bcontent, bdate, bhit, bgroup, bstep, bindent);
				boards.add(vo);
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (resultSet != null)
					resultSet.close();

				if (stmt != null)
					stmt.close();

				if (con != null)
					con.close();

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return boards;
	}
}
[결과값]


0개의 댓글