2

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:

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:

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!

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

5
  • Help with what? You're just dumping some code without saying what's wrong. Commented Dec 4, 2014 at 15:52
  • If you are getting error, post the error messages/stack traces detailing what was expected and what is happening. BTW, I would have used JSON converter If I were you. Commented Dec 4, 2014 at 15:56
  • @Gimby cite: "But now frontend developer used AngularJS and I have to return him a JSON object. And I have no idea how to do it." It's seems obviously for me, that I can't return JSON object to AngularJS. Commented Dec 5, 2014 at 16:26
  • @mityakoval request.getparameter() is always returning null for me also. How did you fix it? Commented Jun 26, 2015 at 7:00
  • @kittu the problem was in AngularJS code. You should send the parameters clearly. For example, instead of $http.get('http://localhost:8080/UIUM_IMT4003/ABTestController', {command:'getTestCaseInfo', testcaseID:$scope.getParam}) you should write http://localhost:8080/UIUM_IMT4003/ABTestController?command=getTestCaseInfo&testcaseID='+$scope.getParam+''. As soon as I did that it worked. Commented Jul 25, 2015 at 16:45

1 Answer 1

1

Try using the javax.json.JsonObject as follow:

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:

response.setContentType("application/json");// set content to json
PrintWriter out = response.getWriter();
out.print(jo);
out.flush();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.