@Controller와 @RestController를 같이 사용하기

2024. 5. 26. 00:35Java/Spring Boot

@Controller와 @RestController를 같이 사용하면, @Controller가 작동하지 않음

@Controller 사용

# Main.java
@Controller
public class Main {
	@RequestMapping("/a")
	public String deGetHelloWorld() {
		System.out.println("ssssssssssssssssssssssssss");
		return "Hello World";
	}
	
	@GetMapping("/")
	public String home() {
		return "home";
	}
}

# /src/main/resources/templates/home.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org">
    <head>
        <title>Spring Security Example</title>
    </head>
    <body>
        <h1>Welcome!</h1>

        <p>Click <a th:href="@{/hello}">here</a> to see a greeting.</p>
    </body>
</html>

@RestController 사용

# Main.java
@RestController
public class Main {
	@RequestMapping("/a")
	public String deGetHelloWorld() {
		System.out.println("ssssssssssssssssssssssssss");
		return "Hello World";
	}
	
	@GetMapping("/")
	public String home() {
		return "home";
	}
}

# /src/main/resources/templates/home.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org">
    <head>
        <title>Spring Security Example</title>
    </head>
    <body>
        <h1>Welcome!</h1>

        <p>Click <a th:href="@{/hello}">here</a> to see a greeting.</p>
    </body>
</html>

에러가 안나도록 조치

# Main.java
@Controller
public class Main {
	@RequestMapping("/a")
	public @ResponseBody String deGetHelloWorld() {
		System.out.println("ssssssssssssssssssssssssss");
		return "Hello World";
	}
	
	@GetMapping("/")
	public String home() {
		return "home";
	}
}

# /src/main/resources/templates/home.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org">
    <head>
        <title>Spring Security Example</title>
    </head>
    <body>
        <h1>Welcome!</h1>

        <p>Click <a th:href="@{/hello}">here</a> to see a greeting.</p>
    </body>
</html>

 

'Java > Spring Boot' 카테고리의 다른 글

Spring boot에 sencha app 생성  (0) 2024.07.13
ViewController 추가  (0) 2024.06.13
Spring boot 3.2.5 and JDK17 셋팅  (0) 2024.05.19
Spring Authorization Server 테스트  (0) 2024.03.14
Spring boot 3.2.3 설정  (0) 2024.03.14