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

时间:2014-12-04 15:34:21

标签: java javascript json angularjs servlets

我必须使用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!

BTW,Servlet不识别command参数。得到null。但是AngularJS函数中有这样的参数。

1 个答案:

答案 0 :(得分:1)

尝试使用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();