Use thymeleaf template of another project - maven

There seems to be problem if using thymeleaf for multiple projects.
Let's say I have a spring application in project 2 & the controller in project 1. With proper #ComponentScan defined, the application able to display the view/html in my template folder. But once I added the thymeleaf-layout-dialect maven dependency, it failed with "There was an unexpected error (type=Not Found, status=404)." error.
My projects:
The prj1 pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>macrohard.org</groupId>
<artifactId>prj1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>nz.net.ultraq.thymeleaf</groupId>
<artifactId>thymeleaf-layout-dialect</artifactId>
</dependency>
</dependencies>
</project>
The prj2 pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>macrohard.org</groupId>
<artifactId>prj2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>macrohard.org</groupId>
<artifactId>prj1</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
The hello-world.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>HW</title>
</head>
<body>
Hello World!!
</body>
</html>
The App2 in prj2:
package prj2;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
#ComponentScan(basePackages = { "prj1"} )
public class App2 {
public static void main(String[] args) {
SpringApplication.run(App2.class, args);
}
}
The Controller1 in prj1
package prj1.web;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
#RestController
#RequestMapping(value="/api")
public class Controller1 {
// this can be run by App2 & App1
#GetMapping(value="/hello")
public String hello() {
return "hello world";
}
// this can be run by App1 only
#GetMapping(value="/hello2")
public ModelAndView hello2() {
ModelAndView mav = new ModelAndView();
mav.setViewName("hello-world");
return mav;
}
}
As in Controller1, The "api/hello" can be requested successfully because it doesn't involve the template. But for the "api/hello2" request, it unable to render the hello-world.html. Here are the error stacks:
2019-07-02 22:21:28.758 INFO 19680 --- [ main] prj2.App2 : Started App2 in 1.89 seconds (JVM running for 2.454)
2019-07-02 22:21:51.807 INFO 19680 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-07-02 22:21:51.807 INFO 19680 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2019-07-02 22:21:51.807 TRACE 19680 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Detected org.springframework.web.multipart.support.StandardServletMultipartResolver#2ded92
2019-07-02 22:21:51.810 TRACE 19680 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : No LocaleResolver 'localeResolver': using default [AcceptHeaderLocaleResolver]
2019-07-02 22:21:51.811 TRACE 19680 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : No ThemeResolver 'themeResolver': using default [FixedThemeResolver]
2019-07-02 22:21:51.814 TRACE 19680 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : No RequestToViewNameTranslator 'viewNameTranslator': using default [DefaultRequestToViewNameTranslator]
2019-07-02 22:21:51.817 TRACE 19680 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : No FlashMapManager 'flashMapManager': using default [SessionFlashMapManager]
2019-07-02 22:21:51.817 DEBUG 19680 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : enableLoggingRequestDetails='false': request parameters and headers will be masked to prevent unsafe logging of potentially sensitive data
2019-07-02 22:21:51.817 INFO 19680 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 10 ms
2019-07-02 22:21:51.829 TRACE 19680 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : GET "/api/hello2", parameters={}, headers={masked} in DispatcherServlet 'dispatcherServlet'
2019-07-02 22:21:51.834 TRACE 19680 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to public org.springframework.web.servlet.ModelAndView prj1.web.Controller1.hello2()
2019-07-02 22:21:51.843 TRACE 19680 --- [nio-8080-exec-1] .w.s.m.m.a.ServletInvocableHandlerMethod : Arguments: []
2019-07-02 22:21:51.851 DEBUG 19680 --- [nio-8080-exec-1] o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, application/xhtml+xml, image/webp, image/apng, application/signed-exchange;v=b3, application/xml;q=0.9, */*;q=0.8]
2019-07-02 22:21:51.851 TRACE 19680 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Rendering view [org.springframework.web.servlet.view.InternalResourceView: name 'hello-world'; URL [hello-world]]
2019-07-02 22:21:51.851 DEBUG 19680 --- [nio-8080-exec-1] o.s.w.servlet.view.InternalResourceView : View name 'hello-world', model {}
2019-07-02 22:21:51.853 DEBUG 19680 --- [nio-8080-exec-1] o.s.w.servlet.view.InternalResourceView : Forwarding to [hello-world]
2019-07-02 22:21:51.857 TRACE 19680 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : "FORWARD" dispatch for GET "/api/hello-world", parameters={}, headers={masked} in DispatcherServlet 'dispatcherServlet'
2019-07-02 22:21:51.860 TRACE 19680 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to HandlerExecutionChain with [ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]] and 3 interceptors
2019-07-02 22:21:51.862 DEBUG 19680 --- [nio-8080-exec-1] o.s.w.s.r.ResourceHttpRequestHandler : Resource not found
2019-07-02 22:21:51.862 TRACE 19680 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : No view rendering, null ModelAndView returned.
2019-07-02 22:21:51.862 DEBUG 19680 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Exiting from "FORWARD" dispatch, status 404, headers={}
2019-07-02 22:21:51.864 DEBUG 19680 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed 404 NOT_FOUND, headers={}
2019-07-02 22:21:51.865 TRACE 19680 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : "ERROR" dispatch for GET "/error", parameters={}, headers={masked} in DispatcherServlet 'dispatcherServlet'
2019-07-02 22:21:51.865 TRACE 19680 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : 2 matching mappings: [{ /error, produces [text/html]}, { /error}]
2019-07-02 22:21:51.866 TRACE 19680 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2019-07-02 22:21:51.875 TRACE 19680 --- [nio-8080-exec-1] .w.s.m.m.a.ServletInvocableHandlerMethod : Arguments: [org.apache.catalina.core.ApplicationHttpRequest#6fdc83, org.apache.catalina.connector.ResponseFacade#119a78b]
2019-07-02 22:21:51.885 DEBUG 19680 --- [nio-8080-exec-1] o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, text/html;q=0.8]
2019-07-02 22:21:51.886 TRACE 19680 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Rendering view [org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration$StaticView#216e30]
2019-07-02 22:21:51.908 DEBUG 19680 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Exiting from "ERROR" dispatch, status 404, headers={}
I am certain that it is due to thymeleaf-layout-dialect, because if I remove it from pom.xml everything work fine.
The problem is I need it to layout thymeleaf page. How to display the template in another different project from spring application?

As you have published an example project, I can't follow the issue :/
Are you sure you did not just confuse the "hello world" messages from the controller with the message from the template?
When I modify: \prj1\src\main\resources\templates\hello-world.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>HW</title>
</head>
<body>
Hello World!! (from Template in prj1)!
</body>
</html>
I had to add this into pom.xml of prj1 because of some weird classpath issue:
(the thymeleaf-layout-dialect lib you use seems to bring in an additional thymeleaf jar - did not investigate that)
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.0.11.RELEASE</version>
</dependency>
When I run prj2 app and call: http://localhost:8080/api/hello3 or http://localhost:8080/api/hello2
I get:
Hello World!! (from Template in prj1)!
Which is what we want?
When I call: http://localhost:8080/api/hello
I get an error because of some not found template ("hello world" is of course not a template file).
So I'm not sure why it does not work for you :/

I'm not sure how this works without that dependency. The controllers that work with templates can return the template name directly. And you are implementing rest controllers which suggest different defaults than required for working with templates (like the content types).
So a controller that would invoke a template looks like (this is my way of doing it, can't claim I know its the only one):
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
#Controller
public class MyController {
#Autowired
public MyController() {
}
#RequestMapping("/hello-world")
public String hello(Model model) {
model.addAttribute("someKey", "someValue");
return "hello-world"; // this is the template name in src/main/resources
}
}
And this way it is also possible to have controllers / templates bundled in one jar and use them in a different spring boot application as dependencies. Since it is all classpath based (there is a property to configure this: spring.thymeleaf.prefix) this just worked for me.
I think the reason really is your rest controller - which might confuse things a bit.

Related

SpringBoot RestApi call 404 Not Found error

I have a SpringBoot application that I am able to start ( http://localhost:80 ).
In my application.yml :
application:
baseurl: /respViewer/api
In my application I defined a #RestController and an endpoint :
#RestController
#RequestMapping("${application.baseurl}/viewer")
....
#PostMapping(value = "/getRespList", consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> getResponsibilities(#RequestBody RequestDetail requestDetail)
When I try to access my application using Insomnia or through the Browser I am getting 404 Error.
http://localhost:8080/respViewer/api/viewer/getRespList
{
"timestamp": "2022-04-25T19:52:32.426+00:00",
"status": 404,
"error": "Not Found",
"message": "",
"path": "/respViewer/api/viewer/getRespList"
}
I also checked console output and found these messages :
POST "/respViewer/api/viewer/getRespList", parameters={}
2022-04-25 15:52:32.253 DEBUG 3744 --- [nio-8080-exec-1] o.s.w.s.h.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]
2022-04-25 15:52:32.382 DEBUG 3744 --- [nio-8080-exec-1] o.s.w.s.r.ResourceHttpRequestHandler : Resource not found
2022-04-25 15:52:32.387 DEBUG 3744 --- [nio-8080-exec-1] o.s.w.s.DispatcherServlet : Completed 404 NOT_FOUND
What am I doing wrong?
Update 1 :
I added packages location where I have a REST Controller to application.yml :
spring:
component:
scan:
packages: com.example.demoRespManager
and now I am not getting 404 Error, however it doesn't look like I am getting into the body of implementation method. I setup a break-point in the first line of the method but never stop there. An output in the Console is :
2022-04-25 21:25:43.749 INFO 27996 --- [nio-8080-exec-1] o.s.w.s.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-04-25 21:25:43.750 DEBUG 27996 --- [nio-8080-exec-1] o.s.w.s.DispatcherServlet : Detected StandardServletMultipartResolver
2022-04-25 21:25:43.915 DEBUG 27996 --- [nio-8080-exec-1] o.s.w.s.DispatcherServlet : enableLoggingRequestDetails='false': request parameters and headers will be masked to prevent unsafe logging of potentially sensitive data
2022-04-25 21:25:43.915 INFO 27996 --- [nio-8080-exec-1] o.s.w.s.DispatcherServlet : Completed initialization in 166 ms
2022-04-25 21:25:44.134 DEBUG 27996 --- [nio-8080-exec-1] o.s.w.s.DispatcherServlet : POST "/respViewer/api/viewer/getRespList", parameters={}
2022-04-25 21:25:44.180 DEBUG 27996 --- [nio-8080-exec-1] .m.m.a.ExceptionHandlerExceptionResolver : Using #ExceptionHandler com.<my_package_path>.exception.ApplicationExceptionHandler#handleException(Exception, WebRequest)
2022-04-25 21:25:44.254 DEBUG 27996 --- [nio-8080-exec-1] o.s.w.s.m.m.a.HttpEntityMethodProcessor : No match for [application/json], supported: []
2022-04-25 21:25:44.261 DEBUG 27996 --- [nio-8080-exec-1] .m.m.a.ExceptionHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type '' not supported]
2022-04-25 21:25:44.262 DEBUG 27996 --- [nio-8080-exec-1] o.s.w.s.DispatcherServlet : Completed 415 UNSUPPORTED_MEDIA_TYPE
UPDATE 2 :
In the Header section of the INSOMNIA application I added Content-type = application/json, since I defined it in my endpoint, and after that it started to work. I was able to start an application in the DEBUG mode and when I made a POST request in INSOMNIA I stopped at the first line of my method implementation.
I solved this issue :
updated my properties file with the list of the packages that contain the beans, it's an equivalent of #ComponentScan in Application ( spring.component.scan.packages )
Added Content-type = application/json to the Header in the Insomnia.

#ResponseBody is not returning String message to error, throwing 404 WhiteLabel error page

I am following a tutorial on Spring MVC and my project is not working as expected. I am using #ResponseBody to return a string message but it is throwing a whitelabel error page. I have scoured the Internet for last 2 days but still clueless about what could I possibly do wrong. Can anybody throw some light upon this?
Spring Framework boot : 2.5.4, Java version : 11
Code snippet for LoginController :
package com.in28minutes.springboot.web.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
public class LoginController {
#RequestMapping(value="/login", method=RequestMethod.GET, produces="text/plain")
#ResponseBody
public String loginMessage() {
return "Hello World";
}
}
2021-09-10 15:33:54.158 DEBUG 8556 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : GET "/login", parameters={}
2021-09-10 15:33:54.158 DEBUG 8556 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler [Classpath [META-INF/resources/], Classpath [resources/], Classpath [static/], Classpath [public/], ServletContext [/]]
2021-09-10 15:33:54.160 DEBUG 8556 --- [nio-8080-exec-1] o.s.w.s.r.ResourceHttpRequestHandler : Resource not found
2021-09-10 15:33:54.160 DEBUG 8556 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed 404 NOT_FOUND
2021-09-10 15:33:54.160 DEBUG 8556 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : "ERROR" dispatch for GET "/error", parameters={}
2021-09-10 15:33:54.161 DEBUG 8556 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#errorHtml(HttpServletRequest, HttpServletResponse)
2021-09-10 15:33:54.177 DEBUG 8556 --- [nio-8080-exec-1] o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, text/html;q=0.8]
2021-09-10 15:33:54.178 DEBUG 8556 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Exiting from "ERROR" dispatch, status 404
#SpringBootApplication
public class SpringBootFirstWebApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootFirstWebApplication.class,
args);
}
}
I will guess that your SpringBootFirstWebApplication is not placed in the parent package of all other packages in your application and therefore #Controller annotation in LoginController is not scanned.
If that is the case, change SpringBootFirstWebApplication to the parent package of all other packages in your application.
It seems like your requested URL in #RequestMapping is wrong. Your expected URL is value="/home", but your actual is value="/login"

Spring boot returning error 404 html page not found

I'm trying to return index.html which is placed under src/main/resources/templates but it seems that it is not loading.
StackTrace
2020-07-24 00:09:11.881 DEBUG 17204 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : GET "/", parameters={}
2020-07-24 00:09:11.884 DEBUG 17204 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.Alex.Flights.FlightsController#getIndexForm(ModelMap)
2020-07-24 00:09:11.885 DEBUG 17204 --- [nio-8080-exec-1] o.j.s.OpenEntityManagerInViewInterceptor : Opening JPA EntityManager in OpenEntityManagerInViewInterceptor
2020-07-24 00:09:11.902 DEBUG 17204 --- [nio-8080-exec-1] o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, application/xhtml+xml, image/webp, application/xml;q=0.9, */*;q=0.8]
2020-07-24 00:09:11.902 DEBUG 17204 --- [nio-8080-exec-1] o.s.w.servlet.view.InternalResourceView : View name 'index', model {userForm=Flights [flightNumber=dummy, origin=dummy, destination=dummy, takeOffTime=dummy, landingTime=dummy, flightDuration=dummy, takeOffDate=Fri Jul 24 00:09:11 SGT 2020, landingDate=Fri Jul 24 00:09:11 SGT 2020, flightReturn=false], org.springframework.validation.BindingResult.userForm=org.springframework.validation.BeanPropertyBindingResult: 0 errors}
2020-07-24 00:09:11.903 DEBUG 17204 --- [nio-8080-exec-1] o.s.w.servlet.view.InternalResourceView : Forwarding to [index]
2020-07-24 00:09:11.905 DEBUG 17204 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : "FORWARD" dispatch for GET "/index", parameters={}
2020-07-24 00:09:11.907 DEBUG 17204 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]
2020-07-24 00:09:11.908 DEBUG 17204 --- [nio-8080-exec-1] o.s.w.s.r.ResourceHttpRequestHandler : Resource not found
Method in controller
package com.Alex.Flights;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String getIndexForm(ModelMap model) {
model.addAttribute("userForm", new Flights("dummy", "dummy", "dummy", "dummy", "dummy","dummy", new Date(), new Date(), false));
return "index";
}
Main
package com.Alex.Mains;
#SpringBootApplication
#ComponentScan(basePackages = {
"com.Alex.JPA", "com.Alex.UserPackage", "com.Alex.Flights"
})
#EntityScan( basePackages = {"com.Alex.UserPackage", "com.Alex.Flights"})
#EnableJpaRepositories({"com.Alex.UserPackage", "com.Alex.Flights"})
public class JpaApplication {
public static void main(String[] args) {
SpringApplication.run(JpaApplication.class, args);
}
}
it seems like it is only looking in folders like /resources but doesn't go to look in /templates.
Solution is to define you own ViewResolver bean and set it up
https://www.baeldung.com/spring-mvc-view-resolver-tutorial

Wrong Header of the API versioning of the Post Request does not come to handleNoHandlerFoundException?

I am using Spring Boot v2.1.7 + HATEOAS + Spring Rest + Spring Security. When consumer doesn't pass the correct Custom Header in the request, say passes X-Accept-Version=v5, it gives me below error.
Error:
2020-03-26 15:44:48.201 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : POST "/employee-catalog-api/reference-types", parameters={}
2020-03-26 15:44:48.216 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]
2020-03-26 15:44:48.217 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] .m.c.d.m.p.s.SAMLUserIdentityServiceImpl : Trying to get UserId from Security Context
2020-03-26 15:44:48.224 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] o.j.s.OpenEntityManagerInViewInterceptor : Opening JPA EntityManager in OpenEntityManagerInViewInterceptor
2020-03-26 15:44:48.234 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] o.s.w.s.r.ResourceHttpRequestHandler : Resource not found
2020-03-26 15:44:48.234 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] o.s.s.w.header.writers.HstsHeaderWriter : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher#5c85f23b
2020-03-26 15:44:48.234 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2020-03-26 15:44:48.254 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] o.j.s.OpenEntityManagerInViewInterceptor : Closing JPA EntityManager in OpenEntityManagerInViewInterceptor
2020-03-26 15:44:48.254 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed 404 NOT_FOUND
2020-03-26 15:44:48.258 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] o.s.s.w.a.ExceptionTranslationFilter : Chain processed normally
2020-03-26 15:44:48.258 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
Code:
#PostMapping(path = "/employee-types", headers = {X-Accept-Version=v1})
public ResponseEntity<Integer> saveEmployeeType(#Valid #RequestBody EmployeeDto employeeDto) {
.....
......
......
return new ResponseEntity<>(HttpStatus.OK);
}
Why its not coming to handleNoHandlerFoundException of the #ControllerAdvice ?
#Override
protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers,
HttpStatus status, WebRequest request) {
...................
return handleExceptionInternal(ex, error, getHeaders(), HttpStatus.BAD_REQUEST, request);
}
I was able to solve this issue by taking a reference from : How to set default value of exported as false in rest resource spring data rest.
By adding below logic, it works greatly.
#Component
public class SpringRestConfiguration extends RepositoryRestConfigurerAdapter {
#Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.setRepositoryDetectionStrategy(RepositoryDetectionStrategy.RepositoryDetectionStrategies.ANNOTATED);
config.setExposeRepositoryMethodsByDefault(false);
}
}

