Spring java based configuration - Could not open ServletContext resource - java

I'm using full java based configuration for a project.
When deploying webapp, I get the following error :
Sep 06, 2016 8:13:37 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
Sep 06, 2016 8:13:37 AM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization started
Sep 06, 2016 8:13:37 AM org.springframework.web.context.support.XmlWebApplicationContext prepareRefresh
INFO: Refreshing Root WebApplicationContext: startup date [Tue Sep 06 08:13:37 CEST 2016]; root of context hierarchy
Sep 06, 2016 8:13:38 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/net.brewspberry.util.SpringWebappConfiguration]
Sep 06, 2016 8:13:38 AM org.springframework.web.context.ContextLoader initWebApplicationContext
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/net.brewspberry.util.SpringWebappConfiguration]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/net.brewspberry.util.SpringWebappConfiguration]
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:344)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:612)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:513)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4813)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5272)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1407)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1397)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/net.brewspberry.util.SpringWebappConfiguration]
at org.springframework.web.context.support.ServletContextResource.getInputStream(ServletContextResource.java:141)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:330)
... 21 more
The thing is I don't get why Spring tries to load an XML config while I registered a Class config :
WebappInitializer :
package net.brewspberry.util.config;
import javax.servlet.Filter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import net.brewspberry.filters.AuthentificationFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class SpringWebappInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer implements
WebApplicationInitializer {
public void onStartup(ServletContext servletContext)
throws ServletException {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.setServletContext(servletContext);
// rootContext.setConfigLocation("net.brewspberry.util");
rootContext.register(SpringCoreConfiguration.class);
servletContext.addListener(new ContextLoaderListener(rootContext));
// now the config for the Dispatcher servlet
AnnotationConfigWebApplicationContext mvcContext = new AnnotationConfigWebApplicationContext();
// mvcContext.setConfigLocation("net.brewspberry.util.config");
//mvcContext.register(SpringWebappConfiguration.class);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
"DispatcherServlet", new DispatcherServlet(mvcContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("*.do");
}
#Override
protected Filter[] getServletFilters() {
return null; // new Filter[] { new AuthentificationFilter() };
}
#Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return null;
}
#Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return null;
}
}
Webapp config :
package net.brewspberry.util.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan({ "net.brewspberry" })
public class SpringWebappConfiguration extends WebMvcConfigurerAdapter {
#Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("forward:/login.jsp");
}
#Bean(name = "viewResolver")
public InternalResourceViewResolver getViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
I have no web.xml necesary as WebAppInitializer replaces it. I tried with or without that line :
mvcContext.register(SpringWebappConfiguration.class);
but it does not change anything.
Moreover, in logs, Spring searches for XML application context while in initializer it is defined as an annotation application context. I don't get it...
Any idea ?

You have to specify dispatcher servlet to use SpringWebappConfiguration as it context or set SpringWebappConfiguration as applicationRoot context.

Related

No mapping found for HTTP request with URI [/proj/] in DispatcherServlet with name 'dispatcher'

I am following "Spring in action - Craig Walls" book and encountered the below error message. Lot of the issues were mentioned in relation to web.xml. I am using Java config and not web.xml.
Controller in spitter.web package:
package spitter.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class HomeController {
#RequestMapping(value="/", method = RequestMethod.GET)
public String home(){
return "home";
}
}
Dispatcher servlet configuration in spittr.config package:
package spittr.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class SpittrWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
#Override
protected Class<?>[] getRootConfigClasses() {
//return new Class<?>[] {RootConfig.Class};
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
//return new Class<?>[] {WebConfig.Class};
return null;
}
}
Rootconfig in same package:
package spittr.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
#Configuration
#ComponentScan(basePackages={"spitter"}, excludeFilters={#Filter(type=FilterType.ANNOTATION, value=EnableWebMvc.class)})
public class RootConfig {
}
WebConfig:
package spittr.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan("spitter.web")
public class WebConfig extends WebMvcConfigurerAdapter{
#Bean
public ViewResolver viewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WebContent/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer){
configurer.enable();
}
}
I am using Maven to resolving dependencies and Tomcat 9 within eclipse to run.
Sep 17, 2016 4:46:48 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 5007 ms Sep 17, 2016 4:46:49 PM
org.springframework.web.servlet.PageNotFound noHandlerFound WARNING:
No mapping found for HTTP request with URI [/SpringMVC/] in
DispatcherServlet with name 'dispatcher'
My view home.jsp is in WebContent/WEB-INF/views/home.jsp.
Thanks for your help. I made the below changes and it is working now.
I move the web.config to the same package as my constructor. Then created the war file and deployed in Apache Tomcat. Now i am able to access the website.

