M
M
Maxim Rybalkin2019-12-27 13:07:25
Java
Maxim Rybalkin, 2019-12-27 13:07:25

How to convert @PathVariable to number?

There is a controller that displays the user edit form:

@GetMapping("{user}")
    public String editForm(@PathVariable User user, Model model) {
        if (user.isAdmin()) {
            return "redirect:/users";
        }
        model.addAttribute("user", user);
        model.addAttribute("roles", Role.values());
        return "userEdit";
    }

The problem is the following - in the user base they are created with a sequence of 100000, and therefore with a similar request:
localhost:8080/users/100%C2%A0002

which means requesting a user profile with id = 100002 I get an error
Failed to convert value of type 'java.lang.String' to required type 'en.topjava.graduation.model.User'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.lang.Integer] for value '100 002'; nested exception is java.lang.NumberFormatException: For input string: "100 002"

On the front, everything is quite simple:
<#import "parts/common.ftl" as c>

<@c.page>
    List of users
    <table>
        <thead>
        <tr>
            <th>Name</th>
            <th>Role</th>
            <th></th>
        </tr>
        </thead>
        <tbody>
        <#list users as user>
            <tr>
                <td>${user.username}</td>
                <td><#list user.roles as role>${role}<#sep>, </#list></td>
                <td><#if !user.isAdmin()><a href="/users/${user.id}">edit</a></#if></td>
            </tr>
        </#list>
        </tbody>
    </table>
</@c.page>

How to get around this without "clumsy cutting" of spaces in the string?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2019-12-27
@MaxRybalkin

For some reason, instead of a number, you are passing a sequence of two numbers separated by a non- breaking space character .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question