Jakarta EE: Conversion & Validation π
The Magical Translator & Gatekeeper Story
Imagine youβre at a magical post office. People come in speaking different languages and writing letters in strange formats. Before any letter can be delivered, two important helpers work together:
- The Translator (Converter) - Changes words from one language to another
- The Gatekeeper (Validator) - Checks if the letter follows the rules
Thatβs exactly what Faces Converters and Faces Validators do in Jakarta EE!
π What Are Faces Converters?
Think of a converter like a language translator at an airport.
The Problem:
- Humans type text:
"January 15, 2024" - Computers need objects:
LocalDate(2024, 1, 15)
The Solution: Converters translate between human text and computer objects!
graph TD A["User Types Text"] --> B["Converter"] B --> C["Java Object"] C --> B B --> D["Display Text"]
How It Works
When you submit a form:
- String β Object (User input becomes Java object)
- Server processes the object
- Object β String (Java object becomes display text)
π¦ Standard Converters
Jakarta Faces gives you FREE translators for common types. No coding needed!
The Built-In Helpers
| Converter | What It Does | Example |
|---|---|---|
f:convertNumber |
Numbers | 1,234.56 β 1234.56 |
f:convertDateTime |
Dates/Times | Jan 15, 2024 β Date |
f:convertBoolean |
Yes/No | true β Boolean |
Example: Number Converter
<h:inputText value="#{bean.price}">
<f:convertNumber
type="currency"
currencySymbol="quot;/>
</h:inputText>
User types: 1234.50
User sees: $1,234.50
Example: Date Converter
<h:inputText value="#{bean.birthday}">
<f:convertDateTime
pattern="MM/dd/yyyy"/>
</h:inputText>
User types: 01/15/2024
Java gets: LocalDate object!
π οΈ Custom Converters
What if you have a special language nobody speaks?
Build your own translator!
When You Need One
- Converting user IDs to User objects
- Phone numbers with special formats
- Custom codes like product SKUs
Building a Custom Converter
Step 1: Create the class
@FacesConverter("phoneConverter")
public class PhoneConverter
implements Converter<Phone> {
@Override
public Phone getAsObject(
FacesContext ctx,
UIComponent comp,
String value) {
// String β Phone object
return new Phone(value);
}
@Override
public String getAsString(
FacesContext ctx,
UIComponent comp,
Phone phone) {
// Phone object β String
return phone.format();
}
}
Step 2: Use it in your page
<h:inputText value="#{bean.phone}"
converter="phoneConverter"/>
The Magic Ingredients
graph TD A["Implement Converter"] --> B["getAsObject"] A --> C["getAsString"] B --> D["String to Object"] C --> E["Object to String"] A --> F["@FacesConverter"]
β What Are Faces Validators?
If converters are translators, validators are gatekeepers.
The gatekeeper checks:
- Is this letter addressed correctly?
- Does it have a stamp?
- Is the message appropriate?
Validators check if user input follows your rules!
When Validation Happens
graph TD A["User Submits Form"] --> B["Convert Input"] B --> C["Validate Input"] C -->|Pass| D["Process Data"] C -->|Fail| E["Show Error"]
π Standard Validators
Free rule-checkers included with Jakarta Faces!
The Built-In Gatekeepers
| Validator | What It Checks |
|---|---|
f:validateLength |
Text length |
f:validateLongRange |
Number range |
f:validateDoubleRange |
Decimal range |
f:validateRequired |
Not empty |
f:validateRegex |
Pattern match |
Example: Length Check
<h:inputText value="#{bean.username}">
<f:validateLength
minimum="3"
maximum="20"/>
</h:inputText>
Rules: Username must be 3-20 characters!
Example: Number Range
<h:inputText value="#{bean.age}">
<f:validateLongRange
minimum="1"
maximum="120"/>
</h:inputText>
Rules: Age must be between 1 and 120!
Example: Pattern Match
<h:inputText value="#{bean.email}">
<f:validateRegex
pattern="[^@]+@[^@]+\.[^@]+"/>
</h:inputText>
Rules: Must look like an email!
Combining Validators
You can stack multiple gatekeepers:
<h:inputText value="#{bean.code}"
required="true">
<f:validateLength
minimum="5" maximum="10"/>
<f:validateRegex
pattern="[A-Z0-9]+"/>
</h:inputText>
All rules must pass!
π¨ Custom Validators
Sometimes you need special rules nobody thought of.
When You Need One
- Check if username already exists
- Validate credit card numbers
- Business-specific rules
Building a Custom Validator
Step 1: Create the class
@FacesValidator("ageValidator")
public class AgeValidator
implements Validator<Integer> {
@Override
public void validate(
FacesContext ctx,
UIComponent comp,
Integer value)
throws ValidatorException {
if (value < 18) {
throw new ValidatorException(
new FacesMessage(
"Must be 18 or older!"));
}
}
}
Step 2: Use it in your page
<h:inputText value="#{bean.age}">
<f:validator validatorId="ageValidator"/>
</h:inputText>
The Validation Blueprint
graph TD A["Implement Validator"] --> B["validate method"] B --> C{Value OK?} C -->|Yes| D["Continue"] C -->|No| E["Throw ValidatorException"] E --> F["Show Error Message"]
Bean Validation Integration
Even easier! Use annotations:
public class User {
@NotNull
@Size(min=3, max=20)
private String username;
@Min(18)
private Integer age;
@Email
private String email;
}
The annotations validate automatically!
π How They Work Together
Converters and Validators are best friends:
graph TD A["User Input"] --> B["CONVERT"] B --> C["VALIDATE"] C -->|Pass| D["Bean Property"] C -->|Fail| E["Error Message"] B -->|Fail| E
The Complete Flow
- User types
"25"in age field - Converter turns
"25"intoInteger(25) - Validator checks: Is 25 β₯ 18? β
- Value goes to your bean!
Real Example
<h:inputText value="#{user.birthday}">
<!-- Convert string to date -->
<f:convertDateTime
pattern="yyyy-MM-dd"/>
<!-- Check date is in past -->
<f:validator
validatorId="pastDateValidator"/>
</h:inputText>
<h:message for="birthday"/>
π― Quick Summary
| Concept | Job | Think Of It As |
|---|---|---|
| Converter | Translate | Airport Translator |
| Standard Converter | Built-in translate | Free translators |
| Custom Converter | Your own translate | Hire your own |
| Validator | Check rules | Gatekeeper |
| Standard Validator | Built-in checks | Free security |
| Custom Validator | Your own rules | Your own guard |
π‘ Key Takeaways
- Converters change text β objects
- Validators enforce your rules
- Standard ones are free and ready
- Custom ones handle special cases
- They work together in every form!
Remember: Every time a user fills out a form, your translators and gatekeepers spring into action, making sure the right data gets through in the right format!
π Now you understand the magic behind web form processing!
