spring boot 1.4 jsp page not evaluated Forward InternalViewResolver - spring

After 2 days of investigation, and looking a lot of answers about my issue, I cannot solve it.
I am not expert of spring framework.
Entry point :
I have generate a jhipster project a year ago. I want to embed jsp pages in my project.
I'm using spring boot 1.4 in a maven project
I have include dependency following :
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
I have created a new servlet in WebConfigurer class which implements ServletContextInitializer.onStartup and created a file named servletJsp-servlet.xml in a WEB-INF resources folder.
The xml instanciate InternalViewResolver with prefix /mesPages/ and suffix=.jsp
I created also a controller :
#Controller
public class TestJspController {
#RequestMapping(value = "/jsp/bbb")
public ModelAndView serveLog4jAdmin() {
return new ModelAndView("log4jAdmin");
}
}
I stick here : (see log below)
The logs say that :
Controller is well called
It returns well the ModelAndView
Launch Forward to resource [/mesPagesJsps/log4jAdmin.jsp] from InternalResourceView 'log4jAdmin'
But after that, instead of getting it and rendering it, no stacktrace and try to resolve jsp page with another servlet : dispatcherServlet (I believe this is the defaut spring autoconfigured and created) spring servlet.
The dispatcherServlet is successfull in getting it because I have put my folder mesPages (which contains my jsps) every where in the project (META-INF, WEB-INF, root folders) of resources and webapp
Finally, the jsp page is not evaluated, and broswer give me to download it as "application/octet-stream".
Previously before putting jsp on all these folders, I uses to have the same controller behaviour but ending with 404 error (blank page).
I really don't understand why app behave like this.
I have another spring (not boot) webapp which works well.
I tried to debug, but to complex for me ... When debugging I was just detect that the requestDispatcher cannot dispatch Forward because there is no Handler with type FORWARD in some 'next' variables.
I think this is the cause ...
If someone has some anwser, I would be very happy
I can give any other information that is required.
The concerned part of log :
[ XNIO-3 task-2] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'servletJSP' processing GET request for [/jsps/jsp/bbb]
[ XNIO-3 task-2] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /jsp/bbb
[ XNIO-3 task-2] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public org.springframework.web.servlet.ModelAndView fr.softeam.testify.web.rest.jsp.TestJspController.serveLog4jAdmin()]
[ XNIO-3 task-2] o.s.web.servlet.DispatcherServlet : Last-Modified value for [/jsps/jsp/bbb] is: -1
[ XNIO-3 task-2] o.s.web.servlet.DispatcherServlet : Rendering view [org.springframework.web.servlet.view.JstlView: name 'log4jAdmin'; URL [/mesPagesJsps/log4jAdmin.jsp]] in DispatcherServlet with name 'servletJSP'
[ XNIO-3 task-2] o.s.web.servlet.view.JstlView : Forwarding to resource [/mesPagesJsps/log4jAdmin.jsp] in InternalResourceView 'log4jAdmin'
[ XNIO-3 task-2] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/mesPagesJsps/log4jAdmin.jsp]
[ XNIO-3 task-2] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /mesPagesJsps/log4jAdmin.jsp
[ XNIO-3 task-2] s.w.s.m.m.a.RequestMappingHandlerMapping : Did not find handler method for [/mesPagesJsps/log4jAdmin.jsp]
[ XNIO-3 task-2] o.s.w.s.handler.SimpleUrlHandlerMapping : Matching patterns for request [/mesPagesJsps/log4jAdmin.jsp] are [/**]
[ XNIO-3 task-2] o.s.w.s.handler.SimpleUrlHandlerMapping : URI Template variables for request [/mesPagesJsps/log4jAdmin.jsp] are {}
[ XNIO-3 task-2] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapping [/mesPagesJsps/log4jAdmin.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#1774cad]]] and 1 interceptor
[ XNIO-3 task-2] o.s.web.servlet.DispatcherServlet : Last-Modified value for [/mesPagesJsps/log4jAdmin.jsp] is: -1
[ XNIO-3 task-2] o.s.web.servlet.DispatcherServlet : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
[ XNIO-3 task-2] o.s.web.servlet.DispatcherServlet : Successfully completed request
[ XNIO-3 task-2] o.s.web.servlet.DispatcherServlet : Successfully completed request

Because I wanted a new path for all jsps (I know we can do that in controller too), and I feared that keep the same servlet for serving both angular frontend and jsp.
Because jhipster generate a lot of class which parameterize (HttpSecurity, ), I though that create a new servlet (without any custom parameters) could be more simple and avoid problems.
DispatcherServlet.render()
--> resolveViewName() qui retourne une JstlView
--> JstlView.render()
--> renderMergedOutputModel()
dispatcherPath = prepareForRendering(request, response); // dispatcherPath = /mesPagesJsps/log4jAdmin.jsp
RequestDispatcher rd = getRequestDispatcher() // rd.path=/mesPagesJsps/log4jAdmin.jsp and rd.servletChain=another DispatcherServlet !!! why ??? named dispatcherServlet, which is not my jsp servlet
--> rd.forward()
--> forwardImpl()
--> response.resetBuffer()
newServletPath = newRequestUri = /mesPagesJsps/log4jAdmin.jsp
pathMatch.servletChain still contains wrond servlet : dispatcherServlet instead of jspServlet
--> servletContext.getDeployment().getServletDispatcher().dispatchToPath(requestImpl.getExchange(), pathMatch, DispatcherType.FORWARD);
--> servletInitialDispatcher.dispatchToPath()
servletRequestContext.servletChain correspond to my servletJSP
--> dispatchRequest( pathInfo = /mesPagesJsps/log4jAdmin.jsp, dispatcherType=FORWARD, servletChain is not my jsp servletJSP but dispatcherServlet )
Exchange is : HttpServerExchange{ GET /mesPagesJsps/log4jAdmin.jsp request {Accept=[text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8], Accept-Language=[fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3], Cache-Control=[max-age=0], Accept-Encoding=[gzip, deflate], User-Agent=[Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0], Connection=[keep-alive], Cookie=[CSRF-TOKEN=f6843de6-766d-4259-8a84-242c020420bc; JSESSIONID=VrVa7HNkUmzv_JM_cAhwyrfGWGCcrjZSltoQh2EJ], Upgrade-Insecure-Requests=[1], Host=[localhost:8080]} response {X-Application-Context=[testify_jhi:swagger,dev:8080], Content-Language=[fr-]}}
--> servletInitialHandler.dispatchRequest()
setCurrentServlet( WITH SERVLET dispatcherServlet and NOT servletJSP )
--> next.handleRequest(exchange) : next is here a SessionRestoringHandler
--> next.handleRequest(exchange) : next is here PredicateHandler. This called because a sessionId has been found ...
--> predicate.resolve() with a predicate of type REQUEST (I think this bad) --> which return falseHandler
--> next.handleRequest() --> with again a predicate of type REQUEST --> which return falseHandler
--> next.handleRequest() --> with a ServletDispatchingHandler whose ServletChain is the wrong servlet : dispatcherServlet instead of servletJSP
the dispatcher type is still FORWARD here but its to late because I thing the wrong servlet process the request

Because I wanted a new path for all jsps (I know we can do that in controller too), and I feared that keep the same servlet for serving both angular frontend and jsp.
Because jhipster generate a lot of class which parameterize (HttpSecurity, ), I though that create a new servlet (without any custom parameters) could be more simple and avoid problems.
For example there is HttpSecurity, and this :
public void customize(ConfigurableEmbeddedServletContainer container) {
MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
// IE issue, see https://github.com/jhipster/generator-jhipster/pull/711
mappings.add("html", "text/html;charset=utf-8");
// CloudFoundry issue, see https://github.com/cloudfoundry/gorouter/issues/64
mappings.add("json", "text/html;charset=utf-8");
//mappings.add("jsp", "text/html;charset=utf-8"); // si je fais ça, en combinaisais avec le addResourcesHandler(), alors la page jsp est affichée dans le navigateur
container.setMimeMappings(mappings);
// When running in an IDE or with ./mvnw spring-boot:run, set location of the static web assets.
setLocationForStaticAssets(container);
}

I finally found and solve the problem (solution bellow), it seems to have link with some undertow elements, which is not configured by defaut to initialize japser. JasperInitializer was never initialized.
If someone want explain me he is welcome :)
You must add this code in a configuration class.
#Bean
public TomcatContextCustomizer tomcatContextCustomizer() {
return new TomcatContextCustomizer() {
#Override
public void customize(Context context) {
context.addServletContainerInitializer(new JasperInitializer(), null);
}
};
}
#Bean
public TomcatEmbeddedServletContainerFactory tomcatContainerFactory() {
TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
factory.setTomcatContextCustomizers(Arrays.asList(new TomcatContextCustomizer[] { tomcatContextCustomizer() }));
return factory;
}
Another question : I have no xml files in my spring boot application, except one :
Is it possible to replace my servlet web application context definition that I build with my WEB-INF/servletJSP-servlet.xml by java/annotation definition ?

Related

Error while configuring View Resolver for mustache template engine

I have the following configuration file in spring-boot project :
#Configuration
public class AppConfig {
#Bean
public ViewResolver mustacheViewResolver() {
MustacheViewResolver viewResolver = new MustacheViewResolver();
viewResolver.setPrefix("/templates/");
viewResolver.setSuffix(".mustache");
viewResolver.setOrder(1);
return viewResolver;
}
}
When I run my application, I am getting the following error:
Description:
The bean 'mustacheViewResolver', defined in class path resource [org/springframework/boot/autoconfigure/mustache/MustacheServletWebConfiguration.class], could not be registered. A bean with that name has already been defined in class path resource [com/example/demo/AppConfig.class] and overriding is disabled.
Action:
Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true
I am not sure if I am configuring the view Resolver properly
Error after removing the configuration class:
o.s.w.s.v.ContentNegotiatingViewResolver : Selected '*/*' given [*/*]
o.s.w.servlet.view.InternalResourceView : View name 'tweets.mustache', model {tweets=null}
o.s.w.servlet.view.InternalResourceView : Forwarding to [tweets.mustache]
o.s.web.servlet.DispatcherServlet : "FORWARD" dispatch for GET "/tweets.mustache?email=tim#gmail.com", parameters={masked}
o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler [classpath [META-INF/resources/], classpath [resources/], classpath [static/], classpath [public/], ServletContext [/]]
o.s.w.s.r.ResourceHttpRequestHandler : Resource not found
o.s.web.servlet.DispatcherServlet : Exiting from "FORWARD" dispatch, status 404
o.s.web.servlet.DispatcherServlet : Completed 404 NOT_FOUND
o.s.web.servlet.DispatcherServlet : "ERROR" dispatch for GET "/error?email=tim#gmail.com", parameters={masked}
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#error(HttpServletRequest)
o.s.w.s.m.m.a.HttpEntityMethodProcessor : Using 'application/json', given [*/*] and supported [application/json, application/*+json, application/json, application/*+json]
o.s.w.s.m.m.a.HttpEntityMethodProcessor : Writing [{timestamp=, status=404, error=Not Found, path=/tweet2}]
o.s.web.servlet.DispatcherServlet : Exiting from "ERROR" dispatch, status 404
#GetMapping("/tweet2")
public ModelAndView getTweetsByEmail(#RequestParam String email) {
HQLExample.insertRecords();
ModelAndView modelAndView = new ModelAndView("tweets.mustache");
List<Tweet> tweets = tweetMap.get(email);
modelAndView.getModel().put("tweets",tweets);
return modelAndView;
}
Assuming you have added spring-boot-starter-mustache as a dependency (to easily include all needed dependencies). When Spring Boot detects Mustache on the classpath it will automatically configure the MustacheViewResolver which will load Mustache templates from /templates on the classpath. The files should end with .mustache.
With this in mind, just remove your AppConfig class as it interferes with the auto configuration.
In your controller the name of the view is the name you have but without the .mustache that will be added by the ViewResolver.
So in short you should remove things and it will work. Do more with less in this case.

Prevent DispatcherServlet from logging endpoint in Spring Boot Actuator

I've turned off the Logging for an actuator endpoint, but DispatcherServlet (and RequestReponseBodyMethodProcessor) still log the mapping and response.
How can i prevent this logging for just this one endpoint? I've already turned them off
management.logging.level.org.springframework.boot.actuate.health=OFF
logging.level.org.springframework.boot.actuate.health=OFF
org.springframework.boot.actuate.health.Logger=OFF
but it still comes like this:
2020-05-06 17:14:01.545 DEBUG 58588 --- [nio-9095-exec-5] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/health]
2020-05-06 17:14:01.552 DEBUG 58588 --- [nio-9095-exec-5] o.s.web.servlet.DispatcherServlet : Last-Modified value for [/health] is: -1
2020-05-06 17:14:01.848 DEBUG 58588 --- [nio-9095-exec-5] m.m.a.RequestResponseBodyMethodProcessor : Written [UP {}] as "application/vnd.spring-boot.actuator.v1+json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter#144409aa]
2020-05-06 17:14:01.849 DEBUG 58588 --- [nio-9095-exec-5] o.s.web.servlet.DispatcherServlet : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2020-05-06 17:14:01.849 DEBUG 58588 --- [nio-9095-exec-5] o.s.web.servlet.DispatcherServlet : Successfully completed request
Just set in application.properties log level to WARN
logging.level.org.springframework.web.servlet.DispatcherServlet=WARN
logging.level.org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor=WARN
please check if this solves the issue
In annotation SpringBootApplication add exclude DispatcherServletAutoConfiguration class in main class.
#SpringBootApplication(exclude = { DispatcherServletAutoConfiguration.class })
reference :
Switch off DispatcherServlet on Spring Boot
If your goal is logging all the incoming HTTP requests, the solution is not enabling DEBUG logging level in the DispatcherServlet.
You can define a bean of type:
org.springframework.web.filter.CommonsRequestLoggingFilter
and override the method:
org.springframework.web.filter.CommonsRequestLoggingFilter.shouldLog(HttpServletRequest)
So you can decide which requests are logged or not.
Obviously, you must set the logging level of the filter to DEBUG:
logging.level.org.springframework.web.filter.CommonsRequestLoggingFilter=DEBUG
More info at Baeldubg site.
Just use the below in the .properties
logging.level.org.springframework.web=WARN
Sorry to necro a thread, but here's the answer I came up with:
Create a bean as below:
package com.package.your.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.CommonsRequestLoggingFilter;
import javax.servlet.http.HttpServletRequest;
#Configuration
public class RequestLoggingFilterConfig {
#Bean
public CommonsRequestLoggingFilter logFilter() {
CommonsRequestLoggingFilter filter = new CommonsRequestLoggingFilter() {
#Override
public void beforeRequest(HttpServletRequest request, String message) {
// Don't log any actuator endpoints
if (!request.getRequestURI().contains("actuator")) {
this.logger.debug(message);
}
}
#Override
public void afterRequest(HttpServletRequest request, String message) {
// Empty because it logs the same content as beforeRequest
}
};
filter.setBeforeMessagePrefix("");
filter.setBeforeMessageSuffix("");
filter.setIncludeClientInfo(true);
filter.setIncludeHeaders(true);
filter.setIncludePayload(true);
filter.setIncludeQueryString(true);
return filter;
}
}
Add the following to applications.properties instead of setting DispatcherServlet to debug:
logging.level.com.package.your.config.RequestLoggingFilterConfig=debug
This works beautifully as intended. Filtering is controlled by the if statement in the beforeRequest method.

SpringBoot cannot find handler method

I have a basic SpringBoot app. using Spring Initializer, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file.
this is the main class
#SpringBootApplication
public class TdkApplication {
public static void main(String[] args) {
SpringApplication.run(TdkApplication.class, args);
}
}
This is a controller
#Controller
public class MockupIndexController {
#RequestMapping("/mockup/index")
public String welcome(Map<String, Object> model) {
return "mockups/index";
}
}
This my pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>com.tdk.iot.core</groupId>
<artifactId>tdk-core</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
But when I put this in the URL:
http://localhost:8080/mockup/index
I got the following log in the console
o.s.web.servlet.DispatcherServlet : Servlet 'dispatcherServlet' configured successfully
o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/mockup/index]
s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /mockup/index
s.w.s.m.m.a.RequestMappingHandlerMapping : Did not find handler method for [/mockup/index]
o.s.w.s.handler.SimpleUrlHandlerMapping : Matching patterns for request [/mockup/index] are [/**]
o.s.w.s.handler.SimpleUrlHandlerMapping : URI Template variables for request [/mockup/index] are {}
o.s.w.s.handler.SimpleUrlHandlerMapping : Mapping [/mockup/index] 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#8b91134]]] and 1 interceptor
o.s.web.servlet.DispatcherServlet : Last-Modified value for [/mockup/index] is: -1
o.s.web.servlet.DispatcherServlet : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
o.s.web.servlet.DispatcherServlet : Successfully completed request
o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/error]
s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /error
I assume your controller class is not found during scanning cause it is in a package that will not be scanned by default. I guess your application is in something like com.tdk.app and your controller in com.tdk.controller, right? If yes just move the app one level up to com.tdk and your issue should go away.
The controller package should be the one level bottom package of "TdkApplication" if your "TdkApplication" is in com.test package, Then your controller should be under com.test.controller package. Means one level down package when we comparing with application package
following will work
App package should be like com.app
then controller would be com.app.controller.
if you use it like below then spring would be unable to scan the controller
App package: com.app.main
controller:com.app.controller

Responses with characteristics not acceptable according to the request "accept" headers - HTTP Status 406 - spring-boot

Any takers to resolve this issue for USD50, please contact
I am getting the not acceptable according to the request "accept" headers, however, I believe I have done everything right, I could. Can someone help to resolve this issue. I am using Spring 4.1.
The OBJECTIVE is to be able to return the response in the text/xml format. if I remove produces=text/xml directive then my application works i.e. no error, but the source system treat the response in an unexpected way.
Request coming in as follows:
curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -H "Authorization: Basic YWRtaW46YWRtaW4=" -H "Cache-Control: no-cache" -H "Postman-Token: 78637a4f-e153-4242-c922-96757d01442a" -d Then values....
My Pom:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.0.rc1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.0.rc1</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
My Controller have the following notations:
#RestController
#RequestMapping("/test")
#EnableWebMvcMy Controller has the following notations:
Main Class has the following notation
#Configuration
#EnableAutoConfiguration
#ComponentScan
I DO NOT have the application context xml, as i am using #Autowired
on my end-point method as follows
#RequestMapping(value="/IDEA", headers = {"Accept=*/*"}, produces="text/xml", method= {RequestMethod.POST, RequestMethod.GET})
#Autowired
public MyResult processMyRequest(HttpServletRequest request)
Current Log
2016-08-11 13:38:04.076 INFO 89535 --- [nio-8080-exec-2] c.f.fnocc.injestor.MyController : POST CALLED
2016-08-11 13:38:04.079 INFO 89535 --- [nio-8080-exec-2] c.f.fnocc.injestor.MyController : Request received from ipAddress:0:0:0:0:0:0:0:1
2016-08-11 13:38:04.082 INFO 89535 --- [nio-8080-exec-2] c.f.fnocc.injestor.MyController : REQUEST INFORMATION: [
2016-08-11 13:38:04.084 INFO 89535 --- [nio-8080-exec-2] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#af3b571: startup date [Thu Aug 11 13:38:04 BST 2016]; root of context hierarchy
2016-08-11 13:38:04.095 INFO 89535 --- [nio-8080-exec-2] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2016-08-11 13:38:04.119 INFO 89535 --- [nio-8080-exec-2] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#142abfa2: startup date [Thu Aug 11 13:38:04 BST 2016]; root of context hierarchy
2016-08-11 13:38:04.124 INFO 89535 --- [nio-8080-exec-2] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2016-08-11 13:38:04.150 ERROR 89535 --- [nio-8080-exec-2] c.f.fnocc.injestor.MyController : Error has occurred.
The first issue I see is #EnableWebMvc should be specified on the main class alongside the #Configuration but I don't think it is even needed when you are specifying #EnableAutoConfiguration.
The other issue is the #RequestMapping() has an attribute for consumes which is what you should probably be using instead of looking for the accept header. Reason for that is the accept header normally includes multiple media types not just */* as such the check for equality on that header wouldn't be there.
* Update * I was wrong on the consumes that is used to interpreting the Content-Type header and not the Accept header. Spring tries to match the produces to the Accept header to determine if the method can respond to the incoming request. That makes more sense why you are getting the 406 error as Spring sees the method trying to output text/xml but the request probably doesn't accept that content type in the Accept header.
To further troubleshoot you can setup a request logger to see the specifics on how the request is coming into the service to determine if there is something that is causing Spring to not process it properly. If you add the following bean and enable DEBUG level logging on org.springframework.web.filter.CommonsRequestLoggingFilterthen you can see.
#Bean
public Filter logFilter() {
CommonsRequestLoggingFilter filter = new CommonsRequestLoggingFilter();
filter.setIncludeQueryString(false);
filter.setIncludePayload(false);
filter.setIncludeHeaders(true);
return filter;
}
If you can update your question with that request log that would help to troubleshoot.
* Update #2 * Was able to reproduce the error. Adding DEBUG logging level for org.springframework.web showed the issue more clearly.
2016-08-11 02:26:58.242 DEBUG 82904 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/test/IDEA]
2016-08-11 02:26:58.244 DEBUG 82904 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /test/IDEA
2016-08-11 02:26:58.247 DEBUG 82904 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public ca.tuatara.stackoverflow.MyController$MyResult ca.tuatara.stackoverflow.MyController.processMyRequest(javax.servlet.http.HttpServletRequest)]
2016-08-11 02:26:58.247 DEBUG 82904 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Last-Modified value for [/test/IDEA] is: -1
2016-08-11 02:26:58.258 DEBUG 82904 --- [nio-8080-exec-1] .m.m.a.ExceptionHandlerExceptionResolver : Resolving exception from handler [public ca.tuatara.stackoverflow.MyController$MyResult ca.tuatara.stackoverflow.MyController.processMyRequest(javax.servlet.http.HttpServletRequest)]: org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
The Could not find acceptable representation is the key. By specifying that you want XML you must include a library to marshall the object as XML as described on the Spring MVC docs. Adding the dependency for:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
Made it work for my sample application. Give that a try!

Define ParameterizableViewController to auto redirect path url with view

I'm using spring boot 1.2.1 and I would like to configure a ParameterizableViewController like I was doing in xml style :
for example before I was doing :
<mvc:view-controller path="/ie7"/>
That code redirects an url like http://mywebsite.com/mycontext/ie7 to a jsp placed in /WEB-INF/views/ie7.jsp without creating a controller directly.
I would like to do the same thing with spring boot. After checking on the net I had this in my config file :
#Bean(name = "ie7Controller")
public ParameterizableViewController getIe7ControllerView() {
ParameterizableViewController viewController = new ParameterizableViewController();
viewController.setViewName("ie7");
return viewController;
}
In my application.properties I configure the view like this :
spring.view.prefix=/WEB-INF/views/
spring.view.suffix=.jsp
I try to add also :
#Bean
public InternalResourceViewResolver getViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
But when I try http://mywebsite.com/mycontext/ie7 I got a 404.
Here is the logs I got :
During app launch :
Rejected bean name 'ie7Controller': no URL paths identified
When I try to call the page :
2015-02-11 09:01:42.693 DEBUG 1160 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/stdapps/ie7]
2015-02-11 09:01:42.699 DEBUG 1160 --- [nio-8080-exec-2] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /ie7
2015-02-11 09:01:42.704 DEBUG 1160 --- [nio-8080-exec-2] s.w.s.m.m.a.RequestMappingHandlerMapping : Did not find handler method for [/ie7]
2015-02-11 09:01:42.706 DEBUG 1160 --- [nio-8080-exec-2] o.s.w.s.handler.SimpleUrlHandlerMapping : Matching patterns for request [/ie7] are [/**]
2015-02-11 09:01:42.708 DEBUG 1160 --- [nio-8080-exec-2] o.s.w.s.handler.SimpleUrlHandlerMapping : URI Template variables for request [/ie7] are {}
2015-02-11 09:01:42.712 DEBUG 1160 --- [nio-8080-exec-2] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapping [/ie7] 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#39689892]]] and 1 interceptor
2015-02-11 09:01:42.714 DEBUG 1160 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Last-Modified value for [/stdapps/ie7] is: -1
do I miss something ? I feel like I need to specify and url somewhere, I try to add #RequestMapping(value="ie7") with #Bean(name = "ie7Controller") with no luck
thanks for your help
If I understand your requirement correctly then the following code should do the trick:
#Configuration
#ComponentScan
#EnableAutoConfiguration
#EnableWebMvc
public class Application extends WebMvcConfigurerAdapter {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/ie7").setViewName("ie7");
};
}

Resources