0

I have a pojo class like this

pulic class Role{
private int roleId;
private String roleName;

//default getters setters and constructors

Another POJO class user

public class User{

private String id;
private String name;
private Role role;

// standard getters setters and constructors

My controller class method to call the page

    @GetMapping("/adduser")
    public String registerUserPage(Model model){

        model.addAttribute("roles",roles.listRoles());
        User user = new User();
        user.setRole(new Role());
        model.addAttribute("user",user);

        return "adduser";
    }

adduser.html

<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org"
      xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
    <title>test</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>

<form name="registerForm" th:action="@{/createUser}" th:object="${user}" method="POST">
    <div><label> First Name : <input type="text" th:field="*{name}"/> </label></div>
    <div><label> Id : <input type="text" th:field="*{id}"/> </label></div>
        <select th:field="*{role}">
            <option value="">Select Test Order</option>
            <option th:each="role : ${roles}"
                    th:value="${role}"
                    th:text="${role.roleName}"></option>
        </select>

    <div><input type="submit" value="Add"/></div>
</form>
</body>
</html>

And the createUser controller

    @PostMapping("/createUser")
    public String registerUser(@ModelAttribute("user") User user, Model model){
        System.out.println(digiUser.getName); //this works
        System.out.println(digiUser.getRole().getRoleName()); //how??
        return "ok";
    }

I am able to list roles form the dropdown and also assign other values like name and id successfully. However when I tried to assign the dropdown to the "*{role}", its breaking..

i get the exception:

 default message [Failed to convert property value of type 'java.lang.String' to required type 'com.vipin.data.Role' for property 'role';

From the exception i see it casting exception. I know I could probably assign a role Id and later process it however, as there are 2 values in role (roleName and roleId) ,how can I assign the role object directly? Is it possible? any alternative approaches to assign both values of role (id and roleName) form single dropdown selection?

1 Answer 1

1

One approach is using Spring Type Conversion service for converting between select's string value like RoleName into Role instance.

For using this approach needs to be done several steps:

  1. Create an instance of Interface Converter<S,T>. For our case, it can be
public class RoleNameToRoleConverter implements Converter<String,Role>

More details about spring conversion can be found here

  1. Register this convertor into MVC configuration
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
     registry.addConverter(new RoleNameToRoleConverter ());    
    }
}

More details about configuration spring mvc type conversion can be found here

  1. Change th:value="${role}" into th:value="${role.roleName}"

All these steps need because HTML form cannot send complicated types such as an object, it always sends simple numbers or strings and after accepting this request SpringMVC needs to know how to convert these simple values into complex objects.

Also, for simplifying, you can add to model only list contains strings with role names instead of attaching list with the whole roles.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.