简体   繁体   English

Spring MVC + Hibernate - 从表单更新一些属性

[英]Spring MVC + Hibernate - Update some attributes from form

I have this controller: 我有这个控制器:

@RequestMapping(value="admins", method=RequestMethod.POST, params="editar")
public String editarAdmin(@ModelAttribute("cadastroform") Usuario usuario){
    usuarioService.atualizaUsuario(usuario); //do the update
    return "redirect:/admin/admins?listar";
}

As you can see, I'm receiving the Usuario object and updating it, but, for that, I need to have this form on my jsp: 正如您所看到的,我正在接收Usuario对象并更新它,但是,为此,我需要在我的jsp上使用此表单:

<sf:form id="formCadastrarAdmin" method="post" modelAttribute="cadastroform">
<label for="tfNome">Nome*: </label>
<sf:input path="nome" type="text" id="tfNome" name="nome" placeholder="Digite o nome do novo administrador"/>
<label for="tfEmail">E-mail*: </label>
<sf:input path="email" type="text" id="tfEmail" name="email" placeholder="Digite o email do novo administrador"/>

<c:choose>
    <c:when test="${!empty param.editar}">
        <sf:input path="login" type="hidden" id="tfLogin" name="login" placeholder="Digite o login do novo administrador"/>
        <sf:input path="senha" type="hidden" name="senha" placeholder="Digitar senha de acesso"/>
    </c:when>
    <c:otherwise>
        <label for="tfLogin">Login*:  </label>
        <sf:input path="login" type="text" id="tfLogin" name="login" placeholder="Digite o login do novo administrador"/>
        <label for="tfSenha">Senha*: </label>
        <sf:input path="senha" type="password" id="tfSenha" name="senha" placeholder="Digitar senha de acesso"/>
        <label for="tfSenhaRepeat">Confirmação de senha*: </label>
        <input type="password" id="tfSenhaRepeat" name="senhaRepeat" placeholder="Redigitar senha de acesso"/>
    </c:otherwise>
</c:choose>

<label for="sfTipo">Autoridades*: </label>

<div id="autoridades">
    <sf:checkboxes items="${listaAutoridades}" delimiter="</br>" path="authorities" cssClass="box_autoridade"
                   itemValue="authority" itemLabel="descricao"></sf:checkboxes>
</div>

<sf:input type="hidden" path="foto" value="default"/>  
<sf:input type="hidden" path="tipo" value="default"/>  
<sf:input type="hidden" path="id"/>
<sf:input type="hidden" path="dataCadastro"/>

<br/>
<button type="submit" id="btEnviar" onclick="return false">Cadastrar</button>
<button type="reset" id="btLimpar">Limpar</button>    

So, I'm having a lot of hidden fields, in order to fill all the attributes of the Usuario object that I don't want to change. 所以,我有很多隐藏的字段,以填充我不想改变的Usuario对象的所有属性。 I could just omit all these hidden fields and retrieve the object from database in my controller, but I think it wouldn't be correct. 我可以省略所有这些隐藏的字段并从我的控制器中的数据库中检索对象,但我认为这是不正确的。

My question is: is the hidden field approach correct? 我的问题是:隐藏的现场方法是否正确? If it's not, what's the most recommended way to update an object from a form? 如果不是,那么从表单更新对象的最佳推荐方法是什么?

Thank you. 谢谢。

I think, the best approach depends on what you need from your application. 我认为,最好的方法取决于您的应用程序需要什么。 Security? 安全? - sending unnecessary data to the client may be a bad idea. - 向客户端发送不必要的数据可能是一个坏主意。 Scalability? 可扩展性? - your approach probably is the most scalable. - 您的方法可能是最具扩展性的。 Performance? 性能? - you may consider storing your usuario object in a session attribute between controller invocations instead of retrieving its data from the DB. - 您可以考虑将您的usuario对象存储在控制器调用之间的会话属性中,而不是从数据库中检索其数据。

If you decide to store the Usuario form backing object as a session attribute between controller invocations, Spring MVC has the @SessionAttribute annotation. 如果您决定将Usuario表单支持对象存储为控制器调用之间的会话属性,则Spring MVC具有@SessionAttribute批注。 Here is an example of its usage. 以下是其用法示例。

Mostly when I have a form that doesn't exactly matches the persisted object I end up creating a new class which will represent that particular piece of data. 大多数情况下,当我有一个与持久化对象不完全匹配的表单时,我最终会创建一个表示该特定数据的新类。 You could also refactor your domain object into several classes which will individually match a form. 您还可以将域对象重构为几个类,这些类将单独匹配表单。 The major benefit from this approach is that can easily validate each instance which would be difficult if you expect the full, in this case, User object with partial data when submitting the form. 这种方法的主要好处是可以轻松验证每个实例,如果您在提交表单时期望完整,在这种情况下, User对象具有部分数据,那将是困难的。

This example is just for illustration. 此示例仅用于说明。 In general it's better to create separate tables/entities instead of one big table/entity. 通常,最好创建单独的表/实体而不是一个大表/实体。

@Entity
class User extends UserDetails {
    @Id
    private Long id;
}


@MappedSuperclass
class User extends UserDetails {
    @NotNull
    @NotBlank
    private String username;
    private String password;
}


@MappedSuperclass
class UserProfile {
    private String name;
    private String address;
    @Email
    private String email;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM