Spring security can't initialize context - java

I am going through the official spring documentation examples:
adding spring security to application without it: http://docs.spring.io/spring-security/site/docs/3.2.x/guides/helloworld.html
creating custom login
http://docs.spring.io/spring-security/site/docs/3.2.x/guides/form.html
and have successfully added security to my application. However, when I go to add a custom login the documentation talks about a dependency "since our project adds the messages-jc project as a dependency..." so I added this to my pom. Since I have added this it throws an error as shown below.
I can remove this error if I exclude my SecurityWebApplicationInitializer and then run the app, however the system does not correctly redirect to the login page, and the login page does not work correctly (I use th:if and none of the if statements work it acts as if all of the if statements are true even if I say th:if="false"). If I remove the jc-messages dependency then it redirects correctly however the login page still does not work and trying to login throws a invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN error.
It seems as if the security class is being registered more than once triggering the error, but when I take away the SecurityWebApplicationInitializer nothing is registering the class. I feel like there is something basic I am missing since I am following a simple tutorial however I can't figure out what it is. The only other thing I could think of besides being a spring problem is that there is something wrong with Thymeleaf which is keeping the login page from not working.
Any help is appreciated!
SecurityWebApplicationInitializer.java
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
public SecurityWebApplicationInitializer() {
super(SecurityConfig.class);
}
}
pom.xml Commented out other dependencies to isolate the springframework dependency problem
<dependencies>
<!-- ... other dependency elements ... -->
<!-- <dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>3.2.4.RELEASE</version>
</dependency> -->
<!-- <dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>3.2.4.RELEASE</version>
</dependency> -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-samples-messages-jc</artifactId>
<version>3.2.4.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
SecurityConfig.java
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/res/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/loginSpring.html")
.permitAll();
}
}
loginSpring.html
<html xmlns:th="http://www.thymeleaf.org" xmlns:tiles="http://www.thymeleaf.org">
<head>
<title tiles:fragment="title">Messages : Create</title>
</head>
<body>
<div tiles:fragment="content">
<form name="f" th:action="#{/login}" method="post">
<fieldset>
<legend>Please Login</legend>
<div th:if="${param.error}" class="alert alert-error">
Invalid username and password.
</div>
<div th:if="${param.logout}" class="alert alert-success">
You have been logged out.
</div>
<label for="username">Username</label>
<input type="text" id="username" name="username"/>
<label for="password">Password</label>
<input type="password" id="password" name="password"/>
<div class="form-actions">
<button type="submit" class="btn">Log in</button>
</div>
</fieldset>
</form>
</div>
</body>
</html>
Stack trace
java.lang.IllegalStateException: Cannot initialize context because there is already a root application context present - check whether you have multiple ContextLoader* definitions in your web.xml!
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:277)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4701)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5204)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5199)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Jul 23, 2014 5:47:10 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error listenerStart
Jul 23, 2014 5:47:10 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/geocounts] startup failed due to previous errors
Jul 23, 2014 5:47:10 PM org.apache.catalina.core.ApplicationContext log
SEVERE: Servlet dispatcher threw unload() exception
javax.servlet.ServletException: Servlet.destroy() for servlet dispatcher threw exception
at org.apache.catalina.core.StandardWrapper.unload(StandardWrapper.java:1397)
at org.apache.catalina.core.StandardWrapper.stopInternal(StandardWrapper.java:1723)
at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:225)
at org.apache.catalina.core.StandardContext$4.run(StandardContext.java:5427)
at java.lang.Thread.run(Unknown Source)
at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5459)
at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:225)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:153)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1033)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:774)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1033)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:291)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:727)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at org.apache.catalina.startup.Catalina.start(Catalina.java:620)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:303)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:431)
Caused by: java.lang.NullPointerException
at org.springframework.web.servlet.FrameworkServlet.destroy(FrameworkServlet.java:809)
at org.apache.catalina.core.StandardWrapper.unload(StandardWrapper.java:1377)
... 24 more
Broken login page

When using Java based configuration for Spring Security, CSRF protection is enabled by default. You can switch it off as http.csrf().disable().

Related

Managed bean with a parameterized bean class must be #Dependent: class org.apache.cxf.jaxrs.provider.DataSourceProvider

