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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27297879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:17:30  来源:igfitidea点击:

How to return JSON object to AngularJS using Java Servlet

javajavascriptjsonangularjsservlets

提问by mityakoval

I have to write a controller in my project using servlets. I've done it before but I've never worked with AngularJS, so I did it via request.setAttribute()and request.getParameter()and put Java code inside of a JSP page. But now frontend developer used AngularJS and I have to return him a JSON object. And I have no idea how to do it. Here's the code of abTestCtrl.js:

我必须使用 servlet 在我的项目中编写一个控制器。我以前做过,但我从来没有与AngularJS工作,所以我通过做了它request.setAttribute()request.getParameter(),并把JSP页面的Java代码内。但是现在前端开发人员使用了 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');
            });
        }

and my processRequest()code from the servlet:

和我processRequest()的 servlet 代码:

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());
        }       

Can you please help me to process this request and finally return this poor JSON!

你能帮我处理这个请求并最终返回这个可怜的 JSON!

BTW, Servlet doesn't recognize commandparameter. It gets null. But there is such parameter in AngularJS function.

顺便说一句,Servlet 不识别command参数。它得到null。但是AngularJS函数中有这样的参数。

采纳答案by cн?dk

Try using the javax.json.JsonObjectas follow:

尝试使用javax.json.JsonObject如下:

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

Then set the response content type to json and send your json object in the response:

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

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