2
서블릿을 사용하여 프로젝트에 컨트롤러를 작성해야합니다. 나는 전에 그것을했지만 AngularJS와 함께 일한 적이 없으므로, 나는 request.setAttribute()
과 을 통해 JSP 페이지 안에 자바 코드를 넣었다. 하지만 프론트 엔드 개발자는 AngularJS를 사용했으며 JSON 객체를 반환해야합니다. 그리고 나는 그것을 어떻게하는지 모른다.Java Servlet을 사용하여 AngularJS로 JSON 객체를 반환하는 방법
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');
});
}
서블릿에서 내 processRequest()
코드 : 여기 abTestCtrl.js
의 코드는
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을 반환하는 데 도움 주실 래요!
현재 서블릿은 command
매개 변수를 인식하지 못합니다. 그것은 null
이됩니다. 그러나 AngularJS 함수에는 이러한 매개 변수가 있습니다.
도움말을 무엇으로 :
그런 다음 JSON 및 응답에서 JSON 개체를 보내 응답 콘텐츠 형식을 설정? 당신은 틀린 말을하지 않고 코드를 버리는 것뿐입니다. – Gimby오류가 발생하는 경우 오류 메시지/스택 추적을 게시하여 예상 내용과 발생 상황을 자세히 설명하십시오. BTW, 나는 JSON 변환기를 사용했을 것이다. – Jimmy
@Gimby 인용 : "프론트 엔드 개발자는 AngularJS를 사용했기 때문에 JSON 객체를 반환해야합니다. 어떻게 해야할지 잘 모릅니다." JSON 객체를 AngularJS로 반환 할 수 없다는 것이 분명합니다. – mityakoval