KD007
KD007

Reputation: 49

Springboot controller issue

Problem with web starter project from spring initializer. Springboot 2.2.0

I just created a spring boot 2.2.0 project from spring initializer website with web starter dependency. The application works fine if I user @RestController annotation and send request from postman but when I use @Controller annotation and try to load the hello.html page which is in /resources/templates directory it throws null or white label errors. It's weird the package structure is perfect but it's not working.

I could not find any answer thread so far for this issue.

Upvotes: 0

Views: 553

Answers (4)

KD007
KD007

Reputation: 49

Simply updating the maven dependency resolved the issue. Thank you guys for your response.

Upvotes: 0

SatyaMounica
SatyaMounica

Reputation: 26

Is thymeleaf dependency added to your project??

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

Upvotes: 0

Ramya
Ramya

Reputation: 95

@RestController : If it is a @RestController it just return the value whatever we given in return statement. For eg:

HomeController.java

package com.example.demo;

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

@RestController
public class HomeController {

@RequestMapping(value="/")
public String index() {
   return "home";
}
}

The output is: home

It just only returns the return statement

@Controller : The @Controller annotation is returns the view page (resource/template/home.html). For Eg:

HomeController.java

 package com.example.demo;

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

 @Controller
 public class HomeController {

 @RequestMapping(value="/")
 public String index() {
    return "home";
 }
 }

home.html

<!DOCTYPE html>
<html>
 <head>
   <meta charset="UTF-8">
   <title>Insert title here</title>
 </head>
 <body>
   <img alt="Image" src="/images/barbie.jpg">
 </body>
</html>

The output: It display home.html page

enter image description here

Upvotes: 0

Romil Patel
Romil Patel

Reputation: 13727

Possible Issue:

When you use @Controller add @ResponseBody @ResponseBody is required when we use @Controller. @RestController is a special version of @Controller in which @ResponseBody is active by default

@Controller vs @RestController


with @Controller

@Controller
public class UserController {

    @GetMapping(value= "/hello")
    public @ResponseBody String sayHello()
    {   
        retrun "Hello";
    }
}

with @RestContoller

@RestController
public class UserController {

    @GetMapping(value= "/hello")
    public String sayHello()
    {   
        retrun "Hello";
    }
}

Upvotes: 1

Related Questions