Spring boot: InternalResourceViewResolver not working - spring

I spent several hours trying to use InternalResourceViewResolver in order to append prefix and suffix to html views.
My views located under static/pages/ and by Spring docs, folder static is considered to be one of defaults for static content. So, I could access profile page by pages/profile.html. But what I really want to have is profile instead of pages/profile.html.
I've tried several answers, but that does not work, like:
#Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("pages/");
resolver.setSuffix(".html");
return resolver;
}
and adding
#Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
Still does not work properly. By adding any suffixes or prefixes I could not found page on any path. I am starting to get 404 on pages/profile.html, but it also does not appear on other urls.

Just need add your own custom configuration like this
#Configuration
public class WebMvcConfig {
#Bean
public InternalResourceViewResolver defaultViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/jsp");
resolver.setSuffix(".jsp");
return resolver;
}
}
Then you can inspect all your beans via "http://localhost:8080/beans"
And you can verfity is it using the custom configured bean:
{
"bean": "defaultViewResolver",
"scope": "singleton",
"type": "org.springframework.web.servlet.view.InternalResourceViewResolver",
"resource": "class path resource [io/cloudhuang/web/WebMvcConfig.class]",
"dependencies": [ ]
}
But the eaiest way should be config it in the application.properties
spring.mvc.view.prefix=
spring.mvc.view.suffix=
For application.yaml
spring:
mvc:
view:
prefix: templates/
suffix: .jsp

Using Spring Boot you actually don't need to declare your own InternalResourceViewResolver. Boot declares it for you, and you can just add a couple of properties to your application.properties file. E.g. in your case these would be:
spring.mvc.view.prefix=/jsp
spring.mvc.view.suffix=.jsp

Related

Problems adding spring webflow to a spring boot and joinfaces application

I am trying to add webflow to a spring boot app using joinfaces library.
I am using primefaces-spring-boot-starter and jetty-spring-boot-starter to configure jetty server.
Added necessary webflow dependencies to pom and configured necessary flowregistry, flowbuilderservices, flowexecutor and flowhandlermapping, ...
The application start correctly, reads the flows definitions from xmls and if enter to a flow via url the decision states are running correctly, reads the corresponding view state .xhtml file, calls the managed bean methods, and all are working apparently well.
But... once finished executing bean methods, when I hope to html be rendered in browser, the application is redirected to app root folder without any error in the log.
I have this behavior with all the flows of the application. Bean methods are executed correctly and when I hope to see the html... redirected to root.
Anyone tried to add webflow to a joinfaces jsf application successfully? I am missing to override some default configuration of joinfaces?
Thanks.
public class MvcConfiguration implements WebMvcConfigurer {
#Autowired
private WebFlowConfiguration webFlowConfiguration;
#Bean
public FlowHandlerMapping flowHandlerMapping() {
FlowHandlerMapping handlerMapping = new FlowHandlerMapping();
handlerMapping.setOrder(-1);
handlerMapping.setFlowRegistry(this.webFlowConfiguration.flowRegistry());
return handlerMapping;
}
#Bean
public FlowHandlerAdapter flowHandlerAdapter() {
JsfFlowHandlerAdapter adapter = new JsfFlowHandlerAdapter();
adapter.setFlowExecutor(this.webFlowConfiguration.flowExecutor());
return adapter;
}
#Bean
public ViewResolver faceletsViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setViewClass(JsfView.class);
resolver.setPrefix("/");
resolver.setSuffix(".xhtml");
return resolver;
}
}
#Configuration
public class WebFlowConfiguration extends AbstractFacesFlowConfiguration {
#Bean
public FlowDefinitionRegistry flowRegistry() {
return getFlowDefinitionRegistryBuilder()
.setBasePath("classpath*:/META-INF/resources/flows")
.addFlowLocationPattern("/**/*.xml")
.setFlowBuilderServices(flowBuilderServices())
.build();
}
#Bean
public FlowBuilderServices flowBuilderServices() {
return getFlowBuilderServicesBuilder()
.setDevelopmentMode(true)
.setViewFactoryCreator(new JsfViewFactoryCreator())
.build();
}
#Bean
public FlowExecutor flowExecutor() {
return getFlowExecutorBuilder(flowRegistry())
.addFlowExecutionListener(new FlowFacesContextLifecycleListener())
.addFlowExecutionListener(new SecurityFlowExecutionListener())
.setMaxFlowExecutionSnapshots(0)
.build();
}
}

Why application.properties is not executing properties after applying spring security in spring boot application?

