Spring/Boot
[Boot] Gradle
hvoon
2022. 9. 10. 20:41
workspace 폴더 바꾸기


기본 설정




프로젝트 생성




server 연결
build.gradle

src\main\resources\application.properties
# Server port
server.port = 8070
html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>index.html</title>
</head>
<body>
<h1>스트링 부트 시작페이지</h1>
<img src="images/베어배경1.jpg" width="500">
</body>
</html>
open web browser


JSP
build.gradle
plugins {
id 'org.springframework.boot' version '2.5.3'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'com.ecl'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation 'javax.servlet:jstl'
implementation 'org.apache.tomcat.embed:tomcat-embed-jasper'
}
test {
useJUnitPlatform()
}
src\main\resources\application.properties
# Server port
server.port=8070
# about JSP
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp

package com.ecl.g02;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class SpringBootController {
@RequestMapping("/")
public @ResponseBody String root() {
return "<h1>JSP in Gradle</h1>";
//@RequestMapping 값이 "/"이고 리턴값이 "main"이라면
// http://localhost:8070/ 의 결과는 main.jsp이겠지만(별도 경로 설정 및 폴더 생성 필요)
// 함수 이름에 @ResponseBody가 있으면 리턴되는 문자열이 웹 브라우져에 직접 쓰여지게 됨
}
}

package com.ecl.g02;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class SpringBootController {
@RequestMapping("/")
public @ResponseBody String root() {
return "<h1>JSP in Gradle</h1>";
//@RequestMapping 값이 "/" 이고 리턴값이 "main" 이라면
// http://localhost:8070/ 의 결과는 main.jsp 이겠지만(별도 경로 설정 및 폴더 생성 필요)
// 함수 이름에 @ResponseBody 가 있으면 리턴되는 문자열이 웹 브라우져에 직접 쓰여지게 됩니다
}
@RequestMapping("/test1") // localhost:8070/test1
public String test1() {
return "main";
// 실제 호출 될 webapp/WEB-INF/views/main.jsp
}
@RequestMapping("/test2") // localhost:8070/test2
public String test2() {
return "sub/sub"; // 실제 호출 될 /WEB-INF/views/sub/sub.jsp
}
}
src\main\webapp\WEB-INF\views\main.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>스트링 부트 메인 페이지</h1>
</body>
</html>

src\main\webapp\WEB-INF\views\sub\sub.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>스트링 부트 서브 페이지</h1>
</body>
</html>

Model
build.gradle
plugins {
id 'org.springframework.boot' version '2.7.2'
id 'io.spring.dependency-management' version '1.0.12.RELEASE'
id 'java'
}
group = 'com.ecl'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation 'javax.servlet:jstl'
implementation 'org.apache.tomcat.embed:tomcat-embed-jasper'
}
tasks.named('test') {
useJUnitPlatform()
}
src\main\resources\application.properties
# Server port
server.port=8070
# about JSP
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp


package com.ecl.g03;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class ModelController {
@RequestMapping("/")
public @ResponseBody String root() throws Exception{
return "<h1>Model & View</h1>";
}
이 안에 코드 추가
}

@RequestMapping("/test1")
public String test1(Model model, HttpServletRequest request){
// 리턴되는 jsp 파일까지만 해당 내용을 전달할 수 있는 1회용 자료 전달 도구
model.addAttribute("name1","홍길동");
// request의 수명이 다하는 순간까지는 내용을 살려서 다시 전달할 수 있는 전달 도구
request.setAttribute("name2", "김하나");
return "test1";
}
src\main\webapp\WEB-INF\views\test1.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>test1</title>
</head>
<body>
<h1><%out.println("Model:Hello World"); %></h1>
<h1>당신의 이름은 ${name1 }</h1>
<h1>당신의 또 다른 이름은 ${name2 }</h1>
</body>
</html>

ModelController 코드 추가
@RequestMapping("/test2")
public String test2(Model model, HttpServletRequest request) {
model.addAttribute("name1", "홍길동");
request.setAttribute("name2", "김하나");
return "redirect:/test3?name1=홍길동";
}
@RequestMapping("/test3")
public String test3(Model model, HttpServletRequest request) {
String name1=(String)model.getAttribute("name1");
String name2=(String)model.getAttribute("name2");
model.addAttribute("name1", name1);
request.setAttribute("name2", name2);
System.out.println(name1+" "+name2);
return "test3";
}
src\main\webapp\WEB-INF\views\test3.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>test3</title>
</head>
<body>
<h1><%out.println("Model:Hello World"); %></h1>
<h1>당신의 이름은 ${name1 }</h1>
<h1>당신의 또 다른 이름은 ${name2 }</h1>
</body>
</html>

String name4;
String name5;
@RequestMapping("/test2")
public String test2(Model model, HttpServletRequest request) {
model.addAttribute("name1", "홍길동");
request.setAttribute("name2" , "김하나");
request.setAttribute("model", model);
name4 = "홍길동";
name5 = "김하나";
return "redirect:/test3";
}
@RequestMapping("/test3")
public String test3(Model model, HttpServletRequest request) {
// 새로운 객체가 매개변수로 지정되어 전달되어지는 model과 request가 적용되지 않음.
// test2 메서드에서 보내려고 했던 model과 request는 전달인수로 보낸게 아니기 때문에
// test3 메서드의 매개변수에 저장되지 않음.
// request와 model의 내용을 꺼내쓰는 건 return 되는 jsp 파일 내부만 가능
// model=(Model)request.getAttribute("model"); // 전달 불가능
model.addAttribute("name1", name4);
request.setAttribute("name2", name5);
return "test3";
}

