Я пытался сделать пост-запрос на вставку данных через UserTransaction Model
для пользователей, которые существуют в классе UserModel
. Он работает до тех пор, пока я отдельно не вставлю данные в таблицу пользователей с помощью метода обработчика запросов public String addUser(@RequestBody HashMap<String, String> userJson)
, используя класс UserModel
в контроллере LoginForm.
Но, проблема в том, когда я пытаюсь вставить данные, которые являются реляционными. Это не работает, и результат даже не вызывается к методу контроллера RequestHandler
public void doTransaction(@RequestBody usertransaction tr)
поскольку неявное преобразование JSON, полученного от jsp зависимостью Джексона, в объект tr пользовательской транзакции, по-видимому, не происходит.
Транзакция Jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link href="https://fastcdn.org/Animate.css/3.4.0/animate.min.css"
rel="stylesheet">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form method="post" id="form" style="">
<table cellspacing="15" style="">
<tr>
<th><label>UserId </label></th>
<tr>
<td><input type="text" id="userId" name="userId" required
placeholder="" /></td>
</tr>
<tr>
<th><label>transactionAmount</label></th>
</tr>
<tr>
<td><input type="text" id="transactionAmount"
name="transactionAmount" required placeholder="transactionAmount"></td>
</tr>
<tr>
<th><label>From</label></th>
</tr>
<tr>
<td><input type="text" id="from" name="from" required
placeholder="from"></td>
</tr>
<tr>
<th><label>To</label></th>
</tr>
<tr>
<td><input type="text" id="to" name="to" required
placeholder="to"></td>
</tr>
<tr>
<th><label>transactionDate</label></th>
</tr>
<tr>
<td><input type="text" id="transactionDate"
name="transactionDate" required placeholder="transactionDate"></td>
</tr>
<tr>
<th><label>PaymentMode</label></th>
</tr>
<tr>
<td><input type="text" id="PaymentMode" name="PaymentMode"
required placeholder="PaymentMode"></td>
</tr>
<tr>
<th><label> CurrentBalance</label></th>
</tr>
<tr>
<td><input type="text" id=" CurrentBalance" name="CurrentBalance"
required placeholder=" CurrentBalance"></td>
</tr>
<tfoot>
<tr>
<th><button class="btn btn-primary " id="submit">Register</button>
</tr>
</tfoot>
</table>
</form>
<script>
$("#submit")
.click(
function(e) {
//alert('hello');
var loginForm = $('#form').serializeArray();
var loginFormObject = {};
$.each(loginForm, function(i, v) {
loginFormObject[v.name] = v.value;
});
var loginFormObject = {};
$.each(loginForm, function(i, v) {
loginFormObject[v.name] = v.value;
});
alert("hello");
alert(JSON.stringify(loginFormObject));
$
.ajax({
url : "userTransaction.obj",
type : "POST",
data : JSON.stringify(loginFormObject),
contentType : 'application/json;charset=utf-8',
dataType : "text",
success : function(res) {
alert(res);
}
});
e.preventDefault();
});
</script>
</body>
</html>
Класс LoginController
package com.controller;
import java.util.HashMap;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import com.model.LoginModel;
import com.model.usertransaction;
import com.service.LoginService;
@RestController
@EnableWebMvc
public class LoginForm {
@Autowired
SessionFactory sessionFactory;
@Autowired
LoginService loginservice;
/*
* @RequestMapping(value="users", method=RequestMethod.POST
* ,headers="Accept=*", consumes = {MediaType.APPLICATION_JSON_VALUE})
* public ResponseEntity<LoginModel> addUser(@RequestBody LoginModel users1)
* { System.out.println("calllleddd");
* this.loginservice.insertDetails(users1);
*
* return new ResponseEntity<LoginModel>(users1,HttpStatus.OK); }
*/
@Autowired
LoginService ls;
@RequestMapping(value = "TransactionPortal")
public ModelAndView getTransactionPage() {
// System.out.println("called");
ModelAndView mv = new ModelAndView("Transaction");
return mv;
}
@RequestMapping(value = "userTransaction", method = RequestMethod.POST, headers = "Accept=*", consumes = { MediaType.APPLICATION_JSON_VALUE })
public void doTransaction(@RequestBody usertransaction tr) {
System.out.println("called for registration.....");
this.ls.doTransaction(tr);
}
@RequestMapping(value = "users", method = RequestMethod.POST, headers = "Accept=*", consumes = { MediaType.APPLICATION_JSON_VALUE })
public String addUser(@RequestBody HashMap<String, String> userJson) {
String message = "";
System.out.println("calllleddd");
if (this.loginservice.createUser(userJson) == true) {
message = "Congrats! The credentials have been registered";
} else {
message = "The credentials already exists";
}
return message;
}
}
Класс модели UserTransaction
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
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.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.SecondaryTable;
import javax.persistence.Table;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.CollectionOfElements;
import org.hibernate.annotations.ForeignKey;
import org.hibernate.annotations.ManyToAny;
import org.hibernate.engine.Cascade;
import org.springframework.beans.factory.annotation.Autowired;
@Entity
@Table(name = "usertransaction")
@Access(AccessType.FIELD)
public class usertransaction implements Serializable {
@ManyToOne
@JoinColumn(name = "userId")
private UserModel user;
public int getUserId() {
return user.userId;
}
public void setUserId(int userid) {
user.userId = userid;
}
@Id
@GeneratedValue
@Column(name = "transactionId")
private int transactionId;
@Column(name = "transactionAmount")
private String transactionAmount;
@Column(name = "from")
private String from;
@Column(name = "to")
private String to;
@Column(name = "transactionDate")
private String transactionDate;
@Column(name = "PaymentMode")
private String PaymentMode;
@Column(name = "CurrentBalance")
private String CurrentBalance;
public int getTransactionId() {
return transactionId;
}
public void setTransactionId(int transactionId) {
this.transactionId = transactionId;
}
public String getTransactionAmount() {
return transactionAmount;
}
public void setTransactionAmount(String transactionAmount) {
this.transactionAmount = transactionAmount;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getTransactionDate() {
return transactionDate;
}
public void setTransactionDate(String transactionDate) {
this.transactionDate = transactionDate;
}
public String getPaymentMode() {
return PaymentMode;
}
public void setPaymentMode(String paymentMode) {
PaymentMode = paymentMode;
}
public String getCurrentBalance() {
return CurrentBalance;
}
public void setCurrentBalance(String currentBalance) {
CurrentBalance = currentBalance;
}
}
Класс UserModel
package com.model;
import java.util.HashSet;
import java.util.Set;
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.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.CascadeType;
@Entity
@Table(name="users")
public class UserModel {
@OneToMany(mappedBy="user")
Set<usertransaction> s=new HashSet<usertransaction>();
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="userId")
public int userId;
@Column(name="userName")
private String userName;
@Column(name="userDescription")
private String userDescription;
@Column(name="status")
private String status;
@Column(name="statusCode")
private String statusCode;
@Column(name="statusDescription")
private String statusDescription;
@Column(name="userSince")
private String userSince;
@Column(name="PIN")
private String PIN;
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 String getUserDescription() {
return userDescription;
}
public void setUserDescription(String userDescription) {
this.userDescription = userDescription;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getStatusCode() {
return statusCode;
}
public void setStatusCode(String string) {
this.statusCode = string;
}
public String getStatusDescription() {
return statusDescription;
}
public void setStatusDescription(String statusDescription) {
this.statusDescription = statusDescription;
}
public String getUserSince() {
return userSince;
}
public void setUserSince(String userSince) {
this.userSince = userSince;
}
public String getPIN() {
return PIN;
}
public void setPIN(String pIN) {
PIN = pIN;
}
public String getErrorDescription() {
return errorDescription;
}
public void setErrorDescription(String errorDescription) {
this.errorDescription = errorDescription;
}
@Column(name="errorDescription")
private String errorDescription;
}
Для проверки ссылки ниже первое изображение показывает неверный запрос и контроллер не вызывается, но когда я удаляю
@Request, где это работает показано на втором изображении