error with spring template parsing - spring

I started from new Spring Boot project included Web, Devtools, JPA and Mustache modules.
I have simple controller:
package com.example.elephant;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.HashMap;
import java.util.Map;
#Controller
public class IndexController {
#GetMapping("/")
public ModelAndView index() {
Map<String, String> model = new HashMap<>();
model.put("name", "Spring");
System.out.println("11111111111111111111");
return new ModelAndView("index",model);
}
}
and simple template /resources/templates/index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{name}}
</body>
</html>
application class:
package com.example.elephant;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class ElephantApplication {
public static void main(String[] args) {
SpringApplication.run(ElephantApplication.class, args);
}
}
Application log:
2018-04-24 15:09:11.333 INFO 7402 --- [ restartedMain] c.example.elephant.ElephantApplication : Started ElephantApplication in 5.906 seconds (JVM running for 6.477)
2018-04-24 15:09:29.231 INFO 7402 --- [nio-8036-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2018-04-24 15:09:29.232 INFO 7402 --- [nio-8036-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2018-04-24 15:09:29.252 INFO 7402 --- [nio-8036-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 19 ms
11111111111111111111
All ok, but I have 404 error. It seems I have a problem with template parsing but I can't understand why.
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Apr 24 15:09:29 MSK 2018
There was an unexpected error (type=Not Found, status=404).
No message available

You have to rename your template file to:
index.mustache
The file ending has changed with Spring Boot 2 from html to mustache:
https://github.com/spring-projects/spring-boot/issues/8997

Related

Springboot : failed while scanning for beans

I am trying to understand a concept in springboot.
I have project structure as mentioned below. There are two packages and I have one class in each package.
src/main/java
> com.emerald.paymentengine
ApplicationRun.java
> com.emerald.paymentengine.config
DataSourceDbConfig.java
When I am trying to run the ApplicationRun.java following above structure, I am getting below error :
Error:
2020-08-19 01:33:08.673 INFO 30128 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-08-19 01:33:08.673 INFO 30128 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.37]
2020-08-19 01:33:08.749 INFO 30128 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-08-19 01:33:08.750 INFO 30128 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 657 ms
2020-08-19 01:33:08.779 WARN 30128 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'applicationRun': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.emerlad.paymentengine.config.DataSourceDbConfig' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
2020-08-19 01:33:08.781 INFO 30128 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2020-08-19 01:33:08.791 INFO 30128 --- [ restartedMain] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-08-19 01:33:08.883 ERROR 30128 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in com.emerald.paymentengine.ApplicationRun required a bean of type 'com.emerlad.paymentengine.config.DataSourceDbConfig' that could not be found.
Action:
Consider defining a bean of type 'com.emerlad.paymentengine.config.DataSourceDbConfig' in your configuration.
But when I moved DataSourceDbConfig.java in the same package as mentioned below, it's running and I am getting below output :
src/main/java
> com.emerald.paymentengine
ApplicationRun.java
DataSourceDbConfig.java
Output :
2020-08-19 01:37:24.726 INFO 34364 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-08-19 01:37:24.726 INFO 34364 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.37]
2020-08-19 01:37:24.810 INFO 34364 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-08-19 01:37:24.810 INFO 34364 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 722 ms
2020-08-19 01:37:24.849 INFO 34364 --- [ restartedMain] f.a.AutowiredAnnotationBeanPostProcessor : Autowired annotation is not supported on static fields: static com.emerald.paymentengine.DataSourceDbConfig com.emerald.paymentengine.ApplicationRun.dbConfig
Connection established !!
2020-08-19 01:37:24.981 INFO 34364 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-08-19 01:37:25.116 INFO 34364 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2020-08-19 01:37:25.140 INFO 34364 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8082 (http) with context path ''
2020-08-19 01:37:25.148 INFO 34364 --- [ restartedMain] c.emerald.paymentengine.ApplicationRun : Started ApplicationRun in 1.335 seconds (JVM running for 2.406)
I was thinking #SpringBootApplication will automatically scan the main and subpackages and will be able to pick the required bean. How can I make it work by placing Config.java file in different package as mentioned in the very first scenario?
Code :
ApplicationRun.java
package com.emerald.paymentengine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class ApplicationRun {
#Autowired
static
DataSourceDbConfig dbConfig;
public ApplicationRun(DataSourceDbConfig dbConfig){
ApplicationRun.dbConfig = dbConfig ;
}
public static void main(String[] args) {
SpringApplication.run(ApplicationRun.class, args);
dbConfig.dataSource();
}
}
DataSourceDbConfig.java
package com.emerlad.paymentengine.config;;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import oracle.jdbc.pool.OracleDataSource;
import java.sql.SQLException;
import javax.sql.DataSource;
#Component
#Configuration
#ConfigurationProperties("spring.datasource")
public class DataSourceDbConfig {
#Value("${spring.datasource.url}")
private String dbUrl;
#Value("${spring.datasource.username}")
private String dbUser;
#Value("${spring.datasource.secure}")
private String dbPasswrd;
#Bean
public DataSource dataSource() {
OracleDataSource dataSource = null;
try {
dataSource = new OracleDataSource();
dataSource.setUser(dbUser);
dataSource.setPassword(dbPasswrd);
dataSource.setURL(dbUrl);
System.out.println("Connection established !!");
} catch (SQLException e) {
System.out.println("An issue occured while establishing connection !!");
e.printStackTrace();
}
return dataSource;
}
}
I'll be honest, I do not understand what it is that you want to accomplish, but this is how to get the DataSource bean in your main method:
ApplicationRun.java:
package com.emerald.paymentengine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.emerlad.paymentengine.config.DataSourceDbConfig;
import org.springframework.context.annotation.Import;
import javax.sql.DataSource;
#SpringBootApplication
#Import(DataSourceDbConfig.class)
public class ApplicationRun {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(ApplicationRun.class, args);
DataSource dataSource = context.getBean(DataSource.class)
}
}
DataSourceDbConfig.java:
package com.emerlad.paymentengine.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import oracle.jdbc.pool.OracleDataSource;
import java.sql.SQLException;
import javax.sql.DataSource;
#Configuration
#ConfigurationProperties("spring.datasource")
public class DataSourceDbConfig {
#Value("${spring.datasource.url}")
private String dbUrl;
#Value("${spring.datasource.username}")
private String dbUser;
#Value("${spring.datasource.secure}")
private String dbPasswrd;
#Bean
public DataSource dataSource() {
OracleDataSource dataSource = null;
try {
dataSource = new OracleDataSource();
dataSource.setUser(dbUser);
dataSource.setPassword(dbPasswrd);
dataSource.setURL(dbUrl);
System.out.println("Connection established !!");
} catch (SQLException e) {
System.out.println("An issue occured while establishing connection !!");
e.printStackTrace();
}
return dataSource;
}
}
class DataSourceDbConfig - using #Configuration includes #Component, so you can get rid of it
class ApplicationRun - I would keep it simple and remove the DataSourceDbConfig
#SpringBootApplication
public class ApplicationRun {
public static void main(String[] args) {
ApplicationContext appContext = SpringApplication.run(ApplicationRun.class, args);
// Getting datasource from application context.
DataSource dataSource = appContext.getBean(DataSource.class);
}
}

