无法从类型 [java.lang.String] 转换为类型 [java.lang.Long]

Posted

技术标签:

【中文标题】无法从类型 [java.lang.String] 转换为类型 [java.lang.Long]【英文标题】:Failed to convert from type [java.lang.String] to type [java.lang.Long] 【发布时间】:2021-03-04 01:37:26 【问题描述】:

此映射应返回一组订阅者或订阅。但相反,我得到了错误:

出现意外错误(类型=错误请求,状态=400)。 无法将“java.lang.String”类型的值转换为所需类型“org.project.notablog.domains.User”;嵌套异常是 org.springframework.core.convert.ConversionFailedException: 的值“订阅”;嵌套异常是 java.lang.NumberFormatException:对于输入字符串:“订阅” org.springframework.web.method.annotation.MethodArgumentTypeMismatchException:无法将类型“java.lang.String”的值转换为所需类型“org.project.notablog.domains.User”;嵌套异常是 org.springframework.core.convert.ConversionFailedException: 的值“订阅”;嵌套异常是 java.lang.NumberFormatException: For input string: "subscriptions"

控制器:


@Controller
@RequestMapping("/user")
public class UserController 


    @GetMapping("type/user/list")
    public String userList(
            Model model,
            @PathVariable User user,
            @PathVariable String type
    ) 
        model.addAttribute("userChannel", user);
        model.addAttribute("type", type);

        if ("subscriptions".equals(type)) 
            model.addAttribute("users", user.getSubscriptions());
         else 
            model.addAttribute("users", user.getSubscribers());
        

        return "subscriptions";
    


实体:

@Entity
@Table(name = "usr")
public class User implements UserDetails 
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @NotBlank(message = "Username cannot be empty")
    private String username;

    @NotBlank(message = "Password cannot be empty")
    private String password;

    private boolean active;

    @Email(message = "Email isn't correct")
    @NotBlank(message = "Email cannot be empty")
    private String email;
    private String activationCode;

    @ElementCollection(targetClass = Role.class, fetch = FetchType.EAGER)
    @CollectionTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"))
    @Enumerated(EnumType.STRING)
    private Set<Role> roles;

    @OneToMany(mappedBy = "author", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private Set<Message> messages;

    @ManyToMany
    @JoinTable(
            name = "user_subscriptions",
            joinColumns =  @JoinColumn(name = "author_id") ,
            inverseJoinColumns =  @JoinColumn(name = "subscriber_id") 
    )
    private Set<User> subscribers = new HashSet<>();

    @ManyToMany
    @JoinTable(
            name = "user_subscriptions",
            joinColumns =  @JoinColumn(name = "subscriber_id") ,
            inverseJoinColumns =  @JoinColumn(name = "author_id") 
    )
    private Set<User> subscriptions = new HashSet<>();



    public User() 
    

    public User(String username, String password, boolean active, Set<Role> roles) 
        this.username = username;
        this.password = password;
        this.active = active;
        this.roles = roles;
    

    @Override
    public boolean equals(Object o) 
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
        return Objects.equals(id, user.id);
    

    @Override
    public int hashCode() 

        return Objects.hash(id);
    

    public Boolean isAdmin()
    
        return roles.contains(Role.ADMIN);
    

    public Long getId() 
        return id;
    

    public void setId(Long id) 
        this.id = id;
    

    public String getUsername() 
        return username;
    

    @Override
    public boolean isAccountNonExpired() 
        return true;
    

    @Override
    public boolean isAccountNonLocked() 
        return true;
    

    @Override
    public boolean isCredentialsNonExpired() 
        return true;
    

    @Override
    public boolean isEnabled() 
        return isActive();
    

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

    public boolean isActive() 
        return active;
    

    public void setActive(boolean active) 
        this.active = active;
    

    public Set<Role> getRoles() 
        return roles;
    

    public void setRoles(Set<Role> roles) 
        this.roles = roles;
    

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() 
        return getRoles();
    

    public String getPassword() 
        return password;
    

    public void setPassword(String password) 
        this.password = password;
    

    public String getEmail() 
        return email;
    

    public void setEmail(String email) 
        this.email = email;
    

    public String getActivationCode() 
        return activationCode;
    

    public void setActivationCode(String activationCode) 
        this.activationCode = activationCode;
    

    public Set<Message> getMessages() 
        return messages;
    

    public void setMessages(Set<Message> messages) 
        this.messages = messages;
    

    public Set<User> getSubscribers() 
        return subscribers;
    

    public void setSubscribers(Set<User> subscribers) 
        this.subscribers = subscribers;
    

    public Set<User> getSubscriptions() 
        return subscriptions;
    

    public void setSubscriptions(Set<User> subscriptions) 
        this.subscriptions = subscriptions;
    


Freemarker 模板:

<#import "parts/common.ftlh" as c>

<@c.page>
    <h3>$author.username</h3>
    <div>$type</div>
    <ul class="list-group">
        <#list users as user>
            <li class="list-group-item">
                <a href="/user-messages/$user.id">$user.getUsername()</a>
            </li>
        </#list>
    </ul>
</@c.page>

我已经尝试了所有想到的方法,但我无法弄清楚问题出在哪里。

【问题讨论】:

【参考方案1】:

有了这个

    @PathVariable User user,

您指的是路径 type/user/list 中的变量,它只是一个字符串,可能是 userId。

应该是这样的

    @PathVariable("user") String userId

之后您可以加载用户,例如User user = userService.getUser(userId); UserService 或 UserRepository 必须为此连接到控制器。

【讨论】:

感谢您的回答!我尝试了这种方法(我通过 UserRepository 搜索),但不幸的是它没有帮助,我得到了所有相同的错误 你也改成这个@PathVariable("user") String userId了? 是的,但没有帮助

以上是关于无法从类型 [java.lang.String] 转换为类型 [java.lang.Long]的主要内容,如果未能解决你的问题,请参考以下文章

无法将类型“java.lang.String”的属性值转换为属性“事务”所需的类型“java.util.List”

JSONException:Java.lang.String 类型的值 <?xml 无法转换为 JSONObject

BlueJ 错误:“不兼容的类型:int 无法转换为 java.lang.String”和“不兼容的类型:java.lang.String 无法转换为 int”

org.json.JSONException:java.lang.String 类型的值 <br 无法转换为 JSONObject

不兼容的类型:java.lang.Object 无法转换为 java.lang.String

无法将类型 [java.lang.String] 的属性值转换为所需类型 [java.lang.Integer]