Error while configuring View Resolver for mustache template engine - spring-boot

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.

Related

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

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

Gradle Spring Boot Application in IntelliJ is not recognizing web resources in WEB-INF folder

This is a new issue that derived from a previous question I had. I am writing a Spring Boot Application which is using a .jsp as the mvc view. My folder structure is:
My application.properties is as follows:
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
spring.mvc.view.prefix= /WEB-INF/view/
spring.mvc.view.suffix= .jsp
Finally, my HomeController.java is as follows:
#Controller
#Slf4j
public class HomeController {
#RequestMapping(value="/", method= RequestMethod.GET)
public String showPage()
{
return "main-menu";
}
}
The program should render the main-menu.jsp file on my home page at localhost:8080, but instead I get an error. Here is the stack trace for the error:
2021-06-28 20:40:12.243 DEBUG 27388 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : GET "/", parameters={}
2021-06-28 20:40:12.245 DEBUG 27388 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.example.springdemo.mvc.HomeController#showPage()
2021-06-28 20:40:12.257 DEBUG 27388 --- [nio-8080-exec-1] o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, application/xhtml+xml, image/avif, image/webp, image/apng, application/xml;q=0.9, application/signed-exchange;v=b3;q=0.9, */*;q=0.8]
2021-06-28 20:40:12.257 DEBUG 27388 --- [nio-8080-exec-1] o.s.w.servlet.view.InternalResourceView : View name 'main-menu', model {}
2021-06-28 20:40:12.258 DEBUG 27388 --- [nio-8080-exec-1] o.s.w.servlet.view.InternalResourceView : Forwarding to [/WEB-INF/view/main-menu.jsp]
2021-06-28 20:40:12.261 DEBUG 27388 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : "FORWARD" dispatch for GET "/WEB-INF/view/main-menu.jsp", parameters={}
2021-06-28 20:40:12.263 DEBUG 27388 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler [Classpath [META-INF/resources/], Classpath [resources/], Classpath [static/], Classpath [public/], ServletContext [/]]
2021-06-28 20:40:12.263 WARN 27388 --- [nio-8080-exec-1] o.s.w.s.r.ResourceHttpRequestHandler : Path with "WEB-INF" or "META-INF": [WEB-INF/view/main-menu.jsp]
2021-06-28 20:40:12.263 DEBUG 27388 --- [nio-8080-exec-1] o.s.w.s.r.ResourceHttpRequestHandler : Resource not found
2021-06-28 20:40:12.263 DEBUG 27388 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Exiting from "FORWARD" dispatch, status 404
2021-06-28 20:40:12.264 DEBUG 27388 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed 404 NOT_FOUND
2021-06-28 20:40:12.265 DEBUG 27388 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : "ERROR" dispatch for GET "/error", parameters={}
2021-06-28 20:40:12.266 DEBUG 27388 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#errorHtml(HttpServletRequest, HttpServletResponse)
2021-06-28 20:40:12.278 DEBUG 27388 --- [nio-8080-exec-1] o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, text/html;q=0.8]
2021-06-28 20:40:12.281 DEBUG 27388 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Exiting from "ERROR" dispatch, status 404
As far as I can tell, it seems to be an issue with either the way IntelliJ is setup or the way Gradle is setup. Either way, the Resource directory or file is not being recognized.
Here's some of the things I've done/tried:
In Project Structure, I added the folder WEB-INF as a web resource directory in modules.
In Settings >>> Compiler, I added !?.jsp to the Resource Patterns
Finally, in gradle.build, I added sourceSets (this caused an error and I removed it).
Thank you for any help I can get.
Edit:
I've updated my project structure as follows.
I also added apply plugin: 'war' to my gradle.build and added the folder to my project facets.
I am still getting the same issue with resource not found.
I was able to figure it out with the help of a coworker. I had to make a few changes to my SpringMvcDemoApplication.java file and to my gradle.build. Here are the changes.
SpringMvcDemoApplication (added bean for InternalResourceViewResolver):
#SpringBootApplication(exclude=DataSourceAutoConfiguration.class)
public class SpringMvcDemoApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(SpringMvcDemoApplication.class);
}
#Bean
public ViewResolver internalResourceViewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
return bean;
}
public static void main(String[] args) {
SpringApplication.run(SpringMvcDemoApplication.class, args);
}
}
HomeController.java (Removed #Slf4j)
#Controller
public class HomeController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String showPage()
{
return "main-menu";
}
}
gradle.build (added tomcat and jstl dependencies):
plugins {
id 'org.springframework.boot' version '2.5.1'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'com.example.springdemo'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
apply plugin: 'war'
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.projectlombok:lombok:1.18.18'
implementation group: 'javax.servlet', name: 'jstl', version: '1.2' //addee
implementation group: 'org.apache.tomcat.embed', name: 'tomcat-embed-jasper'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
test {
useJUnitPlatform()
}
Everything works fine now.
Following through from last question
https://stackoverflow.com/a/68158449/14967681
please try changing your project structure as mentioned by bringing out WEB-INF out from resources into new folder as webapp. I am not sure of the reason why it fails to detect folder inside resources for that configuration mentioned but this should work for you.
Here is the project structure you should use: https://i.stack.imgur.com/IZXx1.png

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.

spring boot 1.4 jsp page not evaluated Forward InternalViewResolver

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 ?

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