I'm setting up a new server, JBoss EAP 7.1, and having trouble with attempting to get the first successful deployment in place. My stacktrace looks like the following:
ERROR [org.jboss.msc.service.fail] (MSC service thread 1-6) MSC000001: Failed to start service jboss.deployment.unit."foo.war".WeldStartService: org.jboss.msc.service.StartException in service jboss.deployment.unit."foo.war".WeldStartService: Failed to start service
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1978)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.jboss.weld.exceptions.DefinitionException: WELD-000071: Managed bean with a parameterized bean class must be #Dependent: class org.apache.cxf.jaxrs.provider.DataSourceProvider
at org.jboss.weld.bean.ManagedBean.checkType(ManagedBean.java:208)
at org.jboss.weld.bean.AbstractBean.initializeAfterBeanDiscovery(AbstractBean.java:107)
at org.jboss.weld.bean.ManagedBean.initializeAfterBeanDiscovery(ManagedBean.java:122)
at org.jboss.weld.bootstrap.ConcurrentBeanDeployer$AfterBeanDiscoveryInitializerFactory.doWork(ConcurrentBeanDeployer.java:132)
at org.jboss.weld.bootstrap.ConcurrentBeanDeployer$AfterBeanDiscoveryInitializerFactory.doWork(ConcurrentBeanDeployer.java:123)
at org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:62)
at org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:55)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
at org.jboss.threads.JBossThread.run(JBossThread.java:320)
ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("deploy") failed - address: ([("deployment" => "foo.war")]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\"foo.war\".WeldStartService" => "Failed to start service
Caused by: org.jboss.weld.exceptions.DefinitionException: WELD-000071: Managed bean with a parameterized bean class must be #Dependent: class org.apache.cxf.jaxrs.provider.DataSourceProvider"}}
I've had a look at a question asked in the past that might be relevant, but I've been unable translate it to my use-case, probably because my project is not using Spring. Something I have in common with the previous question is that I am using Apache Tika, though.
I expect, when I run the JBoss standalone.sh script, to see mostly clear INFO logs. What I'm seeing, however, are a hefty share of stacktrace logs that indicate that I have an issue with a bean class, from a jaxrs dependency, not being #Dependent.
I think it's a problem with Tika parsers dependency in your pom.xml
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-parsers</artifactId>
<version>1.20</version>
<exclusions>
<!--
Exclude otherwise the following error is thrown:
WELD-000071: Managed bean with a parameterized bean class
must be #Dependent: class org.apache.cxf.jaxrs.provider.XPathProvider
-->
<exclusion>
<artifactId>cxf-rt-rs-client</artifactId>
<groupId>org.apache.cxf</groupId>
</exclusion>
<!--
Exclude otherwise the following error is thrown:
java.lang.NoSuchMethodException: org.objectweb.asm.MethodWriter.visitLabel(org.objectweb.asm.Label)
-->
<exclusion>
<artifactId>asm</artifactId>
<groupId>org.ow2.asm</groupId>
</exclusion>
</exclusions>
</dependency>
You can have the original issue there

404 Error - The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

Really need help!
I am trying to deploy my application on to Tomcat. I tried almost every solution on stackoverflow but no luck.
Maven clean install [Success]
Run on server - 404 error
INFO: No Spring WebApplicationInitializer types detected on classpath
Jul 18, 2018 8:12:22 PM org.apache.catalina.core.StandardContext
listenerStart
SEVERE: Error configuring application listener of class
org.springframework.security.web.session.HttpSessionEventPublisher
java.lang.ClassNotFoundException: org.springframework.security.web.session.HttpSessionEventPublisher
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1352)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1180)
at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:544)
at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:525)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:150)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4822)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5363)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1410)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1400)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Dependencies corresponding to Springframework security
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>5.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>5.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-openid</artifactId>
<version>5.0.1.RELEASE</version>
</dependency>
[EDIT]
Tried adding scope as compile but I didn't see any change in the log.
Solutions tried:
Added Maven dependencies to Deployment Assembly
Tried with both Tomcat 8 and Tomcat 8.5
Tried adding spring-security-web to pom.xml yet not working