SpringBoot, Thymeleaf, Gradle: not accessing static resources, css not showing

I have tried so many things at this point, but my css will not show on my pages. this is my thymeleaf page:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title th:text="${title}">Default Title</title>
<link th:href="#{/css/styles.css}" rel="stylesheet" type="text/css" />
</head>
this is the error i get when I load this page, which i assume it important:
**2018-04-11 05:57:08.425 WARN 7904 --- [nio-8080-exec-2] o.s.web.servlet.PageNotFound : No mapping found for HTTP request with URI [/css/styles.css] in DispatcherServlet with name 'dispatcherServlet'**
I have my static resources in the PROPER folder, like this (image link):
Folders path
sources>main>resources>static and then another css folder, which i did add to the #{}.
I have searched and search everywhere for answers, I even added this to my WebMcvConfigurerAdapter class, like I kept seeing:
#Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}
}
This is my current one(im using interceptors and stuff, just disregard that part):
#Configuration
#EnableWebMvc
public class MyAppConfig extends WebMvcConfigurerAdapter {
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new ProjectManagerInterceptor());
}
}
This is my build.gradle file, in case it helps:
buildscript {
ext {
springBootVersion = '1.5.10.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'org.launchcode'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile('org.springframework.session:spring-session')
compile('org.springframework.boot:spring-boot-starter-thymeleaf')
compile('org.springframework.boot:spring-boot-starter-web')
runtime('org.springframework.boot:spring-boot-devtools')
runtime('mysql:mysql-connector-java')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
bootRun {
addResources = true
}
I have another project that also uses static resources like i'm trying to do, and it works perfectly. I will post some of it's code and information, in case it might help.
Working application's information
CONSOLE WHEN I LOAD A PAGE WITH STATIC RESOURCES:
2018-04-11 05:53:15.553 DEBUG 7448 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/css/bootstrap.css]
2018-04-11 05:53:15.554 DEBUG 7448 --- [nio-8080-exec-2] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /css/bootstrap.css
2018-04-11 05:53:15.554 DEBUG 7448 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/css/techjobs.css]
2018-04-11 05:53:15.554 DEBUG 7448 --- [nio-8080-exec-3] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /css/techjobs.css
2018-04-11 05:53:15.556 DEBUG 7448 --- [nio-8080-exec-2] s.w.s.m.m.a.RequestMappingHandlerMapping : Did not find handler method for [/css/bootstrap.css]
2018-04-11 05:53:15.556 DEBUG 7448 --- [nio-8080-exec-2] o.s.w.s.handler.SimpleUrlHandlerMapping : Matching patterns for request [/css/bootstrap.css] are [/**]
2018-04-11 05:53:15.558 DEBUG 7448 --- [nio-8080-exec-2] o.s.w.s.handler.SimpleUrlHandlerMapping : URI Template variables for request [/css/bootstrap.css] are {}
2018-04-11 05:53:15.559 DEBUG 7448 --- [nio-8080-exec-2] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapping [/css/bootstrap.css] to HandlerExecutionChain with handler [ResourceHttpRequestHandler [locations=[ServletContext resource [/], class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver#3f0bd4d8]]] and 1 interceptor
2018-04-11 05:53:15.560 DEBUG 7448 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Last-Modified value for [/css/bootstrap.css] is: -1
2018-04-11 05:53:15.580 DEBUG 7448 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/js/bootstrap.js]
2018-04-11 05:53:15.581 DEBUG 7448 --- [nio-8080-exec-4] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /js/bootstrap.js
2018-04-11 05:53:15.582 DEBUG 7448 --- [nio-8080-exec-4] s.w.s.m.m.a.RequestMappingHandlerMapping : Did not find handler method for [/js/bootstrap.js]
2018-04-11 05:53:15.582 DEBUG 7448 --- [nio-8080-exec-4] o.s.w.s.handler.SimpleUrlHandlerMapping : Matching patterns for request [/js/bootstrap.js] are [/**]
2018-04-11 05:53:15.582 DEBUG 7448 --- [nio-8080-exec-4] o.s.w.s.handler.SimpleUrlHandlerMapping : URI Template variables for request [/js/bootstrap.js] are {}
2018-04-11 05:53:15.582 DEBUG 7448 --- [nio-8080-exec-4] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapping [/js/bootstrap.js] to HandlerExecutionChain with handler [ResourceHttpRequestHandler [locations=[ServletContext resource [/], class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver#3f0bd4d8]]] and 1 interceptor
2018-04-11 05:53:15.582 DEBUG 7448 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : Last-Modified value for [/js/bootstrap.js] is: -1
2018-04-11 05:53:15.592 DEBUG 7448 --- [nio-8080-exec-3] s.w.s.m.m.a.RequestMappingHandlerMapping : Did not find handler method for [/css/techjobs.css]
2018-04-11 05:53:15.594 DEBUG 7448 --- [nio-8080-exec-3] o.s.w.s.handler.SimpleUrlHandlerMapping : Matching patterns for request [/css/techjobs.css] are [/**]
2018-04-11 05:53:15.595 DEBUG 7448 --- [nio-8080-exec-3] o.s.w.s.handler.SimpleUrlHandlerMapping : URI Template variables for request [/css/techjobs.css] are {}
2018-04-11 05:53:15.595 DEBUG 7448 --- [nio-8080-exec-3] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapping [/css/techjobs.css] to HandlerExecutionChain with handler [ResourceHttpRequestHandler [locations=[ServletContext resource [/], class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver#3f0bd4d8]]] and 1 interceptor
2018-04-11 05:53:15.595 DEBUG 7448 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : Last-Modified value for [/css/techjobs.css] is: -1
HTML:
<head th:fragment="head">
<!-- Bootstrap stylesheets and script -->
<link th:href="#{/css/bootstrap.css}" rel="stylesheet" />
<link th:href="#{/css/techjobs.css}" rel="stylesheet" />
<script type="text/javascript" th:src="#{/js/bootstrap.js}"></script>
<title th:text="'TechJobs' + ${title == null ? '' : ' :: ' + title}">TechJobs</title>
</head>
FOLDER SETUP:
Working app's folder paths
If there are any questions dont hesitate to ask! I'm really bummed out about this, so much time
I just found the answer to my own question, so I'm going to leave this hear for anyone who might find it.
Spring Boot not serving static content
I had an unnecessary #EnableWebMvc annotation, that I took out, and my resources worked :D!

Resources