1. Overview

In this article, we’ll have a look at VRaptor, a simple and straightforward Java MVC web framework which utilizes Java Contexts and Dependency Injection technology and is easy to grasp.

Just like Spring – it relies heavily on annotations and works great with Hibernate.

It also comes with some useful plugins – such as for internalization and unit testing.

So, let’s explore the different components of VRaptor and create a sample project.

2. Maven Dependencies and Setup

One quick way to get up and running is to download the vraptor-blank-project-distribution from the official repository.

The blank project is just a skeleton that can be fleshed out to become a full-fledged web application of choice.

After downloading and unzipping the project, let’s rename the directory to vraptor (or any other name).

The directory should contain:

  • src/
  • pom.xml
  • and README.md

The project is Maven-based and comes with tomcat7 Maven plugin which provides the servlet container for running the application.

It also comes with a default IndexController that has just one method – index().

By default, the view to be rendered by this method is located in webapp/WEB-INF/jsp/index/index.jsp – this follows the convention *WEB-INF/jsp/*controller_name/method_name.

To start the server, we’ll execute the command mvn tomcat7:run from the root of the project.

If successful, if we visit http://localhost:8080, a browser will display “*It works!! VRaptor!*“.

If we face the “java.lang.LinkageError: loader constraint violation”, then, we have to modify the following dependencies in pom.xml:

<dependency>
    <groupId>org.jboss.weld.servlet</groupId>
    <artifactId>weld-servlet-core</artifactId>
    <version>2.1.2.Final</version>
    <exclusions>
        <exclusion>
        <groupId>org.jboss.spec.javax.el</groupId>
        <artifactId>jboss-el-api_3.0_spec</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.jboss.weld</groupId>
    <artifactId>weld-core-impl</artifactId>
    <version>2.1.2.Final</version>
    <exclusions>
       <exclusion>
          <groupId>org.jboss.spec.javax.el</groupId>
        <artifactId>jboss-el-api_3.0_spec</artifactId>
       </exclusion>
    </exclusions>
</dependency>

The culprit is the el-api that is included in weld-servlet-core and weld-core-impl with compile scope; this leads to a dependency clash.

The following dependencies will be needed along the line, so let’s include them in pom.xml:

<dependency>
    <groupId>br.com.caelum.vraptor</groupId>
    <artifactId>vraptor-freemarker</artifactId>
    <version>4.1.0-RC3</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.8-dmr</version>
</dependency>

<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.27-incubating</version>
</dependency>

The latest version of vraptor-freemarker, mysql-connector-java, and freemarker artifacts can be found in Maven Central.

Now that we’re good to go, let’s build a simple blog site.

3. Hibernate Support

VRaptor provides various plugins for interacting with databases, one of them is vraptor-hibernate which works with Hibernate 4.

The plugin makes the Hibernate’s SessionFactory bean available at runtime via CDI.

With the plugin in place, we need a standard Hibernate configuration file – an example can be found in the repository.

VRaptor uses a technique called Producers to make objects available for DI management. More details about this here.

4. Defining Web Routes in VRaptor

In VRaptor, route definitions reside in controllers which are simply @Controller-annotated Java objects – just like in Spring.

@Path annotation is used for mapping a request path to a particular controller and @Get, @Post, @Put, @Delete and @Patch annotations are used for specifying HTTP request types.

Route mapping configuration looks similar to JAX-RS’ way but doesn’t implement the standard officially.

Additionally, when defining a path, it’s possible to specify a path variable in curly braces:

@Get("/posts/{id}")

The value of id can then be accessed inside a controller method:

@Get("/posts/{id}")
public void view(int id) {
    // ...
}

When a form is submitted to a particular route, VRaptor can automatically populate an object with the form-data submitted.

Let’s see this in action in the next section of the article.

5. Views and Template Engine

By default, views can be implemented using JSP. However, other template engines can be used as well – in this article, we’ll work with Freemarker.

Let’s start by creating index.ftl and saving it in the default view directory (src/main/resources/templates):

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>VRaptor Blank Project</title>
</head>
<body>
It works!! ${variable}
</body>
</html>

Now, we can use the defined view with a FreemarkerView class for view rendering:

@Path("/")
public void index() {
    result.include("variable", "VRaptor!");
    result.use(FreemarkerView.class).withTemplate("index");
}

The Result object holds model state – it has methods for redirecting to another page, URL, or a controller method; it can be injected into the controller using CDI.

In our example, the variable gets resolved by Freemarker. Thus ${variable} placeholder in index.ftl gets replaced with the “VRaptor!”.

More advanced usages are documented here.

6. Form Submission Handling Example

Let’s see how can we handle form submissions with validation:

@Post("/post/add")
public void add(Post post) {
    post.setAuthor(userInfo.getUser());
    validator.validate(post);
    if(validator.hasErrors()) {
        result.include("errors", validator.getErrors());
    }
    validator.onErrorRedirectTo(this).addForm();
  
    Object id = postDao.add(post);
  
    if(Objects.nonNull(id)) {
       result.include("status", "Post Added Successfully");
         result.redirectTo(IndexController.class).index();
    } else {
        result.include(
          "error", "There was an error creating the post. Try Again");
        result.redirectTo(this).addForm();
    }
}

The Post object gets validated first using Java bean validation before being persisted into the database using postDao.add().

The fields of the Post object are populated automatically from values of the submitted form-data – which correspond to the form’s input fields in the view file.

Note that the name of the input field has to be prefixed with the name of the object in lowercase.

For example, the view that’s responsible for adding a new post has input fields: post.title and post.post which correspond to fields title and post in Post.java respectively:

<input type="text" class="form-control" placeholder="Title" 
  id="title" name="post.title" required />

<textarea rows="10" class="form-control" placeholder="Post" 
  id="post" name="post.post" required></textarea>

The complete add.ftl file can be found in the source code.

If there is an error in the form submission, the error message gets included and user redirected to the same add() method:

if(validator.hasErrors()) {
    result.include("errors", validator.getErrors());
}
validator.onErrorRedirectTo(this).addForm();

7. Conclusion

In conclusion, we’ve looked at VRaptor at a glance and saw how basic MVC functionality can be achieved.

The documentation contains more detail about the framework as well as available plugins.

The complete source code, including a sample database.sql, is available over on Github.


« 上一篇: 针对Java的Docker指南
» 下一篇: Vavr中的Future简介