gpt4 book ai didi

javascript - 如何将对象从 angularjs 传递到 spring Controller

转载 作者:太空宇宙 更新时间:2023-11-04 11:19:45 25 4
gpt4 key购买 nike

我有一些要求输入用户名的 Angular 代码:

playCtrl.js var myApp = angular.module('myApp');

/*
* CONTROLLERS METHOD
*/

myApp.controller('PlayController', ['$scope', '$http', function($scope, $http) {

var REQUEST_SERVICE_URI = '/Project2/play.do';
//var REQUEST_SERVICE_URI = 'http://13.59.197.145:8085/Project2/#/play';
var playerObject = {} // create playerObject

$scope.message = "Let's play!";
$scope.message2 = "Please enter your name";
$scope.user = {
userid: '',
username: '',
roleId: '',
statusId: ''

};

$scope.register = function() {

playerObject = $scope.user; // adding user to a playerObject
console.log('playerObject.name: ' + playerObject.name);
//console.log('playerObject: ' + $scope.user.name);

console.log("REGISTER BUTTON WAS CLICKED");
$http.post(REQUEST_SERVICE_URI, playerObject).
then(function(playerObject) {
alert("SUCCESS");
//$scope.user = data;
});
}
}])

然后我的 SpringController.java 正在尝试获取此用户对象:

@RestController
public class SpringController {


// has to accept
@RequestMapping(headers="Accept=application/json", value="/play.do", method = RequestMethod.POST)
public String registerUser(Users user, BindingResult bindingResult, ModelMap modelMap, HttpSession session){
Register r = new Register();
System.out.println("TRYING TO CREATE A USER: " + user);

if(r.createUser(user.getUsername())){
session.setAttribute("username", user.getUsername());
session.setAttribute("role", user.getRole());
session.setAttribute("status", user.getStatus());

System.out.println("Created user: " + user.getUsername());

return "lobby";


}else{

return "login";

}

}

我的控制台确实完美地打印出了 angularjs 中的所有内容,并且还从 java 端打印“尝试创建用户:” + user,但是它表明所有内容均为空:尝试创建用户:用户 [userid=0,username=null,roleId=null,statusId=null](我的用户创建实现只需要一个用户名,其他都可以为空)

这是我的 web.xml:

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/beans.xml</param-value>
</context-param>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
<servlet-name>SpringDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/beans.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringDispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

这是我从控制台收到的错误:

javax.validation.ConstraintViolationException: Validation failed for classes 

[com.revature.bean.Users] during persist time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
ConstraintViolationImpl{interpolatedMessage='Username cannot be empty(1-20 characters)', propertyPath=username, rootBeanClass=class com.revature.bean.Users, messageTemplate='Username cannot be empty(1-20 characters)'}

用户.java:

package com.revature.bean;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.validation.constraints.Size;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.stereotype.Component;

@Component
@Entity
@Table(name = "Users")
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY, region = "myAwesomeCache")

public class Users {

@Id
@Column(name = "U_Id")
@SequenceGenerator(name = "UID_SEQ", sequenceName = "UID_SEQ")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "UID_SEQ")
private int userid;

@NotEmpty(message="Username cannot be empty(1-20 characters)")
@Size(min=1,max=20)
@Column(name = "Username")
private String username;


public Users() {
super();
}

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "Role_ID")
private Roles role;

@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "Status_ID")
private Status status;

public Users(int userid, String username, Roles roleId, Status statusId) {
super();
this.userid = userid;
this.username = username;
this.role = roleId;
this.status = statusId;
}

public Users(String username, Roles roleId, Status statusId) {
super();
this.username = username;
this.role = roleId;
this.status = statusId;
}

public int getUserid() {
return userid;
}

public void setUserid(int userid) {
this.userid = userid;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public Status getStatusId() {
return status;
}

public void setStatusId(Status status) {
this.status = status;
}



public Roles getRole() {
return role;
}

public void setRole(Roles role) {
this.role = role;
}

public Status getStatus() {
return status;
}

public void setStatus(Status status) {
this.status = status;
}

@Override
public String toString() {
return "Users [userid=" + userid + ", username=" + username + ", roleId=" + role + ", statusId=" + status
+ "]";
}

}

我该如何正确发送对象?

最佳答案

我刚刚想通了:我必须在 SpringController 方法的 () 中添加 @RequestBody,并将输入从 Object 更改为 String 类型:

public String registerUser(@RequestBody String username, BindingResult bindingResult, ModelMap modelMap, HttpSession session)

关于javascript - 如何将对象从 angularjs 传递到 spring Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45060251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com