PROGRAMMING

m9/ JAVA
REMEMBERS




Last update:   25-09-2021

TEMPLATES

Generate a new Spring Boot project (start.spring.io or IDE). As dependencies use Spring Web, Thymealf and Spring Boot DevTools.
 
/**
 * /webcontent/src/main/java/com/example/App.java 
 */

package com.example.webcontent;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

}
... 6 lines
 
The GreetingController handle GET requests for /greeting. It returns the name of the View responsible to render html content.
 
package com.example.webcontent;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class GreetingController {
    
    /**
     * RequestParam binds the value of GET username
     * into the name parameter of greeting() method
     */
    @GetMapping("/greeting")
    public String greeting(
        @RequestParam(name="username", required=false, defaultValue="guest") 
        String str, Model model) {
        
        model.addAttribute("name", str);
        return "greeting";
    }
}
... 13 lines
 
Thymeleaf parses the greeting.html template.
 
# /src/main/resources/templates/greeting.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.trymeleaf.org">
<head>
    <title>MyPage</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
    <p th:text="'Hello, ' + ${name} + '!'"/>
</body>
</html>
... 5 lines
 
! With Spring Boot DevTools you don't need to restart the server.
 
./mvnx spring-boot:run
 
http://localhost:8080/greeting
    #Hello, guest!

http://localhost:8080/greeting?username=John
    #Hello, John!
You can also build a single executable JAR file (contains all dependencies).
 
./mvnw clean package

cd target/
java -jar webcontent-0.0.1-SNAPSHOT.jar
 
# pom.xml
<version>0.0.1-SNAPSHOT</version>

Questions    
Security

        A B C D E F
🔔
1/1