无法将类型'java.lang.String'的属性值转换为必需类型'com.ujazdowski.SocialPortal.model.tables.User'

时间:2018-03-14 19:37:12

标签: java jsp spring-mvc

我试图通过jsp表单将对象发送到java控制器,但我收到错误:

  

无法将“java.lang.String”类型的属性值转换为   必需类型'com.ujazdowski.SocialPortal.model.tables.User'   property'fromUser';嵌套异常是   org.springframework.core.convert.ConversionFailedException:失败   从类型[java.lang.String]转换为类型[java.lang.Long]   值'User(userId = 2,roles = [Role(userRoleId = 1,role = USER)],   firstName = Bartosz,secondName = Ujazdowski,   email=b.ujazdowski@gmail.com,   密码= $ 2A $ 10 $ da7l / 9VRpIPBm1z0LiONwO7wRXMs55.5QOkdpFVQ3 / eqO9FBu4IXu,   lastTimeOnline = null,profilePhotoId = null,male = true)';嵌套   异常是java.lang.NumberFormatException:对于输入字符串:   “用户(用户ID = 2,角色= [作用(userRoleId = 1,角色= USER)],名字=的Bartosz,secondName = Ujazdowski,电子邮件= b.ujazdowski @ gmail.com,密码= $ 2A $ 10 $ da7l / 9VRpIPBm1z0LiONwO7wRXMs55。 5QOkdpFVQ3 / eqO9FBu4IXu,lastTimeOnline = NULL,profilePhotoId = NULL,雄性=真)”       无法将类型'java.lang.String'的属性值转换为必需类型'com.ujazdowski.SocialPortal.model.tables.User'   property'toUser';嵌套异常是   org.springframework.core.convert.ConversionFailedException:失败   从类型[java.lang.String]转换为类型[java.lang.Long]   值'User(userId = 4,roles = [Role(userRoleId = 1,role = USER)],   firstName = Kamil,secondName = Stonoga,email = kamil.stonoga @ gmail.com,   密码= SECRET,   lastTimeOnline = null,profilePhotoId = null,male = true)';嵌套   异常是java.lang.NumberFormatException:对于输入字符串:   “用户(用户ID = 4,角色= [作用(userRoleId = 1,角色= USER)],名字=卡米尔,secondName = Stonoga,电子邮件= kamil.stonoga @ gmail.com,密码= SECRET,lastTimeOnline = NULL,profilePhotoId =空,男性= 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视图profile.jsp

<%--@elvariable 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;
}

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

  

java.lang.NumberFormatException:对于输入字符串:“User(userId = 4,roles = [Role(userRoleId = 1,role = USER)],firstName = Kamil,secondName = Stonoga,email = kamil.stonoga @ gmail .COM,密码= SECRET,lastTimeOnline = NULL,profilePhotoId = NULL,雄性=真)“

使用EL渲染字符串,在引用的对象上使用toString()。由于此值不是数字,因此无法将其转换为期望数字的模型属性。更改值以打印数字或更改属性以使用字符串类型。然后因为此对象的格式未知,您可以在方法上手动解析它。