Hybris注册页添加自定义属性并持久化

Hybris注册页添加自定义属性并持久化

本文旨在解决Hybris电商平台在注册页添加自定义属性(如“Pan”号)时遇到的数据持久化问题。通过详细阐述ModelSavingException的根源及optional=”true”修饰符的局限性,文章将指导读者如何正确地扩展和修改Hybris的关键组件,包括registerform、RegisterData、RegistrationPageController和CustomerFacade,以确保用户输入的新字段值能完整地从前端传递到后端模型并成功存储到数据库中。

1. 问题背景与根源分析

在hybris注册流程中,当尝试在customermodel上添加一个新的强制性属性(例如pan,即个人识别码),并在注册表单中收集该值时,常常会遇到de.hybris.platform.servicelayer.exceptions.modelsavingexception: missing values for [pan]错误。这个错误表明在创建新的customermodel实例时,其强制性的pan属性没有被赋值。

即使尝试通过在items.xml中将该属性设置为optional=”true”来规避上述错误,虽然可以成功注册,但Pan值却无法被存储到数据库中。这说明问题不仅仅在于属性的强制性,更在于数据从前端用户界面到后端数据模型的完整传递链条中断。核心问题在于,用户在前端表单中输入的值,没有正确地经过Hybris的mvc层级,最终映射并保存到CustomerModel实例中。

2. 解决方案:扩展Hybris核心组件

要彻底解决此问题,需要确保新添加的Pan属性值能够贯穿Hybris的整个数据流,从ui表单到最终的CustomerModel。这涉及到对以下核心组件的扩展和修改:

  • items.xml:定义CustomerModel上的新属性。
  • RegisterForm:承载前端表单提交的数据。
  • RegisterData:作为数据传输对象(DTO),在控制器和门面之间传递数据。
  • RegistrationPageController:处理注册请求,将表单数据绑定到RegisterForm,并传递给CustomerFacade。
  • CustomerFacade:作为业务逻辑的入口,负责将RegisterData中的值映射到CustomerModel并进行保存。

2.1 定义CustomerModel上的新属性 (items.xml)

首先,确保在你的items.xml文件中正确定义了CustomerModel上的pan属性。如果该属性是业务必需的,则不应将其设置为optional=”true”。

<!-- Your extension's items.xml --> <items xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="items.xsd">     <itemtypes>         <itemtype code="Customer" autocreate="false" generate="false">             <attributes>                 <attribute qualifier="pan" type="Java.lang.String">                     <description>Customer's Permanent Account Number (PAN).</description>                     <persistence type="property"/>                     <!-- If 'pan' is mandatory for registration, do NOT set optional="true" -->                     <!-- <modifiers optional="true"/> -->                 </attribute>             </attributes>         </itemtype>     </itemtypes> </items>

注意事项:

  • 在添加新属性后,需要运行ant all并启动Hybris服务器,然后执行系统更新(platform update),以确保数据库模式更新并识别新属性。
  • 如果pan是强制性的,请不要添加optional=”true”修饰符,否则将无法触发ModelSavingException,但数据也无法被强制输入。

2.2 扩展RegisterForm

RegisterForm是spring MVC用来绑定前端表单数据的Java Bean。你需要在此类中添加pan字段,以接收来自html表单的输入。

// Assuming your extension extends the core Hybris storefront // e.g., mystorefront/src/com/mycompany/storefront/forms/MyRegisterForm.java package com.mycompany.storefront.forms;  import de.hybris.platform.acceleratorstorefrontcommons.forms.RegisterForm; import javax.validation.constraints.NotEmpty; // Example validation  public class MyRegisterForm extends RegisterForm {      @NotEmpty(message = "{register.pan.invalid}") // Add appropriate validation     private String pan;      public String getPan() {         return pan;     }      public void setPan(String pan) {         this.pan = pan;     } }

注意事项:

  • 确保在你的jsp/Thymeleaf注册表单中,输入字段的name属性与MyRegisterForm中的pan字段名称匹配。例如:
  • 你可以根据需要添加JSR 303/349验证注解(如@NotEmpty, @Pattern等)。

2.3 扩展RegisterData

RegisterData是一个数据传输对象(DTO),用于在控制器和服务层之间传递注册信息。同样,需要在此DTO中添加pan字段。

// e.g., mycore/src/com/mycompany/core/data/MyRegisterData.java package com.mycompany.core.data;  import de.hybris.platform.commercefacades.user.data.RegisterData;  public class MyRegisterData extends RegisterData {      private String pan;      public String getPan() {         return pan;     }      public void setPan(String pan) {         this.pan = pan;     } }

