Spring does not see resources folder even after adding <mvc:resources mapping="/resources/**" location="/resources"/>
I am typing localhost:8080/resources/qwerty.txt (file is created) and Dispatcher servlet is solving it by ViewResolver like "/WEB-INF/views/resources/qwerty.jsp"
Also I have found a similar project on github with "resorces" folder in "webapp" and there everything is OK. After making the same procedure like I descriped above - spring displays qwerty.txt on the screen.
This is Tomcat console:
Request #1:
TRACE 2017-04-27 15:32:23,455 [http-bio-8080-exec-1] org.springframework.web.servlet.DispatcherServlet - Bound request context to thread: org.apache.catalina.connector.RequestFacade#4dbf1eec
DEBUG 2017-04-27 15:32:23,456 [http-bio-8080-exec-1] org.springframework.web.servlet.DispatcherServlet - DispatcherServlet with name 'di' processing GET request for [/resources/qwerty.txt]
TRACE 2017-04-27 15:32:23,460 [http-bio-8080-exec-1] org.springframework.web.servlet.DispatcherServlet - Testing handler map [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#444835f1] in DispatcherServlet with name 'di'
DEBUG 2017-04-27 15:32:23,463 [http-bio-8080-exec-1] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Looking up handler method for path /resources/qwerty.txt
TRACE 2017-04-27 15:32:23,473 [http-bio-8080-exec-1] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Found 1 matching mapping(s) for [/resources/qwerty.txt] : [{[],methods=[GET]}]
DEBUG 2017-04-27 15:32:23,473 [http-bio-8080-exec-1] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Returning handler method [public void web.SimpleController.index()]
DEBUG 2017-04-27 15:32:23,474 [http-bio-8080-exec-1] org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'simpleController'
TRACE 2017-04-27 15:32:23,475 [http-bio-8080-exec-1] org.springframework.web.servlet.DispatcherServlet - Testing handler adapter [org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter#75ad2983]
TRACE 2017-04-27 15:32:23,475 [http-bio-8080-exec-1] org.springframework.web.servlet.DispatcherServlet - Testing handler adapter [org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter#1d7ba137]
TRACE 2017-04-27 15:32:23,476 [http-bio-8080-exec-1] org.springframework.web.servlet.DispatcherServlet - Testing handler adapter [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#2efb2c32]
DEBUG 2017-04-27 15:32:23,476 [http-bio-8080-exec-1] org.springframework.web.servlet.DispatcherServlet - Last-Modified value for [/resources/qwerty.txt] is: -1
TRACE 2017-04-27 15:32:23,500 [http-bio-8080-exec-1] org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod - Invoking [SimpleController.index] method with arguments []
TRACE 2017-04-27 15:32:23,500 [http-bio-8080-exec-1] org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod - Method [index] returned [null]
DEBUG 2017-04-27 15:32:23,513 [http-bio-8080-exec-1] org.springframework.beans.factory.support.DefaultListableBeanFactory - Invoking afterPropertiesSet() on bean with name 'resources/qwerty'
TRACE 2017-04-27 15:32:23,513 [http-bio-8080-exec-1] org.springframework.web.servlet.view.InternalResourceViewResolver - Cached view [resources/qwerty]
DEBUG 2017-04-27 15:32:23,513 [http-bio-8080-exec-1] org.springframework.web.servlet.DispatcherServlet - Rendering view [org.springframework.web.servlet.view.JstlView: name 'resources/qwerty'; URL [/WEB-INF/views/resources/qwerty.jsp]] in DispatcherServlet with name 'di'
TRACE 2017-04-27 15:32:23,513 [http-bio-8080-exec-1] org.springframework.web.servlet.view.JstlView - Rendering view with name 'resources/qwerty' with model {} and static attributes {}
DEBUG 2017-04-27 15:32:23,521 [http-bio-8080-exec-1] org.springframework.web.servlet.view.JstlView - Forwarding to resource [/WEB-INF/views/resources/qwerty.jsp] in InternalResourceView 'resources/qwerty'
TRACE 2017-04-27 15:32:23,527 [http-bio-8080-exec-1] org.springframework.web.servlet.DispatcherServlet - Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade#4dbf1eec
DEBUG 2017-04-27 15:32:23,527 [http-bio-8080-exec-1] org.springframework.web.servlet.DispatcherServlet - Successfully completed request
TRACE 2017-04-27 15:32:23,529 [http-bio-8080-exec-1] org.springframework.web.context.support.XmlWebApplicationContext - Publishing event in WebApplicationContext for namespace 'di-servlet': ServletRequestHandledEvent: url=[/resources/qwerty.txt]; client=[127.0.0.1]; method=[GET]; servlet=[di]; session=[null]; user=[null]; time=[89ms]; status=[OK]
Request #2:
TRACE 2017-04-27 15:32:49,272 [http-bio-8080-exec-3] org.springframework.web.servlet.DispatcherServlet - Bound request context to thread: org.apache.catalina.connector.RequestFacade#4dbf1eec
DEBUG 2017-04-27 15:32:49,273 [http-bio-8080-exec-3] org.springframework.web.servlet.DispatcherServlet - DispatcherServlet with name 'di' processing GET request for [/resources/qwerty.txt]
TRACE 2017-04-27 15:32:49,274 [http-bio-8080-exec-3] org.springframework.web.servlet.DispatcherServlet - Testing handler map [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#444835f1] in DispatcherServlet with name 'di'
DEBUG 2017-04-27 15:32:49,274 [http-bio-8080-exec-3] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Looking up handler method for path /resources/qwerty.txt
TRACE 2017-04-27 15:32:49,275 [http-bio-8080-exec-3] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Found 1 matching mapping(s) for [/resources/qwerty.txt] : [{[],methods=[GET]}]
DEBUG 2017-04-27 15:32:49,275 [http-bio-8080-exec-3] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Returning handler method [public void web.SimpleController.index()]
DEBUG 2017-04-27 15:32:49,275 [http-bio-8080-exec-3] org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'simpleController'
TRACE 2017-04-27 15:32:49,276 [http-bio-8080-exec-3] org.springframework.web.servlet.DispatcherServlet - Testing handler adapter [org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter#75ad2983]
TRACE 2017-04-27 15:32:49,276 [http-bio-8080-exec-3] org.springframework.web.servlet.DispatcherServlet - Testing handler adapter [org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter#1d7ba137]
TRACE 2017-04-27 15:32:49,276 [http-bio-8080-exec-3] org.springframework.web.servlet.DispatcherServlet - Testing handler adapter [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#2efb2c32]
DEBUG 2017-04-27 15:32:49,276 [http-bio-8080-exec-3] org.springframework.web.servlet.DispatcherServlet - Last-Modified value for [/resources/qwerty.txt] is: -1
TRACE 2017-04-27 15:32:49,277 [http-bio-8080-exec-3] org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod - Invoking [SimpleController.index] method with arguments []
TRACE 2017-04-27 15:32:49,284 [http-bio-8080-exec-3] org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod - Method [index] returned [null]
DEBUG 2017-04-27 15:32:49,287 [http-bio-8080-exec-3] org.springframework.web.servlet.DispatcherServlet - Rendering view [org.springframework.web.servlet.view.JstlView: name 'resources/qwerty'; URL [/WEB-INF/views/resources/qwerty.jsp]] in DispatcherServlet with name 'di'
TRACE 2017-04-27 15:32:49,287 [http-bio-8080-exec-3] org.springframework.web.servlet.view.JstlView - Rendering view with name 'resources/qwerty' with model {} and static attributes {}
DEBUG 2017-04-27 15:32:49,288 [http-bio-8080-exec-3] org.springframework.web.servlet.view.JstlView - Forwarding to resource [/WEB-INF/views/resources/qwerty.jsp] in InternalResourceView 'resources/qwerty'
TRACE 2017-04-27 15:32:49,289 [http-bio-8080-exec-3] org.springframework.web.servlet.DispatcherServlet - Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade#4dbf1eec
DEBUG 2017-04-27 15:32:49,289 [http-bio-8080-exec-3] org.springframework.web.servlet.DispatcherServlet - Successfully completed request
TRACE 2017-04-27 15:32:49,289 [http-bio-8080-exec-3] org.springframework.web.context.support.XmlWebApplicationContext - Publishing event in WebApplicationContext for namespace 'di-servlet': ServletRequestHandledEvent: url=[/resources/qwerty.txt]; client=[127.0.0.1]; method=[GET]; servlet=[di]; session=[null]; user=[null]; time=[18ms]; status=[OK]
servlet context:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="controller, model, service, todo, web"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/views/"
p:suffix=".jsp"
/>
<mvc:resources mapping="/resources/**" location="/resources/"/>
<mvc:annotation-driven />
What I am doing wrong?
SOLVED:
I just changed mapping for some methods from default to their real names and everything gone
Magic
Does anyone knows why it is working in such strange way?
Related
Version of springfox-swagger that I am using [ ![Download] 1]2
What kind of issue is this?
Project structure:
SwaggerConfig is in automate.api.config.swagger.SwaggerConfiguration
Auth Config is in automate.api.web.auth.keycloak.FalconKeycloakConfigurerAdapter
dependencies
As for Spring Boot
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/>
</parent>
As for swagger
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${spring.springfox-swagger2.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${spring.springfox-swagger2.version}</version>
</dependency>
Swagger 2 config
#Configuration
#EnableSwagger2
public class SwaggerConfiguration {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
Security config
#Override
protected void configureAccessRules(final HttpSecurity http) throws Exception {
http.csrf()
.disable()
.authorizeRequests()
.antMatchers("/actuator/health")
.permitAll()
.antMatchers(HttpMethod.GET,
"/v2/api-docs",
"/swagger-resources/**",
"/swagger-ui.html**",
"/webjars/**",
"favicon.ico")
.permitAll();
}
Example for one of my controllers
All of my controllers mapped like /api/...
#RestController
#RequestMapping(value = "/api", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class ExampleResource {
private ExampleFacade catalog;
#Autowired
public ExampleResource(ExampleFacade catalog) {
this.catalog = catalog;
}
#RequestMapping(method = RequestMethod.GET, value = "/examples")
public List<ExampleDTO> index() {
return catalog.listExamples();
}
}
ISSUE
/v2/api-docs works perfectly, I get back all of my endpoints with their details
/swagger-ui.html gives me back a pop up that shows "Unable to infer base url......"
Then I turned on the TRACE log level on my spring-boot app, like
logging:
level:
org:
springframework:
web: TRACE
My logs looks like:
[2019-05-22 21:12:06] TRACE [nio-8080-exec-1] o.s.w.s.DispatcherServlet GET "/v2/api-docs", parameters={}, headers={masked} in DispatcherServlet 'dispatcherServlet'
[2019-05-22 21:12:06] TRACE [nio-8080-exec-1] o.s.w.s.m.m.a.ServletInvocableHandlerMethod Arguments: [null, SecurityContextHolderAwareRequestWrapper[ org.springframework.security.web.header.HeaderWriterFilter$HeaderWriterRequest#b9ed904]]
[2019-05-22 21:12:06] DEBUG [nio-8080-exec-1] o.s.w.s.m.m.a.HttpEntityMethodProcessor Using 'application/json;q=0.8', given [text/html, application/xhtml+xml, image/webp, image/apng, application/signed-exchange;v=b3, application/xml;q=0.9, */*;q=0.8] and supported [application/json, application/*+json, application/json, application/*+json]
[2019-05-22 21:12:06] TRACE [nio-8080-exec-1] o.s.w.s.m.m.a.HttpEntityMethodProcessor Writing [BaseView(data=springfox.documentation.spring.web.json.Json#65455d18)]
[2019-05-22 21:12:06] TRACE [nio-8080-exec-1] o.s.w.s.DispatcherServlet No view rendering, null ModelAndView returned.
[2019-05-22 21:12:06] DEBUG [nio-8080-exec-1] o.s.w.s.DispatcherServlet Completed 200 OK, headers={masked}
[2019-05-22 21:12:10] TRACE [nio-8080-exec-2] o.s.w.s.DispatcherServlet GET "/swagger-ui.html", parameters={}, headers={masked} in DispatcherServlet 'dispatcherServlet'
[2019-05-22 21:12:10] TRACE [nio-8080-exec-2] o.s.w.s.h.SimpleUrlHandlerMapping Mapped to HandlerExecutionChain with [ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]] and 5 interceptors
[2019-05-22 21:12:10] TRACE [nio-8080-exec-2] o.s.w.s.DispatcherServlet No view rendering, null ModelAndView returned.
[2019-05-22 21:12:10] DEBUG [nio-8080-exec-2] o.s.w.s.DispatcherServlet Completed 200 OK, headers={masked}
[2019-05-22 21:12:10] TRACE [nio-8080-exec-3] o.s.w.s.DispatcherServlet GET "/webjars/springfox-swagger-ui/springfox.css?v=2.9.2", parameters={masked}, headers={masked} in DispatcherServlet 'dispatcherServlet'
[2019-05-22 21:12:10] TRACE [nio-8080-exec-4] o.s.w.s.DispatcherServlet GET "/webjars/springfox-swagger-ui/swagger-ui.css?v=2.9.2", parameters={masked}, headers={masked} in DispatcherServlet 'dispatcherServlet'
[2019-05-22 21:12:10] TRACE [nio-8080-exec-3] o.s.w.s.h.SimpleUrlHandlerMapping Matching patterns [/webjars/**, /**]
[2019-05-22 21:12:10] TRACE [nio-8080-exec-3] o.s.w.s.h.SimpleUrlHandlerMapping Mapped to HandlerExecutionChain with [ResourceHttpRequestHandler ["classpath:/META-INF/resources/webjars/"]] and 5 interceptors
[2019-05-22 21:12:10] TRACE [nio-8080-exec-4] o.s.w.s.h.SimpleUrlHandlerMapping Matching patterns [/webjars/**, /**]
[2019-05-22 21:12:10] TRACE [nio-8080-exec-4] o.s.w.s.h.SimpleUrlHandlerMapping Mapped to HandlerExecutionChain with [ResourceHttpRequestHandler ["classpath:/META-INF/resources/webjars/"]] and 5 interceptors
[2019-05-22 21:12:10] TRACE [nio-8080-exec-6] o.s.w.s.DispatcherServlet GET "/webjars/springfox-swagger-ui/swagger-ui-bundle.js?v=2.9.2", parameters={masked}, headers={masked} in DispatcherServlet 'dispatcherServlet'
[2019-05-22 21:12:10] TRACE [nio-8080-exec-3] o.s.w.s.DispatcherServlet No view rendering, null ModelAndView returned.
[2019-05-22 21:12:10] DEBUG [nio-8080-exec-3] o.s.w.s.DispatcherServlet Completed 200 OK, headers={masked}
[2019-05-22 21:12:10] TRACE [nio-8080-exec-5] o.s.w.s.DispatcherServlet GET "/webjars/springfox-swagger-ui/swagger-ui-standalone-preset.js?v=2.9.2", parameters={masked}, headers={masked} in DispatcherServlet 'dispatcherServlet'
[2019-05-22 21:12:10] TRACE [nio-8080-exec-7] o.s.w.s.DispatcherServlet GET "/webjars/springfox-swagger-ui/springfox.js?v=2.9.2", parameters={masked}, headers={masked} in DispatcherServlet 'dispatcherServlet'
[2019-05-22 21:12:10] TRACE [nio-8080-exec-6] o.s.w.s.h.SimpleUrlHandlerMapping Matching patterns [/webjars/**, /**]
[2019-05-22 21:12:10] TRACE [nio-8080-exec-6] o.s.w.s.h.SimpleUrlHandlerMapping Mapped to HandlerExecutionChain with [ResourceHttpRequestHandler ["classpath:/META-INF/resources/webjars/"]] and 5 interceptors
[2019-05-22 21:12:10] TRACE [nio-8080-exec-5] o.s.w.s.h.SimpleUrlHandlerMapping Matching patterns [/webjars/**, /**]
[2019-05-22 21:12:10] TRACE [nio-8080-exec-5] o.s.w.s.h.SimpleUrlHandlerMapping Mapped to HandlerExecutionChain with [ResourceHttpRequestHandler ["classpath:/META-INF/resources/webjars/"]] and 5 interceptors
[2019-05-22 21:12:10] TRACE [nio-8080-exec-7] o.s.w.s.h.SimpleUrlHandlerMapping Matching patterns [/webjars/**, /**]
[2019-05-22 21:12:10] TRACE [nio-8080-exec-7] o.s.w.s.h.SimpleUrlHandlerMapping Mapped to HandlerExecutionChain with [ResourceHttpRequestHandler ["classpath:/META-INF/resources/webjars/"]] and 5 interceptors
[2019-05-22 21:12:10] TRACE [nio-8080-exec-4] o.s.w.s.DispatcherServlet No view rendering, null ModelAndView returned.
[2019-05-22 21:12:10] DEBUG [nio-8080-exec-4] o.s.w.s.DispatcherServlet Completed 200 OK, headers={masked}
[2019-05-22 21:12:10] TRACE [nio-8080-exec-7] o.s.w.s.DispatcherServlet No view rendering, null ModelAndView returned.
[2019-05-22 21:12:10] DEBUG [nio-8080-exec-7] o.s.w.s.DispatcherServlet Completed 200 OK, headers={masked}
[2019-05-22 21:12:10] TRACE [nio-8080-exec-5] o.s.w.s.DispatcherServlet No view rendering, null ModelAndView returned.
[2019-05-22 21:12:10] DEBUG [nio-8080-exec-5] o.s.w.s.DispatcherServlet Completed 200 OK, headers={masked}
[2019-05-22 21:12:10] TRACE [nio-8080-exec-6] o.s.w.s.DispatcherServlet No view rendering, null ModelAndView returned.
[2019-05-22 21:12:10] DEBUG [nio-8080-exec-6] o.s.w.s.DispatcherServlet Completed 200 OK, headers={masked}
[2019-05-22 21:12:10] TRACE [nio-8080-exec-8] o.s.w.s.DispatcherServlet GET "/swagger-resources/configuration/ui", parameters={}, headers={masked} in DispatcherServlet 'dispatcherServlet'
[2019-05-22 21:12:10] TRACE [nio-8080-exec-8] o.s.w.s.m.m.a.RequestMappingHandlerMapping Mapped to public org.springframework.http.ResponseEntity<springfox.documentation.swagger.web.UiConfiguration> springfox.documentation.swagger.web.ApiResourceController.uiConfiguration()
[2019-05-22 21:12:10] TRACE [nio-8080-exec-8] o.s.w.s.m.m.a.ServletInvocableHandlerMethod Arguments: []
[2019-05-22 21:12:10] DEBUG [nio-8080-exec-8] o.s.w.s.m.m.a.HttpEntityMethodProcessor Using 'application/json', given [application/json] and supported [application/json, application/*+json, application/json, application/*+json]
[2019-05-22 21:12:10] TRACE [nio-8080-exec-8] o.s.w.s.m.m.a.HttpEntityMethodProcessor Writing [BaseView(data=springfox.documentation.swagger.web.UiConfiguration#7594a0c7)]
[2019-05-22 21:12:10] TRACE [nio-8080-exec-8] o.s.w.s.DispatcherServlet No view rendering, null ModelAndView returned.
[2019-05-22 21:12:10] DEBUG [nio-8080-exec-8] o.s.w.s.DispatcherServlet Completed 200 OK, headers={masked}
[2019-05-22 21:12:10] TRACE [nio-8080-exec-9] o.s.w.s.DispatcherServlet GET "/swagger-resources/configuration/security", parameters={}, headers={masked} in DispatcherServlet 'dispatcherServlet'
[2019-05-22 21:12:10] TRACE [nio-8080-exec-9] o.s.w.s.m.m.a.RequestMappingHandlerMapping Mapped to public org.springframework.http.ResponseEntity<springfox.documentation.swagger.web.SecurityConfiguration> springfox.documentation.swagger.web.ApiResourceController.securityConfiguration()
[2019-05-22 21:12:10] TRACE [nio-8080-exec-9] o.s.w.s.m.m.a.ServletInvocableHandlerMethod Arguments: []
[2019-05-22 21:12:10] DEBUG [nio-8080-exec-9] o.s.w.s.m.m.a.HttpEntityMethodProcessor Using 'application/json', given [application/json] and supported [application/json, application/*+json, application/json, application/*+json]
[2019-05-22 21:12:10] TRACE [nio-8080-exec-9] o.s.w.s.m.m.a.HttpEntityMethodProcessor Writing [BaseView(data=springfox.documentation.swagger.web.SecurityConfiguration#4605258b)]
[2019-05-22 21:12:10] TRACE [nio-8080-exec-9] o.s.w.s.DispatcherServlet No view rendering, null ModelAndView returned.
[2019-05-22 21:12:10] DEBUG [nio-8080-exec-9] o.s.w.s.DispatcherServlet Completed 200 OK, headers={masked}
[2019-05-22 21:12:10] TRACE [io-8080-exec-10] o.s.w.s.DispatcherServlet GET "/swagger-resources", parameters={}, headers={masked} in DispatcherServlet 'dispatcherServlet'
[2019-05-22 21:12:10] TRACE [io-8080-exec-10] o.s.w.s.m.m.a.RequestMappingHandlerMapping Mapped to public org.springframework.http.ResponseEntity<java.util.List<springfox.documentation.swagger.web.SwaggerResource>> springfox.documentation.swagger.web.ApiResourceController.swaggerResources()
[2019-05-22 21:12:10] TRACE [io-8080-exec-10] o.s.w.s.m.m.a.ServletInvocableHandlerMethod Arguments: []
[2019-05-22 21:12:10] DEBUG [io-8080-exec-10] o.s.w.s.m.m.a.HttpEntityMethodProcessor Using 'application/json', given [application/json] and supported [application/json, application/*+json, application/json, application/*+json]
[2019-05-22 21:12:10] TRACE [io-8080-exec-10] o.s.w.s.m.m.a.HttpEntityMethodProcessor Writing [BaseView(data=[springfox.documentation.swagger.web.SwaggerResource#b35c0d2])]
[2019-05-22 21:12:10] TRACE [io-8080-exec-10] o.s.w.s.DispatcherServlet No view rendering, null ModelAndView returned.
[2019-05-22 21:12:10] DEBUG [io-8080-exec-10] o.s.w.s.DispatcherServlet Completed 200 OK, headers={masked}
[2019-05-22 21:12:11] TRACE [nio-8080-exec-1] o.s.w.s.DispatcherServlet GET "/null/swagger-resources/configuration/ui", parameters={}, headers={masked} in DispatcherServlet 'dispatcherServlet'
[2019-05-22 21:12:11] TRACE [nio-8080-exec-1] o.s.w.s.h.SimpleUrlHandlerMapping Mapped to HandlerExecutionChain with [ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]] and 5 interceptors
[2019-05-22 21:12:11] DEBUG [nio-8080-exec-1] o.s.w.s.r.ResourceHttpRequestHandler Resource not found
[2019-05-22 21:12:11] TRACE [nio-8080-exec-1] o.s.w.s.DispatcherServlet No view rendering, null ModelAndView returned.
[2019-05-22 21:12:11] DEBUG [nio-8080-exec-1] o.s.w.s.DispatcherServlet Completed 404 NOT_FOUND, headers={masked}
[2019-05-22 21:12:11] TRACE [nio-8080-exec-1] o.s.w.s.DispatcherServlet "ERROR" dispatch for GET "/error", parameters={}, headers={masked} in DispatcherServlet 'dispatcherServlet'
[2019-05-22 21:12:11] TRACE [nio-8080-exec-1] o.s.w.s.m.m.a.RequestMappingHandlerMapping Mapped to public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
[2019-05-22 21:12:11] TRACE [nio-8080-exec-1] o.s.w.s.m.m.a.ServletInvocableHandlerMethod Arguments: [SecurityContextHolderAwareRequestWrapper[ FirewalledRequest[ org.apache.catalina.core.ApplicationHttpRequest#dc7df80]]]
[2019-05-22 21:12:11] DEBUG [nio-8080-exec-1] o.s.w.s.m.m.a.HttpEntityMethodProcessor Using 'application/json', given [application/json] and supported [application/json, application/*+json, application/json, application/*+json]
[2019-05-22 21:12:11] TRACE [nio-8080-exec-1] o.s.w.s.m.m.a.HttpEntityMethodProcessor Writing [BaseView(data={timestamp=Wed May 22 21:12:11 CEST 2019, status=404, error=Not Found, message=No message available, path=/null/swagger-resources/configuration/ui})]
[2019-05-22 21:12:11] TRACE [nio-8080-exec-1] o.s.w.s.DispatcherServlet No view rendering, null ModelAndView returned.
[2019-05-22 21:12:11] DEBUG [nio-8080-exec-1] o.s.w.s.DispatcherServlet Exiting from "ERROR" dispatch, status 404, headers={masked}
[2019-05-22 21:12:12] TRACE [nio-8080-exec-2] o.s.w.s.DispatcherServlet GET "/null/swagger-resources/configuration/security", parameters={}, headers={masked} in DispatcherServlet 'dispatcherServlet'
[2019-05-22 21:12:12] TRACE [nio-8080-exec-2] o.s.w.s.h.SimpleUrlHandlerMapping Mapped to HandlerExecutionChain with [ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]] and 5 interceptors
[2019-05-22 21:12:12] DEBUG [nio-8080-exec-2] o.s.w.s.r.ResourceHttpRequestHandler Resource not found
[2019-05-22 21:12:12] TRACE [nio-8080-exec-2] o.s.w.s.DispatcherServlet No view rendering, null ModelAndView returned.
[2019-05-22 21:12:12] DEBUG [nio-8080-exec-2] o.s.w.s.DispatcherServlet Completed 404 NOT_FOUND, headers={masked}
[2019-05-22 21:12:12] TRACE [nio-8080-exec-2] o.s.w.s.DispatcherServlet "ERROR" dispatch for GET "/error", parameters={}, headers={masked} in DispatcherServlet 'dispatcherServlet'
[2019-05-22 21:12:12] TRACE [nio-8080-exec-2] o.s.w.s.m.m.a.RequestMappingHandlerMapping Mapped to public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
[2019-05-22 21:12:12] TRACE [nio-8080-exec-2] o.s.w.s.m.m.a.ServletInvocableHandlerMethod Arguments: [SecurityContextHolderAwareRequestWrapper[ FirewalledRequest[ org.apache.catalina.core.ApplicationHttpRequest#723fa0fe]]]
[2019-05-22 21:12:12] DEBUG [nio-8080-exec-2] o.s.w.s.m.m.a.HttpEntityMethodProcessor Using 'application/json', given [application/json] and supported [application/json, application/*+json, application/json, application/*+json]
[2019-05-22 21:12:12] TRACE [nio-8080-exec-2] o.s.w.s.m.m.a.HttpEntityMethodProcessor Writing [BaseView(data={timestamp=Wed May 22 21:12:12 CEST 2019, status=404, error=Not Found, message=No message available, path=/null/swagger-resources/configuration/security})]
[2019-05-22 21:12:12] TRACE [nio-8080-exec-2] o.s.w.s.DispatcherServlet No view rendering, null ModelAndView returned.
[2019-05-22 21:12:12] DEBUG [nio-8080-exec-2] o.s.w.s.DispatcherServlet Exiting from "ERROR" dispatch, status 404, headers={masked}
Unfortunately, I see there is something weird with the path mapping at the and of the logs:
GET "/null/swagger-resources/configuration/ui"
GET "/null/swagger-resources/configuration/security" etc...
Please, help me ! :)
I gooogled for this problem and read these ones:
Why does springfox-swagger2 UI tell me "Unable to infer base url."
https://github.com/springfox/springfox/issues/2191
https://github.com/springfox/springfox/issues/2907
swagger-ui.html 400 bad request
https://github.com/springfox/springfox/issues/2501
https://github.com/springfox/springfox/issues/2396
Now, I managed to solve my issue.
One of the issues was the pathMApping.
I needed to change my configuration to explicitly to "/", like here
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
#Configuration
#EnableSwagger2
public class SwaggerConfiguration {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.pathMapping("/");
}
}
Other issue was I used ResponseBodyAdvice
import io.falcon.automate.api.web.views.BaseView;
import io.falcon.automate.api.web.views.ErrorView;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
#ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice<Object> {
#Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}
/**
* Wraps all responses in base view class
* #param body
* #param returnType
* #param selectedContentType
* #param selectedConverterType
* #param request
* #param response
* #return
*/
#Override
public Object beforeBodyWrite(
Object body,
MethodParameter returnType,
MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType,
ServerHttpRequest request,
ServerHttpResponse response
) {
if (body instanceof ErrorView) {
return body;
}
return new BaseView(body);
}
}
If I commented out my response wrapper class, everything works like a charm.....
The only issue, that I need my response wrapper. :/
To solve the issue you just need to add the following to the ResponseBodyAdvice implemented class, at #ControllerAdvice annotation you just need to define the base package of your application directory, so this won't return a null when calling the swagger-ui url.
For example, have a look at first line #ControllerAdvice annotation input parameter
#ControllerAdvice("com.main.abc.package")
public class AdapterAdvice implements ResponseBodyAdvice<Object> {
#Override
public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
return true;
}
#Override
public Object beforeBodyWrite(
Object body,
MethodParameter methodParameter,
MediaType mediaType,
Class<? extends HttpMessageConverter<?>> aClass,
ServerHttpRequest serverHttpRequest,
ServerHttpResponse serverHttpResponse) {
// just some wrapper logic, you can just omit the below and return the body Object you got as a param
Map<String, Object> data = new HashMap<>();
data.put("serverTime", new Date(System.currentTimeMillis()));
if(body instanceof Map && ((Map)body).get("error") != null ){
data.put("isSuccess", false);
if(((Map)body).get("trace") != null){
((Map)body).remove("trace");
}
} else if (body instanceof ApiError && ((ApiError)body).getResponseStatusCode().equalsIgnoreCase("0")){
data.put("isSuccess", false);
} else {
data.put("isSuccess", true);
}
data.put("mainResponse",body);
return data;
}
}
In my case with Swagger 3.0.0 - especially io.springfox:springfox-boot-starter - specifying the spring-boot URL context-path solved this loop with "/null/swagger-resources/":
In application.properties: server.servlet.context-path=/
Or if you have an application.yml file:
server:
servlet:
context-path: /
Warning: It will change the base path of all web services, not only Swagger
I used spring boot, hawt.io, camel to test hawt.io dashboard
plugins {
id 'org.springframework.boot' version '1.5.10.RELEASE'
}
repositories {
mavenCentral()
flatDir {
dirs 'lib'
}
}
dependencies {
// Spring actuator, log4j2
compile("org.springframework.boot:spring-boot-starter-log4j2")
//Spring web
compile("org.springframework.boot:spring-boot-starter-web"){
exclude module: "spring-boot-starter-tomcat"
}
compile("org.springframework.boot:spring-boot-starter-jetty")
compile("org.eclipse.jetty:jetty-jaas")
compile("org.eclipse.jetty:jetty-http")
compile("org.springframework.boot:spring-boot-actuator")
//hawtio
compile("io.hawt:hawtio-springboot:1.5.10")
compile("io.hawt:hawtio-core:1.5.10")
and i had disabled authentication via
hawtio.authenticationEnabled=false
Here is the log:
18:00:13.489 [main] DEBUG ConfigManager - Property noCredentials401 is set to value false
18:00:13.490 [main] DEBUG ConfigManager - Property realm is set to value karaf
18:00:13.490 [main] DEBUG ConfigManager - Property role is set to value null
18:00:13.490 [main] DEBUG ConfigManager - Property roles is set to value null
18:00:13.490 [main] DEBUG ConfigManager - Property rolePrincipalClasses is set to value
18:00:13.490 [main] DEBUG ConfigManager - Property authenticationEnabled is set to value false
18:00:13.490 [main] DEBUG ConfigManager - Property noCredentials401 is set to value false
18:00:13.490 [main] DEBUG ConfigManager - Property authenticationContainerDiscoveryClasses is set to value io.hawt.web.tomcat.TomcatAuthenticationContainerDiscovery
18:00:13.490 [main] INFO AuthenticationFilter - Starting hawtio authentication filter, JAAS authentication disabled
18:00:13.500 [main] DEBUG ConfigManager - Property sessionTimeout is set to value 1800
18:00:13.500 [main] INFO LoginServlet - hawtio login is using 1800 sec. HttpSession timeout
When i open url http://localhost:8091/hawtio/index.html, it always be redirected to http://localhost:8091/hawtio/index.html#/login
How can i disable authentication?
According https://github.com/hawtio/hawtio/issues/1963, the issue should be fixed on 6 Dec 2015, but it's still there.
And according those 404 errors, it seems all requests are handled by spring mvc DispatcherServlet, and those servlets registered in HawtioManagementContextConfiguration are not worked as expected.
18:07:52.821 [qtp1016881733-22] DEBUG DispatcherServlet - DispatcherServlet with name 'dispatcherServlet' processing GET request for [/hawtio/keycloak/enabled]
18:07:52.821 [qtp1016881733-22] DEBUG RequestMappingHandlerMapping - Looking up handler method for path /hawtio/keycloak/enabled
18:07:52.821 [qtp1016881733-22] DEBUG RequestMappingHandlerMapping - Did not find handler method for [/hawtio/keycloak/enabled]
18:07:52.821 [qtp1016881733-22] DEBUG SimpleUrlHandlerMapping - Matching patterns for request [/hawtio/keycloak/enabled] are [/hawtio/**, /**]
18:07:52.821 [qtp1016881733-22] DEBUG SimpleUrlHandlerMapping - URI Template variables for request [/hawtio/keycloak/enabled] are {}
18:07:52.822 [qtp1016881733-22] DEBUG SimpleUrlHandlerMapping - Mapping [/hawtio/keycloak/enabled] to HandlerExecutionChain with handler [ResourceHttpRequestHandler [locations=[ServletContext resource [/], ServletContext resource [/app/], class path resource [hawtio-static/], class path resource [hawtio-static/app/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver#244d7ca5]]] and 1 interceptor
18:07:52.822 [qtp1016881733-22] DEBUG DispatcherServlet - Last-Modified value for [/hawtio/keycloak/enabled] is: -1
18:07:52.824 [qtp1016881733-22] DEBUG DispatcherServlet - DispatcherServlet with name 'dispatcherServlet' processing GET request for [/error]
18:07:52.824 [qtp1016881733-22] DEBUG RequestMappingHandlerMapping - Looking up handler method for path /error
18:07:52.825 [qtp1016881733-22] DEBUG RequestMappingHandlerMapping - Returning handler method [public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)]
18:07:52.825 [qtp1016881733-22] DEBUG DispatcherServlet - Last-Modified value for [/error] is: -1
18:07:52.833 [qtp1016881733-22] DEBUG ContentNegotiatingViewResolver - Requested media types are [text/html, text/html;q=0.8] based on Accept header types and producible media types [text/html])
18:07:52.833 [qtp1016881733-22] DEBUG BeanNameViewResolver - No matching bean found for view name 'error.html'
18:07:52.838 [qtp1016881733-22] DEBUG ContentNegotiatingViewResolver - Returning [org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$SpelView#150fc7a7] based on requested media type 'text/html'
18:07:52.838 [qtp1016881733-22] DEBUG DispatcherServlet - Rendering view [org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$SpelView#150fc7a7] in DispatcherServlet with name 'dispatcherServlet'
18:07:52.886 [qtp1016881733-22] DEBUG DispatcherServlet - Successfully completed request
18:07:52.887 [qtp1016881733-22] DEBUG DispatcherServlet - Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
18:07:52.887 [qtp1016881733-22] DEBUG DispatcherServlet - Successfully completed request
18:07:52.965 [qtp1016881733-47] DEBUG DispatcherServlet - DispatcherServlet with name 'dispatcherServlet' processing GET request for [/favicon.ico]
18:07:52.965 [qtp1016881733-47] DEBUG SimpleUrlHandlerMapping - Matching patterns for request [/favicon.ico] are [/**/favicon.ico]
18:07:52.965 [qtp1016881733-47] DEBUG SimpleUrlHandlerMapping - URI Template variables for request [/favicon.ico] are {}
18:07:52.965 [qtp1016881733-47] DEBUG SimpleUrlHandlerMapping - Mapping [/favicon.ico] 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/], class path resource []], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver#ec04917]]] and 1 interceptor
18:07:52.965 [qtp1016881733-47] DEBUG DispatcherServlet - Last-Modified value for [/favicon.ico] is: -1
18:07:52.969 [qtp1016881733-47] DEBUG DispatcherServlet - Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
18:07:52.969 [qtp1016881733-47] DEBUG DispatcherServlet - Successfully completed request
Mostly the reason is that you just forget the final required step to use Hawtio with Spring Boot. You need this line in your application.properties:
endpoints.jolokia.sensitive = false
Without this setting Jolokia endpoint always returns 401 for unauthenticated requests, thus causing redirects to the login page.
You can also refer to a working example of unauthenticated Hawtio with Spring Boot here:
https://github.com/hawtio/hawtio/tree/master/hawtio-sample-springboot
By the way, Hawtio 2.0 will be released very soon.
Finally, i found the root cause is that
management.port != server.port
I referenced this one SpringBootCamelStarter, i also used 8095 for management port and 8091 for server port, and i used the normal server port 8091 to access it, that's the issue, i should use management port 8095 to access hawtio dashboard. here is the clear description:https://github.com/hawtio/hawtio/tree/2.x/examples/springboot
I am exploring spring transactions and after going through the spring docs and the following link i still have few questions. If I have a parent method with Propogation.REQUIRED which is calling 3 methods with Propogation.REQUIRES_NEW as follows:
//#Transactional(isolation=Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
public Contact saveContactInSteps(Contact contact, String newFirstName, String newLastName, Date bDate) throws Exception {
contact.setFirstName(newFirstName);
try {
updateContactFirstName(contact);
} catch (Exception e) {
LOG.error("Contact first name could not be saved !!");
e.printStackTrace();
throw e;
}
contact.setLastName(newLastName);
try {
updateContactLastName(contact);
} catch (Exception e) {
LOG.error("Contact Last name could not be saved !!");
e.printStackTrace();
throw e;
}
contact.setBirthDate(bDate);
updateContactBday(contact);
return contact;
}
public Contact saveById(Contact contact) {
sessionFactory.getCurrentSession().saveOrUpdate(contact);
LOG.info("Contact " + contact + " saved successfully");
return contact;
}
//#Transactional(isolation=Isolation.READ_COMMITTED, propagation = Propagation.REQUIRES_NEW)
public Contact updateContactFirstName(Contact contact) throws Exception {
throw new Exception("Cannot update first name");
//sessionFactory.getCurrentSession().saveOrUpdate(contact);
//LOG.info("Contact First name saved successfully");
//return contact;
}
//#Transactional(isolation=Isolation.READ_COMMITTED, propagation = Propagation.REQUIRES_NEW)
public Contact updateContactLastName(Contact contact) throws Exception {
throw new Exception("Cannot update last name");
//sessionFactory.getCurrentSession().saveOrUpdate(contact);
//LOG.info("Contact " + contact + " saved successfully");
//return contact;
}
//#Transactional(isolation=Isolation.READ_COMMITTED, propagation = Propagation.REQUIRES_NEW)
public Contact updateContactBday(Contact contact) {
sessionFactory.getCurrentSession().saveOrUpdate(contact);
LOG.info("Contact Birth Date saved successfully");
return contact;
}
Whenever i process the parent method i.e. saveContactInSteps, even the last name is getting updated in database. I am not sure how that is happening. If i throw the exception from first child method nothing gets updated. Is it because of the fact that i am setting the attributes i.e. names and birthdate in the parent method ? Even if i am setting the attributes in the parent method, i am not letting the parent method complete as well. Does the isolation level play any part here ? I believe it's for concurrent transactions ? Is there something i am missing ?
EDIT 1:
After going through the article i did realize what i was missing. I needed AOP proxies in place which i have added as follows:
<aop:config>
<aop:pointcut
expression="execution(* org.pack.spring.transactions.ContactService.*(..))"
id="updateOperation" />
<aop:advisor pointcut-ref="updateOperation" advice-ref="saveUpdateAdvice" />
</aop:config>
<tx:advice id="saveUpdateAdvice">
<tx:attributes>
<tx:method name="update*" propagation="REQUIRES_NEW" isolation="DEFAULT" rollback-for="Exception"/>
<tx:method name="save*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception"/>
</tx:attributes>
</tx:advice>
Log output is as follows:
01:23:57.535 [main] DEBUG o.s.t.a.AnnotationTransactionAttributeSource - Adding transactional method 'ContactService.save' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
01:23:57.550 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.transaction.interceptor.TransactionInterceptor#0'
01:23:57.552 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'saveUpdateAdvice'
01:23:57.552 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating instance of bean 'saveUpdateAdvice'
01:23:57.552 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Eagerly caching bean 'saveUpdateAdvice' to allow for resolving potential circular references
01:23:57.553 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'transactionManager'
01:23:57.553 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating instance of bean '(inner bean)#56ac5c80'
01:23:57.553 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
01:23:57.553 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0'
01:23:57.557 [main] DEBUG o.s.t.i.NameMatchTransactionAttributeSource - Adding transactional method [update*] with attribute [PROPAGATION_REQUIRES_NEW,ISOLATION_DEFAULT,-Exception]
01:23:57.557 [main] DEBUG o.s.t.i.NameMatchTransactionAttributeSource - Adding transactional method [save*] with attribute [PROPAGATION_REQUIRED,ISOLATION_DEFAULT,-Exception]
01:23:57.557 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
01:23:57.557 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0'
01:23:57.557 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
01:23:57.557 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0'
01:23:57.558 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Finished creating instance of bean '(inner bean)#56ac5c80'
01:23:57.558 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Invoking afterPropertiesSet() on bean with name 'saveUpdateAdvice'
01:23:57.558 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Finished creating instance of bean 'saveUpdateAdvice'
01:23:57.568 [main] DEBUG o.s.a.a.a.AspectJAwareAdvisorAutoProxyCreator - Creating implicit proxy for bean 'springTxContactService' with 0 common interceptors and 3 specific interceptors
01:23:57.575 [main] DEBUG o.s.aop.framework.CglibAopProxy - Creating CGLIB proxy: target source is SingletonTargetSource for target object [org.pack.ch9.spring.transactions.hibernate.home.ContactService#598260a6]
01:23:57.654 [main] DEBUG o.s.aop.framework.CglibAopProxy - Unable to apply any optimisations to advised method: public org.pack.ch9.spring.transactions.hibernate.home.Contact org.pack.ch9.spring.transactions.hibernate.home.ContactService.save(org.pack.ch9.spring.transactions.hibernate.home.Contact)
01:23:57.654 [main] DEBUG o.s.t.a.AnnotationTransactionAttributeSource - Adding transactional method 'ContactService.saveContactInSteps' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
01:23:57.655 [main] DEBUG o.s.aop.framework.CglibAopProxy - Unable to apply any optimisations to advised method: public org.pack.ch9.spring.transactions.hibernate.home.Contact org.pack.ch9.spring.transactions.hibernate.home.ContactService.saveContactInSteps(org.pack.ch9.spring.transactions.hibernate.home.Contact,java.lang.String,java.lang.String,java.util.Date) throws java.lang.Exception
01:23:57.655 [main] DEBUG o.s.t.a.AnnotationTransactionAttributeSource - Adding transactional method 'ContactService.findAll' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
01:23:57.656 [main] DEBUG o.s.aop.framework.CglibAopProxy - Unable to apply any optimisations to advised method: public java.util.List org.pack.ch9.spring.transactions.hibernate.home.ContactService.findAll()
01:23:57.656 [main] DEBUG o.s.t.a.AnnotationTransactionAttributeSource - Adding transactional method 'ContactService.findById' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
01:23:57.656 [main] DEBUG o.s.aop.framework.CglibAopProxy - Unable to apply any optimisations to advised method: public org.pack.ch9.spring.transactions.hibernate.home.Contact org.pack.ch9.spring.transactions.hibernate.home.ContactService.findById(java.lang.Long)
01:23:57.657 [main] DEBUG o.s.t.a.AnnotationTransactionAttributeSource - Adding transactional method 'ContactService.saveById' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
01:23:57.657 [main] DEBUG o.s.aop.framework.CglibAopProxy - Unable to apply any optimisations to advised method: public org.pack.ch9.spring.transactions.hibernate.home.Contact org.pack.ch9.spring.transactions.hibernate.home.ContactService.saveById(org.pack.ch9.spring.transactions.hibernate.home.Contact)
01:23:57.657 [main] DEBUG o.s.t.a.AnnotationTransactionAttributeSource - Adding transactional method 'ContactService.updateContactFirstName' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
01:23:57.657 [main] DEBUG o.s.aop.framework.CglibAopProxy - Unable to apply any optimisations to advised method: public org.pack.ch9.spring.transactions.hibernate.home.Contact org.pack.ch9.spring.transactions.hibernate.home.ContactService.updateContactFirstName(org.pack.ch9.spring.transactions.hibernate.home.Contact) throws java.lang.Exception
01:23:57.658 [main] DEBUG o.s.t.a.AnnotationTransactionAttributeSource - Adding transactional method 'ContactService.updateContactLastName' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
01:23:57.658 [main] DEBUG o.s.aop.framework.CglibAopProxy - Unable to apply any optimisations to advised method: public org.pack.ch9.spring.transactions.hibernate.home.Contact org.pack.ch9.spring.transactions.hibernate.home.ContactService.updateContactLastName(org.pack.ch9.spring.transactions.hibernate.home.Contact) throws java.lang.Exception
01:23:57.658 [main] DEBUG o.s.t.a.AnnotationTransactionAttributeSource - Adding transactional method 'ContactService.updateContactBday' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
01:23:57.658 [main] DEBUG o.s.aop.framework.CglibAopProxy - Unable to apply any optimisations to advised method: public org.pack.ch9.spring.transactions.hibernate.home.Contact org.pack.ch9.spring.transactions.hibernate.home.ContactService.updateContactBday(org.pack.ch9.spring.transactions.hibernate.home.Contact)
01:23:57.659 [main] DEBUG o.s.t.a.AnnotationTransactionAttributeSource - Adding transactional method 'ContactService.setSessionFactory' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
01:23:57.660 [main] DEBUG o.s.aop.framework.CglibAopProxy - Unable to apply any optimisations to advised method: public void org.pack.ch9.spring.transactions.hibernate.home.ContactService.setSessionFactory(org.hibernate.SessionFactory)
01:23:57.661 [main] DEBUG o.s.t.a.AnnotationTransactionAttributeSource - Adding transactional method 'ContactService.getSessionFactory' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
01:23:57.661 [main] DEBUG o.s.aop.framework.CglibAopProxy - Unable to apply any optimisations to advised method: public org.hibernate.SessionFactory org.pack.ch9.spring.transactions.hibernate.home.ContactService.getSessionFactory()
01:23:57.661 [main] DEBUG o.s.aop.framework.CglibAopProxy - Found 'equals' method: public boolean java.lang.Object.equals(java.lang.Object)
01:23:57.662 [main] DEBUG o.s.aop.framework.CglibAopProxy - Unable to apply any optimisations to advised method: public java.lang.String java.lang.Object.toString()
01:23:57.698 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Finished creating instance of bean 'org.springframework.context.event.internalEventListenerFactory'
01:23:57.698 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0'
01:23:57.698 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'saveUpdateAdvice'
01:23:57.698 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'sessionFactory'
01:23:57.698 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'hibernateProperties'
01:23:57.698 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor'
01:23:57.698 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor'
01:23:57.699 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionalEventListenerFactory'
01:23:57.699 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
01:23:57.746 [main] DEBUG o.s.c.s.GenericXmlApplicationContext - Unable to locate LifecycleProcessor with name 'lifecycleProcessor': using default [org.springframework.context.support.DefaultLifecycleProcessor#21d1b321]
01:23:57.747 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'lifecycleProcessor'
01:23:57.750 [main] DEBUG o.s.c.e.PropertySourcesPropertyResolver - Could not find key 'spring.liveBeansView.mbeanDomain' in any property source
01:23:57.752 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'springTxContactService'
01:23:57.755 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'transactionManager'
01:23:57.762 [main] DEBUG o.s.o.h.HibernateTransactionManager - Creating new transaction with name [org.pack.ch9.spring.transactions.hibernate.home.ContactService.findById]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
01:23:57.962 [main] DEBUG o.s.o.h.HibernateTransactionManager - Opened new Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])] for Hibernate transaction
01:23:57.964 [main] DEBUG o.s.o.h.HibernateTransactionManager - Preparing JDBC Connection of Hibernate Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])]
01:23:57.965 [main] DEBUG o.s.j.d.DriverManagerDataSource - Creating new JDBC DriverManager Connection to [jdbc:mysql://localhost:3306/springorm]
01:23:57.977 [main] DEBUG o.s.jdbc.datasource.DataSourceUtils - Setting JDBC Connection [com.mysql.jdbc.JDBC4Connection#2a685eba] read-only
01:23:57.983 [main] DEBUG o.s.o.h.HibernateTransactionManager - Exposing Hibernate transaction as JDBC transaction [com.mysql.jdbc.JDBC4Connection#2a685eba]
Hibernate: select distinct contact0_.ID as ID1_0_0_, contacttel1_.ID as ID1_2_1_, hobby3_.HOBBY_ID as HOBBY_ID1_3_2_, contact0_.BIRTH_DATE as BIRTH_DA2_0_0_, contact0_.FIRST_NAME as FIRST_NA3_0_0_, contact0_.LAST_NAME as LAST_NAM4_0_0_, contact0_.VERSION as VERSION5_0_0_, contacttel1_.CONTACT_ID as CONTACT_5_2_1_, contacttel1_.TEL_NUMBER as TEL_NUMB2_2_1_, contacttel1_.TEL_TYPE as TEL_TYPE3_2_1_, contacttel1_.VERSION as VERSION4_2_1_, contacttel1_.CONTACT_ID as CONTACT_5_2_0__, contacttel1_.ID as ID1_2_0__, hobbies2_.CONTACT_ID as CONTACT_2_1_1__, hobbies2_.HOBBY_ID as HOBBY_ID1_1_1__ from contact contact0_ left outer join contact_tel_detail contacttel1_ on contact0_.ID=contacttel1_.CONTACT_ID left outer join contact_hobby_detail hobbies2_ on contact0_.ID=hobbies2_.CONTACT_ID left outer join hobby hobby3_ on hobbies2_.HOBBY_ID=hobby3_.HOBBY_ID where contact0_.ID=?
01:23:58.099 [main] DEBUG o.s.o.h.HibernateTransactionManager - Initiating transaction commit
01:23:58.101 [main] DEBUG o.s.o.h.HibernateTransactionManager - Committing Hibernate transaction on Session [SessionImpl(PersistenceContext[entityKeys=[EntityKey[org.pack.ch9.spring.transactions.hibernate.home.Contact#6], EntityKey[org.pack.ch9.spring.transactions.hibernate.home.ContactTelDetail#6], EntityKey[org.pack.ch9.spring.transactions.hibernate.home.ContactTelDetail#7]],collectionKeys=[CollectionKey[org.pack.ch9.spring.transactions.hibernate.home.Contact.contactTelDetails#6], CollectionKey[org.pack.ch9.spring.transactions.hibernate.home.Contact.hobbies#6]]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])]
01:23:58.103 [main] DEBUG o.s.jdbc.datasource.DataSourceUtils - Resetting read-only flag of JDBC Connection [com.mysql.jdbc.JDBC4Connection#2a685eba]
01:23:58.103 [main] DEBUG o.s.o.h.HibernateTransactionManager - Closing Hibernate Session [SessionImpl(PersistenceContext[entityKeys=[EntityKey[org.pack.ch9.spring.transactions.hibernate.home.Contact#6], EntityKey[org.pack.ch9.spring.transactions.hibernate.home.ContactTelDetail#6], EntityKey[org.pack.ch9.spring.transactions.hibernate.home.ContactTelDetail#7]],collectionKeys=[CollectionKey[org.pack.ch9.spring.transactions.hibernate.home.Contact.contactTelDetails#6], CollectionKey[org.pack.ch9.spring.transactions.hibernate.home.Contact.hobbies#6]]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])] after transaction
01:23:58.117 [main] DEBUG o.s.o.h.HibernateTransactionManager - Creating new transaction with name [org.pack.ch9.spring.transactions.hibernate.home.ContactService.saveContactInSteps]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
01:23:58.117 [main] DEBUG o.s.o.h.HibernateTransactionManager - Opened new Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])] for Hibernate transaction
01:23:58.117 [main] DEBUG o.s.o.h.HibernateTransactionManager - Preparing JDBC Connection of Hibernate Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])]
01:23:58.117 [main] DEBUG o.s.j.d.DriverManagerDataSource - Creating new JDBC DriverManager Connection to [jdbc:mysql://localhost:3306/springorm]
01:23:58.127 [main] DEBUG o.s.o.h.HibernateTransactionManager - Exposing Hibernate transaction as JDBC transaction [com.mysql.jdbc.JDBC4Connection#1daf3b44]
01:23:58.127 [main] DEBUG o.s.o.h.HibernateTransactionManager - Found thread-bound Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])] for Hibernate transaction
01:23:58.127 [main] DEBUG o.s.o.h.HibernateTransactionManager - Participating in existing transaction
01:23:58.127 [main] ERROR o.p.c.s.t.h.home.ContactService - Contact First name could not be saved !!
01:23:58.127 [main] ERROR o.p.c.s.t.h.home.ContactService - Contact Last name could not be saved !!
01:23:58.137 [main] INFO o.p.c.s.t.h.home.ContactService - Contact Birth Date saved successfully
01:23:58.138 [main] DEBUG o.s.o.h.HibernateTransactionManager - Initiating transaction commit
01:23:58.138 [main] DEBUG o.s.o.h.HibernateTransactionManager - Committing Hibernate transaction on Session [SessionImpl(PersistenceContext[entityKeys=[EntityKey[org.pack.ch9.spring.transactions.hibernate.home.Contact#6], EntityKey[org.pack.ch9.spring.transactions.hibernate.home.ContactTelDetail#6], EntityKey[org.pack.ch9.spring.transactions.hibernate.home.ContactTelDetail#7]],collectionKeys=[CollectionKey[org.pack.ch9.spring.transactions.hibernate.home.Contact.contactTelDetails#6], CollectionKey[org.pack.ch9.spring.transactions.hibernate.home.Contact.hobbies#6]]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])]
Note - I have removed the #Transactional annotations from the methods as i am relying on proxy to achieve the same.
From the logs, it seems that the proxies are getting created but again as pointed out in the comment, will the 3 methods invoked from saveContactInSteps not have a transaction against them as mentioned in the documentation :
In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target object, will not lead to an actual transaction at runtime even if the invoked method is marked with #Transactional. Also, the proxy must be fully initialized to provide the expected behaviour so you should not rely on this feature in your initialization code, i.e. #PostConstruct
Is there a way to get around this ? Is AspectJ the only solution ?
I have a small ajax request which is lead to exeption PUT http://localhost:8080/carwash/add 405 (Method Not Allowed). Can you explaim me where is a problem?
Ajax request:
$.ajax({
url: '/carwash/add',
dataType: 'json',
type: 'PUT',
success: function(data) {
this.setState({});
}.bind(this),
error: function(xhr, status, err) {
console.error('/carwash/add', status, err.toString());
}.bind(this)
})
My application is handeling by spring security which has the following configuration:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/login", "/logout", "/resources/*").permitAll()
.antMatchers("/owner").access("hasRole('ROLE_OWNER')")
.antMatchers("/admin").access("hasRole('ROLE_ADMIN')")
.antMatchers("/carwash").access("hasRole('ROLE_OWNER')")
.and().formLogin().loginPage("/login").successHandler(authenticationSuccessHandler)
.usernameParameter("username").passwordParameter("password")
.and().exceptionHandling().accessDeniedPage("/login?error");
}
NB: user that call ajax requst has role 'ROLE_OWNER' and can reach "/owner" and "/carwash" without problem.
Also my controller which is resposible for put request:
#RequestMapping(value = "/carwash/add", method = RequestMethod.POST)
#ResponseStatus(HttpStatus.OK)
#ResponseBody
public void addCarWashPOST(){
System.out.println("inside addCarWash");
}
#RequestMapping(value = "/carwash/add", method = RequestMethod.PUT)
#ResponseStatus(HttpStatus.OK)
#ResponseBody
public void addCarWashPUT(){
System.out.println("inside addCarWash");
}
All my application is based on spring boot therefore I have also log after this PUT request:
DEBUG 12640 --- [nio-8080-exec-9] o.s.web.servlet.DispatcherServlet : Successfully completed request
DEBUG 12640 --- [io-8080-exec-10] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing PUT request for [/login]
DEBUG 12640 --- [io-8080-exec-10] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /login
DEBUG 12640 --- [io-8080-exec-10] .m.m.a.ExceptionHandlerExceptionResolver : Resolving exception from handler [null]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'PUT' not supported
DEBUG 12640 --- [io-8080-exec-10] .w.s.m.a.ResponseStatusExceptionResolver : Resolving exception from handler [null]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'PUT' not supported
DEBUG 12640 --- [io-8080-exec-10] .w.s.m.s.DefaultHandlerExceptionResolver : Resolving exception from handler [null]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'PUT' not supported
WARN 12640 --- [io-8080-exec-10] o.s.web.servlet.PageNotFound : Request method 'PUT' not supported
DEBUG 12640 --- [io-8080-exec-10] o.s.web.servlet.DispatcherServlet : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
DEBUG 12640 --- [io-8080-exec-10] o.s.web.servlet.DispatcherServlet : Successfully completed request
DEBUG 12640 --- [io-8080-exec-10] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing PUT request for [/error]
DEBUG 12640 --- [io-8080-exec-10] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /error
DEBUG 12640 --- [io-8080-exec-10] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [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)]
DEBUG 12640 --- [io-8080-exec-10] o.s.web.cors.DefaultCorsProcessor : Skip CORS processing: request is from same origin
DEBUG 12640 --- [io-8080-exec-10] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Written [{timestamp=Wed Sep 14 20:17:20 CEST 2016, status=405, error=Method Not Allowed, exception=org.springframework.web.HttpRequestMethodNotSupportedException, message=Request method 'PUT' not supported, path=/carwash/add}] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter#78b6776e]
DEBUG 12640 --- [io-8080-exec-10] o.s.web.servlet.DispatcherServlet : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
DEBUG 12640 --- [io-8080-exec-10] o.s.web.servlet.DispatcherServlet : Successfully completed request
One more interesting issue, if substitute in ajax request type to POST the exeption will be different: /carwash/add parsererror SyntaxError: Unexpected token < in JSON at position 0
The log from spring boot for POST request:
DEBUG 13348 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/login]
DEBUG 13348 --- [nio-8080-exec-2] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /login
DEBUG 13348 --- [nio-8080-exec-2] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public java.lang.String biz.controllers.mvc.LoginController.login()]
DEBUG 13348 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Last-Modified value for [/login] is: -1
DEBUG 13348 --- [nio-8080-exec-2] o.s.w.servlet.view.BeanNameViewResolver : No matching bean found for view name 'login'
DEBUG 13348 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Rendering view [org.springframework.web.servlet.view.InternalResourceView: name 'login'; URL [WEB-INF/pages/login.html]] in DispatcherServlet with name 'dispatcherServlet'
DEBUG 13348 --- [nio-8080-exec-2] o.s.w.servlet.view.InternalResourceView : Forwarding to resource [WEB-INF/pages/login.html] in InternalResourceView 'login'
DEBUG 13348 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/WEB-INF/pages/login.html]
DEBUG 13348 --- [nio-8080-exec-2] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /WEB-INF/pages/login.html
DEBUG 13348 --- [nio-8080-exec-2] s.w.s.m.m.a.RequestMappingHandlerMapping : Did not find handler method for [/WEB-INF/pages/login.html]
DEBUG 13348 --- [nio-8080-exec-2] o.s.w.s.handler.SimpleUrlHandlerMapping : Matching patterns for request [/WEB-INF/pages/login.html] are [/**]
DEBUG 13348 --- [nio-8080-exec-2] o.s.w.s.handler.SimpleUrlHandlerMapping : URI Template variables for request [/WEB-INF/pages/login.html] are {}
DEBUG 13348 --- [nio-8080-exec-2] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapping [/WEB-INF/pages/login.html] to HandlerExecutionChain with handler [org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler#1aa2d29f] and 1 interceptor
DEBUG 13348 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Last-Modified value for [/WEB-INF/pages/login.html] is: -1
DEBUG 13348 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
DEBUG 13348 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Successfully completed request
DEBUG 13348 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Successfully completed request
and as I undestand from log, the application cannot No matching bean found for view name 'login' how ever I have a controller for #RequestMapping(value ={"/", "/login"}, method = RequestMethod.GET) and without problem can open page with link /login... What I miss ?
Controller for "/" and "/login"
#RequestMapping(value ={"/", "/login"}, method = RequestMethod.GET)
public String login() {
return "login";
}
Configuration:
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("WEB-INF/pages/");
resolver.setSuffix(".html");
return resolver;
}
To make an AJAX/JSON request with CSRF enabled you have to pass CSRF token as a HTTP Request Header, not a parameter or other data.
On the page, your meta tags should look like these:
<meta name="_csrf" content="${_csrf.token}"/>
<meta name="_csrf_header" content="${_csrf.headerName}"/>
Then, prepare values somewhere in the JS code:
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
Pass the CSRF token as a header:
$.ajax({
type: "PUT",
async: false,
url: '/carwash/add',
data: [your data],
beforeSend: function(xhr) {
// here it is
xhr.setRequestHeader(header, token);
},
success: function(obj) {
// ....
},
....
You can see more here
http://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html
When I access my app via browser I get an 404 (Whitelabel Error Page).
After searching around, I think it could be a problem with my sitemesh filter.
#Bean
public FilterRegistrationBean sitemesh() throws Exception {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(new MySiteMeshFilter());
return filterRegistrationBean;
}
MySitemeshFilter:
protected static class MySiteMeshFilter extends ConfigurableSiteMeshFilter {
protected void applyCustomConfiguration(SiteMeshFilterBuilder builder) {
builder.addDecoratorPath("/*", "/decorators/basic-theme.jsp");
}
}
What do you think? Thank you!
EDIT:
It could be also possible, that my Security Configuration is the problem:
#Configuration
#Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class ApplicationSecurity extends WebSecurityConfigurerAdapter {
#Autowired
private MongoTemplate mongoTemplate;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/", "/error").permitAll()
.antMatchers("/register*", "/login", "/lostPassword").anonymous()
.antMatchers("/admin","/admin**").hasRole("ADMIN")
.antMatchers("/user", "/user/**", "/offer/*", "/page", "/page/**").hasAnyRole("USER", "COMPANY_USER", "COMPANY_MASTER", "ADMIN")
.antMatchers("/company", "/company/**").hasAnyRole("COMPANY_USER", "COMPANY_MASTER", "ADMIN")
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").failureUrl("/login?error=true").usernameParameter("username").passwordParameter("password").loginProcessingUrl("/security_check")
.successHandler(new MyAuthenticationSuccessHandler(this.mongoTemplate));
http.logout().logoutUrl("/logout").invalidateHttpSession(true).logoutSuccessUrl("/");
}
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(new MyUserDetailsService(this.mongoTemplate)).passwordEncoder(new ShaPasswordEncoder(256));
}
}
EDIT 2:
The controllers are not resolved. Setting the #ComponentScan "basePackages" attribute helps. The controller-methods are now being executed. But it looks like spring boot cannot find my views(directory) to render the page.
EDIT 3:
This is a part of my logging output. Is there anything unusual? It starts with INFO log (log4j) "starting page" which I put in the method ("/") of my controller. The controller method belonging to the RequestMapping is fired, but I think spring boot cannot find the jsp.
2014-12-30 10:20:09.422 INFO 5884 --- [nio-8080-exec-3] c.l.c.controller.PublicController : starting page
2014-12-30 10:20:09.426 DEBUG 5884 --- [nio-8080-exec-3] o.s.w.s.v.ContentNegotiatingViewResolver : Requested media types are [text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8] based on Accept header types and producible media types [*/*])
2014-12-30 10:20:09.427 DEBUG 5884 --- [nio-8080-exec-3] o.s.w.servlet.view.BeanNameViewResolver : No matching bean found for view name 'home'
2014-12-30 10:20:09.427 DEBUG 5884 --- [nio-8080-exec-3] o.s.w.s.v.ContentNegotiatingViewResolver : Returning [org.springframework.web.servlet.view.JstlView: name 'home'; URL [/WEB-INF/views/home.jsp]] based on requested media type 'text/html'
2014-12-30 10:20:09.427 DEBUG 5884 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : Rendering view [org.springframework.web.servlet.view.JstlView: name 'home'; URL [/WEB-INF/views/home.jsp]] in DispatcherServlet with name 'dispatcherServlet'
2014-12-30 10:20:09.433 DEBUG 5884 --- [nio-8080-exec-3] o.s.web.servlet.view.JstlView : Forwarding to resource [/WEB-INF/views/home.jsp] in InternalResourceView 'home'
2014-12-30 10:20:09.435 DEBUG 5884 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/WEB-INF/views/home.jsp]
2014-12-30 10:20:09.436 DEBUG 5884 --- [nio-8080-exec-3] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /WEB-INF/views/home.jsp
2014-12-30 10:20:09.446 DEBUG 5884 --- [nio-8080-exec-3] s.w.s.m.m.a.RequestMappingHandlerMapping : Did not find handler method for [/WEB-INF/views/home.jsp]
2014-12-30 10:20:09.446 DEBUG 5884 --- [nio-8080-exec-3] o.s.w.s.handler.SimpleUrlHandlerMapping : Matching patterns for request [/WEB-INF/views/home.jsp] are [/**]
2014-12-30 10:20:09.446 DEBUG 5884 --- [nio-8080-exec-3] o.s.w.s.handler.SimpleUrlHandlerMapping : URI Template variables for request [/WEB-INF/views/home.jsp] are {}
2014-12-30 10:20:09.447 DEBUG 5884 --- [nio-8080-exec-3] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapping [/WEB-INF/views/home.jsp] 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#727d5eda]]] and 1 interceptor
2014-12-30 10:20:09.448 DEBUG 5884 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : Last-Modified value for [/WEB-INF/views/home.jsp] is: -1
2014-12-30 10:20:09.448 DEBUG 5884 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2014-12-30 10:20:09.448 DEBUG 5884 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : Successfully completed request
2014-12-30 10:20:09.449 DEBUG 5884 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : Successfully completed request
2014-12-30 10:20:09.450 DEBUG 5884 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/error]
2014-12-30 10:20:09.451 DEBUG 5884 --- [nio-8080-exec-3] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /error
2014-12-30 10:20:09.452 DEBUG 5884 --- [nio-8080-exec-3] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest)]
2014-12-30 10:20:09.452 DEBUG 5884 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : Last-Modified value for [/error] is: -1
2014-12-30 10:20:09.453 DEBUG 5884 --- [nio-8080-exec-3] o.s.w.s.v.ContentNegotiatingViewResolver : Requested media types are [text/html, text/html;q=0.8] based on Accept header types and producible media types [text/html])
2014-12-30 10:20:09.453 DEBUG 5884 --- [nio-8080-exec-3] o.s.w.s.v.ContentNegotiatingViewResolver : Returning [org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$SpelView#5dbc9982] based on requested media type 'text/html'
2014-12-30 10:20:09.453 DEBUG 5884 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : Rendering view [org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$SpelView#5dbc9982] in DispatcherServlet with name 'dispatcherServlet'
2014-12-30 10:20:09.454 DEBUG 5884 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : Successfully completed request
2014-12-30 10:20:09.480 DEBUG 5884 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/favicon.ico]
2014-12-30 10:20:09.481 DEBUG 5884 --- [nio-8080-exec-4] o.s.w.s.handler.SimpleUrlHandlerMapping : Matching patterns for request [/favicon.ico] are [/**/favicon.ico]
2014-12-30 10:20:09.481 DEBUG 5884 --- [nio-8080-exec-4] o.s.w.s.handler.SimpleUrlHandlerMapping : URI Template variables for request [/favicon.ico] are {}
2014-12-30 10:20:09.481 DEBUG 5884 --- [nio-8080-exec-4] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapping [/favicon.ico] to HandlerExecutionChain with handler [ResourceHttpRequestHandler [locations=[class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/], class path resource []], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver#1742114b]]] and 1 interceptor
2014-12-30 10:20:09.481 DEBUG 5884 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : Last-Modified value for [/favicon.ico] is: -1
2014-12-30 10:20:09.490 DEBUG 5884 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2014-12-30 10:20:09.491 DEBUG 5884 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : Successfully completed request
In my application.properties I added:
spring.view.prefix=/WEB-INF/views/
spring.view.suffix=.jsp
For any of you who stumbled here looking for an answer to 'o.s.w.servlet.view.BeanNameViewResolver : No matching bean found for view name 'home'', Spring has tried and failed to locate a view resolver for 'home'.
If it is pure html you want to serve, you need just return '/home.html' from your controller. Spring will look for this file under /src/main/resources/static and return a response accordingly.
For other ways to resolve views, read this excellent answer, How to map requests to HTML file in Spring MVC?