I have created an spring-boot application. It was working fine all the css and js were mapping perfectly with my jsp pages and application was able to map to my jsp pages as well. By appication.properties file in resources folder.
spring.mvc.view.prefix = /WEB-INF/views/
spring.mvc.view.suffix = .jsp
spring.mvc.static-path-pattern=/resources/**
server.port=8181
But since I have enabled Spring security I am not able to do that I needed to initialise #bean class
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
It is weird. Can anybody help me with it?
Thank you in advance,
Priyal shah.
Ensure that your class is extending WebMvcConfigurerAdapter class like below sample.
#Configuration
#ComponentScan(basePackages="com.package")
#EnableWebMvc
public class MvcConfigs extends WebMvcConfigurerAdapter{
#Bean
public ViewResolver getViewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
}

Spring Boot urls with .html ending

I have very simple hello world created with spring boot (just starter web, no thymeleaf etc.).
I want to handle /hello url and it should produces view from /static/view.html
I have /static/view.html and simple method in my controller:
#RequestMapping("/hello")
public String hello2() {
return "hello.html";
}
The problem is that it causes error:
Circular view path [hello.html]: would dispatch back to the current
handler URL [/hello.html] again
I figured out that it does not matter if I visit /hello or /hello.html, Spring treats them the same.
How can I return simple, static html with the same name as the url path and which object in spring mvc/boot causes mapping url like /example.html to just /example?
You have to perform next steps:
Introduce MVC configuration:
#Configuration
#EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter{
#Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/");
return resolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
Put your hello.html into /src/main/webapp/WEB-INF folder
Make sure you have compile dependencies like this:
compile("org.springframework.boot:spring-boot-starter-web")
compile("org.apache.tomcat.embed:tomcat-embed-jasper")
I posted gradle code, if you have maven use similar xml.
NOTE Step 3 is the most important step because if you're using spring boot it applies auto-configurations depending on what you have in classpath. For instance if you add thymeleaf dependency
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
that will most likelly break the code because thymeleaf will introduce its own auto-configured view resolver.
Delete the method in your controller. A #RequestMapping is not needed for static content.

Does a Spring Boot Project that runs as a Jar needs a web.xml file?

As the title states.
I am migrating a Spring-MVC application that uses XML based Configuration.
I don't know where to move the filters located in the web.xml file to the new Spring Boot Project.
You can make use of the annotation : #ImportResource for this
Find more details here
You can define your filters using Java Configurations when using Spring Boot.
As mentioned in the documentation, you only need to declare that filter as a Bean in a configuration class.
#Configuration
public class WebConfig {
#Bean
public Filter someFilter() {
return new someFilter();
}
}
If for some reason "SomeFilter" is not a spring managed bean, or if you need to customize the filter behaviour, then you can register the filter using FilterRegistrationBean as follows
#Configuration
public class WebConfig {
#Bean
public Filter someFilter() {
return new someFilter();
}
#Bean
public FilterRegistrationBean someFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(someFilter());
return registration;
}
}
In case of multiple Filters you can specify the order using FilterRegistrationBean.setOrder() as mentioned in the doc
Finally I registered my Interceptors using Java Configuration (no xml) this way.
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
#Autowired
ControllerInterceptor controllerInterceptor;
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(this.controllerInterceptor).addPathPatterns(this.buildPaths());
}
private String[] buildPaths() {
String paths[] = { "/api/example1/**", "/api/example2/**" };
return paths;
}
}

#Configuration #ImportResource with FileSystemResource reading properties from Web-Inf

I am trying to read a properties file from WEB-INF using Java-based Configuration of my Spring MVC app. I can make this work when I put the properties directory in the src directory and use class: (ClassPathResource).
I want to use #ImportResource with file: (FileSystemResource) that will read from properties/ or resources/properties/ or /properties/ or /resources/properties/ when this is located in WebContent or WEB-INF
When I use file: I get a FileNotFoundException.
I have tried moving the properties directory around and used #ImportResource with "file:/properties/properties-config.xml", "file:/WebContent/properties/properties-config.xml", and /WEB-INF/properties/properties-config.xml".
I mapped in my app-servlet.xml and tried "file:/resources/properties/properties-config.xml"
This should be straightforward and not uncommon. But I can't find an example of getting properties files this way.
#ImportResource("file:/properties/properties-config.xml")
#Configuration
public class AppConfig {
protected final Log logger = LogFactory.getLog(getClass());
private #Value("#{v1Properties['v1.dataUrl']}") String dataUrl;
private #Value("#{v1Properties['v1.metaUrl']}") String metaUrl;
private #Value("#{v1Properties['v1.user']}") String v1User;
private #Value("#{v1Properties['v1.password']}") String v1Password;
#Bean
V1Config v1Config() {
V1Config v1Config = new V1Config();
v1Config.setDataUrl(dataUrl);
v1Config.setMetaUrl(metaUrl);
v1Config.setUserId(v1User);
v1Config.setPassword(v1Password);
return v1Config;
}
#Bean
ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
return resolver;
}
}
Try this out,
#ImportResource("classpath:properties-config.xml")

Resources