184

I used maven to do the tutorial https://spring.io/guides/gs/uploading-files/
All the codes I used was copied.

The Application can run, but I get the error:

Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. Tue Jun 30 17:24:02 CST 2015 There was an unexpected error (type=Not Found, status=404). No message available

How can I fix it?

nbro
  • 15,395
  • 32
  • 113
  • 196
Deng Steve
  • 1,851
  • 2
  • 11
  • 5

56 Answers56

219

Make sure that your main class is in a root package above other classes.

When you run a Spring Boot Application, (i.e. a class annotated with @SpringBootApplication), Spring will only scan the classes below your main class package.

com
   +- APP
         +- Application.java  <--- your main class should be here, above your controller classes
         |
         +- model
         |   +- user.java
         +- controller
             +- UserController.java
m00am
  • 5,910
  • 11
  • 53
  • 69
vignesh Subash
  • 2,577
  • 1
  • 11
  • 15
  • 9
    Above or on the same level? – Martin Erlic Jan 31 '17 at 09:56
  • 32
    I spent almost 2hrs of my life on figuring this out! – Rakesh Feb 03 '17 at 12:15
  • 10
    Tried that too. Still error. At least the main page i.e., http://localhost:8080 should show me the Tomcat homepage, shouldn't it? But that too isn't showing – zulkarnain shah Jul 16 '17 at 06:27
  • 1
    Thanks for the hint. I used to be an Eclipse user and there this configuration was not needed, but now I'm using IntelliJ and it was very hopeful. – Armer B. Jan 12 '19 at 10:24
  • @zulkarnainshah The usual tomcat homepage is generated by a WAR that is not included here. – Thorbjørn Ravn Andersen Feb 25 '19 at 10:33
  • @MartinErlic Above – Ammar Akouri May 31 '19 at 19:44
  • 30minutes wondering what was happening and it was only a simple error in naming packages – Ciaran Whyte Jul 17 '20 at 12:47
  • 1
    And how can this be done? I can't move my class to the very top. I have it at the bottom – Ilya Sep 05 '21 at 13:37
  • UOOWW Thanks my king. helped a lot !! – jonathasborges1 Oct 24 '21 at 21:44
  • I get the same exact error as the OP but have neither model nor controller class in my initial spring boot, as I followed the instructions on Baeldung's Spring 5 tutorial (page 11-12, "Bootstrapping Using Spring Boot"). Could the fact that I have no model and no controller classes be the reason for my error? – WebViewer Oct 06 '22 at 20:33
  • I was getting the same error, tried this solution with putting the files on the same level, it didn't work, when I put the main file to the upper level it worked. I basically created a new package on the same level with Main file and put controller file into the new package which is at the same level with Main file. – Çağatay Şen Jan 21 '23 at 21:17
90

When we create a Spring boot application we annotate it with @SpringBootApplication annotation. This annotation 'wraps up' many other necessary annotations for the application to work. One such annotation is @ComponentScan annotation. This annotation tells Spring to look for Spring components and configure the application to run.

Your application class needs to be top of your package hierarchy, so that Spring can scan sub-packages and find out the other required components.

package com.test.spring.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

Below code snippet works as the controller package is under com.test.spring.boot package

package com.test.spring.boot.controller;

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

@RestController
public class HomeController {

    @RequestMapping("/")
    public String home(){
        return "Hello World!";
    }
}

Below code snippet does NOT Work as the controller package is NOT under com.test.spring.boot package

package com.test.controller;

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

@RestController
public class HomeController {

     @RequestMapping("/")
     public String home(){
         return "Hello World!";
     }
 }

From Spring Boot documentation:

Many Spring Boot developers always have their main class annotated with @Configuration, @EnableAutoConfiguration and @ComponentScan. Since these annotations are so frequently used together (especially if you follow the best practices above), Spring Boot provides a convenient @SpringBootApplication alternative.

The @SpringBootApplication annotation is equivalent to using @Configuration, @EnableAutoConfiguration and @ComponentScan with their default attributes

