HelloWorld HelloWorld - 2 months ago 11
Java Question

spring security : context destroyed event to listener instance AND BeanFactory not initialized or already closed

This is not a

as expected duplicate contains error
java.lang.NoSuchMethodError
and I am getting error
java.lang.IllegalStateException
which are different terms

while working on
spring-security
i am getting error as

SEVERE: Exception sending context destroyed event to listener instance of class org.springframework.web.context.ContextLoaderListener
java.lang.IllegalStateException: BeanFactory not initialized or already closed - call 'refresh' before accessing beans via the ApplicationContext


//rest of Stack trace

Sep 20, 2016 4:06:34 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler [http-nio-8080]
Sep 20, 2016 4:06:34 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler [ajp-nio-8009]
Sep 20, 2016 4:06:34 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 7520 ms


The code is as follow

web.xml

<!-- Servlet mapping -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>


<!-- context parameters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/security-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Filter mappings -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>


security-context.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<security:http auto-config="true">
<security:intercept-url pattern="/add" access="ROLE_ADMIN" />
<security:form-login login-page="/login"
default-target-url="/add" authentication-failure-url="/loginfailed" />
<security:logout logout-success-url="/logout" />
</security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:user-service>
<security:user name="admin" password="admin"
authorities="ROLE_ADMIN" />
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
</beans>


dispatcherServlet-servlet.xml

<mvc:annotation-driven />
<context:component-scan base-package="com" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="com/resources/message" />
</bean>
</beans>


NOTE all these files are directly under
/WEB-INF/


now Since I have everything right in my configurations then why I'am getting error and since I'll do more configurations and therefore I'll be using multiple configuration files.

Any help is appreciated and please help :)

after reading solution from this changing
<context-parms>
, not solved the error

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/security-context.xml,/WEB-INF/dispatcherServlet-servlet.xml</param-value>
</context-param>


This is the other part of code

DomainController

@Controller
public class DomainController {

@Autowired
private DomainRepositiry repostiry;

@RequestMapping("/")
public String getHomePage(Model model) {
model.addAttribute("domains", repostiry.getList());
return "indexPage";
}

@RequestMapping(value = "/add", method = RequestMethod.GET)
public String signUp(Model model) {
Domain domain = new Domain();
model.addAttribute("domain", domain);
return "home";
}

@RequestMapping(value = "/add", method = RequestMethod.POST)
public String showResult(@ModelAttribute("domain") Domain domain, BindingResult result) {
String[] supressedFeilds = result.getSuppressedFields();
if (supressedFeilds.length > 0)
throw new RuntimeException("Attempting to bind disallowed feilds ");
repostiry.addToList(domain);
return "redirect:/";
}

@RequestMapping("/detail")
public String getInfoByName(@RequestParam String firstName, Model model) {
model.addAttribute("domain", repostiry.getDomainByFirstName(firstName));
return "detail";
}

@InitBinder
public void initBinder(WebDataBinder binder) {
binder.setDisallowedFields("dateOfBirth");
}
}


LoginController

@Controller
public class LoginContoller {

@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login() {
return "login";
}

@RequestMapping(value = "/loginfailed", method = RequestMethod.GET)
public String loginFailed(Model model) {
model.addAttribute("error", "true");
return "login";
}

@RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logOut(Model model) {
return "login";
}
}


Login Page



Login



Please enter your Credentials to login


<c:if test="${not empty error}">
<b><U><spring:message
code="AbstractUserDetailsAuthenticationProvider.badCredentials" /></U></b>
</c:if>
</h1>
<form action='<c:url value="/j_spring_security_check"></c:url>'
method="post">
<h3>
User Name : <br> <input type="text" name=j_username>
<hr>
Password : <br> <input type="text" name="j_password">
<hr>
</h3>
<input type="submit" value="login">
</form>
</body>
</html>


User Info Page

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Basic Information</title>
</head>
<body>
<c:forEach var="domain" items="${domains}">
<p>First Name : ${domain.firstName}</p>
<br>
<p>Last Name : ${domain.lastName}</p>
<br>
<p>Number : ${domain.number}</p>
<br>
<p>Date Of Birth : ${domain.dateOfBirth}</p>
<br>
<HR>
<A
href='<spring:url value="/detail?firstName=${domain.firstName}"></spring:url>'>TO
VIEW DETAILS CLICK HERE</A>
<HR>
</c:forEach>
<p>
To add more information <a href='<spring:url value="/add" />'><h2>Click
here</h2></a>
</p>
</body>
</html>


Note : this code is not throwing any
caused by
exception instead it starts server smoothly which is the reason I am getting
error 404
and I am trying to solve this and therefore any help is appreciated

Answer

after working on this error I came to know that there was jar version conflict actually I was using spring4 jars and spring 3 security jar files and like Prasanna Kumar said his configurations was working, I'm not sure why but If I use like context.xsd instead of context.n.m.xsd its giving me error that my spring version must be either 3.1 or above

Short Story-final configuration and this is working

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:security="http://www.springframework.org/schema/security"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.1.xsd">

    <security:http auto-config="true">
        <security:intercept-url pattern="/"
            access="hasRole('ROLE_ADMIN')" />
        <security:form-login login-page="/login"
            default-target-url="/" authentication-failure-url="/loginfailed" />
        <security:logout logout-success-url="/logout" />
        <security:csrf disabled="true" />
    </security:http>
    <security:authentication-manager>
        <security:authentication-provider>
            <security:user-service>
                <security:user name="Admin" authorities="ROLE_ADMIN"
                    password="admin" />
            </security:user-service>
        </security:authentication-provider>
    </security:authentication-manager>
</beans>

and for additional information I found some common errors and here is their fix

1) for error Could not verify the provided CSRF token because your session was not found.

use <security:csrf disabled="true" /> inside <security-http>

2) for error java.lang.IllegalArgumentException: Failed to evaluate expression 'ROLE_ADMIN'

use <security:intercept-url pattern="/" access="hasRole('ROLE_ADMIN')" /> and you don't have to replace it under <security:authentication-manager> tag

Hope that will help