ModelController 코드 추가
@RequestMapping("/test4")
public ModelAndView test2() {
// 데이터와 뷰를 동시에 설정이 가능
ModelAndView mav = new ModelAndView();
List<String> list = new ArrayList<String>();
list.add("test1");
list.add("test2");
list.add("test3");
mav.addObject("lists", list);
mav.addObject("ObjectTest", "테스트입니다.");
mav.addObject("name", "홍길동");
mav.setViewName("view/myView");
return mav;
}
src\main\webapp\WEB-INF\views\myView.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>Insert title here</title>
</head>
<body>
<h1><%out.println("Model(Sub):Hello World"); %></h1>
<h1> ${ObjectTest }</h1>
<h1>${lists }</h1><br>
<c:forEach var="mylist" items="${lists }">
<h1>${mylist }</h1>
</c:forEach>
</body>
</html>
Parameter
src\main\java\com\ecl\g04\MemberDto.java
package com.ecl.g04;
public class MemberDto {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
src\main\java\com\ecl\g04\FormDataController.java
package com.ecl.g04;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class FormDataController {
@RequestMapping("/")
public String root() throws Exception{
return "testForm";
}
추가될 내용
}
src\main\webapp\WEB-INF\views\testForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="test1">
<table border="1" cellspacing="0">
<tr><th>아이디</th><td><input type="text" name="id"/></td></tr>
<tr><th>이름</th><td><input type="text" name="name"/></td></tr>
<tr><td colspan="2" align="center">
<input type="submit" value="전송"/></td></tr>
</table>
</form>
</body>
</html>

@RequestParam
@RequestMapping("/test1")
public String test1(HttpServletRequest request, Model model) {
String id = request.getParameter("id");
String name = request.getParameter("name");
model.addAttribute("id", id);
model.addAttribute("name", name);
return "test1";
}
다른 방법
@RequestMapping("/test1")
public String test1(HttpServletRequest request, Model model,
@RequestParam("id") String id,
@RequestParam("name") String name) {
model.addAttribute("id", id);
model.addAttribute("name", name);
return "test1";
}
src\main\webapp\WEB-INF\views\test1.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>Insert title here</title>
</head>
<body>
<body>
<h1><% out.println("#01 Hello World");%></h1>
<h1>당신의 이름은 ${id} 입니다.</h1>
<h1>당신의 이름은 ${name} 입니다.</h1>
</body>
</html>


Dto객체 멤버변수 이용하기
@RequestMapping("/test2")
public String test2(
MemberDto memberdto, Model model) {
// 파라미터와 일치하는 멤버변수가 있는 객체를 만들고
// 이 객체를 매개변수로 사용 가능
// 전달된 파라미터는 매개변수에 자동 입력됨
model.addAttribute("id", memberdto.getId());
model.addAttribute("name", memberdto.getName());
return "test2";
}
src\main\webapp\WEB-INF\views\test2.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>Insert title here</title>
</head>
<body>
<body>
<h1><% out.println("#02 Hello World");%></h1>
<h1>당신의 이름은 ${id} 입니다.</h1>
<h1>당신의 이름은 ${name} 입니다.</h1>
</body>
</html>


Dto객체 멤버변수를 @ModelAttribute로 전송하기
@RequestMapping("/test2")
public String test2(
@ModelAttribute("member")MemberDto memberdto, Model model) {
// @ModelAttribute 매개변수를 메서드 시작과 함께 Model에 넣음
// 전송될 준비 완료
// @ModelAttribute의 역할은 model.addAttribute("member", memberdto); 라고 쓴 것과 같음
return "test2";
// 위 동작의 필수 조건
// 1. 파라미터 이름과 Dto 객체 멤버변수의 이름 반드시 같아야 함
// 2. 객체 매개변수의 이름과 클래스 이름과 반드시 같아야함. 다만 모두 소문자로 표시.
}
<%@ 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>Insert title here</title>
</head>
<body>
<body>
<h1><% out.println("#02 Hello World");%></h1>
<h1>당신의 이름은 ${member.id } 입니다.</h1>
<h1>당신의 이름은 ${member.name} 입니다.</h1>
</body>
</html>

주소창에 직접 입력하기(@PathVariable)
@RequestMapping("/test3/{studentId}/{name}")
public String getStudent(
@PathVariable String studentId,
@PathVariable String name,
Model model){
model.addAttribute("id", studentId);
model.addAttribute("name", name);
return "test3";
}
<%@ 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>Insert title here</title>
</head>
<body>
<body>
<h1><% out.println("#03 Hello World");%></h1>
<h1>당신의 이름은 ${id} 입니다.</h1>
<h1>당신의 이름은 ${name} 입니다.</h1>
</body>
</html>
