Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Jakarta EE Cookbook

You're reading from   Jakarta EE Cookbook Practical recipes for enterprise Java developers to deliver large scale applications with Jakarta EE

Arrow left icon
Product type Paperback
Published in May 2020
Publisher Packt
ISBN-13 9781838642884
Length 380 pages
Edition 2nd Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Elder Moraes Elder Moraes
Author Profile Icon Elder Moraes
Elder Moraes
Arrow right icon
View More author details
Toc

Table of Contents (14) Chapters Close

Preface 1. New Features and Improvements 2. Server-Side Development FREE CHAPTER 3. Building Powerful Services with JSON and RESTful Features 4. Web and Client-Server Communication 5. Security of the Enterprise Architecture 6. Reducing Coding Effort by Relying on Standards 7. Deploying and Managing Applications on Major Jakarta EE Servers 8. Building Lightweight Solutions Using Microservices 9. Using Multithreading on Enterprise Context 10. Using Event-Driven Programming to Build Reactive Applications 11. Rising to the Cloud - Jakarta EE, Containers, and Cloud Computing 12. Other Books You May Enjoy Appendix - The Power of Sharing Knowledge

Running your first JSF 2.3 code

Jakarta Server Faces (JSF) is the Java technology made to simplify the process of building UIs.

With JSF, you can build components and use (or reuse) them in the UI in an extensible way. You can also use other powerful APIs, such as Jakarta CDI and Jakarta Bean Validation, to improve your application and its architecture.

In this recipe, we will use the Validator and Converter interfaces with the new feature introduced by version 2.3, which is the possibility of using them with generic parameters.

Getting ready

We need to add the required dependencies:

        <dependency>
<groupId>jakarta.platform</groupId>
<artifactId>jakarta.jakartaee-api</artifactId>
<version>8.0.0</version>
</dependency>

How to do it...

We need to perform the following steps to try this recipe:

  1. Let's create a User class as the main object of our recipe:
public class User implements Serializable {

private String name;
private String email;

public User(String name, String email) {
this.name = name;
this.email = email;
}

//DON'T FORGET THE GETTERS AND SETTERS
//THIS RECIPE WON'T WORK WITHOUT THEM
}
  1. Now, we create a UserBean class to manage our UI:
@Named
@ViewScoped
public class UserBean implements Serializable {

private User user;

public UserBean(){
user = new User("Elder Moraes", "elder@eldermoraes.com");
}

public void userAction(){
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage("Name|Password welformed"));
}

//DON'T FORGET THE GETTERS AND SETTERS
//THIS RECIPE WON'T WORK WITHOUT THEM
}
  1. Now, we implement the Converter interface with a User parameter:
@FacesConverter("userConverter")
public class UserConverter implements Converter<User> {

@Override
public String getAsString(FacesContext fc, UIComponent uic,
User user) {
return user.getName() + "|" + user.getEmail();
}

@Override
public User getAsObject(FacesContext fc, UIComponent uic,
String string) {
return new User(string.substring(0, string.indexOf("|")),
string.substring(string.indexOf("|") + 1));
}

}
  1. Now, we implement the Validator interface with a User parameter:
@FacesValidator("userValidator")
public class UserValidator implements Validator<User> {

@Override
public void validate(FacesContext fc, UIComponent uic,
User user)
throws ValidatorException {
if(!user.getEmail().contains("@")){
throw new ValidatorException(new FacesMessage(null,
"Malformed e-mail"));
}
}
}
  1. And then, we create our UI using all of them:
<h:body>
<h:form>
<h:panelGrid columns="3">
<h:outputLabel value="Name|E-mail:"
for="userNameEmail"/>
<h:inputText id="userNameEmail"
value="#{userBean.user}"
converter="userConverter" validator="userValidator"/>
<h:message for="userNameEmail"/>
</h:panelGrid>
<h:commandButton value="Validate"
action="#{userBean.userAction()}"/>
</h:form>
</h:body>

Don't forget to run it in a Jakarta EE 8 server.

How it works...

From the code in the preceding section, we see that the UserBean class manages the communication between the UI and the server. Once you instantiate the user object, it is available for both of them.

That's why, when you run it, Name | E-mail is already filled (the user object is instantiated when the UserBean class is created by the server).

We associated the userAction() method from the UserBean class with the Validate button of the UI:

<h:commandButton value="Validate" action="#{userBean.userAction()}"/>

You can create other methods in UserBean and do the same to empower your application.

The whole core of our recipe is represented by just a single line in the UI:

<h:inputText id="userNameEmail" value="#{userBean.user}" converter="userConverter" validator="userValidator"/>

So, our two implemented interfaces used here are userConverter and userValidator.

Basically, the UserConverter class (with the getAsString and getAsObject methods) converts an object into/from a string and vice versa, according to the logic defined by you.

We have just mentioned it in the preceding code snippet:

value="#{userBean.user}"

The server uses the userConverter object, calls the getAsString method, and prints the result using the preceding expression language.

Finally, the UserValidator class is automatically called when you submit the form, by calling its validate method, and applying the rules defined by you.

There's more...

You could increase the validators by adding a Jakarta Bean Validation on it and, for example, defining the email property from User with an @Email constraint.

See also

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image