Using different packages for Controllers when using in Spring Boot

I am new in Spring boot.I trying to access the controller url but i didn't get any response from them.
We are followed spring boot project structure as per document.
I have used componentscan annotation and added scanBasePackageClasses in SpringBootApplication annotation.But still same.
HomeController :-
package com.main.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class HomeController {
#RequestMapping(value="/home",method=RequestMethod.GET)
public String home() {
System.out.println("home");
return "home";
}
}
GAppsApplication.java:-
package com.main;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import com.main.controllers.HomeController;
#ComponentScan({"com.main.controllers"})
#SpringBootApplication(scanBasePackageClasses={HomeController.class})
public class GAppsApplication {
public static void main(String[] args) {
SpringApplication.run(GAppsApplication.class, args);
}
}
For your reference i shared below logs
logs:-
2018-08-28 08:26:16.404 INFO 8172 --- [ restartedMain] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMatcher#1, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#58b9d6, org.springframework.security.web.context.SecurityContextPersistenceFilter#525747, org.springframework.security.web.header.HeaderWriterFilter#1638752, org.springframework.security.web.csrf.CsrfFilter#324c61, org.springframework.security.web.authentication.logout.LogoutFilter#14a6743, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#12d6ce4, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter#1837d01, org.springframework.security.web.authentication.www.BasicAuthenticationFilter#eda2d2, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#4a5109, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#4bb38c, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#12205be, org.springframework.security.web.session.SessionManagementFilter#2e4343, org.springframework.security.web.access.ExceptionTranslationFilter#1a81a58, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#12e7437]
2018-08-28 08:26:16.558 INFO 8172 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2018-08-28 08:26:16.592 INFO 8172 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-08-28 08:26:16.594 INFO 8172 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'dataSource' has been autodetected for JMX exposure
2018-08-28 08:26:16.600 INFO 8172 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Located MBean 'dataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=dataSource,type=HikariDataSource]
2018-08-28 08:26:16.638 INFO 8172 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2018-08-28 08:26:16.642 INFO 8172 --- [ restartedMain] c.main.GAppsApplication : Started GAppsApplication in 5.153 seconds (JVM running for 5.734)
2018-08-28 08:27:11.961 INFO 8172 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2018-08-28 08:27:11.961 INFO 8172 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2018-08-28 08:27:11.980 INFO 8172 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 19 ms
Change your controller to like below :
#RestController
#RequestMapping("/home")
public class HomeController {
#GetMapping
public String home() {
System.out.println("home");
return "home";
}
}
As your base package is com.main, so any package within com.main will automatically be scanned.
You don't need to put any special annotation to scan.

