Spring MVC表单更新对象

时间:2013-03-06 14:58:31

标签: hibernate spring-mvc

我尝试通过表单更新我的对象,我有两个控制器:

@RequestMapping(value = "/modifyUser{id}", method = RequestMethod.GET)
public String modifyUser(@PathVariable("id") int userId, ModelMap map) {
    UserDetails user = userService.findById(userId);

    List<CompanyDetails> companyDetailsList = companyService.getAllExceptUsers(userId);
    map.addAttribute("userDetails", user);
    map.addAttribute("companiesList",companyDetailsList);
    return "admin/modify_user";
}

@RequestMapping(value = "/modifyUser", method = RequestMethod.POST)
public String modifyUser(@Valid @ModelAttribute("userDetails") UserDetails userDetails,
                             BindingResult result, RedirectAttributes redirectAttributes,
                             @RequestParam("company_id")String companyId,ModelMap map) {
    if (!userService.isPhoneNumbersListValid(userDetails.getPhoneNumbers())){
        result.rejectValue("phoneNumbers", "userDetails.phoneNumbersList.error");
    }
    if(!userDetails.getPasswordConfirmation().equals(userDetails.getPassword())){
        result.rejectValue("passwordConfirmation","userDetails.passwordConfirmation.error");
    }
    if("default".equals(userDetails.getCountry())){
        result.rejectValue("country","userDetails.country.error");
    }
    if (result.hasErrors()){
        List<CompanyDetails> companyDetailsList = companyService.getAllExceptUsers(userDetails.getId());
        map.addAttribute("companiesList",companyDetailsList);
        return "admin/modify_user";
    }

    logger.warn("***********Updated user ID:"+userDetails.getId()+" and companies size: "+userDetails.getUserCompanies().size());

    CompanyDetails companyDetails = companyService.getCompanyById(Integer.parseInt(companyId));
    userDetails.setEnabled(true);

    if (userService.update(userDetails,companyDetails)) {
        redirectAttributes.addFlashAttribute("userModifyStatus", true);
    } else {
        redirectAttributes.addFlashAttribute("userModifyStatus", false);
    }
        return "redirect:modifyUser" + userDetails.getId() + ".html";
    }

UserDetails(这是我的自定义用户对象,而不是org.springframework.security.core.userdetails )实体有一系列公司,当我们第一次获取GET页面时,收集已满(有必要的)。

但是当我尝试POST我更新的对象时,这个内部集合是空的(当我提交表单时它会消失。)

我的自定义对象:

@Entity
@Table(name = "users")
public class UserDetails {

    @Id
    @GeneratedValue
    @Column(name = "user_id")
    private int id;

    @Column(name = "first_name")
    @NotEmpty
    @Size(min = 2, max = 20)
    private String firstName;

    @Column(name = "legal_name")
    @NotEmpty
    @Size(min = 2, max = 30)
    private String legalName;

    @Column(name = "country")
    private String country;

    @Column(name = "legal_address")
    @NotEmpty
    @Size(min = 5, max = 255)
    private String legalAddress;

    @Column(name = "role")
    private String role;

    @Column(name = "login")
    @NotEmpty
    @Email
    private String login;

    @Column(name = "password")
    @NotEmpty
    @Size(min = 3, max = 10)
    private String password;

    @Transient
    private String passwordConfirmation;

    @Column(name = "enabled")
    private boolean enabled;

    @ElementCollection
    @CollectionTable(name = "users_phone_numbers", joinColumns = @JoinColumn(name = "user_id"))
    @Column(name = "phoneNumber")
    private Collection<String> phoneNumbers = new LinkedList();

    @ManyToMany(cascade = CascadeType.REFRESH)
    @JoinTable(name = "users_companies",
            joinColumns = @JoinColumn(name = "user_id"),
            inverseJoinColumns = @JoinColumn(name = "company_id"))
    private Set<CompanyDetails> userCompanies = new HashSet();

    //getters and setters
}

我的提交表格:

<form:form method="post" action="modifyUser.html" commandName="userDetails">
        <form:hidden path="id"/>
        <form:label path="firstName"><spring:message code="addUser.label.firstName"/></form:label>
        <form:input type="text" path="firstName"/>
        <form:errors path="firstName" cssClass="form-errors"/>

        <form:label path="legalName"><spring:message code="addUser.label.legalName"/></form:label>
        <form:input type="text" path="legalName"/>
        <form:errors path="legalName" cssClass="form-errors"/>

        <form:label path="login"><spring:message code="addUser.label.login"/></form:label>
        <form:input type="text" path="login"/>
        <form:errors path="login" cssClass="form-errors"/>

        <form:label path="password"><spring:message code="addUser.label.password"/></form:label>
        <form:input type="password" path="password"/>
        <form:errors path="password" cssClass="form-errors"/>

        <form:label path="passwordConfirmation"><spring:message code="addUser.label.confirmPassword"/></form:label>
        <form:input type="password" path="passwordConfirmation"/>
        <form:errors path="passwordConfirmation" cssClass="form-errors"/>

        <form:label path="country"><spring:message code="addUser.label.country"/></form:label>
        <form:select class="iso-country-select" path="country">
            <form:option value="default"><spring:message code="addUser.label.selectCountry"/></form:option>
        </form:select>
        <form:errors path="country" cssClass="form-errors"/>


        <label for="select-companies"><spring:message code="assignUser.label.companies"/> </label>
        <select id="select-companies" name="company_id">
            <option value="default"><spring:message code="searchUser.label.selectCompany"/></option>
            <c:forEach items="${companiesList}" var="company">
                <option value="${company.id}">${company.name}</option>
            </c:forEach>
        </select>

        <div class="phone-numbers">
            <form:label path="phoneNumbers"><spring:message code="addUser.label.phoneNumber"/></form:label>
            <p class="added-input-text">
                <c:forEach items="${userDetails.phoneNumbers}" var="phoneNumber" varStatus="loop">
                    <form:input type="text" path="phoneNumbers[${loop.index}]"/>
                </c:forEach>
                <a href="#" class="add"><img src="../static/img/add.png"/></a>
            <p/>

            <form:errors path="phoneNumbers" cssClass="form-errors"/>
        </div>

        <form:label path="legalAddress"><spring:message code="addUser.label.legalAddress"/></form:label>
        <form:textarea path="legalAddress"/>
        <form:errors path="legalAddress" cssClass="form-errors"/>

        <form:label path="role"><spring:message code="addUser.label.role"/></form:label>
        <form:select path="role">
            <form:option value="ROLE_USER"><spring:message code="addUser.label.role.external"/></form:option>
            <form:option value="ROLE_ADMIN"><spring:message code="addUser.label.role.internal"/></form:option>
        </form:select>

        <input type="submit" value="<spring:message code="modifyUser.label.submit"/>"/>
    </form:form>

我可以解决这个问题吗?谢谢。

1 个答案:

答案 0 :(得分:0)

您的意思是UserDetails中的org.springframework.security.core.userdetails吗?

在这种情况下,UserDetails中的GrantedAuthority集合没有setter,因此spring mvc无法为其设置值。

public interface UserDetails extends Serializable {

     Collection<GrantedAuthority> getAuthorities();
     ....
}


/* it does not have any setter */
public interface GrantedAuthority extends Serializable {
    String getAuthority();  
}