2
我必須在使用servlet的項目中編寫控制器。我之前做過,但我從未與AngularJS合作過,所以我通過request.setAttribute()
和request.getParameter()
完成了它,並將Java代碼放入JSP頁面中。但是現在前端開發者使用了AngularJS,我必須給他返回一個JSON對象。我不知道該怎麼做。下面是abTestCtrl.js
代碼:如何使用Java Servlet將JSON對象返回到AngularJS
app.controller("abTestCtrl", function($scope, $location, $http) {
$scope.title = "no title";
$scope.description = "no description";
$scope.getParam = $location.search()['id'];
if($scope.getParam === undefined)$scope.getParam = 0;
//$scope.getParam=2;
//path: localhost8080/UIUM.../servlet-name.java
//with two ids
//web.xml: serverlet mapping for the path
if($scope.getParam==='0'||$scope.getParam === 0){
var saveButton = document.getElementById("saveButton");
saveButton.classList.remove("hidden");
}
else{
$http.get('http://localhost:8080/UIUM_IMT4003/ABTestController', {command:'getTestCaseInfo', testcaseID:$scope.getParam}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log('request succesful');
console.log(data);
console.log(status);
console.log(headers);
console.log(config);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log('request not succesful');
});
}
和我從servlet processRequest()
代碼:
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, ClassNotFoundException {
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("application/json; charset=UTF-8");
//PrintWriter printout = response.getWriter();
JSONObject jObject = null;
RequestDispatcher view = null;
TestcaseRepository testcaseRepo = new TestcaseRepository();
String command = request.getParameter("command");
if(command == null)
{
view = request.getRequestDispatcher("/testcases.jsp");
view.forward(request, response);
}
if(command.equals("getTestCaseInfo")){
String testcaseId = request.getParameter("testcaseID");
Testcase testcase = testcaseRepo.getTestcaseById(testcaseId);
jObject = new JSONObject();
jObject.put("id", testcaseId);
jObject.put("title", testcase.getTestcaseName());
jObject.put("testscenario", testcase.getTestcaseDescription());
// printout.print(jObject);
// printout.flush();
jObject.write(response.getWriter());
}
能否請你幫我處理此請求,最後返回這個可憐的JSON!
順便說一句,Servlet不識別command
參數。它得到null
。但是在AngularJS函數中有這樣的參數。
幫助?你只是傾銷一些代碼而不會說出什麼問題。 – Gimby 2014-12-04 15:52:55
如果您遇到錯誤,請發佈錯誤消息/堆棧跟蹤,詳細說明預期的內容和發生的情況。順便說一句,我會用JSON轉換器如果我是你。 – Jimmy 2014-12-04 15:56:11
@Gimby引用:「但現在前端開發人員使用AngularJS,我必須給他返回一個JSON對象,而我不知道該怎麼做。」對我來說,看起來很明顯,我無法將JSON對象返回給AngularJS。 – mityakoval 2014-12-05 16:26:06