스프링 스타터 프로젝트 bootweb1

1 개요[ | ]

SpringBoot 튜토리얼
스프링부트 웹 시작하기
스프링 스타터 프로젝트 시작하기
스프링부트 bootweb1 프로젝트
  • "스프링 스타터 프로젝트"는 스프링부트 기반임
  • 여기서는 Web 모듈, Mustache 모듈을 추가로 선택하여 사용
스프링부트 독립실행형 모듈(데몬)
Web 모듈 웹서비스 모듈(대략 톰캣)
Mustache 모듈 뷰를 위한 템플릿 엔진

2 사전작업[ | ]

3 새 프로젝트[ | ]

  • Package Explorer의 빈공간에서 우클릭 --- New --- Spring Starter Project
  • "New Spring Starter Project" --- Name: bootweb1 --- Package: com.example.bootweb1 --- [Next >]
  • Template Engines --- Mustache
  • Web --- Web
  • [Finish]

4 프로젝트 실행[ | ]

  • Package Explorer --- bootweb1 우클릭 --- Run As --- Spring Boot App
  • 하단 Console 창 확인
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.3.3.RELEASE)

2016-03-10 12:37:43.509  INFO 56 --- [           main] c.example.bootweb1.Bootweb1Application  : Starting Bootweb1Application on WIN-DBOPKTBU0KB with PID 56 (D:\workspace-sts\bootweb1\target\classes started by jmnote in D:\workspace-sts\bootweb1)
2016-03-10 12:37:43.514  INFO 56 --- [           main] c.example.bootweb1.Bootweb1Application  : No active profile set, falling back to default profiles: default
2016-03-10 12:37:43.576  INFO 56 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@4ba2ca36: startup date [Thu Mar 10 12:37:43 KST 2016]; root of context hierarchy
2016-03-10 12:37:44.229  INFO 56 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'beanNameViewResolver' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]
2016-03-10 12:37:44.930  INFO 56 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 99 (http)
2016-03-10 12:37:44.946  INFO 56 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2016-03-10 12:37:44.947  INFO 56 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.0.32
2016-03-10 12:37:45.053  INFO 56 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2016-03-10 12:37:45.053  INFO 56 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1481 ms
2016-03-10 12:37:45.352  INFO 56 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'dispatcherServlet' to [/]
2016-03-10 12:37:45.357  INFO 56 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'characterEncodingFilter' to: [/*]
2016-03-10 12:37:45.358  INFO 56 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2016-03-10 12:37:45.358  INFO 56 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2016-03-10 12:37:45.358  INFO 56 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'requestContextFilter' to: [/*]
2016-03-10 12:37:45.671  INFO 56 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@4ba2ca36: startup date [Thu Mar 10 12:37:43 KST 2016]; root of context hierarchy
2016-03-10 12:37:45.753  INFO 56 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2016-03-10 12:37:45.754  INFO 56 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2016-03-10 12:37:45.786  INFO 56 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-03-10 12:37:45.786  INFO 56 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-03-10 12:37:45.825  INFO 56 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-03-10 12:37:45.954  INFO 56 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2016-03-10 12:37:46.032  INFO 56 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2016-03-10 12:37:46.038  INFO 56 --- [           main] c.example.bootweb1.Bootweb1Application  : Started Bootweb1Application in 2.861 seconds (JVM running for 3.867)

5 실행확인[ | ]

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Tue Mar 15 10:40:58 KST 2016
There was an unexpected error (type=Not Found, status=404).
No message available
→ URL을 풀어주는 곳이 없음. 구현하지 않았기 때문에.
→ 어쨌든 Web 모듈은 정상 작동하고 있음

6 HomeController 작성[ | ]

  • Package Explorer 영역 --- bootweb1 [boot] --- src/main/java 우클릭 --- New --- Package
  • "Java Package" --- Name: com.example.bootweb1.controllers --- [Finish]
  • com.example.bootweb1.controllers 우클릭 --- New --- Class
  • "Java Class" --- Name: HomeController --- [Finish]

( HomeController.java 파일이 아래와 같이 자동 생성됨 )

package com.example.bootweb1.controllers;

public class HomeController {

}
  • 파일 내용 수정
package com.example.bootweb1.controllers;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HomeController {
	@RequestMapping("/")
	public String home() {
		 return "안녕 Spring Boot!";
	}
}
→ 일반 Controller가 아닌 RestController로 하였음
→ 별도의 View 템플릿 없이 return 값이 브라우저에 그대로 출력될 것임

7 실행확인 2[ | ]

  • 상단의 빨간 정지 버튼(■)을 눌러 앱 중지
  • 상단의 빨간 시작 버튼(▶)을 눌러 앱 시작
  • 브라우저에서 http://localhost:8080 접속하여 확인
안녕 Spring Boot!

8 Greet 컨트롤러 작성[ | ]

  • com.example.bootweb1.controllers 우클릭 --- New --- Class
  • "Java Class" --- Name: GreetController --- [Finish]
  • GreetController.java 파일 내용 수정
package com.example.bootweb1.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class GreetController {
	@RequestMapping("/greet")
	public String greet() {
		return "greet";
	}
}
→ 이대로 실행하면 http://localhost:8080/greet 접근시 템플릿 "greet"를 찾지 못하는 오류 발생
Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Tue May 31 11:23:13 KST 2016
There was an unexpected error (type=Internal Server Error, status=500).
Circular view path [greet]: would dispatch back to the current handler URL [/greet] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)

9 Greet 뷰 작성[ | ]

  • Package Explorer --- src/main/resources --- templates 우클릭 --- New --- Other...
  • "New" --- Wizards: html --- [Next >]
  • File name: greet.html --- [Finish]
  • greet.html 내용 수정
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Greet</title>
</head>
<body>
<p>안녕하세요, Greet!</p>
</body>
</html>

10 실행확인 3[ | ]

안녕하세요, Greet!

11 Greet 컨트롤러 수정[ | ]

  • GreetController.java 파일 수정
package com.example.bootweb1.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class GreetController {
	@RequestMapping("/greet/{name}")
	public String greet(@PathVariable("name") String name) {
		return "greet";
	}
}

12 Greet 뷰 수정[ | ]

  • greet.html 파일 수정
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Greet</title>
</head>
<body>
<p>안녕하세요, {{name}}!</p>
</body>
</html>

13 실행확인 4[ | ]

안녕하세요, 홍길동!

14 같이 보기[ | ]

15 참고[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}