관리 메뉴

거니의 velog

231115_SPRING 1 (1) 본문

대덕인재개발원_웹기반 애플리케이션

231115_SPRING 1 (1)

Unlimited00 2023. 11. 15. 08:25


* 서블릿을 만들지 않고 컨트롤러로 컨트롤 한다.

[HomeController.java]

package kr.or.ddit;

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;


// 어노테이션 @Controller. 서블릿과 같은 컨트롤러 임을 명시하는 것.
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	@RequestMapping(value = "/", method = RequestMethod.GET) // 요청 URL을 루트로 잡음. 최종 도착지에 해당하는 목적지가 됨.
	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"; // 그냥 리턴에다가 문자열로 갈 곳을 지정. JSP 페이지에 있는 명칭.
	}
	
}

[home.jsp]

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<!DOCTYPE html>
<html lang="ko">

    <head>
        <title>Home</title>
    </head>

    <body>
        <h1>
            Hello world!
        </h1>

        <p> The time on the server is ${serverTime}. </p>
    </body>

</html>

[servlet-context.xml]

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
	
	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
	<resources mapping="/resources/**" location="/resources/" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>
	
	<context:component-scan base-package="kr.or.ddit" />
	
	
	
</beans:beans>

컨트롤러에서 return한 문자열을 여기서 조합하여 하나의 URL로 만든다.

- http://localhost:8090/ddit/

패키지명의 3번째 이름이 루트가 된다.


- http://localhost:8090/

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

    <head>
        <title>Home</title>
    </head>

    <body>
        <h1>
            Hello world!
        </h1>

        <p> The time on the server is ${serverTime}. </p>
    </body>

</html>

페이지 디렉티브 태그에 pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" 설정해 주면 됨


<프로젝트 환경 설정>

4가지 중요하게 설정해야 함.

(1) 메이븐 체크

(2) JDK, Maven, 톰캣 3대장 추가.

(3) 자바 컴파일러 체크

(4) 프로젝트 설정 값 변경


버전 수정 1
버전 수정 2

https://mvnrepository.com/

호환성 체크 하는 부분


1. 메이븐 클린

2. 메이븐 빌드


<인코딩 필터 설정>

* web-app version="3.1" 체크

* https://java.sun.com/xml/ns/javaee/web-app_3_1.xsd" 체크

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_3_1.xsd">

	<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring/root-context.xml</param-value>
	</context-param>
	
	<!-- Creates the Spring Container shared by all Servlets and Filters -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- Processes application requests -->
	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
		
	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
	<!--  
		브라우저에서 보내는 요청(request)과 응답(response)을 모두 UTF-8로 고정하기 위해 인코딩 필터를 설정한다.
	-->
	<filter>
		<filter-name>encordingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encordingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