java.lang.IllegalStateException: CDI API is not available in this environment. at org.omnifaces.config.BeanManager

I m trying to display an image from a managed bean method which returns byte[] with <o:graphicImage> using omnifaces i deployed omnifaces 2.1 in WEB_INF/lib
here is my code
Register.java
public byte[] getImage() throws IOException{
return Utils.toByteArray(Faces.getResourceAsStream("/resources/images/loader.gif"));
}
Home.xhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:o="http://omnifaces.org/ui">
<h:head>
<h:outputStylesheet library="css" name="style.css"></h:outputStylesheet>
<style>
.center {
align: center;
}
</style>
</h:head>
<h:body>
<h:form>
<table style="float:right;margin-top:5px;">
<tr><td><h:commandLink action="/user/second.xhtml" style="float:right;">Second page</h:commandLink></td>
<td><h:commandLink action="#{login.logout}" style="float:right;">Logout</h:commandLink></td></tr>
</table>
</h:form>
<h:form>
<div style="margin: auto;">
<h:messages globalOnly="true" infoStyle="display:none" styleClass="error" style="list-style-type:none;"/>
<h:messages globalOnly="true" errorStyle="display:none" styleClass="green" style="list-style-type:none;"/>
<h4 align="center">Welcome to JSF #{login.username} Dude</h4>
<h3 align="center">User Profile</h3>
<h:dataTable value="#{register.getUser(login.username)}" var="info"
styleClass="center" style="margin:auto;" border="1">
<h:column>
<f:facet name="header">Image</f:facet>
<o:graphicImage value="#{register.getImage()}" type="jpg" dataURI="true"/>
</h:column>
<h:column>
<!-- column header -->
<f:facet name="header">Email</f:facet>
<!-- row record -->
<h:outputText value="#{info.email}"
rendered="#{not register.edit}" />
<!-- <h:inputText value="#{info.email}" rendered="#{not register.edit}" /> -->
</h:column>
<h:column>
<!-- column header -->
<f:facet name="header">First Name</f:facet>
<!-- row record -->
<h:outputText value="#{info.first}" rendered="#{not register.edit}" />
<!-- <h:inputText value="#{info.first}" rendered="#{not register.edit}" /> -->
</h:column>
<h:column>
<!-- column header -->
<f:facet name="header">Last name</f:facet>
<!-- row record -->
<h:outputText value="#{info.last}" rendered="#{not register.edit}" />
<!-- <h:inputText value="#{info.last}" rendered="#{not register.edit}" /> -->
</h:column>
<h:column>
<!-- column header -->
<f:facet name="header">Phone</f:facet>
<!-- row record -->
<h:outputText value="#{info.phone}"
rendered="#{not register.edit}" />
<!-- <h:inputText value="#{info.phone}" rendered="#{not register.edit}" /> -->
</h:column>
<h:column>
<h:commandButton value="Update" action="/user/Updateprofile.xhtml">
</h:commandButton>
</h:column>
</h:dataTable>
</div>
</h:form>
</h:body>
</html>
At first tomcat got started shown this error <o:graphicImage> Tag Library supports namespace: http://omnifaces.org/ui, but no tag was defined for name: graphicImage] when i have added the omnifaces.jar into my build path in eclipse. After the omnifaces.jar in WEB-INF/lib
it is not letting the tomcat to start and showing the following error
java.lang.ExceptionInInitializerError
at org.omnifaces.application.OmniApplication.<init>(OmniApplication.java:69)
at org.omnifaces.application.OmniApplicationFactory.createOmniApplication(OmniApplicationFactory.java:89)
at org.omnifaces.application.OmniApplicationFactory.getApplication(OmniApplicationFactory.java:54)
at org.apache.myfaces.config.FacesConfigurator.configureApplication(FacesConfigurator.java:1926)
at org.apache.myfaces.config.FacesConfigurator.configure(FacesConfigurator.java:529)
at org.apache.myfaces.webapp.AbstractFacesInitializer.buildConfiguration(AbstractFacesInitializer.java:296)
at org.apache.myfaces.webapp.Jsp21FacesInitializer.initContainerIntegration(Jsp21FacesInitializer.java:73)
at org.apache.myfaces.webapp.AbstractFacesInitializer.initFaces(AbstractFacesInitializer.java:118)
at org.apache.myfaces.webapp.StartupServletContextListener.contextInitialized(StartupServletContextListener.java:111)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5016)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5528)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalStateException: CDI API is not available in this environment.
at org.omnifaces.config.BeanManager.<init>(BeanManager.java:88)
at org.omnifaces.config.BeanManager.<clinit>(BeanManager.java:49)
... 18 more
Caused by: java.lang.ClassNotFoundException: javax.enterprise.inject.spi.BeanManager
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at org.omnifaces.config.BeanManager.<init>(BeanManager.java:82)
... 19 more
Jul 23, 2015 5:16:06 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class org.omnifaces.ApplicationListener
java.lang.NoClassDefFoundError: Could not initialize class org.omnifaces.config.BeanManager
at org.omnifaces.ApplicationListener.checkCDIAvailable(ApplicationListener.java:63)
at org.omnifaces.ApplicationListener.contextInitialized(ApplicationListener.java:55)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5016)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5528)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Jul 23, 2015 5:16:06 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: One or more listeners failed to start. Full details will be found in the appropriate container log file
Jul 23, 2015 5:16:06 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/First] startup failed due to previous errors
Jul 23, 2015 5:16:06 PM org.apache.catalina.core.StandardContext listenerStop
SEVERE: Exception sending context destroyed event to listener instance of class org.apache.myfaces.webapp.StartupServletContextListener
java.lang.NoClassDefFoundError: Could not initialize class org.omnifaces.config.BeanManager
at org.omnifaces.application.OmniApplication.<init>(OmniApplication.java:69)
at org.omnifaces.application.OmniApplicationFactory.createOmniApplication(OmniApplicationFactory.java:89)
at org.omnifaces.application.OmniApplicationFactory.getApplication(OmniApplicationFactory.java:54)
at org.apache.myfaces.context.servlet.FacesContextImplBase.getApplication(FacesContextImplBase.java:131)
at org.apache.myfaces.webapp.AbstractFacesInitializer._dispatchApplicationEvent(AbstractFacesInitializer.java:239)
at org.apache.myfaces.webapp.AbstractFacesInitializer.destroyFaces(AbstractFacesInitializer.java:273)
at org.apache.myfaces.webapp.StartupServletContextListener.contextDestroyed(StartupServletContextListener.java:153)
at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:5063)
at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5723)
at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:232)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:160)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
I am using JSF 2.0(Apache Myfaces), and i also have tomahawk 1.1.14 used for uploading the file.
OmniFaces 2.x requires CDI. See also Download section of OmniFaces homepage:
OmniFaces 2.x
Required: Java 1.7, JSF 2.2, EL 2.2, Servlet 3.0 and CDI 1.1
Optional: BV 1.0
Tomcat as being a barebones JSP/Servlet container doesn't ship with CDI out the box. It's only available in full fledged Java EE containers like WildFly and TomEE. The same applies to JSF (and JSTL), by the way, you'd have to manually install it in Tomcat.
You've 2 options:
Replace Tomcat by TomEE or any other Java EE container.
Manually install CDI in Tomcat.
See also:
How to install and use CDI on Tomcat? - contains detailed installation instructions

