Home



2018/07 - Java Spring in Springy... Summer?

Hi folks,

It's a wonderful last-day-of-June day out as of this writing, so I decided to make a tutorial covering how to develop a simple Spring app that lets you perform CRUD functions for a list of people!

You'll need to have Java 8 installed first for this version of Spring to work. This is my current repo for this project if you get stuck. First, download version 3.9.4 of the Spring Toolsuite at this link. Rename the download to something shorter (I had problems with filenames bring too ong when unzipping) and extract it to your C drive, then run STS.exe. If you get completely lost at this point, this official Spring guide to making a Hello World app might help you out with your installation.

Next, you'll need to click on "Create Spring Starter Project", then download the demo app. Once it's downloaded you should be able to run it. If not just add the following dependency to the pom.xml file tab of your pom.xml file (Courtesy of StackOverflow):

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

 

Once the demo app is running (And not immediately shutting down on you), go to http:localhost:8080/ and you should see a default error page similar to the following:

 

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Sun Jul 01 20:24:21 BST 2018

There was an unexpected error (type=Not Found, status=404).

No message available

 

Great! Your first app is running! In order to get a good idea of what we just did, shut down your application and create the following files in src/main/java under the com.example.demo package:

 

Person class

package com.example.demo;

public class Person {
    
    private String name;
    
    public Person() {
        
    }
    
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
    public String toString() {
        return "Name: " + this.name;
    }

}
 

 

MainController class

package com.example.demo;

import java.util.ArrayList;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class MainController {
    
  public static ArrayList<Person> listOfPeople;
  public static String newLine = "<br/>";

  @RequestMapping("/HelloWorld")
  @ResponseBody
  public String index() {
    return "Hello World!!!";
  }
  
  @RequestMapping("/menu")
  @ResponseBody
  public String menu() {
      if(listOfPeople == null) {
          listOfPeople = new ArrayList<Person>();
      }
      
      StringBuilder sb = new StringBuilder("In order to use this application, simply enter one of the following URLs into your browser to perform the corresponding action:" + newLine + newLine +
                "To visit this menu, enter: http://localhost:8080/menu" + newLine + 
                "To add a new person, enter: http://localhost:8080/addPersonNamed/Marc2" + newLine  + 
                "To update a persons name, enter their index and updated name: http://localhost:8080/updatePersonIndex/0/MarcoPolo" + newLine + 
                "To remove a person from the list, enter their index with this link: http://localhost:8080/removePersonIndex/0/" + newLine);
      
      sb.append(newLine + "List of people: " + newLine);
      
      int indexOf = 0;
      for (Person person : listOfPeople) {
          sb.append("Index: " + indexOf + ", Details: " +person.toString() + "" + newLine);
          indexOf++;
      }
    
      return sb.toString();
  }
  
  
  @RequestMapping("/addPersonNamed/{name}")
  @ResponseBody
  public void addPerson(@PathVariable String name) {
      if(listOfPeople == null) {
          listOfPeople = new ArrayList<Person>();
      }
      
    Person newPerson = new Person();
    newPerson.setName(name);
    listOfPeople.add(newPerson);
  }
  
  @RequestMapping("/removePersonIndex/{index}")
  @ResponseBody
  public void removePerson(@PathVariable int index) {
      if(listOfPeople != null && listOfPeople.get(index) != null) {
          listOfPeople.remove(index);
      }
      else {
          return;
      }
  }
  
  
  @RequestMapping("/updatePersonIndex/{index}/{name}")
  @ResponseBody
  public void updatePerson(@PathVariable int index, @PathVariable String name) {
      if(listOfPeople != null && listOfPeople.get(index) != null) {
          listOfPeople.get(index).setName(name);
      }
      else {
          return;
      }
  }

}

 

Restart your server and go to http://localhost:8080/menu to see what we just created. You should find instructions on how to use the endpoints we just created, specifically how to run CRUD operations on the list of people that we also added. We basically created what is called a "resource representation class" when we created the Person class, then a controller for that class with MainController. You also might have noticed the annotations over the MainController methods. They're largely self-explanatory for this example, but if you'd like to know explcitly what they do, this is a pretty good list/description for all of them.

That pretty much concludes this very basic introduction to Spring. I'll be doing many more tutorials like this one soon, as I've recently wanted to learn more about Java Enterprise and Spring in general. If you have any questions or comments, you know where my email is!

Good luck and have a great summer!