The user can register an account to carry on the goods
purchase operation.
Create User Table in the Database
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
-- Create a table called user, it contains the following fields:
CREATETABLEuser(`id`BIGINT(20)UNSIGNEDNOTNULLAUTO_INCREMENT,`created_at`INT(11)NOTNULL,`updated_at`INT(11)NOTNULL,`last_logged_on`INT(11)NOTNULL,`first_name`VARCHAR(50)NOTNULL,`last_name`VARCHAR(50)NOTNULL,`phone`VARCHAR(50)NOTNULLDEFAULT'',`email`VARCHAR(90)NOTNULLDEFAULT'',`password`VARCHAR(60)NOTNULL,-- BCrypt Encryption
`type`TINYINT(1)NOTNULLDEFAULT1,-- 1: Consumer, 2: Merchant
`is_enabled`TINYINT(1)NOTNULLDEFAULT0,`avatar`VARCHAR(512)NOTNULLDEFAULT'',`introduction`VARCHAR(512)NOTNULLDEFAULT'',`reference_id`BIGINTNOTNULLDEFAULT0,PRIMARYKEY(`id`),UNIQUEKEY`index_email`(`email`));
Add Dependencies
Add Dependencies into Common Module
Copy and paste the following content into the pom.xml file
under the common directory:
packageco.dongchen.shop.common.util;importco.dongchen.shop.common.model.User;importco.dongchen.shop.common.result.ResultMsg;importorg.apache.commons.lang3.StringUtils;publicclassUserHelper{publicstaticResultMsgvalidate(Useruser){// If the password is empty
if(StringUtils.isBlank(user.getEmail())){returnResultMsg.errorMsg("Email is needed");}elseif(// If the password is empty
StringUtils.isBlank(user.getPassword())||// If the confirmed password
StringUtils.isBlank(user.getConfirmedPassword())||// If the password and the confirmed password is not matched
!user.getPassword().equals(user.getConfirmedPassword())){returnResultMsg.errorMsg("Password and confirmed password is not matched");// If the password is less than 6 characters
}elseif(user.getPassword().length()<6){returnResultMsg.errorMsg("Password must consist of 6 or more characters");}// If the validation is succeeded then return an empty string instead
returnResultMsg.successMsg("");}}
packageco.dongchen.shop.common.util;importorg.apache.commons.beanutils.BeanUtils;importorg.apache.commons.beanutils.PropertyUtils;importjava.beans.PropertyDescriptor;importjava.lang.reflect.InvocationTargetException;importjava.time.Instant;publicclassBeanHelper{privatestaticfinalStringcreatedAtKey="createdAt";privatestaticfinalStringlastLoggedOnKey="lastLoggedOn";privatestaticfinalStringupdatedAtKey="updatedAt";publicstatic<T>voidsetDefaultProp(Ttarget,Class<T>clazz){PropertyDescriptor[]descriptors=PropertyUtils.getPropertyDescriptors(clazz);for(PropertyDescriptorpropertyDescriptor:descriptors){StringfieldName=propertyDescriptor.getName();Objectvalue;try{value=PropertyUtils.getProperty(target,fieldName);}catch(IllegalAccessException|InvocationTargetException|NoSuchMethodExceptione){thrownewRuntimeException("can not set property when get for "+target+" and clazz "+clazz+" field "+fieldName);}if(String.class.isAssignableFrom(propertyDescriptor.getPropertyType())&&value==null){try{PropertyUtils.setProperty(target,fieldName,"");}catch(IllegalAccessException|InvocationTargetException|NoSuchMethodExceptione){thrownewRuntimeException("can not set property when set for "+target+" and clazz "+clazz+" field "+fieldName);}}elseif(Number.class.isAssignableFrom(propertyDescriptor.getPropertyType())&&value==null){try{BeanUtils.setProperty(target,fieldName,"0");}catch(Exceptione){thrownewRuntimeException("can not set property when set for "+target+" and clazz "+clazz+" field "+fieldName);}}}}publicstatic<T>voidonUpdate(Ttarget){try{PropertyUtils.setProperty(target,updatedAtKey,Math.toIntExact(Instant.now().getEpochSecond()));}catch(IllegalAccessException|InvocationTargetException|NoSuchMethodExceptione){}}publicstatic<T>voidonInsert(Ttarget){longtimestampLong=Instant.now().getEpochSecond();inttimestamp=Math.toIntExact(timestampLong);try{PropertyUtils.setProperty(target,createdAtKey,timestamp);PropertyUtils.setProperty(target,lastLoggedOnKey,timestamp);PropertyUtils.setProperty(target,updatedAtKey,timestamp);}catch(IllegalAccessException|InvocationTargetException|NoSuchMethodExceptione){}}}
Create User Mapper
User Mapper Class
Right click service/src/main/java/co.dongchen.shop/mapper
directory: New > Java Class
Fill in “UserMapper”
Change Kind to: Interface
Click “OK” button
Copy and paste the following content into UserService.java:
packageco.dongchen.shop.service;importco.dongchen.shop.common.model.User;importco.dongchen.shop.mapper.UserMapper;importcom.google.common.base.Objects;importcom.google.common.cache.Cache;importcom.google.common.cache.CacheBuilder;importcom.google.common.cache.RemovalListener;importcom.google.common.cache.RemovalNotification;importorg.apache.commons.lang3.RandomStringUtils;importorg.apache.commons.lang3.StringUtils;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.mail.SimpleMailMessage;importorg.springframework.mail.javamail.JavaMailSender;importorg.springframework.scheduling.annotation.Async;importorg.springframework.stereotype.Service;importjava.util.List;importjava.util.concurrent.TimeUnit;@ServicepublicclassMailService{privatefinalCache<String,String>emailCache=CacheBuilder.newBuilder().maximumSize(100).expireAfterAccess(15,TimeUnit.MINUTES).removalListener(newRemovalListener<String,String>(){@OverridepublicvoidonRemoval(RemovalNotification<String,String>removalNotification){Stringemail=removalNotification.getValue();Useruser=newUser();user.setEmail(email);List<User>targetUser=userMapper.queryUsersByCondition(user);// Only removes the inactivated users.
if(!targetUser.isEmpty()&&Objects.equal(targetUser.get(0).getIsEnabled(),0)){userMapper.delete(email);}}}).build();@Value("${domain.name}")privateStringdomainName;@AutowiredprivateUserMapperuserMapper;@AutowiredprivateJavaMailSendersender;publicvoidsendMail(Stringtitle,Stringbody,Stringemail){SimpleMailMessagemessage=newSimpleMailMessage();message.setSubject(title);message.setTo(email);message.setText(body);sender.send(message);}@AsyncpublicvoidregisterNotification(Stringemail){StringrandomKey=RandomStringUtils.randomAlphabetic(10);emailCache.put(randomKey,email);Stringurl=domainName+"/user/activate?key="+randomKey;sendMail("Welcome to our shop, just one more step...",url,email);}publicbooleanenable(Stringkey){Stringemail=emailCache.getIfPresent(key);if(StringUtils.isBlank(email)){returnfalse;}UserupdateUser=newUser();updateUser.setEmail(email);updateUser.setIsEnabled(1);userMapper.update(updateUser);emailCache.invalidate(key);returntrue;}}
Create User Service
Right click service/src/main/java/co.dongchen.shop/service
directory: New > Java Class
Fill in “UserService”
Click “OK” button
Copy and paste the following content into UserService.java:
packageco.dongchen.shop.controller;importco.dongchen.shop.common.model.User;importco.dongchen.shop.common.result.ResultMsg;importco.dongchen.shop.common.util.UserHelper;importco.dongchen.shop.service.UserService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Controller;importorg.springframework.ui.ModelMap;importorg.springframework.web.bind.annotation.RequestMapping;@ControllerpublicclassUserController{@AutowiredprivateUserServiceuserService;@RequestMapping("user/register")publicStringregister(Useruser,ModelMapmodelMap){if(user==null||user.getFirstName()==null||user.getLastName()==null){return"/user/register";}ResultMsgresultMsg=UserHelper.validate(user);if(resultMsg.isSuccess()&&userService.register(user)){modelMap.put("email",user.getEmail());return"/user/registration_succeeded";}else{return"redirect:/user/register?"+resultMsg.asUrlParams();}}@RequestMapping("user/activate")publicStringactivate(Stringkey){booleanresult=userService.enable(key);if(result){return"redirect:/home?"+ResultMsg.successMsg("Activation Completed!").asUrlParams();}else{return"redirect:/user/register?"+ResultMsg.errorMsg("Activation Failed, please make sure to activate the email in 15 minutes").asUrlParams();}}}
Create Template
Right click controller/src/main/resources/template
directory: New > Directory
Fill in “user”
Click “OK” button
Right click user directory: New > File
Fill in “register.ftl”
Click “OK” button
Copy and paste the following content into register.ftl:
Copy and paste the following content into
registration_succeeded.ftl:
1
2
3
4
5
6
7
8
<htmllang="en-NZ"><@common.header/>
<body><h1>Registration Succeeded!</h1><p>We have sent an confirmation email and the activation linkage to your inbox (${email}), this link will be expired in 15 minutes, please have a check. Thanks!</p></body><@common.footer/>
</html>
Verify
Run the App
1
2
// Short Cut for "Run the Program"
Alt + Shift + F10
Choose the correspondent option and press enter.
View Register Page in the Browser
1
http://localhost:8080/user/register
Fill in the Information and click register:
We will see a registered succeeded page:
We can see an inactivate user in the database:
We need to click the activation link in 15 minutes:
We will see the following page and url after we clicked the
link:
Check the database again
Now that the user has been activated, our job is done for now.