</web-app>

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

	<!--  
		# log4j 정의
		- 다양한 서버 상의 정보들을 출력하고 다양한 대상으로 출력을 도와주는 친구
		
		# log4j LEVEL 설정
		OFF : 로깅 해제
			> 로깅을 사용하지 않음
		FATAL : 심각한 오류
			> 아주 심각한 에러가 발생한 상태.
			> 시스템적으로 심각한 문제가 발생해서 애플리케이션 작동이 불가능할 경우가 해당하는데 일반적으로는 애플리케이셔넹서는 사용할 일이 없다.
		ERROR : 오류
			> 요청을 처리하는 중 문제가 발생한 상태를 나타낸다.
		WARN : 경고
			> 처리 가능한 문제이지만, 향후 시스템 에러의 원인이 될 수 있는 경고성 메시지를 나타낸다.
		INFO : 강조 정보
			> 로그인, 상태변경과 같은 정보성 메시지를 나타낸다.
		DEBUG : 디버깅
			> 개발시 디버그 용도로 사용한 메시지를 나타낸다.
		TRACE : 세밀
			> log4j1.2.12 버전에서 신규 추가된 레벨
			> debug 레벨이 너무 광범위한 것을 해결하기 위해서 좀 더 상세한 상태를 나타낸다.
			
		FATAL > ERROR > WARN > INFO > DEBUG > TRACE
		
		# log4j Pattern Option
		- log4j 1.2.17 API document를 기준으로 설명
			> 우리가 사용하는 log4j 1.2.15
		
		%p : debug, info, warn, error, fatal 등의 priority 출력
		%m : 로그 내용 출력
		%M : 로깅이 발생한 method 이름 출력
		%c : 로깅 이벤트의 카테고리를 출력
		%C : 로깅 이벤트가 발생한 클래스 이름을 출력
		%d : 로깅 이벤트가 발생한 시간을 출력
		%t : 로그 이벤트가 발생한 쓰레드의 이름을 출력
		%F : 로깅이 발생한 프로그램 파일명 출력
		%L : 로깅이 발생한 라인 번호를 출력
		%n : 플랫폼 종속적인 개행 문자 출력
		% : % 표시 출력
		
	-->

	<!-- Appenders -->
	<appender name="console" class="org.apache.log4j.ConsoleAppender">
		<param name="Target" value="System.out" />
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%-5p: %c - %m%n" />
		</layout>
	</appender>
	
	<!-- Application Loggers -->
	<logger name="kr.or.ddit">
		<level value="info" />
	</logger>
	
	<!-- 3rdparty Loggers -->
	<logger name="org.springframework.core">
		<level value="info" />
	</logger>
	
	<logger name="org.springframework.beans">
		<level value="info" />
	</logger>
	
	<logger name="org.springframework.context">
		<level value="info" />
	</logger>

	<logger name="org.springframework.web">
		<level value="info" />
	</logger>

	<!-- 
		Root Logger 
		> 개발 중에는 가능한 많은 정보가 나오는 것이 개발에 수월하기 때문에, 로그 레벨을 가장 낮은 레벨인 debug로 변경한다.
	-->
	<root>
		<!-- <priority value="warn" /> -->
		<priority value="debug" />
		<appender-ref ref="console" />
	</root>
	
</log4j:configuration>

-----------------------------------------------
	스프링 MVC 하루만에 배우기
	::: 2023.11.15
-----------------------------------------------

1. 필요한 프로그램 설치

	- JDK1.8 설정
	- 이클립스 4.16(2020-06R)
	- Spring Tool Suite 3.9.14.RELEASE Plugins
	- Apache-tomcat 8.5.x
	
	*** 이클립스 설치 후, 진행해야 할 사항들
	1) enc 타입으로 인코딩 설정
	2) 본인이 원하는 font 설정(개인적으로 consolar)
	3) perspective java ee 설정
	4) sts 플러그인 설치
		- help > eclipse marketplace
		- spring tool 3 standlone edition 검색 후 install
			*** 자체 plugin에 에러가 있어 정상적인 플러그인으로서 역할을 하지 못해, 수동 설치로 진행
			
2. Book 게시판 프로젝트 설정하기

	2-1. Spring Legacy Project 생성하기
		- 프로젝트명 : SampleSpringYse
		- Spring MVC Project Template 선택
		- 패키지 : kr.or.ddit
		
	2-2. 프로젝트 환경 설정
		- Java Build Path 설정
		- Java Facets 설정
		- Deployment Assembly 설정
		- Java Complier 설정
		
	2-3. 메이븐(pom.xml) 자바 버전을 1.8로 변경
	
	2-4. 메이븐(pom.xml) 스프링 버전을 5.3.25로 변경
		> 메이븐 설정 후, Maven Clean / Maven Build를 진행한다. (Goals : complie)
			*** 구동중인 서버가 있다면 서버를 중단하고 Build를 진행해야 에러를 방지
		> 스프링 5.3.25 버전은 JDK 1.8이 호환되는 버전이다. (6.x.x대는 JDK 1.8이 호환 되지 않는다.)
			> 호환 설정은 공식문서를 꼭 참고하길 바란다. (확인이 필요한 경우)
	
	2-5. Apache-tomcat 설정
		> SampleSpringYse 올리기
		> Tomcat Overview > timeout > Start 시간을 120s로 설정
		> Tomcat Module > ContextPath를 '/'로 설정
		
	2-6. 인코딩 필터 설정
		> 요청(request)과 응답(response)을 모두 UTF-8로 구성하기 위해 인코딩 필터를 설정
		> web.xml 설정(encodingFilter 설정)
		
	2-7. 로그 레벨 설정
		> log4j.xml 설정 (root 태그의 레벨을 debug로 설정)

	2-8. 기존에 작성된 홈 컨트롤러, 뷰 삭제
		> Controller, jsp 페이지 삭제 (현재 프로젝트에서는 따로 가용하지 않으므로 삭제)

