对Spring MVC Controller的跨域Ajax请求失败,出现302错误

时间:2018-03-15 12:45:00

标签: jquery ajax spring-mvc spring-boot spring-security

对于概念验证,我试图从一个页面上的一个弹簧启动应用程序加载一个jsp。

我正在使用JQuery来创建一个$ .ajax()请求,但从我可以看到的是请求甚至不是弹簧过滤器或控制器。当从自己的浏览器窗口发送时,控制器会正常响应。

错误: 无法加载http://localhost:8082/settings2:重定向来自' http://localhost:8082/settings2'到' http://localhost:8082/settings2/'被CORS政策阻止:No' Access-Control-Allow-Origin'标头出现在请求的资源上。起源' http://localhost:8080'因此不允许访问。

2应用程序:设置&设置2。设置一是尝试向settings2

上的控制器发出AJAX请求

设置应用页面(尝试与settings2 app对话)     

<script>
$.ajax({url:'http://localhost:8082/settings2',
    type:"POST");
}});
//No success method because chrome console already showing error
</script>
</body>

Settings2配置应用(WebMvcConfigurerAdapter被标记为已弃用)     @组态     公共类WebConfig扩展了WebMvcConfigurerAdapter {

@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/").allowedOrigins("http://localhost:8080", "*")
            .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH", "OPTIONS").allowedHeaders("*")
            .exposedHeaders("Access-Control-Allow-Origin", "Access-Control-Allow-Methods",
                    "Access-Control-Allow-Headers", "Access-Control-Max-Age", "Access-Control-Request-Headers",
                    "Access-Control-Request-Method");
}

}

Settings2 websecurity config

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {

    http.cors();
}

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    final CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("*"));
    configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
    configuration.setExposedHeaders(Arrays.asList("Access-Control-Allow-Origin", "Access-Control-Allow-Methods",
            "Access-Control-Allow-Headers", "Access-Control-Max-Age", "Access-Control-Request-Headers",
            "Access-Control-Request-Method"));
    // setAllowCredentials(true) is important, otherwise:
    // The value of the 'Access-Control-Allow-Origin' header in the response must
    // not be the wildcard '*' when the request's credentials mode is 'include'.
    configuration.setAllowCredentials(true);
    // setAllowedHeaders is important! Without it, OPTIONS preflight request
    // will fail with 403 Invalid CORS request
    configuration.setAllowedHeaders(Arrays.asList("Authorization", "Cache-Control", "Content-Type"));
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/", configuration);
    return source;
}
}

settings2 app Cors Filter

public class WebSecurityCorsFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletResponse res = (HttpServletResponse) response;
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Methods", "*");
    res.setHeader("Access-Control-Max-Age", "3600");
    res.setHeader("Access-Control-Allow-Headers", "x-requested-with");
    chain.doFilter(request, res);
}

@Override
public void destroy() {
}
}

Settings2控制器     @CrossOrigin     @RestController     public class SettingsController {

@CrossOrigin
@RequestMapping(value = "/", method = { RequestMethod.POST })
public String getPagePost(HttpServletResponse response) {

    return "home";
}

@RequestMapping(value = "/", method = RequestMethod.OPTIONS)
public ResponseEntity handle() {
    return new ResponseEntity(HttpStatus.OK);
}
 }

设置2 pom

 <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.ddavey</groupId>
<artifactId>settings</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>

<name>settings2</name>
<description>Development Team Register Application</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.0.RELEASE</version>
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>


</project>

Settings2 app启动日志(即使发送请求也没有进一步记录):

。 ____ _ __ _ _  / \ / &#39; __ _ )_ __ __ _ \ \ \ \ (()_ |&#39; _ |&#39; | |&#39; / `| \ \ \ \  \ / )| | )| | | | | || ( | |))))   &#39; | ____ | | | | | | | __,| / / / / /  ========= | _ | ============== | ___ / = / / / _ /  :: Spring Boot ::(v2.0.0.RELEASE)

2018-03-15 13:04:07,585 2029 [restartedMain] DEBUG o.s.s.c.a.a.c.AuthenticationConfiguration $ EnableGlobalAuthenticationAutowiredConfigurer - 急切地初始化{webSecurityConfig=com.ddavey.settings.WebSecurityConfig$$EnhancerBySpringCGLIB $ 5891dd83@30260b10} 2018-03-15 13:04:07,724 2168 [restartedMain] INFO osswDefaultSecurityFilterChain - 创建过滤链:org.springframework.security.web.util.matcher.AnyRequestMatcher @ 1,[org.springframework.security.web.context.request .async.WebAsyncManagerIntegrationFilter @ 52e26e68,org.springframework.security.web.context.SecurityContextPersistenceFilter @ 624ab72f,org.springframework.security.web.header.HeaderWriterFilter @ 618df83a,org.springframework.web.filter.CorsFilter @ 1f0c50a,org.springframework .security.web.csrf.CsrfFilter @ 174cc9cb,org.springframework.security.web.authentication.logout.LogoutFilter @ 4fddc7f,org.springframework.security.web.savedrequest.RequestCacheAwareFilter@23710a6c,org.springframework.security.web.servletapi .SecurityContextHolderAwareRequestFilter @ 231f9098,org.springframework.security.web.authentication.AnonymousAuthenticationFilter @ 72fafc4,org.springframework.security.web.session.SessionManagementFilter @ 17b054e5,org.springframework.security.web.access.Excepti onTranslationFilter @ 57cd8b95]

1 个答案:

答案 0 :(得分:0)

我有同样的问题。我通过使用代理服务器方法解决了我的问题。我将我的ajax请求发送到本地服务器并使用Java后端来引入其他站点并且&#34; relay&#34;它回到了ajax请求。我没有使用SpringBoot,而是使用带有servlet的动态网站,Ajax在通过时调用这些servlet。工作得很好,可以在一个页面中以这种方式加载五个不同的网站,之后只使用我想要的其他页面来构建新的布局外观。

以下是我的出发点Code to get a Java servlet to act as a proxy?