Trace Id not getting sent correctly between spring boot apps - spring-boot

I have a spring boot console app that sends a http request to a spring boot api, the trace id looks correct in the console app, but is a completely different trace id in the api side. Why would this happen? Do I need to inject something into the trace context in the console app? Thanks for any help!
Console app:
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
logger.info("right before setting header");
MultiValueMap<String, String> header = new LinkedMultiValueMap<>();
header.add("X-B3-TraceId", "b3c10720b744fa9d");
header.add("X-B3-SpanId", "b3c10720b744fa9d");
logger.info("right before rest template");
restTemplate
.exchange(builder.build(false).toUriString(), HttpMethod.POST,
new HttpEntity<>("some request body", header), String.class);
logger.info("after rest template");
console app log(b3c10720b744fa9d is expected trace id):
2020-11-13T18:49:41.686 INFO [-,b3c10720b744fa9d,,] 16268 --- [ main] c.m.f.s.common.impl.TrackingServiceImpl : right before setting header
2020-11-13T18:49:41.687 INFO [-,b3c10720b744fa9d,,] 16268 --- [ main] c.m.f.s.common.impl.TrackingServiceImpl : right before rest template
api:
#PostMapping("/trace")
public #ResponseBody ResponseEntity postTracking(
#RequestBody String jsonRequest, HttpServletRequest httpRequest) {
List<String> headers = Collections.list(httpRequest.getHeaderNames());
headers.forEach(header -> logger.info("Header {} Value {}", header, httpRequest.getHeader(header)));
api logs (now showing 221cd9ce3908aa1a as trace id):
2020-11-15 17:19:12.814 INFO [-,221cd9ce3908aa1a,221cd9ce3908aa1a,false] 22372 --- [nio-8081-exec-1] c.m.f.t.controller.TrackingController : Header accept Value text/plain, application/json, application/cbor, application/*+json,
2020-11-15 17:19:12.815 INFO [-,221cd9ce3908aa1a,221cd9ce3908aa1a,false] 22372 --- [nio-8081-exec-1] c.m.f.t.controller.TrackingController : Header content-type Value text/plain;charset=UTF-8
2020-11-15 17:19:12.815 INFO [-,221cd9ce3908aa1a,221cd9ce3908aa1a,false] 22372 --- [nio-8081-exec-1] c.m.f.t.controller.TrackingController : Header x-b3-traceid Value 221cd9ce3908aa1a
2020-11-15 17:19:12.815 INFO [-,221cd9ce3908aa1a,221cd9ce3908aa1a,false] 22372 --- [nio-8081-exec-1] c.m.f.t.controller.TrackingController : Header x-b3-spanid Value 221cd9ce3908aa1a
2020-11-15 17:19:12.815 INFO [-,221cd9ce3908aa1a,221cd9ce3908aa1a,false] 22372 --- [nio-8081-exec-1] c.m.f.t.controller.TrackingController : Header x-b3-sampled Value 0

Related

Why does Post request for an endpoint with same payload returns http 400 for url without trailing slash?

In my controller class , I have an annotated post request method like shown below
#RestController(value="/api")
public class ApiController{
#PostMapping("/post")
#ResponseStatus(HttpStatus.OK)
public ResponseObject postMethod(RequestObject obj){
//service calls
when I call my endpoint with
POST http://localhost:8989/api/post/
with payload my request succesfully hits my controller method.
On the contrary if I only change my request to url with no trailing slash
POST http://localhost:8989/api/post
with exact same payload I get following response from server
{
"timestamp": "2022-11-29T11:23:36.153+03:00",
"status": 400,
"error": "Bad Request",
"message": "",
"path": "/api/post"
}
I enable web logs for spring and below is my trace when I get http 400 from server
[2022-11-29 11:23:36,153] [CID:] [RID:] [http-nio-8989-exec-1] TRACE --- DispatcherServlet : "ERROR" dispatch for POST "/error", parameters={}, headers={masked} in DispatcherServlet 'dispatcherServlet'[2022-11-29 11:23:36,153] [CID:] [RID:] [http-nio-8989-exec-1] TRACE ---
RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#error(HttpServletRequest)
[2022-11-29 11:23:36,153] [CID:] [RID:] [http-nio-8989-exec-1] TRACE --- HandlerMethod : Arguments: [SecurityContextHolderAwareRequestWrapper[ FirewalledRequest[ org.apache.catalina.core.ApplicationHttpRequest#3660b306]]]
[2022-11-29 11:23:36,153] [CID:] [RID:] [http-nio-8989-exec-1] DEBUG --- HttpEntityMethodProcessor : Using 'application/json', given [application/json] and supported [application/xml;charset=UTF-8, text/xml;charset=UTF-8, application/+xml;charset=UTF-8, application/json, application/+json, application/x-jackson-smile]
[2022-11-29 11:23:36,154] [CID:] [RID:] [http-nio-8989-exec-1] TRACE --- HttpEntityMethodProcessor : Writing [{timestamp=Tue Nov 29 11:23:36 TRT 2022, status=400, error=Bad Request, message=, path=/api/loanaccount/cancelLimitTransaction}]
[2022-11-29 11:23:36,154] [CID:] [RID:] [http-nio-8989-exec-1] TRACE --- DispatcherServlet : No view rendering, null ModelAndView returned.
I was thinking that if it was a client error , I should have not be able to succesfully call it by just appending trailing slash to url.Because my payload didn't change. How should I troubleshoot this?

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.

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);
}
}

Spring integration (IntegrationFlowContext): Dynamically registering new paths to same websocket server

I was trying to implement spring websocket solution with JavaDsl by following the link i.e https://github.com/joshlong/techtips/tree/master/examples/spring-integration-4.1-websockets-example
And I successfully tested it by subscribing to the path(i.e /messages) with my stomp client.
Next, I tried the same thing by registering the integration flow with IntegrationFlowContext.
It executed successfully on the server-side, but when I tried to make a request by my stomp client I received an exception of 404 not found.
While going through the logs , i found that previously the "AbstractHandlerMapping" was mapping to SockJsHttpRequestHandler and now it is mapping to ResourceHttpRequestHandler
With Spring-managed integration flow (Successful)
DEBUG [http-nio-8081-exec-1] o.s.c.l.LogFormatUtils: GET "/messages/websocket", parameters={}
DEBUG [http-nio-8081-exec-1] o.s.w.s.h.AbstractHandlerMapping: Mapped to org.springframework.web.socket.sockjs.support.SockJsHttpRequestHandler#46185a1b
DEBUG [http-nio-8081-exec-1] o.s.w.s.s.s.AbstractSockJsService: Processing transport request: GET http://localhost:8081/messages/websocket
DEBUG [http-nio-8081-exec-1] o.s.w.s.FrameworkServlet: Completed 101 SWITCHING_PROTOCOLS
DEBUG [http-nio-8081-exec-1] o.s.w.s.h.LoggingWebSocketHandlerDecorator: New StandardWebSocketSession[id=e11b5ef5-d2e5-e5c7-819d-493f42f4a7c8, uri=ws://localhost:8081/messages/websocket]
And with IntegrationFlow context managed flow (Failure)
DEBUG [http-nio-8081-exec-1] o.s.c.l.LogFormatUtils: GET "/messages/websocket", parameters={}
DEBUG [http-nio-8081-exec-1] o.s.w.s.h.AbstractHandlerMapping: Mapped to ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]
DEBUG [http-nio-8081-exec-1] o.s.w.s.r.ResourceHttpRequestHandler: Resource not found
DEBUG [http-nio-8081-exec-1] o.s.w.s.FrameworkServlet: Completed 404 NOT_FOUND
DEBUG [http-nio-8081-exec-1] o.s.c.l.LogFormatUtils: "ERROR" dispatch for GET "/error", parameters={}
DEBUG [http-nio-8081-exec-1] o.s.w.s.h.AbstractHandlerMapping: Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#error(HttpServletRequest)
DEBUG [http-nio-8081-exec-1] o.s.w.s.m.m.a.AbstractMessageConverterMethodProcessor: Using 'application/json', given [*/*] and supported [application/json, application/*+json, application/json, application/*+json]
DEBUG [http-nio-8081-exec-1] o.s.c.l.LogFormatUtils: Writing [{timestamp=Tue Feb 25 17:06:58 IST
You have a different Mapped to ... because of getHandler(HttpServletRequest request) logic in the AbstractHandlerMapping:
Object handler = getHandlerInternal(request);
if (handler == null) {
handler = getDefaultHandler();
}
if (handler == null) {
return null;
}
// Bean name or resolved handler?
if (handler instanceof String) {
String handlerName = (String) handler;
handler = obtainApplicationContext().getBean(handlerName);
}
HandlerExecutionChain executionChain = getHandlerExecutionChain(handler, request);
if (logger.isTraceEnabled()) {
logger.trace("Mapped to " + handler);
}
We don't support dynamic WS endpoints because we don't scan them in the internal WebSocketHandlerMappingFactoryBean.
Feel free to raise a GH issue https://github.com/spring-projects/spring-integration/issues and we will take a look what we can do for that.

Spring security lead to error for PUT and POST request through Ajax

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

Resources