skip to Main Content

I am using spring MVC and want to send request from React.js but CORS problem. how i can enable it in spring mvc using ApplicationContext.xml?

i have added this these lines in applicationcontext.xml file but failed to build and run the application

<mvc:cors>
    <mvc:mapping path="/**" />
</mvc:cors>

i want to allow the react.js send request and cors is working properly in spring mvc when i build the file it give error can not build.where i am doing wrong i want to solve it using xml file not by java class

2

Answers


  1. Configure this in ApplicationContext.xml

    <bean id="corsFilter" class="org.springframework.web.filter.CorsFilter">
            <constructor-arg>
                <bean class="org.springframework.web.cors.CorsConfiguration">
                    <property name="allowedOrigins" value="http://localhost:8081" />
                    <property name="allowedMethods" value="GET,POST,PUT,DELETE,OPTIONS" />
                    <property name="allowedHeaders" value="*" />
                    <property name="allowCredentials" value="true" />
                </bean>
            </constructor-arg>
        </bean>
    
        <!-- Register CorsFilter bean with the servlet context -->
        <bean class="org.springframework.web.servlet.DispatcherServlet" name="dispatcherServlet">
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value></param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </bean>
    

    replace http://localhost:8081 fro where your client application is making requests.

    Login or Signup to reply.
  2. Add this is package com.your_packge_name and replace MyAppConfig with actual name

    import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
    
    public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    
        @Override
        protected Class<?>[] getRootConfigClasses() {
            return null; 
        }
    
        @Override
        protected Class<?>[] getServletConfigClasses() {
            return new Class[]{MyAppConfig.class}; 
        }
    
        @Override
        protected String[] getServletMappings() {
            return new String[]{"/"}; 
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search