【发布时间】:2016-12-24 14:40:59
【问题描述】:
我正在构建一个简单的 Angular.js、Java HttpServlet、MongoDB Web 项目。不幸的是,由于我是 Angular 和 HttpServlet 的新手,所以我遇到了一些问题。 GET(获取所有版本)和 POST 方法一直工作正常,通过 Java 服务从 Mongo 插入和检索到 Angular UI。
但是,尽管我更新了 tomcat 的 xml 文件以允许按照本网站上的其他答案进行操作,但 DELETE 仍返回 405 method not allowed 错误。然后我尝试创建一个 GET 方法以允许按 ID 检索单个类别,但尽管与现有代码几乎相同,但失败并出现 404 错误。
问题:
我是否需要 POST 到 /angular/1 之类的 url,或者是否可以 POST 为 /angular,因为它正在工作?
失败的 getByID 方法是否使 DELETE 无法正常工作,或者如果没有,问题是什么?
最后:为什么 getByID 方法会遇到 404?
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset="ISO-8859-1">
<title>AJAX with Servlets using AngularJS</title>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script>
var app = angular.module('myApp', []).controller("MyController", MyController);
function MyController($scope, $http) {
$scope.getDataFromServer = function() {
$http({
method : 'GET',
url : '/Service4/angular'
}).success(function(data, status, headers, config) {
$scope.category = data;
}).error(function(data, status, headers, config) {
});
};
$scope.deleteCategory = function() {
$http({
method : 'DELETE',
url : '/Service4/angular',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: 'id='+ $scope.deleteCat
}).success(function(data, status, headers, config) {
//display data, removed for brevity
}).error(function(data, status, headers, config) {
});
};
$scope.postDataToServer = function() {
$http({
method : 'POST',
url : '/Service4/angular',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: 'name='+ $scope.name
}).success(function(data, status, headers, config) {
$http({
method : 'GET',
url : '/Service4/angular'
}).success(function(data, status, headers, config) {
$scope.category = data;
}).error(function(data, status, headers, config) {
});
}).error(function(data, status, headers, config) {
});
};
$scope.getCatByID = function(getID) {
$http({
method : 'GET',
url : '/Service4/angular/' + $scope.getID
}).success(function(data, status, headers, config) {
$scope.category = data;
}).error(function(data, status, headers, config) {
});
};
};
</script>
</head>
<body>
<div ng-app="myApp">
<div ng-controller="MyController">
<button ng-click="getDataFromServer()">Fetch data from
server</button>
<table>
<tr ng-repeat="c in category">
<td>{{c._id}}</td>
<td>{{c.name}}</td>
</tr>
</table>
<form ng-submit="postDataToServer()">
<input ng-model="name" type="text" name="name" />
<button type="submit">Send</button>
</form>
<form ng-submit="deleteCategory()">
<input ng-model="delete" type="text" name="deleteCat" />
<button type="submit">Delete</button>
</form>
<form ng-submit="getCatByID()">
<input ng-model="getID" type="text" name="getID" />
<button type="submit">Get by ID</button>
</form>
</div>
</div>
</body>
</html>
/**
* Servlet implementation class TestServlet
*/
@WebServlet("/angular")
public class AngularServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private int idCount = 0;
private DB db;
private MongoClient mongo;
private DBCollection col;
/**
* @see HttpServlet#HttpServlet()
*/
public AngularServlet() {
super();
// TODO Auto-generated constructor stub
}
@GET
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
//mongo cursor creation removed for brevity
List<DBObject> all2 = cursor.toArray();
String json = new Gson().toJson(all2);
response.setContentType("application/json");
response.getWriter().write(json);
out.close();
}
@GET
@Path("/{id}")
protected void getCategoryByID(HttpServletRequest request,
HttpServletResponse response, @PathParam("id") String id) throws ServletException, IOException {
//mongo manipulation removed for brevity
List<DBObject> all2 = cursor.toArray();
String json = new Gson().toJson(all2);
response.setContentType("application/json");
response.getWriter().write(json);
out.close();
}
/**
* @see HttpServlet#doDelete(HttpServletRequest request, HttpServletResponse response)
*/
@DELETE
protected void doDELETE(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
String id = "";
id = request.getParameter("id");
Category cat = new Category();
cat.setId(Integer.parseInt(id));
DBObject query = BasicDBObjectBuilder.start().add("_id", cat.getId()).get();
WriteResult result = col.remove(query);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
@POST
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
String name = "";
name = request.getParameter("name");
//removed for brevity
}
private static DBObject createDBObject(Category cat) {
//removed for brevity
}
}
【问题讨论】:
标签: javascript java html angularjs servlets