AngularJS $http, spring TEXT response 예제

■ Spring Controller 예제

@Controller
public class TextSampleController {
  @RequestMapping(
    value = "textsample/text.do",
    method = RequestMethod.GET,
    produces=MediaType.TEXT_PLAIN_VALUE)
  @ResponseBody
  public String  text(@ModelAttribute Params params) 
    throws Exception {
    return "Hello, "+params.getName();
  }
}

 
 
 

■ angularjs $http client 예제

<!DOCTYPE html>
<html ng-app="myApp">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta charset="utf-8">
<head>
<title></title>
<script src="/js/angularjs/1.5.6/angular.js"></script>
<script src='/js/jquery/jquery-1.11.0.min.js'></script>
<script>
var myApp = angular.module("myApp",[]);
myApp.controller("myAppCtrl", function($scope,$http){
  $scope.result = "";
  $http({
    method : 'GET',
    url : '/textsample/text.do',
      params : { name:'미리내' }
  })
  .success(function(response){
    $scope.result = response;
  });
});
</script>
</head>
<body ng-controller="myAppCtrl">
  <h1>AngularJS Built-in Service $http<br/></h1>
  <hr/>
  <div>{{result}}</div>
</body>
</html>

 
 
 

■ 브라우저 결과

 
 
 

■ 클라이언트에서 POST로 요청했으면 Spring Controller에서도 POST로 받아야 하고, GET으로 요청을 했으면 GET으로 받아야 한다.
그렇지 않으면 405 (Method Not Allowed) 에러가 발생한다. 만약 GET, POST방식을 동시에 지원하고자 한다면 아래와 같이 method부분에 GET, POST를 같이 적어준다.

@RequestMapping(
  value = "textsample/text.do",
  method = {RequestMethod.POST,RequestMethod.GET},
  produces=MediaType.TEXT_PLAIN_VALUE)
@ResponseBody
public String  text(
  @ModelAttribute Params params) throws Exception {
  return "Hello, "+params.getName();
}