2.4 修改RegistrationPageController

RegistrationPageController负责处理注册页面的请求和表单提交。你需要修改它以使用你的自定义MyRegisterForm和MyRegisterData,并确保数据从表单正确复制到DTO。

通常,你会通过Spring的@Controller注解覆盖或扩展现有的控制器。

// e.g., mystorefront/src/com/mycompany/storefront/controllers/pages/MyRegistrationPageController.java package com.mycompany.storefront.controllers.pages;  import com.mycompany.storefront.forms.MyRegisterForm; import com.mycompany.core.data.MyRegisterData; // Your custom RegisterData import de.hybris.platform.acceleratorstorefrontcommons.controllers.pages.Abstract='de.hybris.platform.acceleratorstorefrontcommons.controllers.pages.AbstractRegisterPageController'; import de.hybris.platform.cms2.exceptions.CMSItemNotFoundException; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.validation.BindingResult; import org.springframework.ui.Model; import javax.validation.Valid;  @Controller("myRegistrationPageController") @RequestMapping(value = "/register") public class MyRegistrationPageController extends AbstractRegisterPageController {      // You might need to override the initBinder or other methods     // to ensure MyRegisterForm is used for binding.      @RequestMapping(method = RequestMethod.POST)     public String doRegister(@Valid final MyRegisterForm form, final BindingResult bindingResult, final Model model)             throws CMSItemNotFoundException {          // If you're extending, call super.doRegister() or copy its logic         // and adapt it to use MyRegisterForm and MyRegisterData.          // Example of adapting the data transfer         final MyRegisterData registerData = new MyRegisterData();         registerData.setFirstName(form.getFirstName());         registerData.setLastName(form.getLastName());         registerData.setEmail(form.getEmail());         registerData.setPassword(form.getPassword());         registerData.setTitleCode(form.getTitleCode());         registerData.setConsentGiven(form.isConsentGiven());         // *** Crucial: Copy your new field from form to data ***         registerData.setPan(form.getPan());          // Now, pass your custom registerData to the customerFacade         // This part usually involves calling a method like register(registerData)         // on the customerFacade.         // If super.doRegister handles this, ensure it's overridden to accept MyRegisterData.          // Example of calling the facade (simplified)         // try {         //     getCustomerFacade().register(registerData);         //     // Handle success         //     return redIRECT_PREFIX + "/register/success";         // } catch (final DuplicateUidException e) {         //     // Handle duplicate email         //     bindingResult.rejectValue("email", "register.email.duplicate");         //     return get  Controller().register(model, form); // Return to form with error         // }          // For a full override, you'd replicate the logic from the original doRegister method,         // replacing RegisterForm with MyRegisterForm and RegisterData with MyRegisterData.         return super.doRegister(form, bindingResult, model); // If super method can be adapted     }      // You might need to override the getRegisterForm() method as well if it's used     // to instantiate the form in GET requests.     @Override     protected MyRegisterForm getRegisterForm() {         return new MyRegisterForm();     } }

注意事项:

  • 你需要确保你的Spring配置(如web-spring.xml)将你的自定义控制器设置为处理/register路径,而不是默认的Hybris控制器。这通常通过Bean定义中的id或name属性来完成。
  • 最重要的是,确保form.getPan()的值被正确地设置到registerData.setPan()中。

2.5 扩展CustomerFacade

CustomerFacade是业务逻辑层面的接口,它将RegisterData转换为CustomerModel并保存。这是将Pan值最终映射到CustomerModel的关键步骤。通常,CustomerFacade会使用一个或多个Populator来完成数据映射。

