【发布时间】:2014-06-10 16:43:57
【问题描述】:
我有通过 AngularJS 将表单数据传递给 spring 控制器的简单代码。在 chrome 调试器中,我可以看到请求传递了正确的值,但我收到一条错误消息,指出 405 (Request method 'POST' not supported) 并且我的控制器中的调试指针没有命中。所以我明白这是因为我的 POST 请求没有映射到我的控制器中,但我已经正确地完成了所有操作。
表格:-
<form name="empForm" ng-controller="insertEmpCtrl" ng-submit="insertEmp()">
<table>
<tr><td>First name: <input type="text" class="form-control" name="fname" ng-model="formData.fname"/></td></tr>
<tr><td>Last name: <input type="text" class="form-control" name="lname" ng-model="formData.lname"/></td></tr>
<tr><td>Contact no: <input type="text" class="form-control" name="contact" ng-model="formData.contactno"/></td></tr>
<tr>
<td><input type="submit" value="Save" /> <input type="reset" value="Edit"></td>
<td></td>
</tr>
</table>
AngularJS 控制器:-
empApp.controller('insertEmpCtrl',function($scope,$http){
$scope.insertEmp = function(){
$http.post("http://localhost:8080/IdeaOne#/addemp", $scope.formData, {
withCredentials: true,
headers: {'Content-Type': 'application/json'},
transformRequest: angular.identity
}).success(function(){console.log("done")}).error(function(){console.log("error")});
};
});
弹簧控制器:-
public class HelloController {
@RequestMapping(method = RequestMethod.GET)
public String home(ModelMap model){
return "hello";
}
//method redirects to hello.jsp
@RequestMapping(value="/addemp",method = RequestMethod.POST)
public String addEmployee(@RequestBody Employee employee) {
EmployeeManager.empDB.add(employee);
return "hello";
}
//method returns a link list as a json doc to the front end
@RequestMapping(value="/viewall",method = RequestMethod.GET)
public @ResponseBody
LinkedList<Employee> viewAll(ModelMap model){
return EmployeeManager.viewEmployees();
}
}
谁能帮我弄清楚我哪里出错了?
【问题讨论】:
-
1.您是否在控制器中包含
@Controller? 2. 为什么不在form中使用action? -
请检查 chrome 的控制台,看看被点击的 URL 是什么
-
value="/addemp" 应该是 value="IdeaOne#/addemp"
标签: javascript spring angularjs spring-mvc post