javascript - 无法通过angular JS访问部署在tomcat上的spring Rest web服务

标签 javascript java angularjs spring tomcat

大家好,我一直在查看与此问题相关的帖子,但没有找到解决问题的方法。实际上我有一个执行 cetain 任务(后端)的 spring RestController 我想通过 angularJs 应用程序使用这些服务但是我有以下错误消息

"XMLHttpRequest cannot load http://localhost:8084/BackendHibernateJPA/abonnes. Origin http://localhost:8383 is not allowed by Access-Control-Allow-Origin. (14:19:15:639 | error, javascript)
  at app/index.html" 

当我运行 Spring Rest 项目时,我可以在浏览器上找到预期的结果。我也可以通过像“Chrome Rest client”这样的 rest client 获得结果,但是我不能使用 angularJS 来使用服务

这是我的 RestController

import com.mycompany.backendhibernatejpa.service.IAbonneService;
import com.mycompany.backendhibernatejpa.entities.Abonne;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;

/**
 *
 * @author 
 */
@CrossOrigin(origins = {"http://localhost:8383"}, methods = {RequestMethod.DELETE, RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT}, allowedHeaders = "true")
@RestController
@RequestMapping("/abonnes")
public class AbonneController {

    @Autowired
    private IAbonneService iAbonneService; //Service which will do all data retrieval/manipulation work

    //-------------------Retrieve All Abonne--------------------------------------------------------
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public ResponseEntity<List<Abonne>> findAllAbonnes() throws Exception {
        List<Abonne> listAbonnes = iAbonneService.findAll();
        if (listAbonnes.isEmpty()) {
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND
        }
        return new ResponseEntity<>(listAbonnes, HttpStatus.OK);
    }

    @RequestMapping(value = "/some/{idDomicile}", method = RequestMethod.GET)
    public ResponseEntity<List<Abonne>> findSomeAbonnes(@PathVariable("idDomicile") long idDomicile) throws Exception {
        List<Abonne> listAbonnes = iAbonneService.findSomeAbonne(idDomicile);
        if (listAbonnes.isEmpty()) {
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND
        }
        return new ResponseEntity<>(listAbonnes, HttpStatus.OK);
    }

