0

This is not a duplicate 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

Community
  • 1
  • 1

2 Answers2

0

You are missing dispatch‌​erServlet in config location

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
           /WEB-INF/dispatch‌​erServlet-servlet.xm‌​l,
           /WEB-INF/security-context.xml
    </param-value>
</context-param>

Update 1: Change to this in web.xml

    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>/WEB-INF/dispatch‌​erServlet-servlet.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
    </servlet>

Update 2:

In your Spring-security.xml schema declaration made to 3.1,but you are using to 3.2,so change it to 3.2 or remove version, no need to mention,it will automatically take that.

<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.xsd
        http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security.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.xsd">

Update 3: Change web.xml to

<?xml version="1.0" encoding="UTF-8"?>  
<web-app version="2.5"   
    xmlns="http://java.sun.com/xml/ns/javaee"   
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  

    <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>  

dispatcherServlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:sec="http://www.springframework.org/schema/security" 
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.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.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

  <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>

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.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.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.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>
Prasanna Kumar H A
  • 3,341
  • 6
  • 24
  • 52
  • it is not showing `caused by` part, It is executing this code showing the stack trace and then returning `error404` –  Sep 20 '16 at 10:36
  • spring version `4.3` and security version `3.2` –  Sep 20 '16 at 10:38
  • I am getting error `org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'springSecurityFilterChain' is defined` –  Sep 20 '16 at 10:45
  • @HelloWorld change the web.xml as per update 3,remove all xsd in both spring xml's...it will definitely work fine..for u update 1 is not required. – Prasanna Kumar H A Sep 20 '16 at 12:07
  • I made the changes but still getting same error, I am posting my entire code, i think something else is wrong –  Sep 20 '16 at 12:10
  • I added `jsp`, `classes` –  Sep 20 '16 at 12:17
  • @HelloWorld change the web.xml,spring and dispatcher xml to updated ones...prblm with those 3 only – Prasanna Kumar H A Sep 20 '16 at 12:17
  • I think I am having either a bad or something else is wrong –  Sep 20 '16 at 12:19
  • @HelloWorld copy paste all 3 xmls as i mentioned in Update 3...and clean the project,build it and check..it has to work...because ur controller and jsp's are fine – Prasanna Kumar H A Sep 20 '16 at 12:23
  • Adding the `dispatcherServlet-servlet.xml` to the `config-location` of the `ContextLoaderListener` is a bad idea/advice. What you are now effectively doing is loading the application twice. Once by the `ContextLoaderListener` and again by the `DispatcherServlet` from a memory perspective and performance perspective not very wise to do, not to mention the weird errors you will eventually start to run into. – M. Deinum Sep 20 '16 at 16:30
  • @denium thank you..I removed that in Update 3...but thanks for explaining – Prasanna Kumar H A Sep 20 '16 at 17:47
  • @PrasannaKumar, I am not sure what you changed I am still getting error despite all the changes you told me –  Sep 21 '16 at 10:28
  • @HelloWorld those are the major possible fixes which can solve this issue...do onething update the question with current setup(means current xmls and controller now you have updated) – Prasanna Kumar H A Sep 21 '16 at 10:38
  • can you tell me about the changes you made precisely so I can make sure I am not missing any thing –  Sep 21 '16 at 11:22
  • @HelloWorld final working xmls(all 3) i have pasted in update 3 including headers....So copy paste entirely... – Prasanna Kumar H A Sep 21 '16 at 11:31
  • i think its may be jar conflicts as I am using `spring4 jars` and `spring3 security jars` so not sure weather it is this or not –  Sep 21 '16 at 11:58
  • @HelloWorld i checked with 4.2.3 and 3.2.5..its worked fine – Prasanna Kumar H A Sep 21 '16 at 12:40
  • you are saying that you are using spring 4 jars and spring 3 security jars and its still working? –  Sep 21 '16 at 12:41
  • No not updated anything...your questions remained same...?? – Prasanna Kumar H A Sep 22 '16 at 11:47
0

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

Community
  • 1
  • 1