2017-12-21 2 views
0

JPA 리포지토리와 스프링 restcontroller를 사용하여 서버에서 데이터를 가져 오려고하는데, angularjs의 http.get 메소드로 전달됩니다. 그러나 console.log에서 볼 때, angular.js : 11048 GET http://127.0.0.1:8096/api/shipmentcount/sample 404 (찾을 수 없음). 이 잘못된 것 같습니다.스프링 부트 - http.get의 rest 컨트롤러를 사용하는 angularjs가 404 상태를 반환합니다.

master.controller.js - 기능

$scope.countTrips = function() { 
    $http.get("/api/shipmentcount/sample").success(function(response) { 
     console.log(response); 
    }); 
} 

$scope.countTrips(); 

ShipmentResources.java - 방법으로 얻을 requestmapping

@RequestMapping(value="/shipmentcount/sample", method=RequestMethod.GET) 
public List<Shipment> getshipmentCount() { 
    return shipmentRepository.findAll(); 
} 

ShipmentRepository.java

package com.pahrsek.smartfleet.repository; 

import java.util.Date; 
import java.util.List; 

import org.springframework.data.jpa.repository.JpaRepository; 
import org.springframework.data.jpa.repository.JpaSpecificationExecutor; 
import org.springframework.data.jpa.repository.Query; 
import org.springframework.stereotype.Repository; 

import com.pahrsek.smartfleet.dto.ShipmentSummary; 
import com.pahrsek.smartfleet.model.Company; 
import com.pahrsek.smartfleet.model.Customer; 
import com.pahrsek.smartfleet.model.Shipment; 
import com.pahrsek.smartfleet.model.Shipment.Status; 
import com.pahrsek.smartfleet.model.Vehicle; 

@Repository 
public interface ShipmentRepository extends JpaRepository<Shipment, Long>, JpaSpecificationExecutor<Shipment>{ 



    @Query(value="select new com.pahrsek.smartfleet.dto.ShipmentSummary(ship.status as status, " 
      + "count(ship.id) as recordCount " 
      + ") from Shipment ship where ship.company=?1 and ship.dateCreated>=?2 AND ship.dateCreated <=?3 group by ship.status") 
    public List<ShipmentSummary> summaryByStatus(Company company, Date from, Date to); 

    public List<Shipment> findFirst10ByVehicle(Vehicle vehicle); 

    public List<Shipment> findByVehicle(Vehicle vehicle); 

    public Shipment findByIdAndCompany(Long id, Company company); 

    public List<Shipment> findByStatus(Status status); 

    public List<Shipment> findByCustomerAndDepotAndOriginAndTypeAndCommodityTypeAndDateCreatedAfter(Customer customer, String depot, String origin, String type, String commodityType, Date dateCreated); 

} 

그리고 이것은 로그입니다 enter image description here

이것은 Shipment.java

입니다
package com.pahrsek.smartfleet.model; 

import java.util.ArrayList; 
import java.util.Date; 
import java.util.List; 

import javax.persistence.Column; 
import javax.persistence.Entity; 
import javax.persistence.EnumType; 
import javax.persistence.Enumerated; 
import javax.persistence.FetchType; 
import javax.persistence.GeneratedValue; 
import javax.persistence.GenerationType; 
import javax.persistence.Id; 
import javax.persistence.JoinColumn; 
import javax.persistence.ManyToOne; 
import javax.persistence.OneToMany; 
import javax.persistence.Table; 

import com.fasterxml.jackson.annotation.JsonIgnore; 


/** 
* Delivery of goods 
* @author JRDomingo 
* 
*/ 
@Entity 
@Table(name="shipment") 
public class Shipment { 

    @Id 
    @GeneratedValue(strategy=GenerationType.AUTO) 
    public Long id; 

    @Column(name="booking_number",unique=true) 
    public String bookingNumber; 

    @Column(name="wb_number") 
    public String wbNumber; 

    @ManyToOne 
    @JoinColumn(name="vehicle_id", referencedColumnName="id") 
    public Vehicle vehicle; 

    @ManyToOne 
    @JoinColumn(name="customer_id", referencedColumnName="id") 
    public Customer customer; 

    public String origin; 

    public String depot; 

    @ManyToOne 
    @JoinColumn(name="vendor_id", referencedColumnName="id") 
    public Vendor vendor; 

    public String type; 

    @Column(name="commodity_type") 
    public String commodityType; 

    @Column(name="truck_type") 
    public String truckType; 

    @Enumerated(EnumType.STRING) 
    public Status status; 

    @Column(name="delivery_date") 
    public Date deliveryDate; 