    //-------------------Retrieve Single Abonne--------------------------------------------------------
    @RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Abonne> findAbonneById(@PathVariable("id") long id) throws Exception {
        System.out.println("Fetching User with id " + id);
        Abonne user = iAbonneService.findById(id);
        if (user == null) {
            System.out.println("Abonne with id " + id + " not found");
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<>(user, HttpStatus.OK);
    }
    //-------------------Create an Abonne--------------------------------------------------------

    @RequestMapping(value = "/", method = RequestMethod.POST)
    public ResponseEntity<Void> createAbonne(@RequestBody Abonne abonne, UriComponentsBuilder ucBuilder) throws Exception {
        iAbonneService.create(abonne);
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/abonne/{id}").buildAndExpand(abonne.getId()).toUri());
        return new ResponseEntity<>(headers, HttpStatus.CREATED);
    }

    //------------------- Update a Abonne --------------------------------------------------------
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public ResponseEntity<Abonne> updateAbonne(@PathVariable("id") long id, @RequestBody Abonne abonne) throws Exception {
        System.out.println("Updating Abonne " + id);
        Abonne currentAbonne = iAbonneService.findById(id);
        if (currentAbonne == null) {
            System.out.println("Abonne with id " + id + " not found");
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        currentAbonne.setNomAbonne(abonne.getNomAbonne());
        currentAbonne.setTel(abonne.getTel());
        iAbonneService.update(currentAbonne);
        return new ResponseEntity<>(currentAbonne, HttpStatus.OK);
    }

    //------------------- Delete a Abonne --------------------------------------------------------
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<Abonne> deleteUser(@PathVariable("id") long id) throws Exception {
        System.out.println("Fetching & Deleting User with id " + id);
        Abonne abonne = iAbonneService.findById(id);
        if (abonne == null) {
            System.out.println("Unable to delete. Abonne with id " + id + " not found");
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        iAbonneService.delete(abonne);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }
}

这是我的servlet

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans    
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <context:component-scan base-package="com.mycompany.backendhibernatejpa.controller" />
    <mvc:annotation-driven />
    <bean id="iAbonneDao" class="com.mycompany.backendhibernatejpa.daoImpl.AbonneDaoImpl"/> 
    <bean id="iAbonneService" class="com.mycompany.backendhibernatejpa.serviceImpl.AbonneServiceImpl"/>

    <!-- couche de persistance JPA -->
    <bean id="entityManagerFactory"
          class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">            
                <property name="databasePlatform" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
                <property name="generateDdl" value="true" />
                <property name="showSql" value="true" />
            </bean>
        </property>
        <property name="loadTimeWeaver">
            <bean
                class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
        </property>
    </bean>

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">   
        <property name="locations" value="classpath:bd.properties"/>
    </bean>

    <!-- la source de donnéees DBCP -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" >
        <property name="driverClassName" value="${bd.driver}" />
        <property name="url" value="${bd.url}" />
        <property name="username" value="${bd.username}" />
        <property name="password" value="${bd.password}" />
    </bean>

    <!-- le gestionnaire de transactions -->

    <bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>


    <!-- traduction des exceptions -->
    <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

    <!-- annotations de persistance -->
    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

    <!--    <bean id="springSecurityFilterChain" class="org.springframework.web.filter.DelegatingFilterProxy"/>-->

</beans>

我什至在我的 web.xml 中添加了它

<!--     ================== Built In Filter Definitions ===================== -->   

<filter>
    <filter-name>CorsFilter</filter-name>
    <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
    <init-param>
        <param-name>cors.allowed.origins</param-name>
        <param-value>*</param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowed.methods</param-name>
        <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowed.headers</param-name>
        <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
    </init-param>
    <init-param>
        <param-name>cors.exposed.headers</param-name>
        <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
    </init-param>
    <init-param>
        <param-name>cors.support.credentials</param-name>
        <param-value>true</param-value>
    </init-param>
    <init-param>
        <param-name>cors.preflight.maxage</param-name>
        <param-value>10</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CorsFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<!-- ==================== Built In Filter Mappings ====================== -->

最后,这是我的 Angular 服务

'use strict';

var services = angular.module('myApp.services', ['ngResource']);
services.factory('abonneFactory', function ($resource) {
    return $resource('http://localhost:8084/BackendHibernateJPA/abonnes/', {}, {
        query: {method: 'GET', isArray: true},
        create: {method: 'POST'}
    });
});
services.factory('abonneFactory', function ($resource) {
    return $resource('http://localhost:8084/BackendHibernateJPA/abonnes/:id', {}, {
        show: {method: 'GET'},
        update: {method: 'PUT', params: {id: '@id'}},
        delete: {method: 'DELETE', params: {id: '@id'}}
    });
});

最佳答案

根据错误消息,这似乎是一个 CORS 问题 访问控制允许来源。当 站点 A 试图从 站点 B 获取内容时,就会发生这种情况。您应该在您的应用程序中实现 CORS,在后端添加此 header :

public static final HttpHeaders HTTP_HEADERS = new HttpHeaders();
static{
    HTTP_HEADERS.add("Access-Control-Allow-Headers", "Content-Type");
    HTTP_HEADERS.add("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
    HTTP_HEADERS.add("Access-Control-Allow-Origin", "*");
}

并将这些 header 添加到服务响应中,例如:

@RequestMapping(value = "/some/{idDomicile}", method = RequestMethod.GET)
public ResponseEntity<List<Abonne>> findSomeAbonnes(@PathVariable("idDomicile") long idDomicile) throws Exception {
    List<Abonne> listAbonnes = iAbonneService.findSomeAbonne(idDomicile);
    if (listAbonnes.isEmpty()) {
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND
    }
    return new ResponseEntity.ok().headers(HTTP_HEADERS).body(listAbonnes);
}

另一种选择是在浏览器中使用扩展

对于 chrome: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en

火狐浏览器 https://addons.mozilla.org/en-US/firefox/addon/cross-domain-cors/

关于javascript - 无法通过angular JS访问部署在tomcat上的spring Rest web服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43069872/

相关文章:

javascript - 使用 jquery easyui,如何通过选项卡中的链接创建选项卡?

java - textArea.setText ("") 不会清除 JTextArea 中的文本

javascript - Ionic 框架 - 弹出取消按钮不起作用 - v1.0.0-beta.1 "actinium"

angularjs - 使用 Jasmine 和 PhantomJS 进行 Angular JS 测试,0 错误

javascript - 找不到解决方案 : load images to div based on page location

javascript - 如何将元素放在两个元素之间

java - 如何在 SOAPHandler 中发送 xml 而不进行任何转换

java - 为什么 IcedTea6 不编译 Java 1.5 特定代码?

javascript - 在 AngularJS 中使用 $interpolate 来减少自动生成的观察者

javascript - JQuery 测试工具