Error when run: http://localhost:8080

Current I have 1 bug when I run 1 project of Spring
1- Create class common: BlogMvcApplication.java
package blog;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class BlogMvcApplication {
public static void main(String[] args) {
SpringApplication.run(BlogMvcApplication.class, args);
}
}
2- Create class control: HomeController.java
package blog.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class HomeController {
#RequestMapping("/")
public String index() {
return "index";
}
}
3- view: index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Blog</title>
</head>
<body>
<h1>Welcome to Spring MVC</h1>
Now is: <b th:text="${execInfo.now.time}"></b>
</body>
</html>
Error when access http://localhost:8080 is :
2017-03-02 00:55:41.931 ERROR 1068 --- [nio-8080-exec-1] org.thymeleaf.TemplateEngine : [THYMELEAF][http-nio-8080-exec-1] Exception processing template "index": Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers
2017-03-02 00:55:41.958 ERROR 1068 --- [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.thymeleaf.exceptions.TemplateInputException: Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers] with root cause
org.thymeleaf.exceptions.TemplateInputException: Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers
at org.thymeleaf.TemplateRepository.getTemplate(TemplateRepository.java:246) ~[thymeleaf-2.1.5.RELEASE.jar:2.1.5.RELEASE]
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1104) ~[thymeleaf-2.1.5.RELEASE.jar:2.1.5.RELEASE]
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1060) ~[thymeleaf-2.1.5.RELEASE.jar:2.1.5.RELEASE]
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1011) ~[thymeleaf-2.1.5.RELEASE.jar:2.1.5.RELEASE]
I think error because duplicate port 8080 when start
Please helpme fix bug this
Thanks!
I don't think this error cause by duplication on port. If it is the issue then you cannot start your application and will see message like this: ".... port 8080 failed to start".
It seen like your index.html cannot be found at default location:/src/main/resources/templates/index.html when thymeleaf engine try to parse your requested template.
Hope it helps.

Home page not displayed in Spring Boot

