본문 바로가기
개발 공부 Today I Learned

[국비 56일차 TIL] 스프링 기본 설치

by 개발자신입 2024. 2. 13.
반응형

앞으로 해야할 내용들

  •  2024-02-13 
  •  스프링 레거시 = jsp
  •  스프링 부트 = jsp, 타임리프
  •  sap
  •  aws
  •  docker
  •  리눅스

스프링 파일 경로


 

pom.xml

기본 설정에 필요한 jar 추가하기

: spring, 전자정부 페이징, 파일 업로드, , mariaDB, mybatis, mybatis-spring, lombok

   <properties>
      <java-version>11</java-version>
      <org.springframework-version>5.0.7.RELEASE</org.springframework-version>
      <org.aspectj-version>1.6.10</org.aspectj-version>
      <org.slf4j-version>1.6.6</org.slf4j-version>
   </properties>
   
   <repositories>
      <repository>
         <id>mvn2</id>
         <url>http://repo1.maven.org/maven2</url>
         <releases>
            <enabled>true</enabled>
         </releases>
         <snapshots>
            <enabled>true</enabled>
         </snapshots>
      </repository>
      <repository>
         <id>egovframe</id>
         <url>http://www.egovframe.go.kr/maven</url>
         <releases>
            <enabled>true</enabled>
         </releases>
         <snapshots>
            <enabled>false</enabled>
         </snapshots>
      </repository>
   </repositories>

   <dependencies>
      <!-- spring jdbc -->
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-jdbc</artifactId>
         <version>${org.springframework-version}</version>
      </dependency>
      <!-- 전자정부 페이징 -->
      <dependency>
         <groupId>egovframework.rte</groupId>
         <artifactId>egovframework.rte.ptl.mvc</artifactId>
         <version>3.8.0</version>
      </dependency>
      <!-- 파일업로드 -->
      <dependency>
         <groupId>commons-fileupload</groupId>
         <artifactId>commons-fileupload</artifactId>
         <version>1.3.3</version>
      </dependency>
      <!-- mariadb-java-client -->
      <dependency>
         <groupId>org.mariadb.jdbc</groupId>
         <artifactId>mariadb-java-client</artifactId>
         <version>2.7.3</version>
      </dependency>
      <!-- mybatis -->
      <dependency>
         <groupId>org.mybatis</groupId>
         <artifactId>mybatis</artifactId>
         <version>3.5.6</version>
      </dependency>
      <!-- mybatis-spring -->
      <dependency>
         <groupId>org.mybatis</groupId>
         <artifactId>mybatis-spring</artifactId>
         <version>1.3.2</version>
      </dependency>
      <!-- lombok -->
      <dependency>
         <groupId>org.projectlombok</groupId>
         <artifactId>lombok</artifactId>
         <version>1.18.30</version>
      </dependency>

 

 

servlet-context.xml

* 파일 경로 : src - main - webapp - WEB-INF - spring - appServlet - servlet-context.xml

 

* 별 표시로 변경:

<context:component-scan base-package="org.yourcodename.*" />
<beans:import resource="classpath:/spring/*-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="org.-----.*" />
	
	<beans:import resource="classpath:/spring/*-context.xml"/>
	
</beans:beans>

 

db-context.xml

* 파일 위치: src/main/resources - spring (패키지 생성) - Bean configuration file으로 db-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 http://www.springframework.org/schema/beans/spring-beans.xsd">

	<!-- DB 접속 정보 -->
	<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
		<property name="username" value=" "/>
		<property name="password" value=" "/>
		<property name="url" value=" "/>
		<property name="driverClassName" value=" "/>
	</bean>
	
	<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"/> <!-- 객체 = ref -->
		<property name="mapperLocations" value="classpath:/mybatis/mappers/*-Mapper.xml"/>
		<property name="configLocation" value="classpath:/mybatis/config/mybatis-Config.xml"/>
	</bean>
	
	<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactoryBean"/>
	</bean>
</beans>

 

mybatis-Config.xml

* 파일 위치 : src/main/resources - mybatis(패키지 생성) - mybatis 안에 config, mappers 폴더 생성 (패키지로 만들어도 됨) 

mybatis - config - mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-config.dtd">
  
<configuration>
	<typeAliases>
		<typeAlias type="java.lang.Integer" alias="integer"/>
		<typeAlias type="org.green.dto.BoardDTO" alias="boardDTO"/>
	</typeAliases>
</configuration>

 

 

board-mapper.xml

* 파일 위치 : mybatis - mappers - board-mapper.xml

<?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="board"> <!-- namespace와 id는 단 하나 -->
	<select id="boardList" resultType="boardDTO">
		SELECT board_no, board_title, board_write, board_date, board_count, comment FROM boardview		<!-- board.boardList -->
		LIMIT 0, 10
	</select>
	
</mapper>

게시판 정보 불러오기

BoardController.java

* 파일 위치 :  src/main/java - org.*****.controller - BoardController.java


Controller = 흐름 제어
Service    = 로직
Repository = DAO

** controller > service > repository(DAO) > mybatis 순서대로

package org.green.controller;

import java.util.List;

import org.green.dto.BoardDTO;
import org.green.service.BoardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

// 게시판 관련 기능

