ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Spring Boot Project] 기본 구조, Hello World 출력 , controller에서 html 호출
    개발 공부/Spring 2022. 1. 18. 10:38
    반응형
    SMALL

    spring boot project 생성 후

    노란 동그라미 부분은 직접 생성했다

     

    검색해보면 다들 src안에 resources 있던데

    나는 없길래 왜 없는지 한참 찾았는데

    그냥 내가 폴더 만들어주면 되더라

     


     

    TestappApplication.java

    package com.example.test;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class TestappApplication {
    
    	public static void main(String[] args) {
    		SpringApplication.run(TestappApplication.class, args);
    	}
    
    }

    여기가 아마 시작부분!

     

    그리고 java에 controller 패키지 하나 만들어서 testcontroller.java를 생성했다

     

    testcontroller.java

    package com.example.test.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @Controller
    public class testController {
    	
    	@RequestMapping("/")
    	public String main(Model model) {
            model.addAttribute("data", "hello rogie!!");
    		return "index";
    	}
    	
    	//@RequestMapping(value = "/home")
    	@GetMapping("/home")
    	public String home() {
    		return "content/home";
    	}
    
    }

     

    매핑을 해줘서 주소마다 다른 페이지가 출력되게 했다.

     

    http://localhost:8080/ 주소로 접속하면 index.html이 출력되고

    http://localhost:8080/home 주소로 접속하면 content의 home.html이 출력된다.

     

    이 때 이 html파일들은 맨 첫번째 이미지에서 보이는 노란부분

    src ->  main -> resources -> templates에 있는 파일들이다.

     


    그럼 이제 html 파일들을 보겠다

    templates의 index.html

    <!DOCTYPE html>
    <html lang="kr" xmlns:th="http://www.thymeleaf.org">
    <head>
      <title>Hello Hello</title>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
      Hello World!
    </body>
    </html>

     

    이렇게 해주고 서버 실행 후 접속해보면 

     

    hello world 출력 완료

     


     

    소스가 다 맞는데 이렇게 자꾸 404에러가 뜨거나 

     

    java소스 Controller 에서 return한 html 페이지가 출력되는게아니라 문자열만 출력된다면

    pom.xml에 이거 추가

     

    <dependency>
    	<groupId>org.springframework.boot</groupId>
    	<artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

     

    이거 설정 안하고 계속 왜안되나 했네 증말

     


    controller에서 html로 값 넘기는 법, 그리고 template 나누는 법은 다음 포스팅에서 설명할예정

     

     

    반응형
    LIST

    댓글

Designed by Tistory.