Spring 3 + Tomcat 6 : Form validation exception - java.lang.NoSuchMethodError: javax.el.ExpressionFactory.newInstance()Ljavax/el/ExpressionFactory;

I am new to Spring 3 MVC and was trying out form validation using the Java validation API and the Hibernate Validator implementation JARs. I am using Tomcat 6 for my application. Below is the pom.xml:
<properties>
<spring.version>3.1.1.RELEASE</spring.version>
<jdk.version>1.6</jdk.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- CGLIB is required to process #Configuration classes -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.0.1.Final</version>
</dependency>
</dependencies>
Below is the model class Employee.java:
#Size(min=2,max=30)
private String name;
#NotEmpty #Email
private String email;
#NotNull #Min(18) #Max(35)
private Integer age;
#Size(min=10)
private String phone;
// Getters and Setters
Below is the JSP containing the form:
<form:form method="post" commandName="empl" action="validate">
<table>
<tr>
<td>
<label for="nameInput">Name:</label>
</td>
<td>
<form:input path="name" id="nameInput"/>
<form:errors path="name"></form:errors>
</td>
</tr>
<tr>
<td>
<label for="ageInput">Age:</label>
</td>
<td>
<form:input path="age" id="ageInput"/>
<form:errors path="age"></form:errors>
</td>
</tr>
<tr>
<td>
<label for="phoneInput">Phone:</label>
</td>
<td>
<form:input path="phone" id="phoneInput"/>
<form:errors path="phone"></form:errors>
</td>
</tr>
<tr>
<td>
<label for="emailInput">Email:</label>
</td>
<td>
<form:input path="email" id="emailInput"/>
<form:errors path="email"></form:errors>
</td>
</tr>
<%--<tr>
<td>
<label for="birthdayInput">Birthday:</label>
</td>
<td>
<form:input path="birthday" id="birthdayInput" placeholder="MM/DD/YYYY"/>
<form:errors path="birthday"></form:errors>
</td>
</tr>
<tr>
<td>
<label for="genderInput">Birthday:</label>
</td>
<td>
<form:select id="genderInput" path="" items="${gender }"> </form:select>
<form:errors path="birthday"></form:errors>
</td>
</tr> --%>
<tr>
<td colspan="2">
<input type="submit" value="Submit">
</td>
</tr>
</table>
</form:form>
When I click the submit button I am getting the error. Even the Controller handler method is not invoked and the below error is thrown:
java.lang.NoSuchMethodError: javax.el.ExpressionFactory.newInstance()Ljavax/el/ExpressionFactory;
org.hibernate.validator.internal.engine.messageinterpolation.InterpolationTerm.<clinit>(InterpolationTerm.java:60)
org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.interpolateExpression(ResourceBundleMessageInterpolator.java:227)
org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.interpolateMessage(ResourceBundleMessageInterpolator.java:187)
org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.interpolate(ResourceBundleMessageInterpolator.java:120)
org.springframework.validation.beanvalidation.LocaleContextMessageInterpolator.interpolate(LocaleContextMessageInterpolator.java:49)
org.hibernate.validator.internal.engine.ValidationContext.interpolate(ValidationContext.java:370)
org.hibernate.validator.internal.engine.ValidationContext.createConstraintViolation(ValidationContext.java:284)
org.hibernate.validator.internal.engine.ValidationContext.createConstraintViolations(ValidationContext.java:246)
org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateSingleConstraint(ConstraintTree.java:289)
org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:133)
org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateComposingConstraints(ConstraintTree.java:233)
org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:102)
org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:91)
org.hibernate.validator.internal.metadata.core.MetaConstraint.validateConstraint(MetaConstraint.java:85)
org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraint(ValidatorImpl.java:478)
org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForDefaultGroup(ValidatorImpl.java:424)
org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:388)
org.hibernate.validator.internal.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:340)
org.hibernate.validator.internal.engine.ValidatorImpl.validate(ValidatorImpl.java:158)
org.springframework.validation.beanvalidation.SpringValidatorAdapter.validate(SpringValidatorAdapter.java:101)
org.springframework.validation.DataBinder.validate(DataBinder.java:722)
org.springframework.web.method.annotation.ModelAttributeMethodProcessor.validateIfApplicable(ModelAttributeMethodProcessor.java:155)
org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:108)
org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:75)
org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:156)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:117)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
I tried adding the following dependency but of no use (hence removed it afterwards):
<dependency>
<groupId>javax.el</groupId>
<artifactId>el-api</artifactId>
<version>2.2</version>
</dependency>
Please advise how to resolve this.
EDIT
If I add this dependency (but of no use, hence removed it as well):
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>el-impl</artifactId>
<version>2.2</version>
</dependency>
Then I am getting the below error:
java.lang.LinkageError: loader constraint violation: when resolving interface method "javax.servlet.jsp.JspApplicationContext.getExpressionFactory()Ljavax/el/ExpressionFactory;" the class loader (instance of org/apache/jasper/servlet/JasperLoader) of the current class, org/apache/jsp/index_jsp, and the class loader (instance of org/apache/catalina/loader/StandardClassLoader) for resolved class, javax/servlet/jsp/JspApplicationContext, have different Class objects for the type javax/el/ExpressionFactory used in the signature
at org.apache.jsp.index_jsp._jspInit(index_jsp.java:22)
at org.apache.jasper.runtime.HttpJspBase.init(HttpJspBase.java:52)
at org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:164)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:340)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:291)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:602)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:662)
EDIT 2
Below is the snapshot for the jars:
The problem is that Tomcat 6 ships an older version of EL (2.1) while Hibernate Validator 5.x requires the newer EL 2.2. Have a look at: http://hibernate.org/validator/faq/#does-hibernate-validator-5-x-work-with-tomcat-6.
You can use 4.3.1.Final version of hibernate-validator and that will solve the primary issue .The changes mentioned in the edit's are not required.This is assuming you dont need the features of EL 2.2 as the example that you are trying is a basic one.
You can still use the latest hibernate-validator jar,but as pointed out you need to upgrade to tomcat 7 or have the latest EL 2.2 jars in tomcat lib.
There's a simple comparision here http://tomcat.apache.org/whichversion.html

