Mapping Controller URLs to JSP in WEB-INF - spring

I am new to Spring and I would like to map some URLs to JSP pages. I am trying this for 2 hours now, but I can't get it working. I am sure this is very simple, but I am new to Spring. I am using Spring Boot.
(Yes, I found topics like How can I map my Spring URL to a JSP file in /WEB-INF/views?, but in my opinion I am doing everything right...)
This is my Controller. If I put a breakpoint there, it gets called. Therefore I think something is wrong with the ViewResolver...
#Controller
#RequestMapping("customers")
public class WebController {
#RequestMapping(method=RequestMethod.GET)
public String customers(Locale locale, Model model) {
return "customers";
}
}
This is my WebSecurityConfigurerAdapter (I am using Spring Security):
#Configuration
#EnableWebMvcSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//Some other methods, not relevant for this
#Bean
public InternalResourceViewResolver getViewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
And my JSP-file is placed in WEB-INF/views/customers.jsp.
When I call localhost:8080/customers/ I get (this is the only error. No others in server log...):
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Mon Aug 11 14:18:47 CEST 2014
There was an unexpected error (type=Not Found, status=404).

Thanks to Serge Ballesta I figured it out. :-)
I needed a configuration class which extends WebMvcConfigurerAdapter and is annotated with #EnableWebMvc. There I need to override the methods below. Annotating only WebSecurityConfigurerAdapter with #EnableWebMvc is not enough and results in "No mapping found for HTTP request with URI...."
#EnableWebMvc
#Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Bean
public InternalResourceViewResolver getViewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}

Related

Sping: #EnableHypermediaSupport gives error "No constructor with 0 arguments defined in class ConverterRegisteringWebMvcConfigurer"

I am following Spring Hateoas documentation where it is mentioned :
To enable the ResourceSupport subtypes be rendered according to the
specification of various hypermedia representations types, the support
for a particular hypermedia representation format can be activated
through #EnableHypermediaSupport.
But the moment I add #EnableHypermediaSupport to my configuration class, I get compilation Error in the problem console of my IDE saying
No constructor with 0 arguments defined in class
`org.springframework.hateoas.config.ConverterRegisteringWebMvcConfigurer'
#Configuration
#EnableWebMvc
#EnableHypermediaSupport(type = HypermediaType.HAL)
#ComponentScan(basePackages = {"com.api.web"})
public class WebConfig implements WebMvcConfigurer {
public WebConfig() {
super();
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
//other beans
}
What might be the issue here?

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 JavaConfig + WebMvcConfigurerAdapter + #Autowired => NPE

I have an application with 2 Contexts. Parent for web agnostic business logic and ChildContext (implicitly created by dispatcher servlet) for web logic.
My setup loks like
#Configuration
public class BusinessConfig {
#Bean
public ObjectMapper jacksonMapper() { return new ObjectMapper() }
}
and
#Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
#Autowired
private ObjectMapper objectMapper; // <- is null for some reason
#Override
public configureMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(objectMapper); // <- bang!
messageConverters.add(converter);
}
}
I need the the object mapper in the parent context, as I use it also in security configuration. But can someone explain me, why the #Autowired objectMapper is null? Its created in the parent context (the fact that the parent exists is even logged by spring at startup). Also #Autowired has required=true by default, so it should not blow up in the configure method (it should have blown up in construction of the context, if the bean wasn't there for some reason).
It seems to me that there might be some lifecycle problem in spring - in a sense that it calls the overridden methods first, and then #Autowires the dependencies... I have also tried to #Autowire the BusinessConfig (should be perfectly legal according to documentation - the result was the same (null)).
What should I do to make this working?
Thanks in advance!
EDIT - ISSUE FOUND
I found the issue. Unfortunately it had nothing to do with WebMvcConfigurerAdapter nor #Configuration. It was caused by premature initialization of context triggered by missing static modifier for propertyPlaceholderConfigurer... I have created issue in Spring core jira (https://jira.spring.io/browse/SPR-14382)
What about simply renaming the bean declaration method to match with the autowired bean?
#Configuration
public class BusinessConfig {
#Bean
public ObjectMapper objectMapper() { return new ObjectMapper() }
}
#Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
#Autowired
private ObjectMapper objectMapper;
[...]
}

Spring mvc + Primefaces resources not found

I am trying to start my new project using spring webmvc (version 4.1.6) with primefaces (version 5.2) I am able start up the project, however when trying to acces css or other resources the urls looks like: http://localhost:8080/rais/public//javax.faces.resource/theme.css?ln=primefaces-aristo and results in a 404. The part: http://localhost:8080/rais/public/ looks as expected.
My configuration:
#Configuration
#EnableTransactionManagement
#EnableSpringConfigured
#EnableWebMvc
public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
//Set init params
// Use JSF view templates saved as *.xhtml, for use with Facelets
servletContext.setInitParameter("javax.faces.DEFAULT_SUFFIX", ".xhtml");
servletContext.setInitParameter("javax.faces.FACELETS_VIEW_MAPPINGS", "*.xhtml");
ServletRegistration.Dynamic facesServlet = servletContext.addServlet("Faces Servlet", javax.faces.webapp.FacesServlet.class);
facesServlet.setLoadOnStartup(1);
facesServlet.addMapping("*.xhtml");
ServletRegistration.Dynamic registration = servletContext.addServlet("dsp", new DispatcherServlet());
registration.setInitParameter("contextConfigLocation", "");
registration.setLoadOnStartup(1);
registration.addMapping("/");
servletContext.addListener(ConfigureListener.class);
servletContext.addListener(org.springframework.web.context.request.RequestContextListener.class);
//Add OpenEntityManagerInViewFilter Filter
servletContext.addFilter("openEntityManagerInViewFilter", OpenEntityManagerInViewFilter.class).addMappingForUrlPatterns(null, true, "/*");
super.onStartup(servletContext);
}
WebMVC configuration:
#Configuration
#EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
#Bean
ViewResolver viewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setViewClass(org.springframework.faces.mvc.JsfView.class);
resolver.setPrefix("/WEB-INF");
resolver.setSuffix(".xhtml");
return resolver;
}
faces-config.xml (ani hint in moving this to java config also greatly appreciated)
<application>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
<action-listener>org.primefaces.application.DialogActionListener</action-listener>
<navigation-handler>org.primefaces.application.DialogNavigationHandler</navigation-handler>
<view-handler>org.primefaces.application.DialogViewHandler</view-handler>
</application>
Any help is greatly appreciated. Please ask if additional information is required:
Ok changed the UrlBasedViewResolver(); to a InternalResourceViewResolver(); now it seems to be working.

Resources