Project Archive

Download Spring Tools Suite

For this course we are going to be using the Spring Tools Suite as our primary development environment. Spring Tool Suite is based on the Eclipse IDE, and is customized to support Spring development.

You can download the Spring Tool Suite from https://spring.io/tools.

Review the basics of Spring Boot

Since we covered the basics of Spring Boot in CMSC 250 I am not going to provide extensive documentation for the example below. If you feel you need a refresher on the basics, here is a link to my CMSC 250 lecture notes on the basics of Spring Boot.

A first simple example application

For our first simple example project I am going to build a simple Spring Boot application that interacts with a single table in our Auction database, the users table. Our first example application will do the bare minimum to insert new users into the users table and then check user names and passwords for existing users.

Start a project

To make a new Spring Boot project, start by selecting New/Spring Starter Project from the File menu.

The first dialog that appears will ask you for basic project settings.

In addition to basic details of the project, including the project name and what language to use, we also specify what build system to use. In this course I will be using Maven as the build system for each of my examples.

The second screen in the project setup dialog will ask you to select dependencies for your project.

Initially, all of the project examples I show in this class will require three dependencies: Spring Web from the Web category and JDBC API and MySQL Driver from the SQL category.

Initial project configuration

Our first step after creating the project is to edit the application.properties file, which stores configuration information for our application. The application.properties file is located in the src/main/resources folder in the project.

We paste the following entries into application.properties:

server.port=8085
spring.datasource.url=jdbc:mysql://localhost:3306/auction
spring.datasource.username=student
spring.datasource.password=Cmsc250!
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.tomcat.max-wait=20000
spring.datasource.tomcat.max-active=50
spring.datasource.tomcat.max-idle=20
spring.datasource.tomcat.min-idle=15

Interacting with the database

The first step in interacting with the users table is to set up a Java class to represent users drawn from the table.

To create this new class we right-click on the edu.lawrence.auction package and select the option to create a new Java class. Name the class User and then paste the following code into the class:

public class User {
    private String key;
    private String name;
    private String password;

    User() {}

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

The next step is to create a RowMapper class to translate ResultSet rows that come back from the database into User objects. Create a new UserRowMapper class and put the following code in it:

import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;

public class UserRowMapper implements RowMapper<User> {
    @Override
    public User mapRow(ResultSet row, int rowNum) throws SQLException {
        User u = new User();
        u.setKey(row.getString("userid"));
        u.setName(row.getString("name"));
        u.setPassword(row.getString("password"));
        return u;
    }
}

Finally, we will need a Repository class that can do the actual interaction with the database. Here is the Repository class for our example application:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

@Repository
public class UserDAO {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    public User findByNameAndPassword(String name,String password) {
      String sql = "SELECT * FROM users WHERE name=? and password=?";
        RowMapper<User> rowMapper = new UserRowMapper();
        User result = null;
        try {
            result = jdbcTemplate.queryForObject(sql, rowMapper, name, password);
        } catch(Exception ex) {
            
        }
        return result;  
    }

    public String save(User user) {
        // Have MySQL generate a unique id
        String idSQL = "select uuid()";
        String key = null;
        try {
            key = jdbcTemplate.queryForObject(idSQL, String.class);
        } catch(Exception ex) {
            key = "Error";
        }
        if(key.equals("Error"))
            return key;

        String insertSQL = "insert into users(userid,name,password) values (?, ?, ?)";
        jdbcTemplate.update(insertSQL,key,user.getName(), user.getPassword());
        return key;
    }
}

I am not going to cover the specifics of this example in great detail, because we have already covered this material in CMSC 250. If you need to refresh your understanding of the JdbcTemplate class you can read sections 5.3.1-5.3.3, 5.4, and 5.5 in the textbook.

A controller class

To implement a REST API we are also going to need a RestController class. Create a new class named UserController and put this code in it:

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/users")
@CrossOrigin(origins = "*")
public class UserController {

    private UserDAO dao;

    public UserController(UserDAO dao) {
        this.dao = dao;
    }

    @GetMapping(params = {"name", "password"})
    public String checkLogin(@RequestParam(value = "name") String user, @RequestParam(value = "password") String password) {
        User result = dao.findByNameAndPassword(user, password);
        if (result == null) {
            return "";
        }
        return result.getKey();
    }

    @PostMapping
    public String save(@RequestBody User user) {
        return dao.save(user);
   }
}

This simple controller will respond to two requests, a GET request with name and password query parameters and a POST request to post new users.

Since we have already covered REST controllers in CMSC 250 I am not going to comment on this example in detail. Section 9.11 in the textbook covers REST controllers in detail: you should read that section to refresh your memory of how controllers work and how the various annotations I used in this example work.