错误500后角球衣

时间:2018-06-01 14:14:20

标签: java angular kendo-ui jersey

我在球衣休息时遇到问题。当我执行更新操作时,eclipse控制台和浏览器控制台显示错误。

对于eclipse的控制台,错误是:

    GRAVE: Servlet.service() for servlet [JerseyWebApplication] in context with path [/APIRest] threw exception [java.lang.IllegalArgumentException: argument type mismatch] with root cause
java.lang.IllegalArgumentException: argument type mismatch
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.eclipse.yasson.internal.model.SetWithSetter.internalSetValue(SetWithSetter.java:27)

对于浏览器的控制台,错误是:

POST http://localhost:8081/APIRest/resources/langue/update 500 (Erreur Interne de Servlet)
localhost/:1 Failed to load http://localhost:8081/APIRest/resources/langue/update: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 500.
update-langue.component.ts:31 Error saving langue!
(anonymous) @ update-langue.component.ts:31

这是我的DAO代码

@Override
    public void update(Langue object) {
        // TODO Auto-generated method stub
        EntityManager em = emf.createEntityManager();
        try {
            em.getTransaction().begin();
            em.merge(object);
            em.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("Erreur lors de la mise a jour d'une Langue");
        } finally {
            if (em.getTransaction().isActive())
                em.getTransaction().rollback();
            em.close();
        }

    }

这是我的休息代码

@Path("/update")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public void update(Langue langue) {
        langueDao.update(langue);
    }

这是我的角度代码服务

    import {Injectable} from '@angular/core';
    import {Http, Response, RequestOptions, Headers, ResponseContentType} from '@angular/http';
    import {AppSettingsService} from "./config.service";
    import { Langue } from "./langue";
    import {Observable} from 'rxjs/Observable';

    @Injectable()
    export class LangueService {

      private baseUrl: string = '';
      private settings: any;

      constructor(private http: Http, private appSettingsService: AppSettingsService) {
        this.appSettingsService.getSettings()
          .subscribe(settings => {
            this.settings = settings;
            this.baseUrl = this.settings.pathAPI + "/langue";
          });

      }
      // lister toutes les Langues
      getAll(): Observable<any[]> {
        let langue$ = this.http
          .get(`http://localhost:8081/APIRest/resources/langue/getall`, this.appSettingsService.setHeaders())
          .map((response: Response) => response.json())
        return langue$;
      }
//create langue
      create(langue: Langue): Observable<Response> {
        return this.http.post(`http://localhost:8081/APIRest/resources/langue/add`, JSON.stringify(langue), this.appSettingsService.setHeaders());
      }
      //delete a langue
      delete(langue: any): Observable<Response> {
        return this.http.post(`http://localhost:8081/APIRest/resources/langue/delete`, JSON.stringify(langue), this.appSettingsService.setHeaders());
      }
      // modifier une langue
      update(langue:Langue) {
        return this.http.post('http://localhost:8081/APIRest/resources/langue/update', JSON.stringify(langue), this.appSettingsService.setHeaders());
      }
    }

这是我的update-langue.component.ts

import { Langue } from "../langue";
import { LangueService } from "../langue.service";
import { LangueComponent } from "../langue/langue.component";
import { Component, OnInit, Input } from '@angular/core';
import { Observable } from "rxjs";

@Component({
  selector: 'app-update-langue',
  templateUrl: './update-langue.component.html',
  styleUrls: ['./update-langue.component.css']
})
export class UpdateLangueComponent implements OnInit {
  @Input() langue: Langue = new Langue; 


  constructor(private langueService: LangueService, private langueComponent: LangueComponent) { }

  ngOnInit() {
    this.langueService.getAll();
  }

  updateLangue() {
    this.langueService.update(this.langue).subscribe(
      data => {
                // refresh the list
                this.langueComponent.getAll()
                alert('Modification avec succes');
                return true;
              },
      error => {
                console.error("Error saving langue!");
                return Observable.throw(error);
               }
    );
  }

}

这是我的langue.component.ts

import { Langue } from "../langue";
import { LangueService } from '../langue.service';
import { Component, OnInit } from '@angular/core';
import { Observable } from "rxjs";

@Component({
  selector: 'app-langue',
  templateUrl: './langue.component.html',
  styleUrls: ['./langue.component.css']
})
export class LangueComponent implements OnInit {
  public langues;
  langue: Langue;
  constructor(private langueService: LangueService) { }

  ngOnInit() {
    this.getAll();
  }

  selectedLangue: Langue;
  modifedLangue: Langue
  getAll() {
    this.langueService.getAll().subscribe(
      data => { this.langues = data }, err => console.error(err), () => console.log('done loading langues'));
  }

  detail(langue: Langue){
    this.selectedLangue = langue;
  }