Somnath Musib
  • 3,548
  • 3
  • 34
  • 47
51

You can solve this by adding an ErrorController in your application. You can have the error controller return a view that you need.

Error Controller in my application looks like below:

import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Basic Controller which is called for unhandled errors
 */
@Controller
public class AppErrorController implements ErrorController{

    /**
     * Error Attributes in the Application
     */
    private ErrorAttributes errorAttributes;

    private final static String ERROR_PATH = "/error";

    /**
     * Controller for the Error Controller
     * @param errorAttributes
     */
    public AppErrorController(ErrorAttributes errorAttributes) {
        this.errorAttributes = errorAttributes;
    }

    /**
     * Supports the HTML Error View
     * @param request
     * @return
     */
    @RequestMapping(value = ERROR_PATH, produces = "text/html")
    public ModelAndView errorHtml(HttpServletRequest request) {
        return new ModelAndView("/errors/error", getErrorAttributes(request, false));
    }

    /**
     * Supports other formats like JSON, XML
     * @param request
     * @return
     */
    @RequestMapping(value = ERROR_PATH)
    @ResponseBody
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        Map<String, Object> body = getErrorAttributes(request, getTraceParameter(request));
        HttpStatus status = getStatus(request);
        return new ResponseEntity<Map<String, Object>>(body, status);
    }

    /**
     * Returns the path of the error page.
     *
     * @return the error path
     */
    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }


    private boolean getTraceParameter(HttpServletRequest request) {
        String parameter = request.getParameter("trace");
        if (parameter == null) {
            return false;
        }
        return !"false".equals(parameter.toLowerCase());
    }

    private Map<String, Object> getErrorAttributes(HttpServletRequest request,
                                                   boolean includeStackTrace) {
        RequestAttributes requestAttributes = new ServletRequestAttributes(request);
        return this.errorAttributes.getErrorAttributes(requestAttributes,
                includeStackTrace);
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request
                .getAttribute("javax.servlet.error.status_code");
        if (statusCode != null) {
            try {
                return HttpStatus.valueOf(statusCode);
            }
            catch (Exception ex) {
            }
        }
        return HttpStatus.INTERNAL_SERVER_ERROR;
    }
}

The above class is based on Springs BasicErrorController class.

You can instantiate the above ErrorController like this in a @Configuration file:

 @Autowired
 private ErrorAttributes errorAttributes;

 @Bean
 public AppErrorController appErrorController(){return new AppErrorController(errorAttributes);}

You can choose override the default ErrorAttributes by implementing ErrorAttributes. But in most cases the DefaultErrorAttributes should suffice.

axiopisty
  • 4,972
  • 8
  • 44
  • 73
owaism
  • 1,118
  • 1
  • 8
  • 21
30

In my case the controller class was annotated with @Controller. Changing that to @RestController resolved the problem. Basically @RestController is @Controller + @ResponseBody So either use @RestController , or @Controller with @ResponseBody annotation with each method.

Some useful notes here : https://www.genuitec.com/spring-frameworkrestcontroller-vs-controller/

Markus
  • 2,071
  • 4
  • 22
  • 44
mykey
  • 1,943
  • 19
  • 13
  • 2
    It works , but as per examples all over internet basic configuration should work with @Controller . Any body aware of this reason why only RestController working? – supernova Nov 16 '17 at 16:06
  • 1
    When annotating your class with `@RestController` it implicitly adds the `@ResponseBody` annotation, but if you're using the `@Controller` annotation, you must explicitly add this annotation yourself. – Robin Keskisarkka Feb 20 '19 at 14:08
  • This was my exact problem as well. – Justin Phillips Nov 24 '21 at 10:35
17

in my case it because of package position , meaning package of controller must be above main class package

if my main class package is package co.companyname.spring.tutorial; any controller package should package co.companyname.spring.tutorial.WHAT_EVER_HERE;

package co.companyname.spring.tutorial; // package for main class
@SpringBootApplication
public class FirstProjectApplication {

    public static void main(String[] args) {
        SpringApplication.run(FirstProjectApplication.class, args);
    }
}


