Mistake in js/spring boot/hibernate project - javascript
I am trying to do some project on Spring Boot with JavaScript, but I have strage mistakes. Here they are:
org.springframework.web.method.annotation.MethodArgumentTypeMismatchException:
Failed to convert value of type [java.lang.String] to required type
[int]; nested exception is java.lang.NumberFormatException: For input
string: "filterByData"
Caused by: java.lang.NumberFormatException: For input string:
"filterByData"
I can`t find this "filterByData" in my project and what parameter I give like int insteed of String.
My entities:
#NamedQueries({
#NamedQuery(name = Contact.GET, query = "SELECT cont FROM Contact cont WHERE cont.id=:id AND cont.user.id=:userId"),
#NamedQuery(name = Contact.ALL_SORTED, query = "SELECT cont FROM Contact cont WHERE cont.user.id=:userId ORDER BY cont.firstName DESC"),
#NamedQuery(name = Contact.DELETE, query = "DELETE FROM Contact cont WHERE cont.id=:id AND cont.user.id=:userId"),
#NamedQuery(name = Contact.GET_FILTERED, query = "SELECT cont FROM Contact cont WHERE cont.user.id=:userId " +
"AND cont.firstName LIKE :fName AND cont.lastName LIKE :lName " +
"AND cont.mobilePhone LIKE :mPhone ORDER BY cont.firstName DESC"),
})
#Entity
#Table(name = "contacts")
public class Contact extends BaseEntity{
public static final String GET = "Contact.GET";
public static final String ALL_SORTED = "Contact.ALL_SORTED";
public static final String DELETE = "Contact.DELETE";
public static final String GET_FILTERED = "Contact.GET_FILTERED";
#Column(name = "first_name", nullable = false)
#NotEmpty
#Length(min = 4)
private String firstName;
#Column(name = "last_name", nullable = false)
#NotEmpty
#Length(min = 4)
private String lastName;
#Column(name = "patronymic", nullable = false)
#NotEmpty
#Length(min = 4)
private String patronymic;
#Column(name = "mobile_phone_number", nullable = false)
#NotEmpty
#Pattern(regexp = "\\+380\\([1-9]{2}\\)[0-9]{7}", message = "format should be like +380(66)1234567" +
"")
private String mobilePhone;
#Column(name = "home_phone_number")
private String homePhone;
#Column(name = "address")
private String address;
#Email
#Column(name = "email", nullable = false)
private String email;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "user_id", nullable = false)
#JsonBackReference
private User user;
public Contact() {
}
public Contact(String firstName, String lastName, String patronymic, String mobilePhone, String homePhone, String address, String email ) {
this(null,firstName,lastName,patronymic,mobilePhone,homePhone,address,email);
}
public Contact( Integer id, String firstName, String lastName, String patronymic, String mobilePhone, String homePhone, String address, String email ) {
super(id);
this.firstName = firstName;
this.lastName = lastName;
this.patronymic = patronymic;
this.mobilePhone = mobilePhone;
this.homePhone = homePhone;
this.address = address;
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPatronymic() {
return patronymic;
}
public void setPatronymic(String patronymic) {
this.patronymic = patronymic;
}
public String getMobilePhone() {
return mobilePhone;
}
public void setMobilePhone(String mobilePhone) {
this.mobilePhone = mobilePhone;
}
public String getHomePhone() {
return homePhone;
}
public void setHomePhone(String homePhone) {
this.homePhone = homePhone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
#Override
public String toString() {
return "Contact{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", patronymic='" + patronymic + '\'' +
", mobilePhone='" + mobilePhone + '\'' +
", homePhone='" + homePhone + '\'' +
", address='" + address + '\'' +
", email='" + email + '\'' +
'}';
}
}
#NamedEntityGraphs({
#NamedEntityGraph(name = User.GRAPH_WITH_ROLES, attributeNodes = #NamedAttributeNode("roles")),
#NamedEntityGraph(name = User.GRAPH_WITH_ROLES_AND_CONTACTS, attributeNodes =
{
#NamedAttributeNode("roles"),
#NamedAttributeNode("contacts")
})
})
#NamedQueries({
#NamedQuery(name = User.DELETE, query = "DELETE FROM User u WHERE u.id=:id"),
#NamedQuery(name = User.BY_LOGIN, query = "SELECT DISTINCT u FROM User u LEFT JOIN FETCH u.roles WHERE u.login=:login"),
#NamedQuery(name = User.ALL_SORTED, query = "SELECT DISTINCT u FROM User u LEFT JOIN FETCH u.roles ORDER BY u.login"),
})
#Entity
#Table(name = "users", uniqueConstraints = {#UniqueConstraint(columnNames = "login", name = "users_unique_login_idx")})
public class User extends NamedEntity{
public static final String GRAPH_WITH_ROLES = "User.WithRoles";
public static final String GRAPH_WITH_ROLES_AND_CONTACTS = "User.WithRolesAndContacts";
public static final String DELETE = "User.DELETE";
public static final String BY_LOGIN = "User.BY_LOGIN";
public static final String ALL_SORTED = "User.All_SORTED";
#Column(name = "password", nullable = false)
#Length(min = 5, max = 100, message = "your password should have 5 or more symbols")
#JsonView(View.REST.class)
#NotEmpty
private String password;
#Column(name = "full_name", nullable = false)
#Length(min = 5, max = 100, message = "your fullName should have 5 or more symbols")
private String fullName;
#Enumerated(EnumType.STRING)
#CollectionTable(name = "user_roles", joinColumns = #JoinColumn(name = "user_id"))
#Column(name = "role")
#ElementCollection(fetch = FetchType.LAZY)
protected Set<Role> roles;
#OneToMany(cascade = CascadeType.REMOVE, fetch = FetchType.LAZY, mappedBy = "user")
#OrderBy("firstName DESC")
#JsonManagedReference
protected List<Contact> contacts;
public User() {
}
public User(User u) {
this(u.getId(), u.getLogin(), u.getPassword(), u. getFullName(), u.getRoles());
}
public User(Integer id, String login, String password, String fullName, Role role, Role... roles) {
this(id, login, password, fullName, EnumSet.of(role, roles));
}
public User(Integer id, String login, String password, String fullName, Set<Role> roles) {
super(id, login);
this.password = password;
this.fullName = fullName;
setRoles(roles);
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = CollectionUtils.isEmpty(roles) ? Collections.emptySet() : EnumSet.copyOf(roles);
}
public List<Contact> getContacts() {
return contacts;
}
#Override
public String toString() {
return "User{" +
"password='" + password + '\'' +
", fullName='" + fullName + '\'' +
", roles=" + roles +
'}';
}
}
Controllers:
#Controller
public class RootController extends AbstractUserController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String root() {
return "redirect:/contacts";
}
#RequestMapping(value = "/contacts", method = RequestMethod.GET)
public String contactList() {
return "contacts";
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
#PreAuthorize("hasRole('ROLE_USER')")
public String login(ModelMap model,
#RequestParam(value = "error", required = false) boolean error,
#RequestParam(value = "message", required = false) String message) {
model.put("error", error);
model.put("message", message);
return "login";
}
#RequestMapping(value = "/register", method = RequestMethod.GET)
public String register(ModelMap model) {
model.addAttribute("userDTO", new UserDTO());
model.addAttribute("register", true);
return "contacts";
}
#RequestMapping(value = "/register", method = RequestMethod.POST)
public String saveRegister(#Valid UserDTO userDTO, BindingResult result, SessionStatus status, ModelMap model) {
if (!result.hasErrors()) {
try {
super.create(UserUtil.createNewUserFromDTO(userDTO));
status.setComplete();
return "redirect:login?message=app.registered";
} catch (DataIntegrityViolationException ex) {
result.rejectValue("Login", "---");
}
}
model.addAttribute("register", true);
return "contacts";
}
}
#RestController
#RequestMapping(value = "/ajax/contacts")
public class ContactAjaxController extends AbstractContactController{
#RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<Contact> getAll() {
return super.getAll();
}
#RequestMapping(value = "/{id}")
public Contact get(#PathVariable("id") int id) {
return super.get(id);
}
#RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public void delete(#PathVariable("id") int id) {
super.delete(id);
}
#RequestMapping(method = RequestMethod.POST)
public void updateOrCreate(#Valid Contact contact) {
if (contact.isNew()) {
super.create(contact);
} else {
super.update(contact, contact.getId());
}
}
#RequestMapping(value = "/filter", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public List<Contact> getFiltered(
#RequestParam(value = "fName", required = false) String fName,
#RequestParam(value = "lName", required = false) String lName,
#RequestParam(value = "mPhone", required = false) String mPhone) {
return super.getFiltered(fName, lName, mPhone);
}
}
#RestController
#RequestMapping("/ajax/users")
public class UserAjaxController extends AbstractUserController{
#RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
#JsonView(View.UI.class)
public List<User> getAll() {
return super.getAll();
}
#RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
#JsonView(View.UI.class)
public User get(#PathVariable("id") int id) {
return super.get(id);
}
#RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public void delete(#PathVariable("id") int id) {
super.delete(id);
}
#RequestMapping(method = RequestMethod.POST)
public void createOrUpdate(#Valid UserDTO userTo) {
if (userTo.isNew()) {
super.create(UserUtil.createNewUserFromDTO(userTo));
} else {
super.update(userTo);
}
}
}
JavaScript files:
var ajaxUrl = 'ajax/contacts/';
var datatableApi;
function updateTable() {
$.ajax({
type: "POST",
url: ajaxUrl + 'filter',
data: $('#filter').serialize(),
success: updateTableByData
});
return false;
}
$(function () {
datatableApi = $('#datatable').DataTable({
"ajax": {
"url": ajaxUrl,
"dataSrc": ""
},
"paging": false,
"info": true,
"columns": [
{
"data": "firstName"
},
{
"data": "lastName"
},
{
"data": "patronymic"
},
{
"data": "mobilePhone"
},
{
"data": "homePhone"
},
{
"data": "address"
},
{
"data": "email"
},
{
"defaultContent": "",
"orderable": false,
"render": renderEditBtn
},
{
"defaultContent": "",
"orderable": false,
"render": renderDeleteBtn
}
],
"order": [
[
0,
"desc"
]
],
"initComplete": function () {
$('#filter').submit(function () {
updateTable();
return false;
});
makeEditable();
}
});
});
var form;
function makeEditable() {
form = $('#detailsForm');
form.submit(function () {
save();
return false;
});
$(document).ajaxError(function (event, jqXHR, options, jsExc) {
failNoty(event, jqXHR, options, jsExc);
});
// var token = $("meta[name='_csrf']").attr("content");
// var header = $("meta[name='_csrf_header']").attr("content");
// $(document).ajaxSend(function(e, xhr, options) {
// xhr.setRequestHeader(header, token);
// });
}
function add() {
form.find(":input").val("");
$('#id').val(null);
$('#editRow').modal();
}
function updateRow(id) {
$.get(ajaxUrl + id, function (data) {
$.each(data, function (key, value) {
form.find("input[name='" + key + "']").val(value);
});
$('#editRow').modal();
});
}
function deleteRow(id) {
$.ajax({
url: ajaxUrl + id,
type: 'DELETE',
success: function () {
updateTable();
successNoty('Deleted');
}
});
}
function updateTableByData(data) {
datatableApi.clear().rows.add(data).draw();
}
function save() {
$.ajax({
type: "POST",
url: ajaxUrl,
data: form.serialize(),
success: function () {
$('#editRow').modal('hide');
updateTable();
successNoty('Saved');
}
});
}
var failedNote;
function closeNoty() {
if (failedNote) {
failedNote.close();
failedNote = undefined;
}
}
function successNoty(text) {
closeNoty();
noty({
text: text,
type: 'success',
layout: 'bottomRight',
timeout: true
});
}
function failNoty(event, jqXHR, options, jsExc) {
closeNoty();
var errorInfo = $.parseJSON(jqXHR.responseText);
failedNote = noty({
text: 'Failed: ' + jqXHR.statusText + '<br>' + errorInfo.cause + '<br>' + errorInfo.details.join('<br>'),
type: 'error',
layout: 'bottomRight'
});
}
function renderEditBtn(data, type, row) {
if (type == 'display') {
return '<a class="btn btn-xs btn-primary" onclick="updateRow(' + row.id + ');">Edit</a>';
}
return data;
}
function renderDeleteBtn(data, type, row) {
if (type == 'display') {
return '<a class="btn btn-xs btn-danger" onclick="deleteRow(' + row.id + ');">Delete</a>';
}
return data;
}
My basic CRUD methods work fine without 'filter' and I got this mistake every time. Can someone tell my what I am doing wrong? Thanks.
public abstract class AbstractUserController {
#Autowired
private UserService service;
public List<User> getAll() {
return service.getAll();
}
public User get(int id){
return service.get(id);
}
public User create(User user) {
user.setId(null);
return service.save(user);
}
public void delete(int id){
service.delete(id);
}
public void update(User user, int id) {
user.setId(id);
service.update(user);
}
public void update(UserDTO userDTO) {
service.update(userDTO);
}
public User getByLogin(String login) {
return service.getByLogin(login);
}
}
Related
How to map html form data to a Spring Boot model containing a composite key?
I have popup form in my html that looks like this: <dialog id="favDialog"> <div id="feedback"></div> <form id="add_watchlist_symbol_form"> <label for="symbol">Enter Symbol:</label> <input type="text" class="form-control" id="symbol" placeholder="SYMB"/><br><br> <button type="submit" class="btn btn-default" id="add-watchlist-symbol-btn">Add</button> </form> <button id="cancelBtn" value="cancel">Cancel</button> </dialog> The dialog pops up successfully when I click a button. The dialog contains a button called Add. It's click event is handled by javascript which sends an ajax POST request containing the form field values to Spring Boot like this: function submit_watchlist_symbol() { console.log("Im in submit_watchlist_symbol"); var formData = { symbol: $("#symbol").val(), name: "My Portfolio" } //$("#btn-search").prop("disabled", true); $.ajax({ type: "POST", contentType: "application/json", url: "/api/v1/AddSymbolToWatchlist", data: JSON.stringify(formData), dataType: 'json', success: function (result) { if(result.status=="Done") { $('#feedback').html(result.data.symbol +" added."); } else { $('#feedback').html("<strong>Error</strong>"); } console.log("ERROR: ",e); }, error: function (e) { alert("Error!") console.log("ERROR: ",e); } }); // Reset FormData after Posting resetData(); } When I click that button I get Spring Boot error: Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: null; nested exception is com.fasterxml.jackson.databind.JsonMappingException: N/A at [Source: (PushbackInputStream); line: 1, column: 11] (through reference chain: net.tekknow.moneymachine.model.Watchlist["symbol"])] I suspect the form data is not being mapped correctly to the Watchlist.java model due to the model containing a composite key, like this: #Entity #Table(name = "watchlist") public class Watchlist { #EmbeddedId public WatchlistId watchlistId; public String getSymbol() { return watchlistId.getSymbol(); } public void setSymbol(String symbol) { watchlistId.setSymbol(symbol); } public String getName() { return watchlistId.getName(); } public void setName(String watchlistName) { watchlistId.setName(watchlistName); } public String toString() { return "watchlist:symbol=" +getSymbol() +", name="+getName(); } } where watchlistId contains the symbol and name, like this: #Embeddable public class WatchlistId implements Serializable { #Column(name="symbol") private String symbol; #Column(name="name") private String name; WatchlistId() { } WatchlistId(String symbol, String name) { this.symbol = symbol; this.name = name; } public String getSymbol() { return symbol; } public void setSymbol(String symbol) { this.symbol = symbol; } public String getName() { return name; } public void setName(String name) { this.name = name; } #Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; WatchlistId that = (WatchlistId) o; return Objects.equals(symbol, that.symbol) && Objects.equals(name, that.name); } #Override public int hashCode() { return Objects.hash(symbol, name); } } Here is the Spring Boot controller that handles the request: #PostMapping("/AddSymbolToWatchlist") #ResponseBody public AddWatchlistSymbolResponse addSymbolToWatchlist(#RequestBody Watchlist watchlist){ System.out.println("made it to AddWatchlistSymbolResponse"); // Create Response Object AddWatchlistSymbolResponse response = new AddWatchlistSymbolResponse("Done", watchlist); return response; } The AddWatchlistSymbolResponse class looks like this: public class AddWatchlistSymbolResponse { private String status; private Object data; public AddWatchlistSymbolResponse(){ } public AddWatchlistSymbolResponse(String status, Object data){ this.status = status; this.data = data; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } } Suggestions?
I figured it out. I changed the controller to this: #PostMapping(value = "/AddSymbolToWatchlist") #ResponseBody public WatchlistIdResponse addSymbolToWatchlist(#RequestBody WatchlistId watchlistId){ System.out.println("made it to AddWatchlistSymbolResponse"); watchlistService.addSymbolToWatchlist(watchlistId); // Create Response Object WatchlistIdResponse response = new WatchlistIdResponse("Done", watchlistId); return response; } And created a separate response for WatchlistId called WatchlistIdResponse.java: package net.tekknow.moneymachine.model; public class WatchlistIdResponse { private String status; private Object data; public WatchlistIdResponse() { } public WatchlistIdResponse(String status, Object data) { this.status = status; this.data = data; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } } The reason is that the Watchlist class contains only the WatchlistId property. WatchlistId contains the symbol and name properties that make up the composite index.
"Could not read JSON document: Can not deserialize instance of java.lang.String out of START_OBJECT token↵
I am having the following error while trying to post a value to my controller. Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON document: Can not deserialize instance of java.lang.String out of START_OBJECT token at [Source: java.io.PushbackInputStream#355134ca; line: 1, column: 655] (through reference chain: com.csps.gabriel.entities.Policy["goodsList"]- >java.util.ArrayList[0]->com.csps.gabriel.dtos.GoodsDto["type"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token at [Source: java.io.PushbackInputStream#355134ca; line: 1, column: 655] (through reference chain: com.csps.gabriel.entities.Policy["goodsList"]- >java.util.ArrayList[0]->com.csps.gabriel.dtos.GoodsDto["type"]) this is the json posted. { "client": { "clientId": 1000002, "firstName": "Jose Anibal", "lastName": "Rodriguez Lopez", "idCard": "07200140809", "enterprise": "", "contactBus": "", "address": "Jardín De Pekes, Calle Lorenzo", "sector": "Los Prados", "city": "2", "phoneNumber1": "8099803135", "phoneNumber2": "8099803135", "phoneNumber3": "8099803135", "email": "joseanibalrl76#gmail.com", "clientContact": "", "clientType": "Persona Fisica", "notes": "", "status": "Activo", "phoneNumber": "8099803135", "fullName": "Jose Anibal Rodriguez Lopez", "rnc": "" }, "policyNumber": "847474141", "branch": "2", "policer": "2", "prime": 48484, "startDate": "2017-05-09", "endDate": "2017-05-10", "status": "1", "itbis": "2", "goodsList": [{ "type": { "name": "Jeep", "index": "1" }, "year": 2000, "brand": "toyota", "model": "corolla", "chassisSerial": "441147", "covertAmount": 10000, "color": "rojo", "cylinder": 6, "passengerAmount": "6", "weight": 6 }] } This is the entity which maps the request body. #Entity #Table(name = "policy") public class Policy { #Id #GeneratedValue(strategy = GenerationType.AUTO) #Column(name = "policy_id") private Long policyId; #Column(name = "client") #Type(type = "serializable") private Client client; #Column(name = "policy_number") private String policyNumber; #Column(name = "branch_name") private String branch; #Column(name = "policer") private String policer; #Column(name = "prime") private String prime; #Column(name = "currency") private String currency; #Column(name = "start_date") private Date startDate; #Column(name = "end_date") private Date endDate; #Column(name = "status") private String status; #Column(name = "itbis") private String itbis; #Column(name = "good_list") #Type(type = "serializable") #JsonProperty private List<GoodsDto> goodsList; public Long getPolicyId() { return policyId; } public void setPolicyId(Long policyId) { this.policyId = policyId; } public Client getClient() { return client; } public void setClient(Client client) { this.client = client; } public String getPolicyNumber() { return policyNumber; } public void setPolicyNumber(String policyNumber) { this.policyNumber = policyNumber; } public String getBranch() { return branch; } public void setBranch(String branch) { this.branch = branch; } public String getPolicer() { return policer; } public void setPolicer(String policer) { this.policer = policer; } public String getPrime() { return prime; } public void setPrime(String prime) { this.prime = prime; } public String getCoin() { return currency; } public void setCoin(String currency) { this.currency = currency; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getItbis() { return itbis; } public void setItbis(String itbis) { this.itbis = itbis; } public List<GoodsDto> getGoodsList() { return goodsList; } public void setGoodsList(List<GoodsDto> goodsList) { this.goodsList = goodsList; } } This is my controller: #RestController public class PolicyController { #Autowired PolicyRepository policyRepository; #RequestMapping(value = "/save-policy", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) public #ResponseBody Response<Policy> saveClient(#RequestBody Policy policy) { policy = this.policyRepository.save(policy); return new Response<Policy>(policy, true, "Successful"); } } this is the GoodsList class: package com.csps.gabriel.dtos; import java.io.Serializable; /** Created by Jose A Rodriguez on 5/20/2017. */ public class GoodsDto implements Serializable{ private static final long serialVersionUID = 1L; private String type; private Long year; private String brand; private String model; private String chassisSerial; private Double covertAmount; private String color; private Long cylinder; private Long passengerAmount; private Long weight; public String getType() { return type; } public void setType(String type) { this.type = type; } public Long getYear() { return year; } public void setYear(Long year) { this.year = year; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } public String getChassisSerial() { return chassisSerial; } public void setChassisSerial(String chassisSerial) { this.chassisSerial = chassisSerial; } public Double getCovertAmount() { return covertAmount; } public void setCovertAmount(Double covertAmount) { this.covertAmount = covertAmount; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public Long getCylinder() { return cylinder; } public void setCylinder(Long cylinder) { this.cylinder = cylinder; } public Long getPassengerAmount() { return passengerAmount; } public void setPassengerAmount(Long passengerAmount) { this.passengerAmount = passengerAmount; } public Long getWeight() { return weight; } public void setWeight(Long weight) { this.weight = weight; } } Has anyone an idea why is it giving me this error. Please.
Your problem is in the memberGoodsDto.type. it's declared as a String in your GoodsDto class but you try to pass it a 2 fields structure in your Json: "goodsList": [{ "type": { "name": "Jeep", "index": "1" }
Angular JS and Spring - how to filter JSON Object
I try to PUT a JSON Object from the Frontend to the Backend via Angular JS and Java Spring using the JHipster Framework. My JSON Object looks as follows: { "anzahl": 0, "category": 0, "id": 0, "parkraumId": 0, "timestamp": "2016-09-07T12:59:04.290Z", "wochentag": 0 } But to save it in the database via the Spring Repository method createCrowdsource(crowdsource) i need to filter out the values wochentag and anzahl to get the following JSON Object: { "category": 0, "id": 0, "parkraumId": 0, "timestamp": "2016-09-07T12:59:04.290Z" } I tried it by specifying the fields: 'category', 'id', 'parkraumId', 'timestamp' in the following Angular JS controller and get this Parameter back in the Spring Resource with #RequestParam String fields but somehow it doesn´t work. Angular Controller: function save() { vm.isSaving = true; if (vm.crowdsource.id !== null) { //JSON needs these two attributes console.log('Updating!') Crowdsource.update(vm.crowdsource, onSaveSuccess, onSaveError, {fields: 'category', 'id', 'parkraumId', 'timestamp'}); } else { Crowdsource.save(vm.crowdsource, onSaveSuccess, onSaveError); } } save() Angular Service: (function () { 'use strict'; angular .module('bahnApp') .factory('Crowdsource', Crowdsource); Crowdsource.$inject = ['$resource', 'DateUtils']; function Crowdsource($resource, DateUtils) { var resourceUrl = 'api/crowdsources/:siteId'; return $resource(resourceUrl, {}, { 'query': {method: 'GET', isArray: true}, 'get': { method: 'GET', transformResponse: function (data) { if (data) { data = angular.fromJson(data); data.timestamp = DateUtils.convertDateTimeFromServer(data.timestamp); } return data; } }, 'update': { method: 'PUT', } }); } })(); Spring Resource: /** * PUT /crowdsources : Updates an existing crowdsource. * * #param crowdsource the crowdsource to update * #return the ResponseEntity with status 200 (OK) and with body the updated crowdsource, * or with status 400 (Bad Request) if the crowdsource is not valid, * or with status 500 (Internal Server Error) if the crowdsource couldnt be updated * #throws URISyntaxException if the Location URI syntax is incorrect */ #RequestMapping(value = "/crowdsources", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE) #Timed public ResponseEntity<Crowdsource> updateCrowdsource(#RequestParam String fields, #RequestBody Crowdsource crowdsource) throws URISyntaxException { log.debug("REST request to update Crowdsource : {}", crowdsource); log.debug(crowdsource.toString()); if (crowdsource.getId() == null) { return createCrowdsource(crowdsource); } Crowdsource result = crowdsourceRepository.save(crowdsource); crowdsourceSearchRepository.save(result); return ResponseEntity.ok() .headers(HeaderUtil.createEntityUpdateAlert("crowdsource", crowdsource.getId().toString())) .body(result); } Crowdsource: /** * A Crowdsource. */ #Entity #Table(name = "crowdsource") #Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) #Document(indexName = "crowdsource") #JsonFilter("myFilter") public class Crowdsource implements Serializable { private static final long serialVersionUID = 1L; #Id #GeneratedValue(strategy = GenerationType.AUTO) private Long id; #Column(name = "category") private Integer category; #Column(name = "timestamp") private ZonedDateTime timestamp; #Column(name = "parkraum_id") private Integer parkraumId; private Integer anzahl; private Integer wochentag; public Integer getAnzahl() { return anzahl; } public void setAnzahl(Integer anzahl) { this.anzahl = anzahl; } public Integer getWochentag() { return wochentag; } public void setWochentag(Integer wochentag) { this.wochentag = wochentag; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Integer getCategory() { return category; } public void setCategory(Integer category) { this.category = category; } public ZonedDateTime getTimestamp() { return timestamp; } public void setTimestamp(ZonedDateTime timestamp) { this.timestamp = timestamp; } public Integer getParkraumId() { return parkraumId; } public void setParkraumId(Integer parkraumId) { this.parkraumId = parkraumId; } #Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Crowdsource that = (Crowdsource) o; if (id != null ? !id.equals(that.id) : that.id != null) return false; if (category != null ? !category.equals(that.category) : that.category != null) return false; if (timestamp != null ? !timestamp.equals(that.timestamp) : that.timestamp != null) return false; return parkraumId != null ? parkraumId.equals(that.parkraumId) : that.parkraumId == null; } #Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (category != null ? category.hashCode() : 0); result = 31 * result + (timestamp != null ? timestamp.hashCode() : 0); result = 31 * result + (parkraumId != null ? parkraumId.hashCode() : 0); return result; } #Override public String toString() { return "Crowdsource{" + "id=" + id + ", category=" + category + ", timestamp=" + timestamp + ", parkraumId=" + parkraumId + '}'; } }
To avoid persisting the values you can annotate them with #javax.persistence.Transient annotation in the CrowdSource entity. Those will be ignored for persistence. #Transient private Integer anzahl; #Transient private Integer wochentag
model binding from ajax for date value passing as null
I have a page called bookprogram and below is its model! public class BookViewModel { [Required(ErrorMessage = "Field cannot be blank!", AllowEmptyStrings = false)] [Display(Name="Name *")] public string name { get; set; } [Required(ErrorMessage = "Field cannot be blank!", AllowEmptyStrings = false)] [DataType(DataType.PhoneNumber)] public string contact { get; set; } [Required(ErrorMessage = "Field cannot be blank!", AllowEmptyStrings = false)] [RegularExpression("[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+.[A-Za-z]{2,4}", ErrorMessage = "Invalid Email Id")] public string email { get; set; } [Required(ErrorMessage = "Please select a category")] public string category { get; set; } [Required(ErrorMessage = "Field cannot be blank!", AllowEmptyStrings = false)] [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)] public DateTime dateofprogram { get; set; } [Required(ErrorMessage = "Field cannot be blank!", AllowEmptyStrings = false)] [StringLength(200,ErrorMessage="Max length exceeded! Should be less than 200 characters")] public string Message { get; set; } } Here is my js for performing AJAX Post function ValidateBookProgramAndPost(form) { $(form).on("submit", function (e) { e.preventDefault(); ValidateForm(form); var selectedVal = $(form).find('select').children(":selected").val(); if(selectedVal=="") { $(form).find('div.bootstrap-select').children(":first").addClass('alert-danger'); $(form).find('div.bootstrap-select').next('.text-danger').html('Please select a category!'); } var dateofprog = moment().format($('#txtDate').val()); console.log(dateofprog); $.ajax({ url: '/BookProgram/', type: "POST", dataType: 'json', contentType: "application/json; charset=utf-8", data: JSON.stringify({ model:{ name: $('#txtName').val(), contact: $('#txtPhone').val(), email: $('#txtEmail').val(), category: $("#hdnSelectedCategory").val(), dateofprogram: dateofprog, Message: $("#txtMessage").val() } }), success: function (data) { if (data.result) { $(form).find('input[type=text], textarea').val('').removeClass("alert-success"); $('.selectpicker').selectpicker('refresh'); } else { if (data.result == "Email Validation failed on server side!") { $("#txtEmail").addClass("alert-danger"); } else { //display error message } return false; } return true; } } $(form).unbind('submit'); return false; }); and here is my controller: [HttpPost] public ActionResult BookProgram(BookViewModel model) { bool valid = false; bool val = false; if (ModelState.IsValid) { if (model.name != "" && model.category != "" && model.contact != "" && model.dateofprogram.ToShortDateString() != "" && model.email != "" && model.Message != "") { if (v.validateEmail(model.email) && v.validatePhone(model.contact)) { valid = true; } else { return Json(new { result = "Email/Phone Validation failed on server side!" }); } } else { return Json(new { result = "One of the field has been modified and has been sent empty!!" }); } if (valid) { using (var context = new MConnectionString()) { tbl_programs book = new tbl_programs(); book.cont = model.contact; book.date = model.dateofprogram; book.email = model.email; book.msg = model.Message; book.category = model.category; book.status = ""; book.name = model.name; context.tbl_programs.Add(book); context.SaveChanges(); val = true; } if (val) { return Json(new { result = true }); } else { return Json(new { result = "Could not book the program. Please try again!" }); } } return Json(new { result = "Could not book the program. Please try again!" }); } return Json(new { success = false }); } But when I check in the controller the date value is coming null and Model.IsValid fails. how I should pass date value from ajax then? Console.log shows selected date[dateofprog] as "14/02/2015"[example] but it will not be assigned to model. Where is the problem actually I cannot make it out. Can anyone help me on this??
You are posting a invalid format for dateofprogram. It cases a failure at the binding process. You must specify the culture in at system.web section of the web.config to get the right date parsed from the json, for exemple: <globalization uiCulture="pt-BR" culture="pt-BR" /> The code above informs the culture of the application, then if I inform a DateTime in BR format like dd/MM/yyyy it will bind correctly.
AngularJS object
I'm newbie in Angularjs,The following Spring controller get object from database I want to print this object attributes in angularjs controller but I get undefined #RequestMapping(value = "/rest/getById", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) #RolesAllowed(AuthoritiesConstants.ADMIN) public ChartConfigs findOne(Integer id) { return chartConfigService.getOne(1); } This is Angularjs service myappApp.factory('ChartConfigService', function ($http) { return { findOne: function() { var promise = $http.get('app/rest/chartConfigs/getById').then(function (response) { return response.data; }); return promise; } } }); This is Angularjs controller myappApp.controller('ChartConfigController', function ($scope, ChartConfigService) { $scope.message = ChartConfigService.findOne(); var obj=ChartConfigService.findOne(); console.log(obj.type); }); chartconfig domain package com.innvo.domain; #Entity #Table(name = "T_CHART_CONFIGS") #Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) public class ChartConfigs { #Id #GeneratedValue(strategy = GenerationType.AUTO) #Column(name="id") private Integer id; #Column(name = "category") private String category; #Column(name = "type") private String type; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
In your case obj will be a promise too so you have to do it like: ChartConfigService.findOne().then(function(obj) { console.log(obj.type); }); obj.type is undefined because type does not exist on the promise object.