@Controller
public class BoardController {
	
	// 서비스와 자동 연결하기
	@Autowired
	private BoardService boardService;
	
	
	@GetMapping("/board")
	public String board(Model model) {
		// DB에서 값을 불러와서(=model) 화면에 출력하기(=jsp)

		// service에게 일 시키기
		System.out.println("컨트롤러입니다.");
		List<BoardDTO> list = boardService.boardList();
		
		// 붙이기
		model.addAttribute("list", list); // ("이름", 값)
		
		return "board"; // jsp file name
	}
	
}

 

indexController.java


@Controller     : 객체 생성 : 컨트롤러로 생성
@Service         : 객체 생성 : 서비스로 생성
@Repository   : 객체 생성  : DAO
@Component  : 객체 생성 : 그 외 객체로 만들기

주입

@autoWired = 스프링 제공 = 객체의 타입으로 검사
@Inject    = 자바 제공 = 객체의 타입이 일치하면 자동 주입
              @name("") : inject 뒤에 name으로 써주기도 함.
@resources = 자바 제공 = id가 일치하는 것 주입
@Resource(name=" ")

 

아래의 4개 모두 사용 가능, 축약해놓은 것으로 사용해도 됨. 
@RequestMapping(value = "/", method = RequestMethod.Get)
@RequestMapping(value = "/", method = RequestMethod.POST)
@RequestMapping(value = "/") get,post 구분 없이 전부 다
@RequestMapping("/") 더 축약해 놓음


POJO = java 코드를 이용해서 객체 구성 방식을 스프링에서 사용 가능
DI (Dependency Injection) = 의존성 주입
AOP (Aspect Oriented Programming) = 관점 지향 프로그래밍
IoC (Inversion of Control) = 제어 역전 = 객체 생명주기 = 스프링에게 제어 권한이 있는 것
   ㄴㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ Life Cycle = (객체 생성 -> 사용 -> 종료)


Controller -> Service -> Repository(DAO) -> Mybatis -> DB(mariadb)

MVC

  • M 데이터   = 데이터베이스 값, DAO/DTO/mybatis/DB
  • V 화면     = Model값을 붙여 사용자에게 보여줌 
  • C 흐름제어 = 사용자 요청이 들어오면 먼저 동작
import javax.inject.Inject;

import org.----.human.Human;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class IndexController {

	@Inject
	private Human human;
	
	@GetMapping("/")
	public String home() {

		// 기존에 해오던 방법
/*		Human h = new Human();
		h.setAge(10);
		h.setName("홍길동");
*/		
		System.out.println(human.getAge()); // 0
		System.out.println(human.getName()); // null
		
		return "index";		// /WEB-INF/views/index.jsp (컨트롤러를 통과하는 것들은 무조건 .jsp)
	}	
}

 

BoardService.java

* 파일 위치 : src/main/java - org.*****.service - BoardService.java


Controller의 요청에 맞춰서 Repository에서 받은 정보를 가공하여 Controller에게 넘겨주는 비즈니스 로직

package org.----.service;

import java.util.List;

import org.-----.dao.BoardDAO;
import org.-----.dto.BoardDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class BoardService {
	
    // 의존성 주입 (BoardDAO 객체에 대한)
	@Autowired
	private BoardDAO boardDAO;

	public List<BoardDTO> boardList() {
		System.out.println("서비스입니다.");
		
		return boardDAO.boardList();
	}
	
}

 

BoardDAO.java

private SqlSession sqlSession; // mybatis에서 SQL을 실행하는데 사용되는 세션 객체

import java.util.ArrayList;
import java.util.List;

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

@Repository
public class BoardDAO {

	@Autowired
	private SqlSession sqlSession; // mybatis에서 SQL을 실행하는데 사용되는 세션 객체
	
	public List<BoardDTO> boardList() {
		System.out.println("DAO입니다.");
		List<BoardDTO> list = new ArrayList<BoardDTO>();
		
        // SqlSession 객체를 통해 MyBatis의 매퍼 파일에서 
        // "board.boardList"라는 namespace와 ID에 해당하는 SQL 쿼리를 실행하여 게시판 목록을 가져옴
        
		return sqlSession.selectList("board.boardList"); // namespace.ID
	}
}

 

BoardDTO.java

lombok의 @Data 사용하기

package org.-----.dto;

import lombok.Data;

@Data
public class BoardDTO {
	private int board_no, board_count, comment;
	private String board_title, board_write, board_date;
	
}

 

board.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>Board</title>
</head>
<body>
	<h2>💚 게시판입니다. 💚</h2>
	<table>
		<thead>
			<tr>
				<th>번호</th>
				<th>제목</th>
				<th>작성자</th>
				<th>날짜</th>
				<th>조회수</th>
			</tr>
		</thead>
		<tbody>
		 <c:forEach items="${list }" var="row">
			<tr>
				<td>${row.board_no }</td>
				<td>
				<a href="./detail?no=${row.board_no }">${row.board_title } </a>  
				</td>
				<td>${row.board_write }</td>
				<td>${row.board_date }</td>
				<td>${row.board_count }</td>
			</tr>
			</c:forEach>
		</tbody>
	</table>
</body>
</html>

 

spring 파일 경로

반응형

댓글