Ad

Failed To Convert Property Value Of Type 'java.lang.String' To Required Type 'com.ujazdowski.SocialPortal.model.tables.User'

- 1 answer

I am trying to send the object by jsp form to java controller but i am getting error:

Failed to convert property value of type 'java.lang.String' to required type 'com.ujazdowski.SocialPortal.model.tables.User' for property 'fromUser'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.lang.Long] for value 'User(userId=2, roles=[Role(userRoleId=1, role=USER)], firstName=Bartosz, secondName=Ujazdowski, [email protected], password=$2a$10$da7l/9VRpIPBm1z0LiONwO7wRXMs55.5QOkdpFVQ3/eqO9FBu4IXu, lastTimeOnline=null, profilePhotoId=null, male=true)'; nested exception is java.lang.NumberFormatException: For input string: "User(userId=2,roles=[Role(userRoleId=1,role=USER)],firstName=Bartosz,secondName=Ujazdowski,[email protected],password=$2a$10$da7l/9VRpIPBm1z0LiONwO7wRXMs55.5QOkdpFVQ3/eqO9FBu4IXu,lastTimeOnline=null,profilePhotoId=null,male=true)" Failed to convert property value of type 'java.lang.String' to required type 'com.ujazdowski.SocialPortal.model.tables.User' for property 'toUser'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.lang.Long] for value 'User(userId=4, roles=[Role(userRoleId=1, role=USER)], firstName=Kamil, secondName=Stonoga, [email protected], password=SECRET, lastTimeOnline=null, profilePhotoId=null, male=true)'; nested exception is java.lang.NumberFormatException: For input string: "User(userId=4,roles=[Role(userRoleId=1,role=USER)],firstName=Kamil,secondName=Stonoga,[email protected],password=SECRET,lastTimeOnline=null,profilePhotoId=null,male=true)"

MyController - ProfileController.java:

package com.ujazdowski.SocialPortal.controller;

import com.ujazdowski.SocialPortal.exceptions.UserNotExistsException;
import com.ujazdowski.SocialPortal.model.tables.Invitation;
import com.ujazdowski.SocialPortal.model.tables.User;
import com.ujazdowski.SocialPortal.repository.UsersRepository;
import com.ujazdowski.SocialPortal.service.CustomUser;
import com.ujazdowski.SocialPortal.service.InvitationsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.util.Optional;

@RequestMapping("/home/profile")
@Controller
public class ProfileController {
    private static Logger logger = LoggerFactory.getLogger(ProfileController.class);
    private final UsersRepository usersRepository;
    private final InvitationsService invitationsService;

    public ProfileController(UsersRepository usersRepository, InvitationsService invitationsService){
        this.usersRepository = usersRepository;
        this.invitationsService = invitationsService;
    }

    @RequestMapping(value = "/{userId}", method = RequestMethod.GET)
    public ModelAndView profile(@PathVariable("userId") Long userId, Model model) throws Exception {
        Optional<User> oUser = this.usersRepository.findByUserId(userId);

        logger.info("USERID {}", userId);
        logger.info("USER {}", oUser.get().getEmail());

        oUser.orElseThrow(() -> new UserNotExistsException());
        User user = oUser.get();
        User logged = ((CustomUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUser();

        ModelAndView mv = new ModelAndView("profile");
        mv.addObject("user", user);
        mv.addObject("friends", this.invitationsService.usersAreFriends(user, logged));
        Invitation i = new Invitation();
        i.setAccepted(false);
        i.setFromUser(logged);
        i.setToUser(user);
        mv.addObject("invitation", new Invitation());

        return mv;
    }

    @RequestMapping(value = "/{userId}", method = RequestMethod.POST)
    public ModelAndView invite(@PathVariable("userId") Long userId,
                         @ModelAttribute("invitation")Invitation invitation,
                         BindingResult result,
                         Model model) throws Exception {
        if (result.hasErrors()) {
            for (ObjectError error: result.getAllErrors()) {
                logger.warn("ERROR {}", error.getDefaultMessage());
            }
            return profile(userId, model);
        }
        User user = invitation.getFromUser();
        logger.info("FROM USER: "  + user.getUserId());
        this.invitationsService.addNewUser(invitation);

        return profile(userId, model);
    }
}

JSP view profile.jsp:

<%[email protected] id="invitation" type="com.ujazdowski.SocialPortal.model.tables.Invitation"--%>
<form:errors path="invitation.*"></form:errors>
<form:form method="post" modelAttribute="invitation">
    <form:input path="fromUser" type="hidden" name="fromUser" value="${logged}"/>
    <form:input path="toUser" type="hidden" name="toUser" value="${user}"/>
    <form:button id="sendInvitation" type="submit" class="btn btn-primary btn-lg"><spring:message code="profile.addToFriends" /></form:button>
</form:form>

Invitation.java:

package com.ujazdowski.SocialPortal.model.tables;

import lombok.Data;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.sql.Timestamp;

@Data
@Entity
@Table(name = "INVITATION_T")
public class Invitation {
    @NotNull
    @Id
    @GeneratedValue
    @Column(name = "INVITATION_ID")
    private Long invitationId;

    @NotNull
    @OneToOne
    @JoinColumn(name = "FROM_USER_ID")
    private User fromUser;

    @NotNull
    @OneToOne
    @JoinColumn(name = "TO_USER_ID")
    private User toUser;

    @NotNull
    @Column(name = "SENDED")
    private Timestamp sended;

    @NotNull
    @Column(name = "ACCEPTED")
    private Boolean accepted;
}

How to solve this problem?

Ad

Answer

java.lang.NumberFormatException: For input string: "User(userId=4,roles=[Role(userRoleId=1,role=USER)],firstName=Kamil,secondName=Stonoga,[email protected],password=SECRET,lastTimeOnline=null,profilePhotoId=null,male=true)"

The string is rendered with EL which is used toString() on the object referenced. Because this value is not a number it cannot be converted to the model property where the number is expected. Either change the value to print a number or change the property to use string type. Then because the format of this object is unknown you can parse it manually on the method.

Ad
source: stackoverflow.com
Ad