1

源服务器拒绝为请求提供服务,因为负载的格式不受目标资源上此方法的支持。

控制器代码

@RestController
public class UserController
{
    @Autowired
    public IretrieveService retrieveService;

    @RequestMapping(value="/register", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ModelAndView doRegister(@RequestBody UserBean userBean,BindingResult result)
    {
        ModelAndView view = new ModelAndView("index");
        System.out.println("username "+userBean.getUsername());
        if(!result.hasFieldErrors())
        {
            if(retrieveService.insert(userBean) != null)
            {
                System.out.println("done");
            }

        }   
        return view;

    }
}

角度js代码

<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller("UserController", ['$scope', '$http', function($scope, $http, httpPostService) {
 var self=this;
 self.userBean={username:''};
$scope.insertData = function()
{
    alert($scope.userBean.username);
     $http({
         method: "POST",
         url: "register",
         data: $scope.userBean.username
        }).then(function(response){
         console.log(response.status);
         console.log("in success");

     }, function(response){
         console.log(response.status);
         console.log("in fail");     
     });
};
}]);
</script>


<form method="post" action="register" name="myForm">
      <label for="username" class="control-label">First Name:</label>
      <input type="text" data-ng-model="userBean.username" class="form-control"  placeholder="Enter Firstname"/>
       <button type="submit" data-ng-click="insertData()" class="btn btn-primary">Submit</button>
    </form>

错误来了,但没有将值从 angular js 传递给控制器​​类

4

2 回答 2

2

您收到 415 http 错误,因为您的控制器需要 application/json 但您正在发送原始字符串数据。

这是一个如何发布 json 数据的工作示例:

Javascript:

var data = { "name":"emre" }
$.ajax({
    type: "POST",
    url: "http://localhost:8080/yourUrl",
    data: JSON.stringify(data),
    contentType: "application/json",
    cache: false,
    timeout: 600000,
    success: function (data) {
        alert("success")
    },
    error: function (e) {
        alert("ERROR : ", e);
    }
});

控制器 :

@CrossOrigin
@PostMapping
public ResponseEntity post(@RequestBody UserBean request) {
    return ResponseEntity.status(HttpStatus.CREATED).body(request); // your response

}

用户豆类:

@Data // comes from lombok for getter setter purpose
class UserBean {
    private String name;
}

您可以根据需要调整控制器和 javascript。

于 2018-10-30T10:13:27.210 回答
0

在我看来,您发送给控制器的数据是 String 而不是 UserBean 对象。您的有效载荷是$scope.userBean.username,但您的控制器期望@RequestBody UserBean userBean.

将控制器更改为

    public ModelAndView doRegister(@RequestBody String userName, BindingResult result)

可能会解决问题。

于 2018-10-30T10:07:06.303 回答