본문 바로가기

Spring

[Spring Boot] html, JSP 파일 생성 & Controller 연결

728x90
반응형

Spring Boot에서 html과 jsp 파일 생성 후 controller와 연결하는 방법까지 알아보려고 한다. 

 

 

new에서 html, jsp 파일을 생성하려고 보니 검색을 해도 나오지않기때문에 사용하기 위해서 

마켓에서 Eclipse Web Developer Tools를 다운받는다. 

 


1) html 

 

html은 정적 리소스 파일들을 넣어두는 static 파일 하위에 위치해야한다. 

 

html로 사진을 페이지에서 출력하기위해서 images 파일에 사진을 넣어준 뒤 하기와 같이 작성한다. 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>표지페이지 </title>
</head>
<body>

<img alt="곰사진" src="/images/bear.jfif">

</body>
</html>

 

서버를 실행시킨 뒤 url을 통해서 index.html에 넣어둔 사진이 잘뜨는 것을 확인할 수 있다. 


2) jsp 

 

- build.gradle

jsp를 사용하기 위해서 라이브러리를 추가해주어야 하는데 gradle에서 pom.xml의 역할을 하는

build.gradle에 라이브러리를 추가해준다.  

plugins {
	id 'org.springframework.boot' version '2.7.5'
	id 'io.spring.dependency-management' version '1.0.15.RELEASE'
	id 'java'
	id 'war'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

repositories {
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-web'
	providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
	
	implementation 'javax.servlet:jstl' //jstl을 사용하기 위한 주입
	implementation 'org.apache.tomcat.embed:tomcat-embed-jasper'//jsp를 사용하기 위한 주입 
}

tasks.named('test') {
	useJUnitPlatform()
}

해당 작업 이후 저장을 하여도 자동으로 업데이트가 안되기때문에 

반드시 Gradle -> Refresh Gradle Project을 해주어야 정상적으로 라이브러리 추가가 된다. 

 

 

- application.properties

해당 파일에 경로 설정을 해준다. 

#JSP 페이지 볼 수 있도록 설정 추가 
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp

 

[동작순서] 
1. 프로그램 실행
2. application.properties 파일의 설정을 로드 
3. 이후 사용자가 무언가 요청을 하게되면,
4. 그에 응답할 내용(jsp 파일)에 prefix 및 suffix 설정을 조합해줌 

 

 

jsp 파일의 경우에는 application.properties에서 지정한대로 main 폴더 하위에 추가적으로 폴더들을 생성해준다. 

 

- Controller 

package com.kim.springboot.test;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class TestController {
	@RequestMapping("/")
	public @ResponseBody String root() {
		
		return "커맨드 객체 사용하는 예제 : 사용자로부터 데이터를 받아올 예정";
	}
	
	//1. jsp방식 
	@RequestMapping("/test1")
	public String test1(HttpServletRequest req,Model model) { //코드 가독성이 1번이 좀 떨어지니 2번을 채택

		model.addAttribute("id",req.getParameter("id"));
		
		String name=req.getParameter("name"); //코드 가독성을 위해 변수를 추가 사용함 & 유지보수 용이 
		model.addAttribute("name", name);
		
		return "test1"; 
	}
	
	//2. jsp방식을 어노테이션 사용하여 spring 방식으로 변경한 방식
	//vo에 없는 값들을 받아오는데 유리하다
	//일시적으로 vo를 딱한번 받아와야할때 사용되는 방법
	@RequestMapping("/test2")
	public String test2(@RequestParam("id")String id, @RequestParam("name")String name, Model model) {
		model.addAttribute("id", id);
		model.addAttribute("name", name);
		return "test2"; 
	}
	
	//3. 커맨드 객체(vo)를 다이렉트로 사용하는 방식
	@RequestMapping("/test3")
	public String test3(Student student, Model model) {
	
		return "test3"; 
	}
	
	//4. 경로에 변수를 추가하는 방식
	@RequestMapping("/test4/{studentId}/{studentName}")
	public String test4(@PathVariable String studentId, @PathVariable String studentName, Model model) {
		model.addAttribute("id", studentId);
		model.addAttribute("name", studentName);
		return "test4"; 
	}
    }

test1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>1</title>
</head>
<body>

${id} | ${name}

</body>
</html>

 

url에 직접 파라미터 값을 전달하여 출력이 정상적으로 되는걸 확인할 수 있다. 

 

test1.jsp
test4.jsp

728x90
반응형