Subscribe / Unsubscribe Enewsletters | Login | Register

Pencil Banner

Jump into Java microframeworks, Part 3: Spark

Matthew Tyson | Jan. 8, 2016
An extra lightweight, flexible, and scalable architecture for single-page web apps.

Now we can reference the new controller and DAO layers in App.java, the main class for our Spark application:

Listing 5. App.java



import org.mtyson.dao.DAO;

import org.mtyson.dao.JdbcDAO;

import org.mtyson.service.Controller;

public class App {

	private final static DAO dao = new JdbcDAO();

	private final static Controller controller = new Controller(dao);

    public static void main( String[] args ){

    	//...

        Spark.post("/person", (req, res) -> { return controller.addPerson(req.body()); } ); // 1

    }

}



Notice the line in Listing 5 that is commented with the number 1. You'll recall from Part 1 that this line is how we handle a route in Spark. In the route-handler lambda, we just access the App.controller member (given that lambdas have full access to the enclosing class context), then call the addPerson() method. We pass in the request body via req.body(). A JSON request body will be expected in our request, and that body should contain the fields for the new Person entity.

If we now hit the POST /person URL (using Postman, which I introduced in Part 2) we'll get a message back indicating success. Postman shows us what a response message would look like, but it's empty of real content. For that we need to populate our database.

Populating the database

We'll use JdbcDAO to add a row or two to our database. To set this up, we first need to add some items to pom.xml, the application's Maven dependency file. The updated POM in Listing 6 includes a MySQL JDBC implementation, Apache DBUtils, and a simple wrapper library so that we don't have to manage the JDBC ourselves. I've also included Boon, a JSON project that is reputed to be the fastest way to process JSON in Java. If you're familiar with Jackson or GSON, Boon does the same thing with a similar syntax. We'll put Boon to use shortly. The POM updates are shown in Listing 6.

Listing 6. Add MySQL, DBUtils, and Boon to Maven POM



<dependency>

			<groupId>mysql</groupId>

			<artifactId>mysql-connector-java</artifactId>

			<version>5.1.37</version>

		</dependency>

		<dependency>

			<groupId>commons-dbutils</groupId>

			<artifactId>commons-dbutils</artifactId>

			<version>1.6</version>

		</dependency>

		<dependency>

			<groupId>io.fastjson</groupId>

			<artifactId>boon</artifactId>

			<version>0.33</version>

		</dependency>



Now, change JdbcDAO to look like Listing 7. The addPerson() will take the first_name and last_name values from the map argument and use them to insert a Person into the database.

Listing 7. Add a Person to the database



package org.mtyson.dao;

import java.sql.SQLException;

import java.util.ArrayList;

import java.util.List;

import java.util.Map;

import java.util.stream.Collectors;

import org.apache.commons.dbutils.QueryRunner;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

public class JdbcDAO implements DAO {

	private static MysqlDataSource dataSource;

    static {

        try {

        	dataSource = new MysqlDataSource();

        	dataSource.setUser("root");

        	dataSource.setPassword("password");

        	dataSource.setServerName("localhost");

        	dataSource.setDatabaseName("spark_app");

        } catch (Exception e) {

            throw new ExceptionInInitializerError(e);

        }

    }

    public boolean addPerson(Map<String, Object> data) {

    	QueryRunner run = new QueryRunner( dataSource );

		try	{

		    int inserts = run.update( "INSERT INTO Person (first_name, last_name) VALUES (?,?)", data.get("first_name"), data.get("last_name"));

		} catch(SQLException sqle) {

		    throw new RuntimeException("Problem updating", sqle);

		}

		return true;    	

    }

}



 

Previous Page  1  2  3  4  5  6  7  8  Next Page 

Sign up for CIO Asia eNewsletters.