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

[국비 57일차 TIL] 스프링 설정하기 반복

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

< spring legacy project 생성>


spring folder


< pom.xml >

java, springframework 설정 변경

  • 프로젝트 우측클릭 - 설정 - project Facets에서 java 버전 11로 수정 & 빌드패스에서도 변경
  • 하나씩 추가하는게 좋음.
  • pom.xml - maven - update project에서 혹시나 받아지지 않은 것들 내려받기.

 

버전 아래의 </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>

		<!-- mybatis - spring, mariadb (.jar) 추가해주기 -->
		
		<!-- 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>
		<!-- https://mvnrepository.com/artifact/com.zaxxer/HikariCP -->
		<dependency>
			<groupId>com.zaxxer</groupId>
			<artifactId>HikariCP</artifactId>
			<version>5.1.0</version>
		</dependency>

 

 

java 버전 11로 변경

pom.xml 아래 부분에서 플러그인의 소스와 타깃도 11로 바꿔주면 계속 유지됨.

 

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.5.1</version>
				<configuration>
					<source>11</source>
					<target>11</target>
					<compilerArgument>-Xlint:all</compilerArgument>
					<showWarnings>true</showWarnings>
					<showDeprecation>true</showDeprecation>
				</configuration>
			</plugin>

 

lombok

lombok 코드를 pom.xml 에 추가하기

 

<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.30</version>
    <scope>provided</scope>
</dependency>

 


< servlet-context.xml >


코드네임 뒤의 controller를 * 표시로 변경

<context:component-scan base-package="org.codename.*" />



추가 xml 연결 설정

<beans:import resource="classpath:/spring/db-context.xml"/>



db-context.xml 생성하기

 

* 위치 : src/main/resources - spring 패키지 생성 -> Bean configuration file으로 db-context.xml 생성


 

< db-context.xml >

코드 추가

 

	<bean
		class="org.springframework.jdbc.datasource.DriverManagerDataSource"
		id="dataSource">
		<property name="username" value="-----" />
		<property name="password" value="-----" />
		<property name="url" value="jdbc:mariadb://-----/----" />
		<property name="driverClassName" value="org.mariadb.jdbc.Driver" />
	</bean>

	<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"></property>
		<property name="mapperLocations" value="classpath:/mybatis/mappers/*-Mapper.xml"></property>
		<property name="configLocation" value="classpath:/mybatis/config/mybatisConfig.xml"></property>
	</bean>

	<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactoryBean" />
	</bean>

 


 

mybatis

패키지로 생성

mybatis

mybatis.config

mybatis.mappers 

 

 

1. mybatis-config.xml 생성 후 코드 붙여넣기

<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-config.dtd">

 


2. board-mapper.xml 생성 후 코드 붙여넣기

<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-mapper.dtd">

< board-mapper.xml >

 

<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="board">
	<select id="boardList" resultType="HashMap">
		SELECT * FROM boardview LIMIT 0, 10
	</select>
</mapper>

 


spring folder


BoardController.java

controller 패키지 안에 생성하기


스프링에서 객체 생성 방법

  • @Controller
  • @Service
  • @Repository
  • @Component

 

@Controller
public class BoardController {
	
	// 데이터 흐름 : controller -> service -> repository -> mybatis -> DB
	
	@GetMapping("/board")
	public String board() {
		return "board"; // 위치 : /WEB-INF/views/board.jsp
	}
	
}

 


 

< BoardService.java >

@Service

@Service
public class BoardService {

@Autowired
private BoardDAO boardDAO;

public List<Map<String, Object>> boardList(){
return boardDAO.boardList();

	}
}

< BoardDAO.java >

@Repository

 

DTO 만들지 않고 Map으로 하는 방법

@Repository
public class BoardDAO {
	
	@Autowired
	private SqlSession sqlSession;
	
	// DTO 만들지 않고 Map으로 하는 방법
	
	public List<Map<String, Object>> boardList(){
		return sqlSession.selectList("board.boardList");
	}
	
	public List<Map<String, Object>> boardList2(){
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("board_no", 1);
		map.put("board_title", "첫번째 글");
		map.put("board_write", "글쓴이1");
		map.put("board_date", "2024-02-14");
		map.put("board_count", "10");
		map.put("comment", "1");
		list.add(map);
		
		map = new HashMap<String, Object>();
		map.put("board_no", 2);
		map.put("board_title", "2번째 글");
		map.put("board_write", "글쓴이2");
		map.put("board_date", "2024-02-15");
		map.put("board_count", "17");
		map.put("comment", "3");
		list.add(map);
		
		map = new HashMap<String, Object>();
		map.put("board_no", 3);
		map.put("board_title", "3번째 글");
		map.put("board_write", "글쓴이3");
		map.put("board_date", "2024-02-16");
		map.put("board_count", "25");
		map.put("comment", "11");
		list.add(map);
		
		map = new HashMap<String, Object>();
		map.put("board_no", 4);
		map.put("board_title", "4번째 글");
		map.put("board_write", "글쓴이4");
		map.put("board_date", "2024-02-17");
		map.put("board_count", "87");
		map.put("comment", "19");
		list.add(map);
		
		map = new HashMap<String, Object>();
		map.put("board_no", 5);
		map.put("board_title", "5번째 글");
		map.put("board_write", "글쓴이5");
		map.put("board_date", "2024-02-18");
		map.put("board_count", "34");
		map.put("comment", "9");
		list.add(map);
		
		return list;
	}

}

 


< board.jsp >

 

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

 