Spring mvc Java based Configuration not working. Console display no error but my jsp page is not showing

Hello i am converting my simple demo project from bean configuration to pure java based configuration. Bean configuration works fine creating tables and all. But my java configuration is not displaying any pages. I solved many errors bur now console shows no error specifying the problem. here's my code please find whats wrong, or have i missed anything in the configuration. I am new to spring and fairly new to java based configuration. These are the sites from which i took code.
http://codehustler.org/blog/spring-security-tutorial-form-login-java-config/
for hibernate i use used this tutorial
http://websystique.com/spring/spring4-hibernate4-mysql-maven-integration-example-using-annotations/
My classes
1. AppConfiguration
package com.kharoud.configuration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
#Configuration
#ComponentScan({"com.kharoud"})
#Import({MvcConfiguraion.class, RepositoryConfiguration.class})
public class AppConfiguration {
}
2.MvcConfigurtion
package com.kharoud.configuration;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#EnableWebMvc
#Configuration
public class MvcConfiguraion extends WebMvcConfigurerAdapter{
#Override
public void configureDefaultServletHandling( DefaultServletHandlerConfigurer configurer ){
configurer.enable();
}
#Bean
public InternalResourceViewResolver getInternalResourceViewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views");
resolver.setSuffix(".jsp");
return resolver;
}
}
3.RepositoryConfiguration
package com.kharoud.configuration;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
#PropertySource({ "classpath:hibernate.properties" })
public class RepositoryConfiguration {
#Autowired
private Environment environment;
#Bean
public LocalSessionFactoryBean sessionFactory(){
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] {"com.kharoud.model"});
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
return properties;
}
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
return dataSource;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
}
4.SpringConfigurationInitializer
package com.kharoud.configuration.initilizer;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import com.kharoud.configuration.AppConfiguration;
public class SpringConfigurationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfiguration.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
only added these new classes. I deleted my web.xml.
Later on i will add Spring Security configuration class
this is my console output
Feb 25, 2015 2:32:13 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.8.0_25\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Window s;C:/Program Files/Java/jre1.8.0_25/bin/server;C:/Program Files/Java/jre1.8.0_25/bin;C:/Program Files/Java/jre1.8.0_25/lib/amd64;C:\ProgramData\Oracle\Java\javapath;C:\Windows\ system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShe ll\v1.0\;C:\Program Files\Java\jdk1.8.0_25\bin;;C:\ECLIPSE\eclipse;;.
Feb 25, 2015 2:32:14 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:ProjectDemo' did not find a matching property.
Feb 25, 2015 2:32:14 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Feb 25, 2015 2:32:14 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Feb 25, 2015 2:32:14 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1063 ms
Feb 25, 2015 2:32:14 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Feb 25, 2015 2:32:14 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.47
Feb 25, 2015 2:32:15 PM org.apache.catalina.util.SessionIdGenerator createSecureRandom
INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [217] milliseconds.
Feb 25, 2015 2:32:18 PM org.apache.catalina.core.ApplicationContext log
INFO: Spring WebApplicationInitializers detected on classpath: [com.kharoud.configuration.initilizer.SpringConfigurationInitializer#389ae113]
Feb 25, 2015 2:32:18 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
log4j:WARN No appenders could be found for logger (org.springframework.web.context.ContextLoader).
log4j:WARN Please initialize the log4j system properly.
Feb 25, 2015 2:32:26 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'dispatcher'
Feb 25, 2015 2:32:26 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Feb 25, 2015 2:32:26 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Feb 25, 2015 2:32:26 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 11876 ms
MyHomeController
package com.kharoud;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class HomeController {
#RequestMapping("/")
public String welcome(Model model){
return "index";
}
}
Myindex.jsp file is in WEB-INF/views folder under webapp folder
The views were properly resolved with bean configuration.
Thank you for your answers. I found the problem. When i wrote #ComponentScan on top of my MvcConfiguration class it worked and pages are displaying.

Spring data rest and spring security

I am in the proces of creating simple CRUD program with Spring data rest Spring data rest,
but I have a problem with security configuration (example was taken from here.
I have a WebAppInitializer:
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{JpaRepositoryConfig.class, SecurityConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{CustRepositoryRestMvcConfiguration.class};
}
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
#Override
protected Filter[] getServletFilters() {
return new Filter[]{ new DelegatingFilterProxy("springSecurityFilterChain")};
}
}
I have a next crud repository:
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.rest.repository.annotation.RestResource;
import org.springframework.security.access.prepost.PreAuthorize;
#PreAuthorize("hasRole('ROLE_USER')")
#RestResource(path = "products", rel = "products")
public interface ProductRepository extends PagingAndSortingRepository<Product, Long> {
#PreAuthorize("hasRole('ROLE_ADMIN')")
#Override
Product save(Product s);
#PreAuthorize("hasRole('ROLE_ADMIN')")
#Override
void delete(Long aLong);
}
I have a next security configuration:
#Configuration
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("greg").password("turnquist").roles("USER").and()
.withUser("ollie").password("gierke").roles("USER", "ADMIN");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic().and()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/products").hasRole("ADMIN")
.antMatchers(HttpMethod.PUT, "/products/**").hasRole("ADMIN")
.antMatchers(HttpMethod.PATCH, "/products/**").hasRole("ADMIN").and()
.csrf().disable();
}
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
I used next version of dependencies:
<java-version>1.7</java-version>
<spring-data-rest-version>1.0.0.RELEASE</spring-data-rest-version>
<spring.version>3.2.2.RELEASE</spring.version>
<org.slf4j-version>1.7.5</org.slf4j-version>
From project configured log4j I am getting these errors:
SEVERE: Error filterStart
org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/admin] startup failed due to previous errors
INFO : org.springframework.web.context.support.AnnotationConfigWebApplicationCon
text - Closing Root WebApplicationContext: startup date [Tue Dec 30 00:09:21 EET
2014]; root of context hierarchy
......
DEBUG: org.springframework.beans.factory.support.DisposableBeanAdapter - Invokin
g destroy() on bean with name 'org.springframework.security.config.annotation.au
thentication.configuration.AuthenticationConfiguration'
DEBUG: org.springframework.beans.factory.support.DefaultListableBeanFactory - Re
trieved dependent beans for bean '(inner bean)': [(inner bean), productRepositor
y]
DEBUG: org.springframework.beans.factory.support.DisposableBeanAdapter - Invokin
g destroy() on bean with name 'securityConfig'
From tomcat 7.0.56 localhost log I also have these errors in the logs:
SEVERE: Exception starting filter delegatingFilterProxy
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'springSecurityFilterChain' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:568)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1102)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:278)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1121)
at org.springframework.web.filter.DelegatingFilterProxy.initDelegate(DelegatingFilterProxy.java:326)
at org.springframework.web.filter.DelegatingFilterProxy.initFilterBean(DelegatingFilterProxy.java:236)
at org.springframework.web.filter.GenericFilterBean.init(GenericFilterBean.java:194)
at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:279)
at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:109)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4830)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5510)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:649)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1083)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1879)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
What is causing the errors in these logs?