    @Column(name="fuel_po") 
    public String fuelPo; 

    @Column(name="client_ref_no") 
    public String clientReferenceNumber; 

    public String remarks; 

    @ManyToOne 
    @JoinColumn(name="driver_id",referencedColumnName="id") 
    public Personnel driver; 

    @ManyToOne 
    @JoinColumn(name="helper1_id",referencedColumnName="id") 
    public Personnel helper1; 

    @ManyToOne 
    @JoinColumn(name="helper2_id",referencedColumnName="id") 
    public Personnel helper2; 


    public enum Status{ 
     New, Dispatched, Delivered, Completed, Cancelled 
    } 

    /****** 
    * ACTUAL DATES IMPLEMENTED 
    ******/ 
    @Column(name="date_created") 
    public Date dateCreated; 

    @Column(name="date_dispatched") 
    public Date dateDispatched; 

    @Column(name="date_completed") 
    public Date dateCompleted; 

    @Column(name="date_cancelled") 
    public Date dateCancelled; 

    @Column(name="date_received") 
    public Date dateReceived; 

    @Column(name="farthest_destination") 
    public String farthestDestination; 

    @Column(name="client_rate") 
    public Double clientRate; 

    @Column(name="is_sub_con") 
    public boolean isSubCon; 

    @Column(name="sub_con_rate") 
    public Double subConRate; 

    @Column(name="fuel") 
    public Double fuel; 

    @Column(name="fuel_amount") 
    public Double fuelAmount; 

    @Column(name="route_code") 
    public String routeCode; 

    @ManyToOne 
    @JsonIgnore 
    @JoinColumn(name="dispatched_odometer_id",referencedColumnName="id") 
    public RegularOdometerUsage dispatchedOdometer; 

    @ManyToOne 
    @JsonIgnore 
    @JoinColumn(name="delivered_odometer_id",referencedColumnName="id") 
    public RegularOdometerUsage deliveredOdometer; 

    @ManyToOne 
    @JsonIgnore 
    @JoinColumn(name="completed_odometer_id",referencedColumnName="id") 
    public RegularOdometerUsage completedOdometer; 


    /** 
    * index 0 = Driver , index 1 = Helper1, index 2 = Helper2 
    */ 
    @JsonIgnore 
    @OneToMany(mappedBy="shipment",targetEntity=PersonnelRate.class) 
    public List<PersonnelRate> personnelRates = new ArrayList<PersonnelRate>(); 

    @JsonIgnore 
    @ManyToOne 
    @JoinColumn(name="company_id", referencedColumnName="id") 
    public Company company; 


    @JsonIgnore 
    @ManyToOne 
    @JoinColumn(name="prepared_user_id", referencedColumnName="id") 
    public User preparedBy; 


    @JsonIgnore 
    @ManyToOne 
    @JoinColumn(name="customer_invoice", referencedColumnName="id") 
    public CustomerInvoice customerInvoice; 

    @JsonIgnore 
    @ManyToOne 
    @JoinColumn(name="trucker_settlement", referencedColumnName="id") 
    public TruckerSettlement truckerSettlement; 

} 

난의 상태 열을 얻기 위해하는 것입니다 노력하고 무엇 테이블 선적. 나는 나머지 컨트롤러를 만들려고 시도하고 프런트 엔드에 대한 angularjs와 통합. 문제의 원인을 찾을 수 없습니다. 나는 컨트롤러/api/shipmentcount/sample을 찾을 수 없다고 생각한다. 나는 봄 부츠를 처음 사용한다. 이것은 처음 개발하는 것입니다. 나머지 컨트롤러를 사용하여 수행하려는 작업은 서버의 데이터를 대시 보드의 차트에 사용하고자하는 것입니다. 내 차트에 chart.js를 사용했습니다.

이 내 완료 ShipmentResource.java입니다 - 나는 귀하의 질문에 당신이 다른 경로가있을 것 같다 무엇을보고에서 컨트롤러

package com.pahrsek.smartfleet.web.rest; 

import java.net.URISyntaxException; 
import java.text.DateFormat; 
import java.text.ParseException; 
import java.text.SimpleDateFormat; 
import java.util.ArrayList; 
import java.util.Date; 
import java.util.HashMap; 
import java.util.List; 
import java.util.Map; 

import javax.servlet.http.HttpServletRequest; 

import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.beans.factory.annotation.Value; 
import org.springframework.data.domain.Page; 
import org.springframework.data.domain.Pageable; 
import org.springframework.data.domain.Sort; 
import org.springframework.data.domain.Sort.Direction; 
import org.springframework.http.HttpHeaders; 
import org.springframework.http.HttpStatus; 
import org.springframework.http.ResponseEntity; 
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.RequestParam; 
import org.springframework.web.bind.annotation.RestController; 

