使用@Requestbody将String从angular传递给Spring

时间:2017-04-11 13:00:13

标签: angularjs spring rest

我正在使用angularjs + springboot进行项目。我试图使用spring-boot-starter-mail通过我的应用程序发送电子邮件。电子邮件的消息和对象由用户以表单形式写入。我想要做的是使用@RequestBody在我的RestController中获取消息和对象值。

我的service.js中的函数

// send mail
                var sendMail = function(id, objet, msg) {
                    var deferred = $q.defer();
                    $http.post(urlBase + id, objet, msg).then(
                            function(response) {
                                deferred.resolve(response.data);
                            }, function(errResponse) {
                                console.error('Error while sending email');
                                deferred.reject(errResponse);
                            });
                    return deferred.promise;
                }

我的restContoller中的方法

@RestController 公共类EmailController {

@Autowired
private JavaMailSender javaMailSender;
@Autowired
UtilisateurService service;

@RequestMapping(value = "/users/{id}", method = RequestMethod.POST)
public ResponseEntity<Void> sendMail(@PathVariable("id") int id, @RequestBody String objet,
        @RequestBody String msg) {
    Utilisateur currentUser = service.findById(id);
    SimpleMailMessage message = new SimpleMailMessage();
    message.setTo(currentUser.getEmailUtil());
    message.setSubject(objet);
    message.setText(msg);
    javaMailSender.send(message);
    return new ResponseEntity<Void>(HttpStatus.OK);
}}

这引发了这个例外:

Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public org.springframework.http.ResponseEntity<java.lang.Void> com.sla.utilisateur.controller.EmailController.sendMail(int,java.lang.String,java.lang.String)

我该如何解决?

谢谢,

1 个答案:

答案 0 :(得分:0)

您对$http.post的使用不正确。你应该看一下AngularJS POST documentation$http.post个参数如下:

post(url, data, [config]);

AngularJS默认以JSON格式发送数据。所以你应该使用以下语句发送请求(例如):

$http.post(urlBase + id, {subject:objet, body:msg})

在您的控制器中,您应该只为一个@RequestBody定义一个Map地图以便于示例(您可以将其更改为POJO)。

@RequestMapping(value = "/users/{id}", method = RequestMethod.POST)
public ResponseEntity<Void> sendMail(@PathVariable("id") int id, @RequestBody Map<String,String> msg) {
    Utilisateur currentUser = service.findById(id);
    SimpleMailMessage message = new SimpleMailMessage();
    message.setTo(currentUser.getEmailUtil());
    message.setSubject(msg.get("subject");
    message.setText(msg.get("body"));
    javaMailSender.send(message);
    return new ResponseEntity<Void>(HttpStatus.OK);
}}