Configuring Spring Wicket using Java Conf instead of xml

I'use Spring for a short time, but to wicket I am newbie. But I would like to give a try to this framework.
I would like to configure this both frameworks togheter. But I would like to avoid usage of xml configuration file.
I know that wicket can be configured that way, according to this:
http://wicket.apache.org/guide/guide/single.html#helloWorld_2
and this:
https://github.com/bitstorm/Wicket-tutorial-examples/tree/master/SpringInjectionExample
But for now I am getting only errors:
lis 15, 2014 4:31:15 PM org.apache.catalina.core.StandardContext filterStart
SEVERE: Exception starting filter com.derp.wicket.ProjectFilter
java.lang.NoSuchMethodError: org.apache.wicket.protocol.http.WebApplication.setMetaData(Lorg/apache/wicket/MetaDataKey;Ljava/lang/Object;)Lorg/apache/wicket/Application;
at org.apache.wicket.spring.injection.annot.SpringComponentInjector.<init>(SpringComponentInjector.java:115)
at org.apache.wicket.spring.injection.annot.SpringComponentInjector.<init>(SpringComponentInjector.java:92)
at com.derp.wicket.WicketApplication.init(WicketApplication.java:52)
at org.apache.wicket.Application.initApplication(Application.java:823)
at org.apache.wicket.protocol.http.WicketFilter.init(WicketFilter.java:424)
at org.apache.wicket.protocol.http.WicketFilter.init(WicketFilter.java:351)
at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:279)
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:260)
at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:105)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4603)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5210)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:724)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:700)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:714)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:581)
at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1686)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
lis 15, 2014 4:31:15 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error filterStart
lis 15, 2014 4:31:15 PM org.apache.catalina.core.StandardContext startInternal
Here my confs:
package com.derp.common.init;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.DispatcherServlet;
public class Initializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebAppConfig.class);
servletContext.addListener(new ContextLoaderListener(ctx));
ctx.setServletContext(servletContext);
Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
// Allow to use Put and Delete method for REST architecture
registerHiddenFieldFilter(servletContext);
}
private void registerHiddenFieldFilter(ServletContext aContext) {
aContext.addFilter("hiddenHttpMethodFilter", new HiddenHttpMethodFilter()).addMappingForUrlPatterns(null ,true, "/*");
}
}
package com.derp.common.init;
import java.util.Properties;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
#Configuration
#ComponentScan("com.derp")
#EnableWebMvc
#EnableTransactionManagement
#PropertySource("classpath:application.properties")
public class WebAppConfig {
private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO = "hibernate.hbm2ddl.auto";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN_SERVICES = "services.entitymanager.packages.to.scan";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN_COMMON = "common.entitymanager.packages.to.scan";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN_CMS = "cms.entitymanager.packages.to.scan";
#Resource
private Environment env;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
return dataSource;
}
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
//sessionFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
sessionFactoryBean.setPackagesToScan(new String[] {
env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN_SERVICES),
env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN_COMMON),
env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN_CMS)
});
sessionFactoryBean.setHibernateProperties(hibProperties());
return sessionFactoryBean;
}
private Properties hibProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
properties.put(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO));
return properties;
}
#Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
#Bean
public UrlBasedViewResolver setupViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/pages/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
}
package com.derp.wicket;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.WebPage;
import com.derp.wicket.ejbBean.EnterpriseMessage;
public class HomePage extends WebPage {
private static final long serialVersionUID = 1L;
#SpringBean
private EnterpriseMessage enterpriseMessage;
public HomePage(final PageParameters parameters) {
super(parameters);
add(new Label("message", enterpriseMessage.message));
}
}
package com.derp.wicket;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebFilter;
import org.apache.wicket.protocol.http.WicketFilter;
#WebFilter(value = "/*", initParams = { #WebInitParam(name = "applicationClassName", value = "com.derp.wicket.WicketApplication"),
#WebInitParam(name="filterMappingUrlPattern", value="/*")
})
public class ProjectFilter extends WicketFilter {
}
package com.derp.wicket;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.spring.injection.annot.SpringComponentInjector;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* Application object for your web application. If you want to run this application without deploying, run the Start class.
*
* #see org.wicketTutorial.Start#main(String[])
*/
public class WicketApplication extends WebApplication {
/**
* #see org.apache.wicket.Application#getHomePage()
*/
#Override
public Class<HomePage> getHomePage() {
return HomePage.class;
}
/**
* #see org.apache.wicket.Application#init()
*/
#Override
public void init() {
super.init();
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.scan("com.derp.wicket.ejbBean");
ctx.refresh();
getComponentInstantiationListeners().add(new SpringComponentInjector(this, ctx));
}
}
<!DOCTYPE html>
<html xmlns:wicket="http://wicket.apache.org">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<h2> <wicket:container wicket:id="message"></wicket:container></h2>
wwiicckkeet
</body>
</html>
Can anyone could help me struggle with this?
It seems that your are mixing Wicket with Spring Web MVC. Below i pasted some of my code or you can try something found on github: Spring Boot + Wicket: https://github.com/Pentadrago/spring-boot-example-wicket
My WebApplicationInitializer looks like this:
public class WebAppInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
container.addListener(new ContextLoaderListener(context));
context.register(ApplicationConfiguration.class);
FilterRegistration filter = container.addFilter("wicket.myproject", WicketFilter.class);
filter.setInitParameter("applicationClassName", WicketApplication.class.getName());
filter.setInitParameter(WicketFilter.FILTER_MAPPING_PARAM, "/*");
filter.addMappingForUrlPatterns(null, false, "/*");
}
}
The ApplicationConfiguration class used there looks like this:
#Configuration
#ComponentScan
public class ApplicationConfiguration {
#Bean
public TestService testService(){
return new TestServiceImpl();
}
}
My inherited WebApplication class looks like this:
public class WicketApplication extends WebApplication {
#Override
public Class<? extends WebPage> getHomePage() {
return HomePage.class;
}
#Override
public void init() {
super.init();
getComponentInstantiationListeners().add(new SpringComponentInjector(this));
}
}
In your POM you should have this deps:
<dependency>
<groupId>org.apache.wicket</groupId>
<artifactId>wicket-core</artifactId>
<version>6.17.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.wicket</groupId>
<artifactId>wicket-spring</artifactId>
<version>6.17.0</version>
</dependency>