package co.companyname.spring.tutorial.controllers; // package for controllers 

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

@RestController 
public class HelloController { 

@RequestMapping("/hello")  
public String hello() {   
 return "Hello, world"; 
 }}

after finish coding press boot dashboard

enter image description here

one last thing to make sure your controller is mapping or not just console you should see somehting smilliar

Mapped "{[/hello]}" onto public java.lang.String co.companyname.spring.tutorial.controllers.HelloController.hello()

happy coding

Mina Fawzy
  • 20,852
  • 17
  • 133
  • 156
12

Try adding the dependency.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Sree
  • 153
  • 1
  • 2
  • 4
    what does this actually do though? – Stealth Rabbi Feb 18 '17 at 21:14
  • I added this dependency, and it worked. Just like @StealthRabbi ... I'm also wondering what that actually does. – twindham Dec 01 '17 at 20:28
  • @StealthRabbi This adds a dependency to a templating framework called Thymeleaf, which is an alternative and the preferred approach to JSP. This answer is not a real answer imo, throwing around dependencies does not help anybody who is really interested in the core issue – Christian Aug 19 '19 at 09:43
  • thanks so much. because i create my index.html with thymeleaf and it take the error because its unknown for spring boot.thanks so muxh again :))) – norullah karimi Aug 03 '22 at 16:00
10

100% working add this class inside controller package

.

This happens when an explicit error page is not defined. To define an error page, create a mapping of /error with a view. e.g. the below code maps to a string value being returned in case of an error.

package com.rumango.controller;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class IndexController implements ErrorController{
    private final static String PATH = "/error";
    @Override
    @RequestMapping(PATH)
    @ResponseBody
    public String getErrorPath() {
        // TODO Auto-generated method stub
        return "No Mapping Found";
    }

}
prabhat kumar
  • 97
  • 1
  • 7
  • Can you add some explanation to your code? Why does it solve the question, which are the crucial parts? – Nico Haase Nov 12 '18 at 09:50
  • There is one specific thing to note in this answer relative to Spring Boot that caused me a bit of a headache at first. It is important to implement springframework's ErrorController interface. If you create a controller endpoint mapped to "/error" without doing this you will get an error telling you that method is already mapped. – mmaynar1 Dec 07 '18 at 03:56
9

By default spring boot will scan current package for bean definition. So if your current package where main class is defined and controller package is not same or controller package is not child package of your main app package it will not scan the controller. To solve this issue one can include list of packages for bean definition in main package

@SpringBootApplication(scanBasePackages = {"com.module.restapi1.controller"})

or create a hierarchy of package where child package is derived from main package

package com.module.restapi;
package com.module.restapi.controller
anand shukla
  • 666
  • 5
  • 14
  • One of the best answers here IMO, as it gives you a guidance on how to scan to provide the controller if you don't want to (or can't) rearrange the packages. Thanks! – Konrad Feb 11 '21 at 09:56
7

I am developing Spring Boot application for a few weeks.. And I was gettig same error like below;

Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. Thu Jan 18 14:12:11 AST 2018 There was an unexpected error (type=Not Found, status=404). No message available