I am getting below error when developing first web app in STS in Spring Boot (v1.2.3.RELEASE) while opening this url (http://localhost:8080/riyan/):
Error:
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Fri Jun 05 23:08:55 PKT 2015
There was an unexpected error (type=Not Found, status=404).
No message available
Application.properties
logging.config = ${app.root.dir}/config/logback.xml
spring.view.prefix = /WEB-INF/views/
spring.view.suffix = .jsp
spring.datasource.url=jdbc:hsqldb:file:${app.root.dir}/data/accounts;crypt_key=901a6105813eb65326bf35790a965432;crypt_type=blowfish;hsqldb.write_delay=false;create=false;sql.syntax_ora=true
spring.datasource.username=accounts
spring.datasource.password=accounts
spring.jpa.show-sql=false
spring.jpa.hibernate.ddl-auto=none
spring.datasource-internal.jpa.database-platform=org.hibernate.dialect.HSQLDialect
HomeController.java
package com.riyan.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class HomeController {
#RequestMapping("/")
public String getHomePage() {
return "login";
}
}
JSP:
login.jsp is present at WEB-INF->views->login.jsp
Followings are contents from pivotal server console:
Console Output:
23:08:47.239 [localhost-startStop-1] INFO org.apache.tiles.access.TilesAccess - Publishing TilesContext for context: org.springframework.web.servlet.view.tiles3.SpringWildcardServletTilesApplicationContext
23:08:47.989 [localhost-startStop-1] INFO o.s.w.s.m.m.a.RequestMappingHandlerAdapter - Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#5596ab: startup date [Fri Jun 05 23:08:32 PKT 2015]; root of context hierarchy
23:08:48.333 [localhost-startStop-1] INFO o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped "{[/error],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
23:08:48.333 [localhost-startStop-1] INFO o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped "{[/error],methods=[],params=[],headers=[],consumes=[],produces=[text/html],custom=[]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest)
23:08:48.427 [localhost-startStop-1] INFO o.s.w.s.h.SimpleUrlHandlerMapping - Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
23:08:48.427 [localhost-startStop-1] INFO o.s.w.s.h.SimpleUrlHandlerMapping - Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
23:08:48.614 [localhost-startStop-1] INFO o.s.w.s.h.SimpleUrlHandlerMapping - Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
Please let me know if anything further is required.
I don't see anything in your config that is setting the server context to "/riyan". You should add this to your application.properties
server.contextPath=/riyan
Otherwise you will probably find your actual login.jps is at
http://localhost:8080/

Spring boot can't mapp to the links in HTML

I am using Spring boot starter project with maving pluging,
spring boot can't know the links in my HTML templates.
this is my controller :
#Controller
#EnableAutoConfiguration
#ComponentScan
public class Demoproject2Application {
#RequestMapping("/")
public String home() {
return "/html/Authentification";
}
}
and this is the Authentification.HTML:
<!DOCTYPE html>
<html>
<head>
<title>Authentification</title>
<link rel="stylesheet" type="text/css" href="css/style2.css" />
and this is the error :
2015-02-19 14:29:58.749 INFO 5136 --- [nio-8090-exec-1] o.a.c.c.C.[Tomcat]. [localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2015-02-19 14:29:58.749 INFO 5136 --- [nio-8090-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2015-02-19 14:29:58.774 INFO 5136 --- [nio-8090-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 25 ms
2015-02-19 14:29:59.086 WARN 5136 --- [nio-8090-exec-2] o.s.web.servlet.PageNotFound : No mapping found for HTTP request with URI [/css/style2.css] in DispatcherServlet with name 'dispatcherServlet'
2015-02-19 14:30:00.813 WARN 5136 --- [nio-8090-exec-4]o.s.web.servlet.PageNotFound
here is a snapshot of the hierarchy of my project :
https://fbcdn-sphotos-f-a.akamaihd.net/hphotos-ak-xfp1/v/t1.0-9/11011221_811266045595770_3095529215585152558_n.jpg?oh=a51a1196651bd62c81a76679869c1bdd&oe=558FD62B&gda=1431221666_e2d5202a80db81801ed9903c48014130
If you didn't changed any defaults it should be served when you put it into src/main/resources/static/css/style2.css. Please see official documentation.

Resources