简体   繁体   中英

JavaEE application create a unique key using java.util.UUID

I want to make a javaEE application when users can register and confirm their email when receiving a email with a link after inserting their data in registration form (name, mail...)

To do that I am going to generate a long and unique key with java.util.UUID, store in a database and then send an email to the user with that key being part of the URL (Example: www.mysite.com/account.xhtml?id=KEY). Then the user will click the link, I extract the key from the URL and check if that key is stored in the DB. If it is, the user registration will be completed.

My question is, when creating that key with java.util.UUID, how can I know that it is a unique key? Should I check if there is another equal key in the DB and if so create a new one until the created key is unique?

What's the chance that a randomly-generated 128-bit integer will be equal to another randomly-generated integer?

If you just need peace of mind, use a primary key and if the insert fails due to a key collision, re-create a new UUID and retry the insert.

There are couple of ways you can do UUID in Java.

Java 5 onwards better practice is using java.util.UUID It is size of the string 36 characters. This link gives you simple example .

This discussion will give you answer to your question . It is very strong. I have never came across someone is complaining about its uniqueness.

But if you adding into DB or using in storage or using through network, size may be matters. So converting to other formats - Bases is good solution (Base64, Base85 etc). Please check this discussion here . You can use apache library org.apache.commons.codec.binary.Base64 . Base85 is not safe for URLs.

My recommendation is, if you have may application/session beans/web services (many interconnections other applications and data transfers etc) are creating UUIDs, I prefer to do unique application name padding too. Like APP1, APP2 etc and then decode to other bases. If UUID is 6fcb514b-b878-4c9d-95b7-8dc3a7ce6fd8, then APP1-6fcb514b-b878-4c9d-95b7-8dc3a7ce6fd8 like that...

Though it is off the topic here, BUT When you use a URL like this www.mysite.com/account.xhtml?id=KEY , beware about SQL injection hacking attacks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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