java.lang.IllegalStateException when run spring java based configuration?

When I try to run Spring java annotation based configuration I get that exception trace
Sep 28, 2014 10:24:38 PM
org.springframework.context.support.AbstractApplicationContext
prepareRefresh INFO: Refreshing
org.springframework.context.annotation.AnnotationConfigApplicationContext#20ad9418:
startup date [Sun Sep 28 22:24:38 EET 2014]; root of context hierarchy
Exception in thread "main" java.lang.IllegalStateException: Cannot
load configuration class: com.learn.HelloWorldConfig at
org.springframework.context.annotation.ConfigurationClassPostProcessor.enhanceConfigurationClasses(ConfigurationClassPostProcessor.java:378)
at
org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanFactory(ConfigurationClassPostProcessor.java:263)
at
org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:265)
at
org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:126)
at
org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:609)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at com.learn.MainApp.main(MainApp.java:9) Caused by:
org.springframework.cglib.core.CodeGenerationException:
java.lang.reflect.InvocationTargetException-->null at
org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:237)
at
org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:377)
at
org.springframework.cglib.proxy.Enhancer.createClass(Enhancer.java:317)
at
org.springframework.context.annotation.ConfigurationClassEnhancer.createClass(ConfigurationClassEnhancer.java:128)
at
org.springframework.context.annotation.ConfigurationClassEnhancer.enhance(ConfigurationClassEnhancer.java:100)
at
org.springframework.context.annotation.ConfigurationClassPostProcessor.enhanceConfigurationClasses(ConfigurationClassPostProcessor.java:368)
... 6 more Caused by: java.lang.reflect.InvocationTargetException at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483) at
org.springframework.cglib.core.ReflectUtils.defineClass(ReflectUtils.java:384)
at
org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:219)
... 11 more Caused by: java.lang.SecurityException: class
"com.learn.HelloWorldConfig$$EnhancerBySpringCGLIB$$3f39adab"'s signer
information does not match signer information of other classes in the
same package at
java.lang.ClassLoader.checkCerts(ClassLoader.java:895) at
java.lang.ClassLoader.preDefineClass(ClassLoader.java:665) at
java.lang.ClassLoader.defineClass(ClassLoader.java:758) ... 17 more
HelloWorld.java
public class HelloWorld {
private String message;
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
}
HelloWorldConfig.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
public class HelloWorldConfig {
#Bean
public HelloWorld helloWorld(){
return new HelloWorld();
}
}
MainApp.java
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MainApp {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(HelloWorldConfig.class);
ctx.refresh();
HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
helloWorld.setMessage("Hello World!");
helloWorld.getMessage();
ctx.close();
System.out.println("Test");
}
}
Why I get that exception ?

Categories

Resources