// e.g., myfacades/src/com/mycompany/facades/customer/impl/MyCustomerFacade.java package com.mycompany.facades.customer.impl;  import com.mycompany.core.data.MyRegisterData; // Your custom RegisterData import de.hybris.platform.commercefacades.customer.impl.DefaultCustomerFacade; import de.hybris.platform.core.model.user.CustomerModel; import de.hybris.platform.servicelayer.model.ModelService; import de.hybris.platform.servicelayer.user.UserService; import org.springframework.beans.factory.annotation.Required;  public class MyCustomerFacade extends DefaultCustomerFacade {      private ModelService modelService;     private UserService userService; // Inject if needed      @Override     public void register(final MyRegisterData registerData) {         final CustomerModel newCustomer = modelService.create(CustomerModel.class);         // Populate common fields (first name, last name, email, password, etc.)         // You might use a populator chain here, or manually map.          // Example: Manually mapping         newCustomer.setUid(registerData.getEmail());         newCustomer.setName(registerData.getFirstName() + " " + registerData.getLastName());         newCustomer.setCustomerID(registerData.getEmail()); // Or generate unique ID         newCustomer.setSessionCurrency(getCommonI18NService().getCurrentCurrency());         newCustomer.setSessionLanguage(getCommonI18NService().getCurrentLanguage());         newCustomer.setLoginDisabled(false);         newCustomer.setEncodedPassword(getUserService().encodePassword(registerData.getPassword(), newCustomer.getSalt()));          // *** Crucial: Set your new field on the CustomerModel ***         newCustomer.setPan(registerData.getPan());          // Save the customer model         modelService.save(newCustomer);          // Optionally, authenticate the newly registered user         // getCustomerFacade().loginSuccess();     }      @Required     public void setModelService(final ModelService modelService) {         this.modelService = modelService;     }      @Required     public void setUserService(final UserService userService) {         this.userService = userService;     } }

最佳实践:使用Populator 在更复杂的场景中,推荐使用Hybris的Populator机制来映射数据。你可以创建一个新的RegisterDataToCustomerPopulator来处理MyRegisterData到CustomerModel的映射。

  1. 定义Populator接口:

    // myfacades/src/com/mycompany/facades/populators/MyRegisterDataToCustomerPopulator.java package com.mycompany.facades.populators;  import com.mycompany.core.data.MyRegisterData; import de.hybris.platform.converters.Populator; import de.hybris.platform.core.model.user.CustomerModel; import de.hybris.platform.servicelayer.dto.converter.ConversionException;  public class MyRegisterDataToCustomerPopulator implements Populator<MyRegisterData, CustomerModel> {      @Override     public void populate(final MyRegisterData source, final CustomerModel target) throws ConversionException {         // Populate common fields if this populator is the primary one         // target.setUid(source.getEmail());         // target.setName(source.getFirstName() + " " + source.getLastName());          // Populate your new field         target.setPan(source.getPan());     } }
  2. 在Spring配置中注册Populator并将其注入到CustomerFacade中:

    <!-- myfacades-spring.xml --> <bean id="myRegisterDataToCustomerPopulator" class="com.mycompany.facades.populators.MyRegisterDataToCustomerPopulator"/>  <bean id="customerRegisterConverter" parent="abstractPopulatingConverter">     <property name="targetClass" value="de.hybris.platform.core.model.user.CustomerModel"/>     <property name="populators">         <list>             <!-- Existing populators -->             <ref bean="registerDataToCustomerPopulator"/>             <!-- Your custom populator -->             <ref bean="myRegisterDataToCustomerPopulator"/>         </list>     </property> </bean>  <bean id="customerFacade" class="com.mycompany.facades.customer.impl.MyCustomerFacade" parent="defaultCustomerFacade">     <property name="registerConverter" ref="customerRegisterConverter"/>     <!-- Inject other dependencies as needed --> </bean>

    注意事项:

    • 确保你的CustomerFacade(MyCustomerFacade)被配置为使用这个包含你自定义Populator的Converter。
    • 如果MyCustomerFacade继承自DefaultCustomerFacade,并且DefaultCustomerFacade已经使用了registerConverter,那么你只需要覆盖其register方法以使用你的MyRegisterData,并确保registerConverter(如果你使用了Populator)被正确配置以包含你的myRegisterDataToCustomerPopulator。

3. 部署与测试

完成上述代码修改后,需要进行以下步骤:

  1. ant all:编译你的Hybris项目。
  2. 启动Hybris服务器:运行hybrisserver.bat或hybrisserver.sh。
  3. 执行系统更新:登录Hybris Administration console (HAC),导航到Platform -> Update,勾选你的扩展,并执行Update running system。这会确保items.xml中的新属性被正确添加到数据库模式中。
  4. 清理缓存:在HAC中执行Clear all caches。
  5. 测试:访问你的注册页面,填写包括Pan在内的所有信息,尝试注册。检查是否成功注册,并通过HAC或数据库工具验证新注册用户的CustomerModel中Pan属性是否已正确存储。

4. 总结

在Hybris中添加自定义属性并确保其数据持久化,需要对整个数据流进行端到端的管理。从items.xml定义属性,到前端表单收集数据,再到RegisterForm、RegisterData、RegistrationPageController和CustomerFacade(或其背后的Populator机制)的层层传递和映射,每一步都至关重要。遵循上述步骤,可以有效解决ModelSavingException并确保自定义属性值的正确存储。

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享