When I get this error massage I realized my controller or rest controller class is not defined in my project. I mean our all controller packages aren't same package with main class which include @SpringBootApplication annotation.. I mean you need to add you controller package's name to @ComponentScan annotation to your main class which is includes @SpringBootApplication annotation. If you write codes of below your problem will be solving... Most important thing is you have to add your all controller's package to @ComponentScan annotation like I did in the below

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan({ "com.controller.package1, com.controller.package2, com.controller.package3, com.controller.packageN", "controller", "service" } // If our Controller class or Service class is not in the same packages we have //to add packages's name like this...directory(package) with main class
public class MainApp {
    public static void main(String[] args) {
        SpringApplication.run(MainApp.class, args);
    }
}

I hope this codes are going to help someone...

If you find another way to solve this error or you have some suggestions for me, please write to comments... thanks...

Semih Erkaraca
  • 146
  • 1
  • 6
7

In the main class, after the configuration "@SpringBootApplication", adding "@ComponentScan" without having any arguments, worked for me !!!

Main Class :

@SpringBootApplication
@ComponentScan
public class CommentStoreApplication {

    public static void main(String[] args) {
        SpringApplication.run(CommentStoreApplication.class, args);

    }
}

RestController Class :

@RestController
public class CommentStoreApp {

    @RequestMapping("/") 
    public String hello() {
        return "Hello World!";
    }
}

P.S: Don't miss to run mvn clean and mvn install commands, before launching the application

Harika
  • 71
  • 1
  • 1
6

I added this dependency and it solved my problem.

<dependency>
    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Pang
  • 9,564
  • 146
  • 81
  • 122
  • Here's my theory: If we 're using "@Controller", somehow Spring would require us to have a certain template engine. And in this case, Thymeleaf. Therefore, spring-boot-starter-thymeleaf is required. Whereas if we're using "@RestController", Spring Boot wouldn't require a template engine. And therefore, it works without Thymeleaf. – Yosi Pramajaya Feb 08 '19 at 23:49
5

You might be getting the error i.e.

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

This is because it is not scanning your Controller & Service classes which you have to specify in your main() class like this,

package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableAutoConfiguration
**@ComponentScan({"com.example.demo", "controller", "service"})**
public class SpringBootMvcExample1Application {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootMvcExample1Application.class, args);
    }
}

Note: Here, I have specified various classes like demo, controller and service to be scanned then only it will work properly.

Soren
  • 14,402
  • 4
  • 41
  • 67
4

Quite late to the party. As per spring official documentation "Spring Boot installs a whitelabel error page that you see in a browser client if you encounter a server error." https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-customize-the-whitelabel-error-page

  1. You can disable the feature by setting server.error.whitelabel.enabled=false in application.yml or application.properties file.

2.Recommended way is set your error page so that end user can understand. Under resources/templates folder create a error.html file and add dependency in pom.xml file

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

Spring will automatically choose the error.html page as the default error template. Note:- Don't forget to update maven project after adding dependency.

Joginder Malik
  • 455
  • 5
  • 12
  • No! You are assuming that everyone is using or wants to use thymeleaf. There are other template engines out there too. So this is not a good solution – TheRealChx101 Feb 09 '21 at 22:37
3

You have to organize the packages so that the package containing public static main(or where you wrote @SpringBootApplication), the father of all your other packages.

ppreetikaa
  • 1,149
  • 2
  • 15
  • 22
sakgeek
  • 31
  • 1
  • - com.mypackage +nameApplication.java - com.mypachage.model - com.mypachage.controller - com.mypachage.dao – sakgeek May 09 '19 at 10:17
3

I need to mention this way and give the reference to packages and it worked out. You may exclude @EnableAutoConfiguration this annotation but required for me to bypass any DB related depenencies.

@SpringBootApplication
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
@ComponentScan(basePackages = {"your package 1", "your package2"})

public class CommentStoreApplication {

    public static void main(String[] args) {
        SpringApplication.run(CommentStoreApplication.class, args);

    }
}
Suresh
  • 1,491
  • 2
  • 22
  • 27
2

The problem is that you are navigating to localhost:8080/ instead of localhost:8080/upload as prescribed in the guide. Spring Boot has a default error page used when you navigate to an undefined route to avoid giving away server specific details (which can be viewed as a security risk).

You're options are to either: visit the right page, add your own landing page, or override the white error page.

To simplify this particular situation, I updated the guide so that it uses / instead of /upload.

gregturn
  • 2,625
  • 3
  • 25
  • 40
2

I too got the same error and was able to resolve the error by adding the below dependency to my pom.xml.

<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
    <scope>provided</scope>
</dependency>

Reason is we are using JSP as the view. Default embedded servlet container for Spring Boot Starter Web is tomcat. To enable support for JSP’s, we would need to add a dependency on tomcat-embed-jasper.

In my case I was returning a JSP as view from controller. Hope this answer helps someone who are struggling with same issue.

