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);
}
입니다이것은 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;
}
}
희망 : 당신은 당신의 방법 위의이 주석으로 그렇게? – jstuartmilne
또한 전체 컨트롤러 코드를 게시 할 수 있습니까? @RequestMapping ("/ api")으로 주석을다는 것을 잊었을 가능성이 있습니까? – vtosh
Sudakatux - 아니요. "/"경로로 리디렉션됩니다. 404 오류 상태를 리턴합니다. – cleem