我有兩個web應用程序在單個tomcat實例上運行。其中之一是Spring MVC Rest應用程序,它具有基本結構,其餘控制器,服務層和與postgresql交互的DAO層。 下面你可以看到我的RestController我的角度前端應用程序無法將PUT請求發送到我的後端REST應用程序
package com.hizir.acil.main.controller;
import com.hizir.acil.main.model.Donor;
import com.hizir.acil.main.service.DonorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
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;
import org.joda.time.*;
import javax.validation.Valid;
import java.util.List;
/**
* Created by TTTDEMIRCI on 12/29/2015.
*/
@RestController
@RequestMapping("/")
public class AppController {
@Autowired
DonorService donorService;
@Autowired
MessageSource messageSource;
/*
* This method will list all existing Donors in for JSP .
*/
@RequestMapping(value = { "/", "/listAllDonors" }, method = RequestMethod.GET)
public String listDonors(ModelMap model) {
List<Donor> donors = donorService.findAllDonors();
model.addAttribute("donors", donors);
return "alldonors";
}
/*
* This method will list all existing Donors in json format.
*/
@RequestMapping(value = { "/listjson" }, method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<List<Donor>> listDonors() {
List<Donor> donors = donorService.findAllDonors();
if (donors.isEmpty()) {
return new ResponseEntity<List<Donor>>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<List<Donor>>(donors, HttpStatus.OK);
}
/*
* This method will provide the medium to add a new donor.
*/
@RequestMapping(value = { "/new" }, method = RequestMethod.GET)
public String newDonor(ModelMap model) {
Donor donor = new Donor();
model.addAttribute("donor", donor);
model.addAttribute("edit", false);
return "registration";
}
//-------------------Create a Donor--------------------------------------------------------
@RequestMapping(value = "/listjson", method = RequestMethod.POST)
public ResponseEntity<Void> createUser(@RequestBody Donor donor, UriComponentsBuilder ucBuilder) {
System.out.println("Creating Donor " + donor.getName());
// if (donorService.isUserExist(user)) {
// System.out.println("A User with name " + user.getUsername() + " already exist");
// return new ResponseEntity<Void>(HttpStatus.CONFLICT);
// }
donor.setCreationDate(new LocalDate());
donorService.saveDonor(donor);
System.out.println("donor created.............."+donor.getId());
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/listjson/{id}").buildAndExpand(donor.getId()).toUri());
return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}
//------------------- Update a donor --------------------------------------------------------
@RequestMapping(method = RequestMethod.PUT)
public ResponseEntity<Donor> updateUser(@PathVariable("id") int id, @RequestBody Donor donor) {
System.out.println("Updating donor " + id);
Donor currentDonor = donorService.findById(id);
// if (currentUser==null) {
// System.out.println("User with id " + id + " not found");
// return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
// }
currentDonor.setName(donor.getName());
currentDonor.setSurname(donor.getSurname());
currentDonor.setBloodType(donor.getBloodType());
donorService.updateDonor(currentDonor);
return new ResponseEntity<Donor>(currentDonor, HttpStatus.OK);
}
/*
* This method will be called on form submission, handling POST request for
* saving donor in database. It also validates the user input
*/
@RequestMapping(value = { "/new" }, method = RequestMethod.POST)
public String saveDonor(@Valid Donor donor, BindingResult result,
ModelMap model) {
if (result.hasErrors()) {
return "registration";
}
donorService.saveDonor(donor);
model.addAttribute("success", "Donor " + donor.getName() + " registered successfully");
return "success";
}
/*
* This method will provide the medium to update an existing Donor.
*/
@RequestMapping(value = { "/edit-{id}-donor" }, method = RequestMethod.GET)
public String editDonor(@PathVariable int id, ModelMap model) {
Donor donor= donorService.findById(id);
model.addAttribute("donor", donor);
model.addAttribute("edit", true);
return "registration";
}
/*
* This method will be called on form submission, handling POST request for
* updating donor in database. It also validates the user input
*/
@RequestMapping(value = { "/edit-{id}-donor" }, method = RequestMethod.POST)
public String updateDonor(@Valid Donor donor, BindingResult result,
ModelMap model, @PathVariable int id) {
if (result.hasErrors()) {
return "registration";
}
// if(!service.isEmployeeSsnUnique(employee.getId(), employee.getSsn())){
// FieldError ssnError =new FieldError("employee","ssn",messageSource.getMessage("non.unique.ssn", new String[]{employee.getSsn()}, Locale.getDefault()));
// result.addError(ssnError);
// return "registration";
// }
donorService.updateDonor(donor);
model.addAttribute("success", "Donor " + donor.getName() + " updated successfully");
return "success";
}
/*
* This method will delete a donor by it's id value.
*/
@RequestMapping(value = { "/delete-{id}-donor" }, method = RequestMethod.GET)
public String deleteDonorById(@PathVariable int id) {
donorService.deleteDonorById(id);
return "redirect:/listAllDonors";
}
}
正如你可以看到有幾個請求映射。列出捐贈者和創建捐助者在前端應用程序中工作良好,我可以創建新捐助者並列出它們。但是,當我嘗試更新任何請求不訪問此休息控制器方法。 以下是我的角色服務的前端應用程序。
App.factory('User', [
'$resource',
function($resource) {
return $resource(
'http://localhost:8080/HizirAcilBackendApp/listjson/:id', {id: '@id'}, {
update : {
method : 'PUT'
}
},
{
stripTrailingSlashes: false
});
} ]);
以下是我的角度控制器
/**
*
*/
'use strict';
App.controller('UserController', ['$scope', 'User', function($scope, User) {
var self = this;
self.user= new User();
self.users=[];
self.fetchAllUsers = function(){
self.users = User.query();
};
self.createUser = function(){
self.user.$save(function(){
self.fetchAllUsers();
});
};
self.updateUser = function(){
self.user.$update(function(){
self.fetchAllUsers();
});
};
self.deleteUser = function(identity){
var user = User.get({id:identity}, function() {
user.$delete(function(){
console.log('Deleting user with id ', identity);
self.fetchAllUsers();
});
});
};
self.fetchAllUsers();
self.submit = function() {
if(self.user.id==null){
console.log('Saving New User', self.user);
self.createUser();
}else{
console.log('Upddating user with id ', self.user.id);
self.updateUser();
console.log('User updated with id ', self.user.id);
}
self.reset();
};
self.edit = function(id){
console.log('id to be edited', id);
for(var i = 0; i < self.users.length; i++){
if(self.users[i].id === id) {
self.user = angular.copy(self.users[i]);
break;
}
}
};
self.remove = function(id){
console.log('id to be deleted', id);
if(self.user.id === id) {//If it is the one shown on screen, reset screen
self.reset();
}
self.deleteUser(id);
};
self.reset = function(){
self.user= new User();
$scope.myForm.$setPristine(); //reset Form
};
}]);
我努力學習角,休息和春天都在一個地方,我想我已經取得了良好的進展,但我還是堅持了這個PUT請求問題。 任何幫助和意見,將不勝感激。 問候 土庫曼
您是否查看了瀏覽器的調試器以瞭解瀏覽器發送的請求內容。 – Knu8
你好,下面是我的http日誌。有404錯誤代碼。什麼可能導致這一點? PUT/HizirAcilBackendApp/listjson/11 HTTP/1.1 主機:本地主機:8080 接受:應用/ JSON,純文本/,*/* 接受編碼:gzip,緊縮,SDCH 接受語言:EN-US帶連接; q = 0.8 內容類型:應用/ JSON;字符集= UTF-8 曲奇:JSESSIONID = 8112D94E896D0CC544363849DE6C3A96 產地:HTTP://本地主機:8080 的Referer:HTTP://本地主機:8080/HizirAcilFrontEnd/DonorManagement .jsp User-Agent:Mozilla/5.0(Windows NT 6.3; Win64; x64) HTTP/1.1 404 Not Found –
PUT/HizirAcilBackendApp/listjson/11 HTTP/1.1 Host:localhost:8080 接受:application/json,text/plain,*/* Accept-Encoding:gzip,deflate,sdch Accept-Language:zh-cn,en; q = 0.8 Content-Type:application/json; charset = UTF -8 曲奇:JSESSIONID = 8112D94E896D0CC544363849DE6C3A96 產地:HTTP://本地主機:8080 的Referer:HTTP://本地主機:8080/HizirAcilFrontEnd/DonorManagement.jsp 的User-Agent:Mozilla的/ 5.0(Windows NT的6.3; Win64平臺; x64)AppleWebKit/537.36(KHTML,如Gecko)Chrome/47.0.2526.80 Safari/537.36 HTTP/1.1 404 Not Found Content-Language:en 內容長度:992 –