JHipster:向用户注册其他信息 [英] JHipster : Registering a user with additional information

查看:43
本文介绍了JHipster:向用户注册其他信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JHispter 3.12.2开发应用程序.

I am developping an application using JHispter 3.12.2.

由于我需要的信息比JHipster所提供的更多,因此我创建了一个实体UserExtra,其中包含两个String:电话号码和skype地址. 我以一对一关系将此实体链接到JHI_User.

Since I needed more information than what JHipster provides, I created an entity UserExtra containing two Strings : a phone number and a skype address. I linked this entity to the JHI_User in a One to One relationship.

现在我面临的问题是,当用户注册时,我想创建一个与注册用户关联的新UserExtra.

Now the problem I am facing is, when a user is registering, I want to create a new UserExtra associated with the registered User.

为此,我已经在客户端尝试了几件事.

To achieve that, I have tried several things on the client side.

标准JHipster注册页面的工作方式是使用名为vm.registerAccount的变量,该变量包含firstName,lastName,登录名和密码等.

The way the standard JHipster register page works is by using a variable named vm.registerAccount that holds the firstName, lastName, login, password and so on.

我尝试使用另一个变量vm.userExtra来保存我的电话号码和skype.然后,我尝试了几件事:

I have tried using another variable vm.userExtra holding my phone number and skype. Then, I tried several things :

  • 在register.controller.js中,我将userExtra传递给createAccount函数:

  • In the register.controller.js, I passed my userExtra to the createAccount function :