create user yse identified by java;

grant connect, resource, dba to yse;

select * from all_users;

-- SPRING 1
-- BOOK 테이블 생성
create table book(
    book_id NUMBER(8) not null,
    title VARCHAR2(300) not null,
    category VARCHAR2(200) DEFAULT '' null,
    price NUMBER(10) null,
    insert_date date DEFAULT sysdate null,
    CONSTRAINT pk_book PRIMARY KEY(book_id)
);

CREATE SEQUENCE seq_book
INCREMENT by 1 
start with 1 
nocache;

commit;


[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/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>kr.or</groupId>
	<artifactId>ddit</artifactId>
	<name>SampleSpringYse</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	<properties>
		<java-version>1.8</java-version>
		<org.springframework-version>5.3.25</org.springframework-version>
		<org.aspectj-version>1.6.10</org.aspectj-version>
		<org.slf4j-version>1.6.6</org.slf4j-version>
	</properties>
	<dependencies>
	
		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework-version}</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				 </exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
				
		<!-- AspectJ -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>${org.aspectj-version}</version>
		</dependency>	
		
		<!-- Logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.15</version>
			<exclusions>
				<exclusion>
					<groupId>javax.mail</groupId>
					<artifactId>mail</artifactId>
				</exclusion>
				<exclusion>
					<groupId>javax.jms</groupId>
					<artifactId>jms</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jdmk</groupId>
					<artifactId>jmxtools</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jmx</groupId>
					<artifactId>jmxri</artifactId>
				</exclusion>
			</exclusions>
			<scope>runtime</scope>
		</dependency>

		<!-- @Inject -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>
				
		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		
		<!-- 데이터베이스 설정 -->
		
		<!--  
			mybatis는 xml로 쿼리를 작성하게 해주는 라이브러리
			쿼리를 문자열로 코딩하지 않고 xml을 사용해서 관리하게 해준다.
		-->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.5.4</version>
		</dependency>
		
		<!--  
			mybatis-spring은 스프링과 mybatis를 연동하게 해주는 라이브러리
		-->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>2.0.4</version>
		</dependency>
		
		<!--  
			jdbc는 자바에서 데이터베이스에 접속하기 위한 API
			spring-jdbc는 스프링에서 jdbc를 통해 데이터베이스와 연결할 수 있게 해준다.
		-->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		
		<!--  
			dbcp2는 데이터베이스 커넥션 풀
			데이터베이스 서버와 웹 서버는 서로 다른 프로그램이고,
			실무에서는 전혀 다른 컴퓨터에 설치되어 있을 가능성이 높다.
			서로 다른 컴퓨터와 프로그램이 통신을 하기 위해서는 서로 연결을 맺는 과정이 필요
			미리 데이터베이스와 연동하기 위한 길을 만들어놓는 라이브러리
			요즘은 dbcp2보다 hikaricp를 자주 사용하기도 함
		-->
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-dbcp2</artifactId>
			<version>2.7.0</version>
		</dependency>
		
		<!--  
			로깅을 위한 라이브러리
			데이터베이스에 연동하는 쿼리를 콘솔이나 파일 로그로 볼 수 있게 해준다.
		-->
		<dependency>
			<groupId>org.bgee.log4jdbc-log4j2</groupId>
			<artifactId>log4jdbc-log4j2-jdbc4</artifactId>
			<version>1.16</version>
		</dependency>
		
		<!-- oracle 데이터베이스 연동 라이브러리 -->
		<dependency>
			<groupId>com.oracle.database.jdbc</groupId>
			<artifactId>ojdbc8</artifactId>
			<version>21.1.0.0</version>
		</dependency>
		
		<!-- 데이터베이스 설정 End -->
	
		<!-- Test -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.7</version>
			<scope>test</scope>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
		<dependency>
		    <groupId>commons-fileupload</groupId>
		    <artifactId>commons-fileupload</artifactId>
		    <version>1.3.3</version>
		</dependency>
		     
	</dependencies>
	
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                    </additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                    </additionalBuildcommands>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>org.test.int1.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


SqlSession이라는 최종 생산품이 있음. 이것은 마이바티스를 통해 만들어냄.

FACTORY라는 객체를 통해서 공장을 가동하여 여러 자원들을 가지고 최종 생산품 생성.
각각의 자원이 뭐가 있었는가?

(1) DB에 접속하기 위한 정보들 : driver, url, id, pw
(2) sql 쿼리가 담긴 위치 정보, 즉 mapper 정보. namespace.id로 찾아서 해당 쿼리를 실행
(3) Mybatis 설정 : vo 설정, alias 설정,
mapper의 데이터를 저장하기 위한 vo 안에 들어 있는 각각의 필드가 mem_id로 존재하지 않고 memId로 사용. DB 쿼리의 컬럼은 mem_id로 설정했다 치자. memId로 쓰려면 camelcase 설정도 해줄 것.

root-context.xml에서 이를 설정해 나갈 것임.


[ root-context.xml ]

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
	
	<!-- Root Context: defines shared resources visible to all other web components -->
	
	<!--  
		데이터 소스
		- 데이터 베이스 관련 정보를 데이터소스(dataSource)라고 한다.
		jdbc:oracle:thin:@//localhost:1521/yse
		- jdbc를 이용하여 oracle 드라이버로 현재 localhost 데이터베이스 yse에 접속한다.
		
		username은 데이터베이스 사용자명이다.
		password는 데이터베이스 비밀번호이다.
	-->
	<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
		<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />
		<property name="username" value="yse" />
		<property name="password" value="java" />
	</bean>
	
	<!--  
		sqlSessionFactory는 데이터베이스와 연결을 맺고 끊어질 때까지의 라이프 사이클을 관리하는 sqlSession 객체를 만든다.
		sqlSessionFactory 객체의 프로퍼티는 총 두 가지
		1) 데이터 소스를 설정하는 프로퍼티
		2) mapper 파일의 위치를 지정하는 프로퍼티
			mapper 파일은 실제 쿼리 내용이 담겨 있는 파일들
		3) mybatis 설정
			** SampleSpringYse 안에서는 데이터를 주고 받을 때 Map 컬렉션을 활용하기 때문에 임시적으로 주석 처리함.
	-->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="mapperLocations" value="classpath:/sqlmap/**/*_SQL.xml" />
		<!-- <property name="configLocation" value="/WEB-INF/mybatisAlias/mybatisAlias.xml" /> -->
	</bean>
	
	<!--  
		sqlSessionTemplate은 데이터베이스에 개별적으로 쿼리를 실행하는 객체
		sqlSessionTemplate을 소스코드에서 사용하여 쿼리를 실행시킨다
		sqlSessionTemplate 빈은 sqlSessionFactory 객체를 생성자로 받고,
		sqlSession 객체가 가지고 있는 데이터베이스 접속 정보와 mapper 파일의 위치를 알 수 있다.
		
		ex) SqlSessionTemplate sqlSession = new SqlSessionFactory();
	-->
	<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg index="0" ref="sqlSessionFactory" />
	</bean>
		
</beans>

3. Book 게시판 만들기

	3-1. yse 계정을 생성
		> 명령 프롬프트를 이용하여 sqlplus로 oracle 데이터베이스에 접속 후 yse 계정을 생성
		> 계정명 : yse / java
		
	3-2. yse 계정을 이용해 sqldeveloper 접속 후 Book 테이블 생성
		
		-- BOOK 테이블 생성
		create table book(
		    book_id NUMBER(8) not null,
		    title VARCHAR2(300) not null,
		    category VARCHAR2(200) DEFAULT '' null,
		    price NUMBER(10) null,
		    insert_date date DEFAULT sysdate null,
		    CONSTRAINT pk_book PRIMARY KEY(book_id)
		);
		
		-- BOOK 테이블 시퀀스 생성
		CREATE SEQUENCE seq_book
		INCREMENT by 1 
		start with 1 
		nocache;
		
		commit;
		
	3-3. 메이븐 데이터베이스 라이브러리 설정
	
		- 총 6개의 데이터베이스 라이브러리 등록
		> mybatis
		> mybatis-spring
		> spring-jdbc
		> commons-dbcp2
		> log3jdbc-log4j-jdbc4
		> ojdbc8
		
		** 설정 후, Maven Build 또는 Maven의 update project를 진행하여 반영
		
	3-4. 데이터 소스 설정(root-context.xml)
		> 총 3가지의 bean 등록
		> dataSource
		> sqlSessionFactory
		> sqlSessionTemplate