Sujana
  • 331
  • 1
  • 3
  • 12
2

I know it's not exactly answer to question, but this question is first which appears on Google :)

Problem ("This application has no explicit mapping for /error") appears when trying to access Swagger UI.

In my case problems were caused by @RestController("/endpoint"), which isn't handled properly by swagger.

So, this resulted in errors:

@RestController("/endpoint")
public class EndpointController {

And this was fine

@RestController
@RequestMapping("/endpoint")
public class EndpointController {
Elas
  • 212
  • 2
  • 16
2

this can happen if you forget the @RestController annotation on top of your controller class import import org.springframework.web.bind.annotation.RestController;

and add the annotation as below

refer the simple example below

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


@RestController
public class HelloController {
@RequestMapping("/")
    public String index() {
        return "Greetings from Spring Boot!";
    }

}
2

Ensure that you have jasper and jstl in the list of dependencies:

<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
</dependency>

Here is a working starter project - https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-web-jsp

Author: Biju Kunjummen

Yersin
  • 1,639
  • 1
  • 9
  • 6
2

Same problem I have faced recently. I have solved it by just getter and setter method spelling correction!

Abdus Salam
  • 83
  • 1
  • 11
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Neeraj Nov 19 '21 at 07:15
1

The tutorial expects you to have the Thymeleaf template engine in classpath. I ran into the same problem and finally figured this out. I'll reach out to the tutorial author to include that info.

The easiest way if you've followed the tutorial is to add the dependency to your pom.xml in the project root folder. Next time you run your app Spring will detect Thymeleaf and use the uploadform template

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

For the full example see their Github repository.

toomasr
  • 4,731
  • 2
  • 33
  • 36
  • If you follow the tutorial, you will be directed to put that dependency into your build file, gradle or maven. The "what you'll need" section is what you'll need before embarking on the tutorial. – gregturn Apr 25 '16 at 15:32
1

Change @Controller to @RestController in your controller class and everything should go smoothly.

Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
supernova
  • 3,111
  • 4
  • 33
  • 30
1

I was facing the same problem, using gradle and it got solved on adding following dependencies-

compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test')
compile('org.apache.tomcat.embed:tomcat-embed-jasper')

earlier I was missing the last one causing the same error.

  • I had same problem, and i was missing tomcat-embed-jasper plugin in pom.xml. And tomcat-embed-jasper is important for rendering jsp. – rinilnath Aug 13 '20 at 16:13
  • https://www.boraji.com/spring-boot-creating-web-application-using-spring-mvc, this lead to find that tomcat-embed-jasper was missing – rinilnath Aug 13 '20 at 16:15
1

I was facing this issue and then later realized that I was missing the @Configuration annotation in the MvcConfig class which basically does the mapping for ViewControllers and setViewNames.

Here is the content of the file :

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
**@Configuration**
public class MvcConfig implements WebMvcConfigurer{
   public void addViewControllers(ViewControllerRegistry registry)
   {
      registry.addViewController("/").setViewName("login");
      registry.addViewController("/login").setViewName("login");
      registry.addViewController("/dashboard").setViewName("dashboard");
   }
}

Hope this helps somebody!!

Unheilig
  • 16,196
  • 193
  • 68
  • 98
1

Make sure @RestController annotation is added right after the @SpringBootApplication. RestController annotation tells Spring that this code describes an endpoint that should be made available over the web.

1

You may have not included thymleaf in your pom.xml file.

alphcoder
  • 71
  • 9
1

I had a similar problem. And I had Main.class on the top of all the controllers, yet I was facing this issue. All I needed to do is to create a separate swagger configuration file and initialize docket bean in it.

note: location of this file should be either in the same package of the Main.class file or in a package inside that main package.

SwaggerCongiguration.java file

package com.example.springDataJPAUsingGradle;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2).select().build();
    }
}

I also had to add @RequestMapping("/api") in my controller.java. Here's how:

package com.example.springDataJPAUsingGradle.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.springDataJPAUsingGradle.service.StudentService;

