본문 바로가기

programming/Spring

Spring 공부 정리

스프링 스타트 부트

https://start.spring.io/

 



error - could not find main class

1. 프로젝트 JDK 설정
2. gradle JDK 설정
3. closs project
4. .idle 파일 삭제
5. 다시 오픈

 

 

실행

1.  ide내 실행
helloSpringApplication-main class-run 클릭
2. jar 실행(cmd)

gradlew build
cd build/libs 
java -jar hello-spring-0.0.1-SNAPSHOT.jar


3. 빌드 폴더 제거하기
3.1 gradlew clean
고로 잘 안될경우 gradlew clean build

 

 

 

package hello.hellospring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloController {

    //컨트롤러에 없는 매핑일경우 정적 컨텐츠 : static/????.html을 찾게됨.

    @GetMapping("hello")        // 일반적인 방식
    // 컨트롤러에서 hello를 찾으면 모델 리턴, 뷰리졸버가 resource/templates에서 hello.html을 찾아서 합성후 웹브라우저로 전달 
    public String hello(Model model){
        model.addAttribute("data", "hello!!");
        return "hello";
    }

    @GetMapping("hello-mvc")    // get 방식
    public String helloMvc(@RequestParam("name") String name, Model model) {
        model.addAttribute("name", name);
        return "hello-template";
    }

    @GetMapping("hello-string") // 뷰리졸버를 사용하지 않음. HTTP의 BODY로 바로 전달.
    @ResponseBody
    public String helloString(@RequestParam("name") String name) {
        return "hello " + name;
    }

    @GetMapping("hello-api")    // json방식, 최근 json방식으로 통일함.
    @ResponseBody               // 리스폰스바디를 사용할경우 대부분 json으로 반환하는게 기본임(아주 레거시 일경우 xml존재)
    public Hello helloApi(@RequestParam("name") String name) {
        Hello hello = new Hello();
        hello.setName(name);
        return hello;           // 객체를 받으면 default : json방식으로 만들어서 반환하겠다가 기본 정책임
    }

    static class Hello {
        private String name;

        public String getName() {       //java bean 표준방식 : 게터 세터, 프로터티 접근방식
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }


    }
}

 

static/index.html

<!DOCTYPE HTML>
<html>
<head>
    <title>Hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
Hello
<a href="/hello">hello</a>
</body>
</html>

 

 

hello-static

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
정적 컨텐츠 입니다.
</body>
</html>

 

templates/hello.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'안녕하세요. ' + ${data}" > 안녕하세요. 손님</p>
</body>
</html>

 

templates/hello-template.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}" > hello! empty</p>
</body>
</html>