Не найдено сопоставления для HTTP-запроса с URI. Где я ошибаюсь

#java #spring #spring-security

#java #spring #spring-безопасность

Вопрос:

У меня есть эти файлы ниже. Я не понимаю, что я делаю неправильно. Я получаю сообщение об ошибке, в котором говорится, что Не найдено сопоставления для HTTP-запроса с URI [/ pages/j_spring_security_check] в DispatcherServlet с именем ‘dispatcher’

Может кто-нибудь, пожалуйста, помочь в этом.

ApplicationContext.xml

             <?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"
                xmlns:webflow-config="http://www.springframework.org/schema/webflow-config"
                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.xsd
                   http://www.springframework.org/schema/webflow-config 
                    http://www.springframework.org/schema/webflow-config/spring-webflow-config.xsd">

                <!-- database properties DataSource -->
                <!-- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
                    <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" 
                    /> <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" /> <property 
                    name="username" value="system" /> <property name="password" value="123456" 
                    /> </bean> -->

                <bean id="dataSource"
                    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
                    <property name="driverClassName" value="org.h2.Driver" />
                    <property name="url"
                        value="jdbc:h2:~/veeratest;DB_CLOSE_ON_EXIT=TRUE;FILE_LOCK=NO" />
                    <property name="username" value="sa" />
                    <property name="password" value="12345" />
                </bean>
                <bean id="sessionFactory"
                    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

                    <!-- dependency Injection of dataSource -->
                    <property name="dataSource" ref="dataSource"></property>
                    <property name="hibernateProperties">
                        <props>
                            <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>

                            <!-- hibernate mapping to database automatically -->
                            <!-- when we use create-drop instead of update the table is created automatically 
                                when the server runs after that it will drop when server stops -->
                            <prop key="hibernate.hbm2ddl.auto">create-drop</prop>

                            <!-- whether the query wants to show the data in console -->
                            <prop key="hibernate.show_sql">true</prop>
                            <prop key="hibernate.format_sql">true</prop>

                        </props>
                    </property>

                    <!-- packages to scan for Entity Classes annotated Classes package -->
                    <property name="annotatedClasses">
                        <list>
                            <value>com.model.Product</value>
                            <value>com.model.Authorities</value>
                            <value>com.model.BillingAddress</value>
                            <value>com.model.Cart</value>
                            <value>com.model.CartItem</value>
                            <value>com.model.Customer</value>
                            <value>com.model.CustomerOrder</value>
                            <value>com.model.ShippingAddress</value>
                            <value>com.model.User</value>
                            <value>com.model.Queries</value>
                        </list>
                    </property>

                </bean>

                <!-- A transaction manager is the part of an application that is responsible 
                    for coordinating transactions across one or more resources. In the Spring 
                    framework, the transaction manager is effectively the root of the transaction 
                    system. -->
                <bean id="transactionManager"
                    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
                    <property name="sessionFactory" ref="sessionFactory" />
                </bean>

                <!-- Spring - Security Purpose -->

                <security:http auto-config="true" use-expressions="true">
                    <security:intercept-url pattern="/index/**"
                        access="permitAll" />

                    <security:intercept-url pattern="/index1/**"
                        access="permitAll" />
                    <security:intercept-url pattern="/cart/**"
                        access="permitAll" />
                    <security:intercept-url pattern="/get*/**"
                        access="hasAnyRole('ROLE_ADMIN','ROLE_USER')" />
                    <security:intercept-url pattern="/admin*/**"
                        access="hasRole('ROLE_ADMIN')" />
                    <security:intercept-url pattern="/login"
                        access="hasAnyRole('ROLE_ADMIN','ROLE_USER')" />
                    <!-- <security:form-login login-processing-url="/j_spring_security_check"
                        login-page="/login" authentication-failure-url="/login?error"
                        default-target-url="/index1" username-parameter="j_username"
                        password-parameter="j_password" />
                    <security:logout logout-success-url="/login?logout" /> -->

                </security:http>

                <security:authentication-manager>
                    <security:authentication-provider>
                        <security:user-service>
                            <security:user name="rahul@gmail.com" password="12345"
                                authorities="ROLE_USER" />
                            <security:user name="admin@gmail.com" password="12345"
                                authorities="ROLE_ADMIN" />
                        </security:user-service>

                        <security:jdbc-user-service
                            data-source-ref="dataSource"
                            authorities-by-username-query="SELECT 
                            emailId,authorities FROM authorities WHERE emailId =?"
                            users-by-username-query="SELECT 
                            emailId, password, enabled FROM users WHERE emailId=? " />
                    </security:authentication-provider>

                </security:authentication-manager>

                <webflow-config:flow-executor id="flowExecutor"
                    flow-registry="flowRegistry">
                </webflow-config:flow-executor>

                <webflow-config:flow-registry id="flowRegistry"
                    base-path="/WEB-INF/flow">
                    <webflow-config:flow-location path="/checkout/checkout-flow.xml"
                        id="checkout"></webflow-config:flow-location>
                </webflow-config:flow-registry>
                <bean id="flowHandleMapping"
                    class="org.springframework.webflow.mvc.servlet.FlowHandlerMapping">
                    <property name="flowRegistry" ref="flowRegistry"></property>
                </bean>
                <bean id="flowHandlerAdapter"
                    class="org.springframework.webflow.mvc.servlet.FlowHandlerAdapter">
                    <property name="flowExecutor" ref="flowExecutor"></property>
                </bean>

            </beans>
  