@RestController
@RequestMapping("/api")
public class StudentController {

    @Autowired(required = true)
    @GetMapping("/home")
    public String home() {
        return "Welcome to home page";
    }
}

Then after hitting the url: http://localhost:9090/your-app-root/swagger-ui/ swagger UI will be visible. For eg, in my case the url is: http://localhost:9090/students/swagger-ui/

1

I faced this issue while I'm learning spring HATEOAS. I checked all the answers that has given above but the issue is not solved. Finally, i pasted my controller class in "main application.java" package and it worked for me.[![You can see in picture i added my controller class and main class in one package. you can also add "model class, main class and controller class" in same package that also worked for me. In below picture i added controller and main class in the same package.

Project Structure

Lokeshwar
  • 171
  • 1
  • 4
1

this error occured for me,

because of controller file(in restfortest package) not in Application.java (SpbdemoApplication) file directory.

enter image description here

to solove this problem,

  1. you can put restfortest package as sub package like rest package which is show in the bellow diagram.

2.other wise you can edit application.java file as bellow diagram.

enter image description here

this error occur because @SpringBootApplication tells Spring to look for Spring components and configure the application to run. spring cannot see the controller class if it not place with in the same package(in here com.pj.lerningcurve.spddemo)

pamal Sahan
  • 451
  • 3
  • 7
1

Add devtools dependency, this will enable H2ConsoleAutoConfiguration.

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>

In logs you can see following line:

o.s.b.a.h2.H2ConsoleAutoConfiguration    : H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:my-app'

Then try access from

http://localhost:8080/h2-console/
Priya
  • 143
  • 4
  • 17
0

All I have done to solve this kind of problem is to mention anotation @Configuration in MVCConfig Class.

Like this one :

package com.example;

/**
 * Created by sartika.s.hasibuan on 1/10/2017.
 */
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@EnableAutoConfiguration
@Configuration
@ComponentScan
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/home").setViewName("home");
        registry.addViewController("/").setViewName("home");
        registry.addViewController("/hello").setViewName("hello");
        registry.addViewController("/login").setViewName("login");
    }

}
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
0

I had a similar mistake, I use the spring boot and velocity, my solution is to check the file application.properties, spring.velocity.toolbox-config-location found that this property is wrong

叶为正
  • 81
  • 1
  • 2
0

In my case, this problem occurs when running the SpringApplication from within IntelliJ after running it first with maven.

To solve the problem, I run first mvn clean. Then I run SpringApplication from within IntelliJ.

Mert Nuhoglu
  • 9,695
  • 16
  • 79
  • 117
0

Make sure your Main.class should be on top of your controllers. In case of the following example:

Main.class containing:

@SpringBootApplication
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }
}

EmployeeController.class containing:

@RestController
public class EmployeeController {
    @InitBinder
    public void setAllowedFields(WebDataBinder dataBinder) {
        dataBinder.setDisallowedFields("id");
    }

    @RequestMapping(value = "/employee/save", method = RequestMethod.GET)
    public String save(){
        Employee newEmp = new Employee();
        newEmp.setAge(25);
        newEmp.setFirstName("Pikachu");
        newEmp.setId(100);
        return "Name: " + newEmp.getFirstName() + ", Age: " + newEmp.getAge() + ", Id = " + newEmp.getId();
    }
}

If your main class is in the root folder, just like this path: {projectname}/src/main/java/main then make sure your controllers below your Main class. For example {projectname}/src/main/java/main/controllers.

A. Gh
  • 631
  • 9
  • 24
0

In your java file ( say: Viper.java )having main class add: "@RestController" and @RequestMapping("/")

@SpringBootApplication
@RestController
public class Viper {

  @RequestMapping("/")

   public String home(){
          return "This is what i was looking for";                      
     }

public static void main( String[] args){

   SpringApplication.run(Viper.class , args);
}

}
Mayur Chavan
  • 833
  • 8
  • 14
0

Do check if you have marked the controller class with @RestController annotation.

Karthik Kamath
  • 101
  • 1
  • 4
0