Auth.createAccount(vm.registerAccount, vm.userExtra).then(function () {
                    vm.success = 'OK';
                }).catch(function (response) {
                    vm.success = null;
                    if (response.status === 400 && response.data === 'login already in use') {
                        vm.errorUserExists = 'ERROR';
                    } else if (response.status === 400 && response.data === 'e-mail address already in use') {
                        vm.errorEmailExists = 'ERROR';
                    } else {
                        vm.error = 'ERROR';
                    }
                });

  • 我修改了auth.service.js的createAccount函数以遵循所做的更改:

  • I modified the createAccount function of auth.service.js to follow the changes made :

    function createAccount (account, userExtra, callback) {
                var cb = callback || angular.noop;
            return Register.save(account, userExtra,
                function () {
                    return cb(account);
                },
                function (err) {
                    this.logout();
                    return cb(err);
                }.bind(this)).$promise;
        }</pre>
    

  • 最后,我在服务器端更新了AccountResource.java的registerAccount函数:

  • Finally, I updated the registerAccount function of AccountResource.java on the server side :

    public ResponseEntity registerAccount(@Valid @RequestBody ManagedUserVM managedUserVM, UserExtra userExtra) { ... }

    但是从我记忆中还没有执行registerAccount函数.

    But the registerAccount function wasn't even executed from what I remember.

    我还尝试过将新用户添加到register.controller.js的createAccount函数的回调中,如下所示:

    I also tried adding the new user in the callback of the createAccount function of register.controller.js like this :

    Auth.createAccount(vm.registerAccount).then(function (result) {
                    vm.userExtra.user = result;
                    UserExtra.save(vm.userExtra, function() { // success }, function() { // fail });
                    vm.success = 'OK';
                })...
    

    但是在尝试保存新的UserExtra时,我只是遇到错误.

    But I was only getting an error while trying to save the new UserExtra.

    我很确定我需要修改AccountResource.java中的registerAccount()函数,但是我只是无法检索要从客户端发送的其他信息.我设法在此函数内创建了一个新用户,并将其链接到JHI_User,但没有其他信息.

    I am pretty sure I need to modify the registerAccount() function inside AccountResource.java, but I just can't retrieve the additional information I am trying to send from the client side. I managed to create a new User inside this function and link it to the JHI_User, but without the additional information.

    很有可能已经有人遇到了这个问题,什么可能是解决这个问题的最佳解决方案?

    It's very likely somebody has already faced this issue, what could possibly be the best solution to that problem ?

    使用解决方案进行

    多亏了GaëlMarziou,我解决了我的问题.

    Thanks to Gaël Marziou, I fixed my problem.

    这是我正在描述的解决方案的一个最小项目示例在这里.

    在客户端,在我重写为使用的register.html页面中,我有两个字段绑定到vm.registerAccount属性:

    On the client side, in the register.html page that I have rewritten to my use, I have two fields bound to vm.registerAccount properties :

    <input class="form-control" id="phone" ng-model="vm.registerAccount.phone" placeholder="{{'global.form.phone.placeholder' | translate}}" />
    ...
    <input class="form-control" id="skype" ng-model="vm.registerAccount.skype" placeholder="{{'global.form.skype.placeholder' | translate}}" />
    

    在ManagedUserVM中,我实际上只是添加了两个字段及其获取器:

    In ManagedUserVM I really just added my two fields and their getters :

    private String phone;
    
    private String skype;
    
    public String getPhone() {
        return phone;
    }
    
    public String getSkype() {
        return skype;
    }
    

    我更改了UserExtra类,以映射User和UserExtra ID,以便对其进行镜像.由于UserExtra实际上只是对User的扩展,因此可以加快检索过程并使其更有意义:

    I changed my UserExtra class to map the User and UserExtra ids so that they are mirrored. This accelerates the retrieval process and makes more sense as UserExtra really is just an extension to User :

    public class UserExtra implements Serializable {
    
        private static final long serialVersionUID = 1L;
    
        @Id
        private Long id;
    
        @Column(name = "phone")
        private String phone;
    
        @Column(name = "skype")
        private String skype;
    
        @OneToOne
        @MapsId
        private User user;
        ...
    }
    

    我在UserService中创建了一个名为createUser()的新自定义函数,该函数除了基本字段外还需要我的两个字段.我没有更新现有功能,因此不必更改测试类:

    I created a new custom function called createUser() in UserService which needs my two fields in addition to the basic ones. I didn't update the existing function so that I don't have to change the test classes :

    public User createUser(String login, String password, String firstName, String lastName, String email,
                           String langKey, String phone, String skype) {
    
        User newUser = new User();
        Authority authority = authorityRepository.findOne(AuthoritiesConstants.USER);
        Set<Authority> authorities = new HashSet<>();
        String encryptedPassword = passwordEncoder.encode(password);
        newUser.setLogin(login);
        // new user gets initially a generated password
        newUser.setPassword(encryptedPassword);
        newUser.setFirstName(firstName);
        newUser.setLastName(lastName);
        newUser.setEmail(email);
        newUser.setLangKey(langKey);
        // new user is not active
        newUser.setActivated(false);
        // new user gets registration key
        newUser.setActivationKey(RandomUtil.generateActivationKey());
        authorities.add(authority);
        newUser.setAuthorities(authorities);
        userRepository.save(newUser);
        userSearchRepository.save(newUser);
        log.debug("Created Information for User: {}", newUser);
    
        // Create and save the UserExtra entity
        UserExtra newUserExtra = new UserExtra();
        newUserExtra.setUser(newUser);
        newUserExtra.setPhone(phone);
        newUserExtra.setSkype(skype);
        userExtraRepository.save(newUserExtra);
        userExtraSearchRepository.save(newUserExtra);
        log.debug("Created Information for UserExtra: {}", newUserExtra);
    
        return newUser;
    }
    

    最后,我更新了AccountResource的registerAccount()函数,以使用另外两个字段来调用我的自定义函数:

    Finally, I updated the registerAccount() function of AccountResource to call my custom function using the two additional fields :

    public ResponseEntity<?> registerAccount(@Valid @RequestBody ManagedUserVM managedUserVM) {
    
        HttpHeaders textPlainHeaders = new HttpHeaders();
        textPlainHeaders.setContentType(MediaType.TEXT_PLAIN);
    
        return userRepository.findOneByLogin(managedUserVM.getLogin().toLowerCase())
            .map(user -> new ResponseEntity<>("login already in use", textPlainHeaders, HttpStatus.BAD_REQUEST))
            .orElseGet(() -> userRepository.findOneByEmail(managedUserVM.getEmail())
                .map(user -> new ResponseEntity<>("e-mail address already in use", textPlainHeaders, HttpStatus.BAD_REQUEST))
                .orElseGet(() -> {
                    User user = userService
                        .createUser(managedUserVM.getLogin(), managedUserVM.getPassword(),
                            managedUserVM.getFirstName(), managedUserVM.getLastName(),
                            managedUserVM.getEmail().toLowerCase(), managedUserVM.getLangKey(),
                            managedUserVM.getPhone(), managedUserVM.getSkype());
    
                    mailService.sendActivationEmail(user);
                    return new ResponseEntity<>(HttpStatus.CREATED);
                })
        );
    }
    

    推荐答案

    ManagedUserVM是一个视图模型,最简单的方法是向其中添加额外的字段,一个视图模型可以是多个实体的集合.这样一来,您无需更改角度服务,客户端代码就无需知道用户在服务器上的存储方式.

    ManagedUserVM is a view model so simplest way is to add your extra fields to it, a view model can be an aggregate of several entities. This way you don't change your angular service, your client code does not need to know how a User is stored on server.

    然后在服务器上,您应考虑修改UserExtra实体以使用与User相同的ID,而不是生成的ID,请使用@MapIds.参见此不错的文章以获得详细信息.

    Then on server, you should consider modifying the UserExtra entity to use same id as User rather than a generated id, use @MapIds. See this very nice article for details.

    这篇关于JHipster:向用户注册其他信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