import com.pahrsek.smartfleet.dto.ShipmentDTO; 
import com.pahrsek.smartfleet.dto.ShipmentSummary; 
import com.pahrsek.smartfleet.dto.SimpleVehicle; 
import com.pahrsek.smartfleet.model.Company; 
import com.pahrsek.smartfleet.model.Shipment; 
import com.pahrsek.smartfleet.model.Shipment.Status; 
import com.pahrsek.smartfleet.model.ShipmentCharge; 
import com.pahrsek.smartfleet.model.Vehicle; 
import com.pahrsek.smartfleet.repository.PersonnelRateRepository; 
import com.pahrsek.smartfleet.repository.PersonnelRepository; 
import com.pahrsek.smartfleet.repository.ShipmentChargeRepository; 
import com.pahrsek.smartfleet.repository.ShipmentRepository; 
import com.pahrsek.smartfleet.security.SecurityUtils; 
import com.pahrsek.smartfleet.service.ShipmentService; 
import com.pahrsek.smartfleet.web.rest.filter.ShipmentFilter; 
import com.pahrsek.smartfleet.web.rest.filter.VehicleFilter; 
import com.pahrsek.smartfleet.web.rest.util.PaginationUtil; 

@RestController 
@RequestMapping("/api") 
public class ShipmentResource { 

    private static final Logger logger = LoggerFactory.getLogger(ShipmentResource.class); 

    @Autowired 
    ShipmentService shipmentService; 

    @Autowired 
    ShipmentRepository shipmentRepository; 

    @Autowired 
    PersonnelRateRepository personnelRateRepository; 

    @Autowired 
    PersonnelRepository personnelRepository; 

    @Autowired 
    ShipmentChargeRepository shipmentChargeRepository; 

// @Value("#{'${jentec.shipmentTypes}'.split(',')}") 
    public List<String> shipmentTypes; 

    @Value("${jentec.shipment.footer}") 
    public String shipmentFooter; 

    @RequestMapping(value="/shipments", method=RequestMethod.POST) 
    public void create(@RequestBody ShipmentDTO request){ 
     Company company = SecurityUtils.getCurrentCompany(); 
     String depot = null; 

     Shipment shipment = shipmentService.save(request,company); 
     logger.info("shipment saved:{}",shipment); 
    } 


    @RequestMapping(value="/shipments/{shipmentId}/status", method=RequestMethod.POST) 
    public void saveDispatch(@PathVariable("shipmentId")Long shipmentId, @RequestBody UpdateStatusDTO request){ 
     shipmentService.updateStatus(shipmentId, request); 
    } 

    @RequestMapping(value="/shipmentcount", method=RequestMethod.GET) 
    public List<Shipment> getshipmentCount() { 
     return shipmentRepository.findAll(); 
    } 

    @RequestMapping(value="/shipments", method=RequestMethod.GET) 
    public ResponseEntity<List<ShipmentDTO>> list(@RequestParam(value="page", defaultValue="1") int page, 
      @RequestParam(value="per_page", defaultValue="10") int size, 
      @RequestParam(value="sort", defaultValue="id") String sort, 
      @RequestParam(value="direction", defaultValue="DESC") Direction direction, 
      HttpServletRequest request) throws URISyntaxException{ 
     Pageable pageRequest = PaginationUtil.generatePageRequest(page, size, new Sort(direction,sort)); 
     Company company = SecurityUtils.getCurrentCompany(); 
     String depot = SecurityUtils.getCurrentDepot(); 
     Page<Shipment> pageResult = shipmentRepository.findAll(new ShipmentFilter(request, company, depot), pageRequest); 
     HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(pageResult, "/api/shipments", page, size); 
     List<ShipmentDTO> shipmentDTOs = new ArrayList<ShipmentDTO>(); 
     for(Shipment shipment:pageResult.getContent()){ 
      shipmentDTOs.add(new ShipmentDTO(shipment, true)); 
     } 

     return new ResponseEntity<List<ShipmentDTO>>(shipmentDTOs, headers, HttpStatus.OK); 
    } 


    @RequestMapping(value="/shipments/summary", method=RequestMethod.GET) 
    public List<ShipmentSummary> getSummary(@RequestParam("from") String from, @RequestParam("to") String to) throws URISyntaxException{ 
     Company company = SecurityUtils.getCurrentCompany(); 
     DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); 
     try { 
      return shipmentRepository.summaryByStatus(company, df.parse(from), df.parse(to)); 
     } catch (ParseException e) { 
      logger.error("Cannot parse date",e); 
      return new ArrayList<ShipmentSummary>(); 
     } 
    } 

    @RequestMapping(value="/shipmentTypes") 
    public List<String> getShipmentTypes(){ 
     return shipmentTypes; 
    } 

    @RequestMapping(value="/shipments/{id}", method=RequestMethod.GET) 
    public ResponseEntity<ShipmentDTO> get(@PathVariable("id") Long id) throws URISyntaxException{ 
     Company company = SecurityUtils.getCurrentCompany(); 
     Shipment shipment = shipmentRepository.findOne(id); 
     return new ResponseEntity<ShipmentDTO>(new ShipmentDTO(shipment, true), HttpStatus.OK); 
    } 

    @RequestMapping(value="/shipments/{id}/charges", method=RequestMethod.GET) 
    public List<ShipmentCharge> getCharges(@PathVariable("id") Long shipmentId){ 
     return shipmentChargeRepository.findByShipmentId(shipmentId); 
    } 


    @RequestMapping(value="/shipmentFooter", method=RequestMethod.GET) 
    public Map<String,String> getShipmentFooter(){ 
     Map<String,String> footer = new HashMap<String,String>(); 
     footer.put("message", shipmentFooter); 
     return footer; 
    } 

    public static class UpdateStatusDTO{ 
     public Status status; 
     public Date date; 
     //for delivery date 
     public Date deliveryDate; 
     public Integer odometer; 
     public Double clientRate; 
     public String remarks; 
     public String farthestDestination; 
     public Double fuel; 
     public String fuelPo; 
     public Double fuelAmount; 
     public String clientReference; 
     public String routeCode; 
    } 
} 
+0

희망 : 당신은 당신의 방법 위의이 주석으로 그렇게? – jstuartmilne

+0

또한 전체 컨트롤러 코드를 게시 할 수 있습니까? @RequestMapping ("/ api")으로 주석을다는 것을 잊었을 가능성이 있습니까? – vtosh

+0

Sudakatux - 아니요. "/"경로로 리디렉션됩니다. 404 오류 상태를 리턴합니다. – cleem

답변

0

. angularJS에서 "/api/shipmentcount/sample"을 호출했지만 "/shipmentcount/sample"@RequestMapping으로 선언했습니다. "/api" 부분이 누락되었습니다. 둘 다, 당신과 같이 엔드 포인트 방법을 수정할 수없는 경우 server.contextPath=/api

:

컨트롤러가 주석이 체크 경우 : @RequestMapping(value="/api")

그렇지 않은 경우, 당신은 같은이있는 경우 파일을 당신의 appication.properties 체크인 :

@RequestMapping(value="/api/shipmentcount/sample", method=RequestMethod.GET) 
public List<Shipment> getshipmentCount() { 
    return shipmentRepository.findAll(); 
} 

angleJS가 다른 도메인이나 포트에서 실행되는 경우 서버 도메인과 포트를 제공해야합니다.예를 들어

는 각 http://127.0.0.1:4200에서 실행하고 http://127.0.0.1:8096에서 서버, 당신은 지금처럼 수정해야하는 경우 :

$http.get("http://127.0.0.1:8096/api/shipmentcount/sample").success(function(response) { 
    console.log(response); 
}); 

또한 다른 도메인의 요청을 만들기 위해 CORS를 허용해야합니다. // YOURHOST : 8080/shipmentcount/sample`이 예상되는 응답을 볼 수 있습니까 당신은`HTTP를 치면 @CrossOrigin

나는이 도움이 :)

+0

Vasilis Antonakis의 답변에 감사드립니다. 하지만 여전히 각도를 반환하고 있습니다 .js : 11048 GET http://127.0.0.1:8096/api/shipmentcount/sample 404 (찾을 수 없음). 컨트롤러에 전체 코드를 제공했습니다. 고맙습니다. – cleem

+0

OK :) @RequestMapping (value = "/ shipmentcount/sample") 메소드가 아니라 사용자의 컨트롤러에서 메소드에서 '@RequestMapping (value = "/ shipmentcount", method = RequestMethod.GET) = RequestMethod.GET)':) 그게 맞습니까? –

+0

아, 죄송합니다. 실수로 복사 한 후 실수로 삭제했습니다. 하지만 여전히 각도가 돌아오고 있습니다 .js : 11048 GET http://127.0.0.1:8096/api/shipmentcount/sample 404 (찾을 수 없음). – cleem

관련 문제