dispatcher-servelet.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:tx="http://www.springframework.org/schema/tx"
                xsi:schemaLocation="http://www.springframework.org/schema/beans
                   http://www.springframework.org/schema/beans/spring-beans.xsd
                   http://www.springframework.org/schema/mvc
                   http://www.springframework.org/schema/mvc/spring-mvc.xsd
                   http://www.springframework.org/schema/context
                   http://www.springframework.org/schema/context/spring-context.xsd">

                <mvc:annotation-driven></mvc:annotation-driven>

                <context:component-scan base-package="com.*"></context:component-scan>

                <!-- it will scan all the class under the package com.tutorial create instances 
                    for all the -->
                <!-- class which has an annotations like @Component, @Controller, @Service, 
                    @Repository -->



                <!-- Using this it get the actual view name by converting logical view name -->
                <!-- for eg: logical view name is welcome -->
                <!-- it will convert it to WEB-INF/Views/welcome.jsp -->

                <bean id="viewResolver"
                    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                    <property name="prefix" value="/WEB-INF/page/" />
                    <property name="suffix" value=".jsp" />
                </bean>

                <!-- mvc:resources is to find the resource file like bootstrap,css,JQuery 
                    and Images in resource folder -->

                <mvc:resources mapping="/resource/**" location="/WEB-INF/resource/" />
            </beans>
  

WebSecurityConfig.Java

             package com.config;

            import javax.sql.DataSource;

            import org.springframework.beans.factory.annotation.Autowired;
            import org.springframework.context.annotation.Bean;
            import org.springframework.context.annotation.Configuration;
            import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
            import org.springframework.security.config.annotation.web.builders.HttpSecurity;
            import org.springframework.security.config.annotation.web.builders.WebSecurity;
            import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
            import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
            import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
            import org.springframework.security.crypto.password.PasswordEncoder;
            import org.springframework.security.provisioning.JdbcUserDetailsManager;
            import org.springframework.web.servlet.config.annotation.EnableWebMvc;

            @EnableWebMvc
            @EnableWebSecurity
            @Configuration
            public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

                @Autowired
                DataSource dataSource;

                @Bean
                public PasswordEncoder passwordEncoder() {
                    return new BCryptPasswordEncoder();
                }

                // Enable jdbc authentication
                @Autowired
                public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
                    auth.jdbcAuthentication().dataSource(dataSource).passwordEncoder(passwordEncoder());
                }

                @Bean
                public JdbcUserDetailsManager jdbcUserDetailsManager() throws Exception {
                    JdbcUserDetailsManager jdbcUserDetailsManager = new JdbcUserDetailsManager();
                    jdbcUserDetailsManager.setDataSource(dataSource);
                    return jdbcUserDetailsManager;
                }

                @Override
                public void configure(WebSecurity web) throws Exception {
                    web.ignoring().antMatchers("/resources/**");
                }

                @Override
                protected void configure(HttpSecurity http) throws Exception {
                    http.formLogin().loginProcessingUrl("/j_spring_security_check").and().authorizeRequests()
                            .antMatchers("/register").permitAll().antMatchers("/login").hasAnyRole("USER", "ADMIN")
                            .antMatchers("/login").hasAnyRole("USER", "ADMIN").antMatchers("/addNewEmployee").hasAnyRole("ADMIN")
                            .anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll().and().logout()
                            .permitAll();
                    /*
                     * http.csrf().disable();
                     */
                }
            }
  

web.xml

             <?xml version="1.0" encoding="UTF-8"?>
            <!DOCTYPE web-app PUBLIC
                    "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
                    "http://java.sun.com/dtd/web-app_2_3.dtd" >
            <web-app>
                <display-name>Veera Enterprises</display-name>

                <!-- to connect the dispatcher servlet and applicationContext -->
                <context-param>
                    <param-name>contextConfigLocation</param-name>
                    <param-value>
                        /WEB-INF/dispatcher-servlet.xml,
                        /WEB-INF/applicationContext.xml
                    </param-value>
                </context-param>

            <!--    <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> -->
                <filter>
                    <filter-name>springSecurityFilterChain</filter-name>
                    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
                </filter>
                <!-- it is used to listen the contextloader -->
                <listener>
                    <listener-class>
                        org.springframework.web.context.ContextLoaderListener
                    </listener-class>
                </listener>

                <servlet>
                    <servlet-name>dispatcher</servlet-name>
                    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
                </servlet>

                <servlet-mapping>
                    <servlet-name>dispatcher</servlet-name>
                    <url-pattern>/</url-pattern>
                </servlet-mapping>
            </web-app>
  

Ответ №1:

Я думаю, вам нужно обновить конфигурацию вашей системы безопасности, чтобы разрешить /pages/j_spring_security_check

Похоже, что вы закомментировали / j_spring_security_check, но нет разрешения root или чего-либо еще, чтобы пропустить это, если это было вашим намерением. Что-то вроде:

В противном случае обновите фильтр безопасности, чтобы включить /pages/j_spring_security_check