[英]Spring boot - angularjs using rest controller in http.get returns status 404
I am trying to get a data from the server using JPA repository and spring restcontroller passed to the http.get method of the angularjs.
我正在尝试使用JPA存储库从服务器获取数据,并将spring restcontroller传递给angularjs的http.get方法。 but when I view it in console.log, it shows: angular.js:11048 GET http://127.0.0.1:8096/api/shipmentcount/sample 404 (Not Found).
但是当我在console.log中查看它时,它显示:angular.js:11048 GET http://127.0.0.1:8096/api/shipmentcount/sample 404(未找到)。 What seems to be wrong?
怎么了?
master.controller.js - function
master.controller.js-功能
$scope.countTrips = function() {
$http.get("/api/shipmentcount/sample").success(function(response) {
console.log(response);
});
}
$scope.countTrips();
ShipmentResources.java - requestmapping with a method get
ShipmentResources.java-使用方法get的请求映射
@RequestMapping(value="/shipmentcount/sample", method=RequestMethod.GET)
public List<Shipment> getshipmentCount() {
return shipmentRepository.findAll();
}
ShipmentRepository.java
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);
}
This is the Shipment.java
这是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;
}
What am I trying to do is to get the status column in the table shipment.
我想做的是获取表装运中的“状态”列。 I tried creating a rest controller and integrated it with angularjs for front end.
我尝试创建一个rest控制器,并将其与angularjs集成到前端。 I cant find what is causing the problem.
我找不到导致问题的原因。 I think it cant find the the controller /api/shipmentcount/sample.
我认为找不到控制器/ api / shipmentcount / sample。 I am new to spring boot.
我是春季靴的新手。 and This is my first time developing it.
这是我第一次开发它。 What I am trying to do with the rest controller is I want to get a data from the server to be used in the charts in my dashboard.
我要使用rest控制器执行的操作是,我想从服务器获取数据以在仪表板的图表中使用。 I used chart.js for my charts.
我将chart.js用于图表。
This is my complete ShipmentResource.java - controller
这是我完整的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;
}
}
from what I see in your question it seems you have different paths. 从我在您的问题中看到的情况来看,您似乎有不同的道路。 you call:
"/api/shipmentcount/sample"
in angularJS but you have declared: "/shipmentcount/sample"
in @RequestMapping
. 您在angularJS中调用:
"/api/shipmentcount/sample"
,但在@RequestMapping
声明了: "/shipmentcount/sample"
。 You are missing "/api"
part. 您缺少
"/api"
部分。
check if your controller has an annotation: @RequestMapping(value="/api")
检查您的控制器是否具有注释:
@RequestMapping(value="/api")
if not, check in your appication.properties file if you have something like: server.contextPath=/api
如果没有,请检查您的appication.properties文件是否具有以下内容:
server.contextPath=/api
if neither, you can correct your endpoint method like so: 如果两者都不是,则可以像这样纠正端点方法:
@RequestMapping(value="/api/shipmentcount/sample", method=RequestMethod.GET)
public List<Shipment> getshipmentCount() {
return shipmentRepository.findAll();
}
also, if angularJS runs on different domain or port you need to provide the server domain and port. 另外,如果angularJS在不同的域或端口上运行,则需要提供服务器域和端口。
for example if angular runs on http://127.0.0.1:4200 and your server at http://127.0.0.1:8096 , you need to correct it like so: 例如,如果angular在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);
});
also you need to allow CORS in order to make requests from different domains. 您还需要允许CORS才能从不同的域发出请求。 You do that with this annotation above your method:
@CrossOrigin
您可以在方法上方使用以下注释进行此操作:
@CrossOrigin
I hope that helps :) 希望对您有所帮助:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.