Pagination with Spring Hibernate

I am trying to implement Spring Pagination in my (Spring MVC / Hibernate / MySQL) project under Eclipse STS so I've followed the example in [A Pagination Technique Using Spring][1] since I found it recommended here in Stackoverflow in many answers to similar questions. Now I have a question and a problem:
Question: How can I import the pagination tag file into my project? Specially that I don't see any Tag folder under my project WEB-INF folder?
Problem: I am facing some trouble as each time I try to build / run the project I get error:
java.lang.ClassNotFoundException: org.springframework.web.context.support.StandardServletEnvironment
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
at org.springframework.web.servlet.HttpServletBean.(HttpServletBean.java:90)
at org.springframework.web.servlet.FrameworkServlet.(FrameworkServlet.java:211)
at org.springframework.web.servlet.DispatcherServlet.(DispatcherServlet.java:303)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at java.lang.Class.newInstance0(Class.java:357)
at java.lang.Class.newInstance(Class.java:310)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:138)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1144)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1088)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5123)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5407)
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:633)
at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1114)
at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1672)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
at java.lang.Thread.run(Thread.java:662)
I have double checked my code and I don't see what might be wrong. So can anyone please tell me what I might be doing wrong?
Controller:
public String listVolDisc(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
List searchResults = ivoldiscservice.getAllVolDisc();
PagedListHolder pagedListHolder = new PagedListHolder(searchResults);
int page = ServletRequestUtils.getIntParameter(request, "p", 0);
pagedListHolder.setPage(page);
int pageSize = 10;
pagedListHolder.setPageSize(pageSize);
model.addAttribute("pagedListHolder", pagedListHolder);
return "VolDiscount";
}
JSP:
<c:url value="/paging.do" var="pagedLink">
<c:param name="action" value="list"/>
<c:param name="p" value="~"/>
</c:url>
<div class="section">
<h2 class="section_title">Volume Discounts</h2>
<tg:paging pagedListHolder="${pagedListHolder}" pagedLink="${pagedLink}"/>
<div class="table">
<div class="table_header">
<div class="cell">ID</div>
<div class="cell">From</div>
<div class="cell">To</div>
<div class="cell">Discount</div>
</div>
<%-- <c:forEach var="voldiscount" items="${voldiscountList}"> --%>
<c:forEach var="voldiscount" items="${pagedListHolder}">
<div class="table_row">
<div class="cell important">${voldiscount.id}</div>
<div class="cell">${voldiscount.rangeStarts}</div>
<div class="cell">${voldiscount.rangeEnds}</div>
<div class="cell">${voldiscount.discount}</div>
</div>
</c:forEach>
</div><!-- .table -->
<tg:paging pagedListHolder="${pagedListHolder}" pagedLink="${pagedLink}"/>
</div><!-- .section -->
DAO:
public List<VolumeDiscount> getAllVolDisc() {
return sessionfactory.getCurrentSession().createQuery("from VolumeDiscount v").list();
}
Thanks for your time
It seems you have missing dependency: spring-web.

Categories