Intro to Spring Boot: Controllers

Notes

Spring Boot is a framework used to build Java web applications that implement the MVC pattern. For more about Spring, check out Spring IO. Some of the benefits of Spring Boot are:

  • Web development is simplified even more in Spring Boot than in Spring
  • It provides Tomcat as an embedded web server
  • A lot of settings are preconfigured for us so there's no need for additional XML configuration

Create a Simple Spring Boot Project

  • Go to start.spring.io
  • Select Gradle Project, Java, and 1.5.x (that is, the most recent 1.5 non-SNAPSHOT release) from the dropdown for "Generate a ___ with ___ and Spring Boot ___"
  • Put the title for your project, hello-spring, in the section marked Artifact
  • Search for and add the following dependencies: Web, Thymeleaf, DevTools then click "Generate"
  • Move the downloaded unzipped folder from downloads into another location such as LC101 or your home directory
  • Start IntelliJ
  • Select Import Project and browse to where you put the downloaded file
  • Select "Create project from existing sources"
  • Accept all defaults as you create the project
  • If you see an Unlinked Gradle Project popup, go ahead and click "Import Gradle Project", then check the "Use auto-import" box and leave everything else as it is.
  • To run the application, click on the Gradle icon on the side, then go into Tasks->application and double-click bootRun
  • You can then visit the corresponding web page at localhost:8080 (Right now, you'll see an error page, but we'll fix that below.) Now go ahead and stop the application.

Create a Controller for your Spring Boot Project

  • First, add the necessary classes to your src->main->java->org.yourorgname->HelloSpringApplication: SpringBootApplication and SpringApplication.
  • Next, go to src->main->java and right click on your org.yourorgname package and then select New->Package and name your new package controllers.
  • Add a New->Java Class to the package controllers and name it HelloController.
  • Above the class definition for HelloController add the annotation @Controller and add the corresponding class to your project.
  • Add this code to the body of your HelloController class:
    @RequestMapping(value="")
    @ResponseBody
    public String index(){
        return "Hello World";
    }
  • Use Gradle to bootRun again and visit localhost:8080. You should see "Hello World"
  • Now add another controller at another path by adding this code below the code posted above:
    @RequestMapping(value="goodbye")
    @ResponseBody
    public String goodbye(){
        return "Goodbye";
    }
  • Run the application again and visit localhost:8080/goodbye and you should see "Goodbye".

Congratulations! You just ran your first Spring Boot program in IntelliJ!