如何使用Java Servlet将JSON对象返回到AngularJS

How to return JSON object to AngularJS using Java Servlet

本文关键字:对象 返回 AngularJS JSON 何使用 Java Servlet      更新时间:2023-09-26

我必须使用 servlet 在我的项目中编写一个控制器。我以前做过,但我从来没有使用过AngularJS,所以我通过request.setAttribute()request.getParameter()做到了,并将Java代码放在JSP页面中。但是现在前端开发人员使用了AngularJS,我必须向他返回一个JSON对象。我不知道该怎么做。这是abTestCtrl.js的代码:

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 函数中有这样的参数。

尝试按如下方式使用javax.json.JsonObject

JsonObject jo=Json.createObjectBuilder()
            .add("id", testcaseId)
            .add("title", testcase.getTestcaseName())
            .add("testscenario", testcase.getTestcaseDescription()).build();

然后将响应内容类型设置为 json,并在响应中发送 json 对象:

response.setContentType("application/json");// set content to json
PrintWriter out = response.getWriter();
out.print(jo);
out.flush();