【问题标题】:How to return JSON object to AngularJS using Java Servlet如何使用 Java Servlet 将 JSON 对象返回给 AngularJS
【发布时间】:2015-02-02 13:26:31
【问题描述】:

我必须使用 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函数中有这样的参数。

【问题讨论】:

  • 帮助什么?您只是在转储一些代码而没有说明问题所在。
  • 如果您遇到错误,请发布错误消息/堆栈跟踪,详细说明预期内容和正在发生的事情。顺便说一句,如果我是你,我会使用 JSON 转换器。
  • @Gimby 引用:“但现在前端开发人员使用了 AngularJS,我必须返回一个 JSON 对象。我不知道该怎么做。”对我来说很明显,我无法将 JSON 对象返回给 AngularJS。
  • @mityakoval request.getparameter() 也总是为我返回 null 。你是怎么解决的?
  • @kittu 问题出在 AngularJS 代码中。您应该清楚地发送参数。例如,您应该写 http://localhost:8080/UIUM_IMT4003/ABTestController?command=getTestCaseInfo&testcaseID='+$scope.getParam+'',而不是 $http.get('http://localhost:8080/UIUM_IMT4003/ABTestController', {command:'getTestCaseInfo', testcaseID:$scope.getParam})。一旦我这样做了,它就起作用了。

标签: java javascript json angularjs servlets


【解决方案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();

【讨论】:

    猜你喜欢
    • 2018-01-30
    • 2011-01-01
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    • 2014-03-29
    • 2011-08-20
    • 2018-01-08
    • 2015-12-11
    相关资源
    最近更新 更多