< BoardController.java >

 

	@GetMapping("/detail")
    
// HTTP 요청 정보를 처리하고, 모델에 데이터를 추가하여 상세 정보를 표시할 뷰 페이지를 반환함.
// HttpServletRequest request : HTTP 요청 정보를 담고 있는 객체, 여기서는 게시물 번호(no)를 가져오기 위해 사용.
// Model model: 컨트롤러에서 뷰로 데이터를 전달하는 데 사용되는 Spring의 Model 객체
    
    
	public String detail(HttpServletRequest request, Model model) {
		String no = request.getParameter("no"); // 글 번호를 가져와서 변수 no에 저장
//		System.out.println(no);
		
		Map<String, Object> detail = boardService.detail(no); // board의 no에 해당하는 상세 정보를 가져옴.
		model.addAttribute("detail", detail); // detail 객체에 담긴 상세 정보를 모델에 추가
		return "detail";
	}

 

<BoardDAO.java>

만들었던 map.put 접어놓고 아래의 detail 추가하기

	public Map<String, Object> detail(String no) {
		return sqlSession.selectOne("board.jsp");
		return null;
	}
}

 

< board-Mapper.xml >

<select id="detail" parameterType="String" resultType="HashMap"> <!-- no의 데이터타입 = string -->
	SELECT *
	FROM board
	WHERE board_no=#{no}
</select>

 

 

< detail.jsp >

 

<title>DETAIL</title>
</head>
<body>
	<h1></h1>
	${detail.board_no } 
	${detail.board_title } 
	${detail.board_content } 
	${detail.board_write } 
	${detail.board_date } 
</body>
</html>

 

 


Member 만들기


 

< MemberController.java >

 

@Controller
public class MemberController {
	
	
	@Autowired
	private MemberService memberService;
	
	@GetMapping("/member")
	public String member(Model model) {
		// service에서 받아옴. Model에 값을 붙임.
		List<MemberDTO> lists = memberService.memberList();
		model.addAttribute("list", lists);
		return "member";
	}
}

 

< MemberDTO >

 

pom.xml 과 컨트롤러 파일 생성 후, DTO 만드는 게 편함.

하지만 이번 수업에서는 아래의 순서대로 진행하였음.

 

import lombok.Data;

@Data
public class MemberDTO {
	private int mno, mgrade;
	private String mid, mname, mdate;
	
}

 


< MemberService.java >

	@Service
	public class MemberService {

	@Autowired
	private MemberDAO memberDAO; // DAO 생성 필요

	public List<MemberDTO> memberList() {
		return memberDAO.memberList();
	} 
}

< mybatis-Config.xml>

<typeAlias type="풀네임" alias="별칭" />

 

<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-config.dtd">
  
  <configuration>
   <typeAliases>
      <typeAlias type="org.mask.dto.MemberDTO" alias="memberDTO" />
   </typeAliases>
</configuration>

< MemberDAO.java >

	@Repository
	public class MemberDAO {

	@Autowired
	private SqlSession sqlSession;

	public List<MemberDTO> memberList(){
	return sqlSession.selectList("member.memberList"); // "namespace.id"
	}
}

 


< MemberController.java >

 

	@GetMapping("/member2")
	public String member2(Model model) {
		List<Map<String, Object>> lists = memberService.memberList2();
		model.addAttribute("list", lists);
		return "member";
	}

 

 

ModelAndView

데이터와 이동하고자 하는 View Page를 같이 저장

ModelAndView 사용시 위의 코드와 같음.

 

	@GetMapping("/member2")
	public ModelAndView member2() {
		List<Map<String, Object>> lists = memberService.memberList2();
		ModelAndView mv = new ModelAndView("member2");
		mv.addObject("list", lists);
		return mv;


	@GetMapping("/member3")
	public @ResponseBody String member3() {  // @ResponseBody 화면에 바로 출력
		List<MemberDTO> lists = memberService.memberList();
		return lists.get(0).toString(); // 문자열로 변경
	}


< MemberDAO.java>

	public List<Map<String, Object>> memberList2() {
		return sqlSession.selectList("member.memberList2");
}


< MemberService.java >

	public List<Map<String, Object>> memberList2() {
		return memberDAO.memberList2();
}


< member-Mapper.xml >

<select id="memberList2" resultType="Map">
	SELECT * FROM member
</select>

< member.jsp >

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>member</title>
</head>
<body>
	<table>
		<thead>
			<tr>
				<th>회원번호</th>
				<th>회원등급</th>
				<th>ID</th>
				<th>회원이름</th>
				<th>가입날짜</th>
			</tr>
		</thead>

		<tbody>
			<c:forEach items="${list }" var="row1">
				<tr>
					<td>${row1.mno }</td>
					<td>${row1.mgrade }</td>
					<td>${row1.mid }</td>
					<td>${row1.mname }</td>
					<td>${row1.mdate}</td>
				</tr>
			</c:forEach>
		</tbody>
	</table>
</body>
</html>

 


< MemberDTO.java >

 

출력 시 가입일자 변경하기

 

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;

import lombok.Data;

@Data
public class MemberDTO {
	private int mno, mgrade;
	private String mid, mname;
	private LocalDate mdate;
    
	// LocalDate를 Date로 변환하는 메서드
    public Date getMdateAsDate() {
        return Date.from(mdate.atStartOfDay(ZoneId.systemDefault()).toInstant());
    }
}

 

 

member로 접속했을 때 보여지는 화면

member

 

member2로 접속했을 때 보여지는 화면

member2

 

반응형

댓글