it means you are trying to access the page which is not there. suppose your jsp file is at /webapp/home.jsp now if you use @RequestMapping("/home") on your code and return "home.jsp"; then you will get this error if you try to access using localhost:port/ but if you try localhost:port/home there will be no error you can fix this by checking your @RequestMapping("/") here put /mapping_path of the page you are trying to access. and you can also try adding a dependency of tomcat jaspher from maven dependency

Jasbin karki
  • 127
  • 2
  • 8
0

In tutorial, the controller is annotated with @Controller which is used to to create a Map of model object and find a view but @RestController simply return the object and object data is directly written into HTTP response as JSON or XML. If you want to view response, use @RestController or use @ResponseBody as well with @Controller.

@Controller
@ResponseBody

Read more: https://javarevisited.blogspot.com/2017/08/difference-between-restcontroller-and-controller-annotations-spring-mvc-rest.html#ixzz5WtrMSJHJ

batflix
  • 196
  • 5
0

Using Spring Boot and application.properties file I had to change a structure of my project. JSP files should to be in this location: \src\main\resources\META-INF\resources\WEB-INF\jsp. After this change my project works. I've found solution here: https://www.logicbig.com/tutorials/spring-framework/spring-boot/boot-serve-dynamic.html

Tom
  • 1
  • 1
0

Please make sure You are not placing your View or JSP or HTML in WEB-INF or META-INF

Mention this details carefully:

spring.mvc.view.prefix
spring.mvc.view.suffix
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
Sid
  • 1
  • 1
0

I've been getting a similar error while trying out a Spring Boot sample application with Thymeleaf, tried all the different solutions provided unfortunately didn't worked.

My error was that the returned string from Controller method was not having a respective view html.

It might be you have missed or there could be some typo in the file name. As shown in the example inside the controller

@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {

    model.addAttribute("files", storageService.loadAll().map(
            path -> MvcUriComponentsBuilder.fromMethodName(FileUploadController.class,
                    "serveFile", path.getFileName().toString()).build().toString())
            .collect(Collectors.toList()));

    return "uploadForm";
}

the return String should be match the html file name at

src/main/resources/templates/uploadForm.html

Thymeleaf will look for the file with same name as in the return type and display the view. You can try with any html file and give the file name in return statement and it will populate the respective view.

Vishal Vijayan
  • 308
  • 1
  • 4
  • 13
0

It sometime happen when your spring app not able to find the spring component and it's not get initialised in sprint container you can add component using @ComponentScan along with your @SpringBootApplication like below example

@SpringBootApplication
@ComponentScan({"model", "service"})
class MovreviewApplication {

                public static void main(String[] args) {
        SpringApplication.run(MovreviewApplication.class, args);

}

in above example model and service are the packages in my app.

Pavan T
  • 716
  • 9
  • 12
0

If you have annotated the interface with requestMapping, make sure you also annotate the Class which implements the interface with @Component.

  • Welcome to stackoverflow. There are already a lot of answers on this question - please expand your answer so it is clear what new details you are providing. – Simon.S.A. Apr 03 '19 at 22:39
0

If all configurations are done correctly (as described in first two-three answers of this question) and still you are getting "Whitelabel Error Page" This application has no explicit mapping for /error, then this solution may help you

Sometimes beside configuration, issue can also be from your code side as well. You might have missed something very basic.
To identify issue you need to check the trace ,for that follow below steps

Open terminal.
1)cd project_location, to get the project location.
e.g. eclipse->project(right click)->properties->resource(tab)->copy path against location field.
2)then run script ./mvnw spring-boot:run

then go to http://localhost:8080/ , http://localhost:8080/xyz whichever url you expecting data.As soon as you hit the link ,trace would have got updated .

I was getting error like
2020-05-23 06:52:42.405 ERROR 3512 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: No default constructor for entity: : com.ibsplc.com.payroll.model.Employee; nested exception is org.hibernate.InstantiationException: No default constructor for entity: : com.ibsplc.com.payroll.model.Employee] with root cause