빈은 메모리 상에 객체화 되어 올라감. 컨테이너 어노테이션이 있다. 이 녀석도 메모리에 올라감. 우리가 만든 서블릿으로서 역할을 할 수 있었던 이유는 거기도 어노테이션이 있었다. @WebServlet("url정보")

홈컨트롤러에 컨테이너 어노테이션이 있어서 컨테이너 정보를 가지고 서버가 런 되었을 시 객체화 될 수 있는 것.

우리는 그 메모리에 올라가 있는 여러 객체들을 배포한 플랫폼에서 활용할 수 있게 되는 것이다.


DTD 설정 가지러 가쟈

https://mybatis.org/mybatis-3/

 

mybatis – MyBatis 3 | Introduction

What is MyBatis? MyBatis is a first class persistence framework with support for custom SQL, stored procedures and advanced mappings. MyBatis eliminates almost all of the JDBC code and manual setting of parameters and retrieval of results. MyBatis can use

mybatis.org

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="Blank"></mapper>

서버를 돌릴 때 에러가 없어야 성공!


[BookInsertController.java]

package kr.or.ddit.book.web;

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

/*
 * @Controller 어노테이션이 있는 클래스는 스프링이 브라우저의 요청(request)을 받아들이는 컨트롤러라고 인지해서
 * 자바 빈(Java Bean)으로 등록해서 관리한다.
 */
@Controller
@RequestMapping("/book")
public class BookInsertController {
	
	/*
	 * @RequestMapping
	 * - 요청 URL을 어떤 메소드가 처리할 지 여부를 결정한다.
	 * 	> 클래스 라인에 들어있다면 시작 URL을 처리한다.
	 * 	> 메소드 라인에 들어있다면 최종 목적지 URL을 처리한다.
	 * 
	 * method 속성은 http 요청 메소드를 의미한다.
	 * 일반적인 웹 페이지 개발에서 GET 메소드는 데이터를 변경하지 않는 경우에, POST 메소드는 데이터가 변경될 때 사용된다.
	 * 
	 * ModelAndView는 컨트롤러가 반환할 데이터를 담당하는 모델(Model)과 화면을 담당하는 뷰(View)의 경로를 합쳐놓은 객체이다.
	 * ModelAndView의 생성자에 문자열 타입 파라미터가 입력되면 뷰의 경로라고 간주한다.
	 * 
	 * 뷰의 경로를 'book/form'과 같은 형태로 전달하는 이유는 요청(request)에 해당하는 url의 mapping되는 화면의 경로 값을 ViewResolver라는 녀석이
	 * 제일 먼저 받게 된다. 받아서 suffix, prefix 속성에 의해서 앞에는 'WEB-INF/views/'를 붙이고 뒤에는 '.jsp'를 붙여 최종 위치에 해당하는
	 * jsp 파일을 찾아준다.
	 */

	// bookForm() 메서드는 '/book/form.do'를 받는 최종 목적지이다.
	// 이 때, return 으로 나가는 정보가 'book/form' 이라는 페이지 정보를 리턴한다.
	// 문자열로 이뤄진 페이지 정보기 때문에 리턴 타입을 String으로 설정한 것이다.
	// 페이지 정보를 리턴하는 방법은 여러 가지가 존재한다.
	// - 문자열 그대로를 리턴하는 String, 문자열을 리턴타입으로 설정
	// - ModelAndView 객체를 이용한 리턴 설정
	@RequestMapping(value="/form.do", method = RequestMethod.GET)
	public ModelAndView bookForm() {
		return new ModelAndView("book/form");
	}
	
}

- http://localhost/book/form.do


 

'대덕인재개발원_웹기반 애플리케이션' 카테고리의 다른 글

231117_SPRING 1 (3)  (0) 2023.11.17
231116_SPRING 1 (2)  (0) 2023.11.16
231114_JSP 개론 14  (1) 2023.11.14
231113_JSP 개론 13  (0) 2023.11.13
231110_JSP 개론 12  (0) 2023.11.10