Programming/스프링(spring) - Enterprise

스프링(spring)/ 스프링부트(springBoot) JAR 패키징

esoog Polaris 2023. 8. 23. 21:55
반응형

# 스프링부트 Jar 패키징

 

그동안 서블릿 컨테이너 설정과 jsp 사용을 위해, War 패키징으로만 사용해왔다.

하지만, 보다 독립적인 실행이 가능하고, 간편한 배포를 위해 Jar 패키징을 사용해 프로젝트 생성.

의존성 패키지로(mysql, mybatis, jdbc, thymeleaf)를 추가 했다.

 

pom.xml 의존성 관리 파일은 기존 spring Boot와 진행이 같고,

application.properties 파일에 jsp관련 구문을 빼고는 기존 spring Boot과 진행이 같다.

 

그 다음, 이제 다른 것이 JAR 패키징에서는 jsp를 사용하지 않는다.

단순히 src/main/resources 폴더의 static, templetes 폴더에 html과 css, js파일을 넣어 사용한다.

나머지 M C 파트는 같아서 기존 진행과 같이 하면 된다.

구조는 단순히 이렇다. 

 

 

 

 

 

 

# run 하면, 기본적으로 첫화면이 로그인 화면이 뜬다?

 

스프링 시큐리티 프레임 워크 사용시, 자동 생성되는 페이지다.

보안 및 인증 관련 기능을 간편하게 구현하기 위해서다. /login 페이지

단, 필수는 아니다. templetes 폴더에 login.html파일을 만들어 커스터 마이징 하거나, 컨트롤러로 수정 가능.

 

 

* 사용법

# 아이디 : user

# 비밀번호 : [콘솔창에 출력되는 보안 비밀번호]

 

 

* 이 페이지를 사용 않으려면, 메인 앱 클래스의

기존 @SpringBootApplication 어노테이션을 수정 추가 해주면 된다.

@SpringBootApplication(exclude = {SecurityAutoConfiguration.class})

 

 

 

 

# 그럼 이제 .jsp파일 없이 웹 화면을 꾸미는 방법만 알면 된다.

 

jstl언어 대신에 thymeleaf 라이브러리(View templete engine)를 사용해서 처리한다.

라이브러리 설정 부터(pom.xml 파일에서)

 

		<dependency>
			<groupId>org.thymeleaf.extras</groupId>
			<artifactId>thymeleaf-extras-springsecurity5</artifactId>
		</dependency>

* 타임리프와 시큐리티 통합 라이브러리다.

 

 

사용은 별거 없다. Controller에서 return값(viewName)을 넘긴다. html 이름이다.

스프링 부트 템플릿엔진은 기본적으로 viewName을 매핑한다. 이것은 아래와 같이 매핑된다.
resources:templates/ + viewName + .html

 

 

그럼 thymeleaf 템플릿 엔진 문법을 살펴보자.

 

<div th:text="${data}"></div>
<!-- th:text="${}" 
데이터 사용 -->


<div th:with=”userId=${number}” th:text=”${usesrId}”>
<!--  th:with="${}" 
변수 세팅 -->


<input type="text" id="userId" th:value="${userId} + '의 이름은 ${userName}"/>
<!--  th:value="${}" 
값 삽입 -->


<span th:if="${userNum} == 1"></span> 
<span th:unless="${userNum} == 2"></span>
<!--  th:if="${}", th:unless="${}" 
조건문 -->


<body>
  <li th:each="pageButton" : ${#numbers.sequece(paging.firstPage, paging.lastPage)}></li>
</body>
<!-- th:each="변수 : ${list}" 
반복문 -->


<body>
  <a th:hrf="@{/boardListPage?currentPageNum={page}}"></a>
</body>
<!-- th:href="@{}" 
링크 url -->

 

 

가볍게 사용한 html 파일 예시

 

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="ko">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link th:href="@{/css/home.css}" rel="stylesheet">
<link rel="stylesheet"
	href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<link rel="stylesheet"
	href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap-theme.min.css">
<script src="https://code.jquery.com/jquery-latest.min.js"></script>

<title>McMurpeace</title>
</head>

<body>

	<div class="logBox">
		<div th:with="member=${session.member}">
			<!-- 여기서 member 변수 사용 -->
		</div>
		<!-- 세션스코프는 서블릿에서 제공하는 스코프 중 하나인데 서블릿에서 이미 저장되어 있다. -->
		<div th:if="${member}">
			<p class="userLog" th:text="${member.id + '님 환영합니다.'}"></p>
		</div>

		<div class="myBtn">
			<a href="/account/login">
				<button class="btn btn-info" id="loginBtn">로그인</button>
			</a>
		</div>
	</div>

	<div class="input-group mb-3 searching">
		<input type="text" class="form-control" placeholder="검색어를 입력해 주세요"
			name="keyword" aria-label="Recipient's username"
			aria-describedby="basic-addon2" id="blank">
		<button class="btn btn-info" id="searchBtn">검색</button>
	</div>

	<div class="debateBox">
		<h2>폴리텍 토론의 콜로세움</h2>
		<div th:each="boardAll : ${boardAll}">
			<!-- debate 변수로 작업 수행 -->
			<div th:if="${boardAll}" class="debate">
				주제
				<p class="userLog" th:text="${boardAll.title}"></p>
				이름
				<p class="userLog" th:text="${boardAll.nick}"></p>
				의견
				<p class="userLog" th:text="${boardAll.text}"></p>
			</div>
		</div>
	</div>

	<script>
		var member = /*[[${member}]]*/null;
		var loginBtn = $("#loginBtn"); // loginBtn 변수 가져오기

		// 로그인 상태인 경우
		if (member) {
			loginBtn.hide(); // 로그인 버튼 숨기기
		} else {
			loginBtn.show(); // 로그인 버튼 보이기
		}
	</script>

</body>

</html>

* jsp와 크게 다르지 않지만, 조금 더 복잡한 태그를 사용할 뿐이다.

 

* <html xmlns:th="http://www.thymeleaf.org" lang="ko"> 태그를 사용한다는 점.

 

* 경로를 사용 한다면 타임리프 문법으로 사용 해야 한다는 점. <link th:href="@{/css/home.css}" rel="stylesheet">

(static까지 기본 경로이기에 /부터 시작)

 

* 스크립트의 var member = /*[[${member}]]*/null; 부분이 특이한데;

먼저 타임리프를 자바스크립트 안에서 쓰려면 주석 처리 후,[[ ${} ]] 이런 형태로 사용.

서버에서 렌더링 될 때, 클라이언트 측에서 보여지게 하는 로직.

뒤에 null값은 초기화를 위해.

 

 

 

 

 

(참고: https://velog.io/@alicesykim95/Thymeleaf)

 

Spring Thymeleaf 기본 문법

타임리프(Thymeleaf)는 View Templete Engine으로 JSP, Freemarkerd와 같이 서버에서 클라이언트에게 응답할 브라우저 화면을 만들어주는 역할을 한다. 타임리프의 주 목표는 템플릿을 만들 때 유지관리가 쉽

velog.io

 

728x90