  modification(langue: Langue){
    this.modifedLangue = langue;
  }

  delete(langue) {

    if (confirm("Are you sure you want to delete " + this.langue.Id + "" + this.langue.cod + "?")) {
        this.langueService.delete(this.langue).subscribe(
          data => {
             // refresh the list
             this.getAll();
             return true;
          },
          error => {
           console.error("Error deleting langue!");
           return Observable.throw(error);
         }
      );
    }
  }
}

这是我的lang.component.html

<app-new-langue></app-new-langue>
<kendo-grid [data]="langues" [height]="410">
            <kendo-grid-column field="Id" title="ID" width="40">
            </kendo-grid-column>
            <kendo-grid-column field="cod" title="Code" width="40">
            </kendo-grid-column>
            <kendo-grid-column field="des" title="Description" width="60">
            </kendo-grid-column>
            <kendo-grid-column field="cod1" title="code 1" width="80">
            </kendo-grid-column>
            <kendo-grid-column field="cod2" title="code 2" width="80">
            </kendo-grid-column>
            <kendo-grid-column field="dat1" title="date 1" width="80">
            </kendo-grid-column>
            <kendo-grid-column field="dat1" title="date 2" width="80">
            </kendo-grid-column>
            <kendo-grid-column title="Opération" width="120">
                <ng-template kendoGridCellTemplate column="column" let-dataItem let-columnIndex="columnIndex" >
                    <button (click)="modification(dataItem)">Modifier</button>
                    <button (click)="delete(dataItem)">Supprimer</button>
                    <button (click)="detailLangue(dataItem)">Consulter</button>
                </ng-template>
            </kendo-grid-column>
 </kendo-grid>
 <app-langue-details [langue]="selectedLangue"></app-langue-details>
 <app-update-langue [langue]="modifedLangue"></app-update-langue>

这是我的更新-lang.component.html

<h2>Modification de la langue</h2>
<div *ngIf="langue">
<form>
<table>
  <!-- <tr>
      <td>Id</td><td><input name="id" [(ngModel)]="langue.langueId"/></td>
  </tr> -->
  <tr>
      <td>Code</td><td><input name="code" [(ngModel)]="langue.codlan"/></td>
  </tr>
  <tr>  
      <td>des</td><td><input name="des" [(ngModel)]="langue.deslan"/></td>
  </tr>
  <tr>    
      <td>Code1</td><td><input name="code1" [(ngModel)]="langue.codopercrehoro"/></td>
  </tr>
  <tr>    
      <td>Code2</td><td><input name="code2" [(ngModel)]="langue.codopermajhoro"/></td>
  </tr>
  <!--<tr>  
      <td>T1</td><td><input type="datetime-local" name="date1"  [(ngModel)]="langue.dattimcrehoro"/></td>
  </tr>
  <tr>
      <td>T2 </td><td><input type="datetime-local" name="date2" [(ngModel)]="langue.dattimmajhoro"/></td>
  </tr>-->
  <tr>
        <td></td><td><button (click)="updateLangue()">Enregistrer</button></td>
  </tr>
</table>
</form> 

</div>

这是我的文件配置config.service.ts

import {Injectable} from '@angular/core';
import {Http, Headers, Response, RequestOptions} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

/**
 *  Service permettant de mettre en commun des fonctions utilisées dans toute l'application
 */

@Injectable()
export class AppSettingsService {
  settings: Observable<any>;
  currentUser: any;
  toasterTradMessage: string;

  constructor(
    private http: Http,
  ) {
    this.settings = this.http.get("../../assets/appsettings.json")
      .map(this.extractData)
      .catch(this.handleErrors);
  }

  /**
  * Fonction de recuperation du lien vers l'API contenu dans le json assets/appsettings.json
  * Retour : json avec lien vers API (settings.pathAPI)
  *
  */
  getSettings(): Observable<any> {
    return this.settings;
  }

  private extractData(res: Response) {
    let body = res.json();
    return body || {};
  }

  private handleErrors(error: any): Observable<any> {
    console.error(error);
    return Observable.throw(error.message || error);
  }
}

这是我的实体lange.ts

export class Langue {
  Id: number;
  cod: string;
  des: string;
  cod1: string;
  cod2: string;
  dat1: null;
  dat2: null;
}

拜托,你能帮助我,因为它很重要,这是我第一次遇到这些问题,这就是我遇到麻烦的原因。

1 个答案:

答案 0 :(得分:0)

您对其他域的请求(在您的情况下为localhost),然后您的页面已打开。因此浏览器会阻止它,因为出于安全原因,它通常允许同一来源的请求。

http://localhost:8081/APIRest/resources/langue/update: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP状态代码500。

如果仔细查看URL,您会发现相同主机的端口号不同。

<强>更新 请参阅以下链接:

Why does my JavaScript get a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error when Postman does not?