So, i added a default constructor for Employee model. run project as maven-build then then run script ./mvnw spring-boot:run,
it worked for me

Vivek Singh
  • 959
  • 7
  • 10
0

Main class need to be outside of your app packages tree structure. For example: example

0

I was getting this error while using the Keycloak authentication for my Web Application. I could not find the answer with respect to the Keycloak so thought of posting as it can help someone else.

I got this error

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

because I was using the property keycloak.bearer-only=true within the application.properties file in the resource of Java application. This will ensure that login cannot take place from the browser so we need to use the token. I removed this commant and it worked within the browser.

If you are using the command keycloak.bearer-only=true and trying to access the application using the browser then you may run into the same issue.

BATMAN_2008
  • 2,788
  • 3
  • 31
  • 98
0

In my case, I was facing the issue because my server was already running from the execution of UploadingFilesApplication.java(file with the @SpringBootApplication annotation).

I fixed this issue by simply re-running the server by executing the FileUploadController.java(file with the @Controller annotation).

KP Singh
  • 348
  • 3
  • 11
0

In addition to all the cool answers above. Just check request mapping is available for the method. Here is a sample code.

@RestController
@RequestMapping("api/v1/data")
public class SampleController {

  private final SampleService sampleService;

  @Autowired
  public SampleController(SampleService sampleService) {
    this.sampleService= sampleService;
  }

  @GetMapping
  public List<SimpleData> getData() {
    return sampleService.getData();
  }
}

You may tend to forget to add @GetMapping to the getData method.

dhanushkac
  • 520
  • 2
  • 8
  • 25
0

Late in the queue, but this is what helped me.

If your return type for the controller is a custom object then, defining the getter, setters for that will solve the problem assuming we have other annotations in place. eg.

@SpringBootApplication
public class MainApplication {
    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }
}

Controller:

@RestController
public class HelloController {

    @GetMapping("/")
    public Response index() {
        return new Response( "Greetings from Spring Boot!" );
    }

}

Response:

@Getter
@Setter
public class Response{
    String testResponse;

    public Response(String testResponse) {
        this.testResponse = testResponse;
    }
}
saiba sheikh
  • 126
  • 1
  • 2
0

One of the reasons it may not be working its simply because you didnt add the root in the controller. I was following Intellij idea and they said if you dont, it will automatically set to root but in my case it didnt. Im using the latest version of everything.

This will work.

package com.sprindemo.demohelloword;

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

@RestController
public class HelloWorldController {

    @RequestMapping("/") //  <<<<<<<<<<<
    public String helloWord() {
        return "Hello world from Spring Boot";
    }
}

This wont, root missing

package com.sprindemo.demohelloword;

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

@RestController
public class HelloWorldController {

    @RequestMapping //  <<<<<<<<<<<
    public String helloWord() {
        return "Hello world from Spring Boot";
    }
}

Olivia22
  • 131
  • 7
0

I was getting a HTTP 404, but slightly different from this on the post...

enter image description here

Please check out my fix for this... Hopefully it will help. If the other answers provided here did not work.

https://stackoverflow.com/a/75688580/13797046

Wesley Masunika
  • 153
  • 2
  • 10
0

Sometimes wrong comments in HTML like // (double slash ) can have also this message. Start to check line by line.

0

Check your controller if you add @RequestMapping("/api") under @RestController

-1

Do maven clean or clean verify and try to run it.The instances has to be cleaned before deploying the another project. It worked for me. I tried it for 2 days to understand this.

raju
  • 1
-1

I had tried many ways to fix this problem too, was like, I changed dependency <artifactId>spring-boot-starter-web</artifactId> to <artifactId>spring-boot-starter-thymeleaf</artifactId>, or I replaced annotation @RestController to @Controller but It was the same error. Finally I found a solution by adding a single line of annotation @ComponentScan(basePackages = {"hello"}) on the top of Application class and it works perfectly.

@ComponentScan(basePackages = {"hello"})
public class Application {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(App.class, args);
    }
}

I hope it helps you guys too.

Dimang Chou
  • 595
  • 6
  • 9