Running your first MVC 1.0 code
If you are following the news about Java EE 8, you may now be wondering: why is MVC 1.0 here if it was dropped from the Java EE 8 umbrella?
Yes, it is true. MVC 1.0 doesn't belong (anymore) to the Java EE 8 release. But it didn't reduce the importance of this great API and I'm sure it will change the way some other APIs work in future releases (for example, JSF).
So why not cover it here? You will use it anyway.
This recipe will show you how to use a Controller (the C) to inject a Model (the M) into the View (the V). It also brings some CDI and JAX-RS to the party.
Getting ready
Add the proper dependencies to your project:
<dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>8.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.mvc</groupId> <artifactId>javax.mvc-api</artifactId> <version>1.0-pr</version> </dependency>
How to do it...
- Start by creating a root for your JAX-RS endpoints:
@ApplicationPath("webresources") public class AppConfig extends Application{ }
- Create a
User
class (this will be your MODEL):
public class User { 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 }
- Now, create a Session Bean, which will be injected later in your Controller:
@Stateless public class UserBean { public User getUser(){ return new User("Elder", "[email protected]"); } }
- Then, create the Controller:
@Controller @Path("userController") public class UserController { @Inject Models models; @Inject UserBean userBean; @GET public String user(){ models.put("user", userBean.getUser()); return "/user.jsp"; } }
- And finally, the web page (the View):
<head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>User MVC</title> </head> <body> <h1>${user.name}/${user.email}</h1> </body>
Run it on a Java EE 8 server and access this URL:
http://localhost:8080/ch01-mvc/webresources/userController
How it works...
The main actor in this whole scenario is the Models
class injected into the Controller:
@Inject Models models;
It's a class from MVC 1.0 API that owns the responsibility, in this recipe, of letting the User
object be available for the View layer. It's injected (using CDI) and uses another injected bean, userBean
, to do it:
models.put("user", userBean.getUser());
So, the View can easily access the values from the User
object using expression language:
<h1>${user.name}/${user.email}</h1>
See also
- You can stay tuned with everything related to MVC specification at https://github.com/mvc-spec
- The source code of this recipe is at https://github.com/eldermoraes/javaee8-cookbook/tree/master/chapter01/ch01-mvc