Create WordPress Theme x Bootstrap 5

WordPress adalah sistem manajemen konten (CMS) open-source yang digunakan untuk membuat dan mengelola situs web dan blog. WordPress populer karena mudah digunakan, bahkan oleh pemula, dan tidak memerlukan pengetahuan dasar pemrograman.

Bootstrap adalah kerangka kerja front-end yang digunakan untuk membuat situs web dan aplikasi web.

Persiapan

Setup environment

  1. Download WordPress dan install wordpress di lokal https://wordpress.org/download/
  2. Download local server XAMPP , sesuaikan dengan System Operasi yang kita gunakan.
  3. Copy folder wordpress yang telah di download ke dalam folder xampp/htdocs.

Membuat file-file utama yang dibutuhkan untuk tema yang akan kita buat

  1. Masuk ke dalam folder wordpress/wp-content/themes
  2. Buat folder baru untuk temet yang akan kita buat , contoh bootstrap-tutorial-theme
  3. Buat file berikut pada folder yang telah kita buat
1. style.css (for theme metadata)
2. index.php (main template file)
3. functions.php (for theme functionality)
4. header.php (header template)
5. footer.php (footer template)
6. single.php (single post template)
7. page.php (page template)
8. front-page.php (landing page template)
9. archive.php (archive page template)
10. 404.php (404 error page)
11. screenshot.png (theme thumbnail)

Tambahkan Metadata pada file styles.css

Ini digunakan sebagai identitas pembuat tema

/*
Theme Name: Bootstrap Tutorial Theme
Theme URI: https://example.com/bootstrap-tutorial-theme
Author: Your Name
Author URI: https://example.com
Description: A modern WordPress theme built with Bootstrap 5 for a tutorial website.
Version: 1.0
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Text Domain: bootstrap-tutorial-theme
*/

Enqueue Bootstrap 5

  1. Download Bootstrap versi compailled CSS dan JS getbootstrap.com.
  2. Extract file hasil download lalu pindahkan / copy file bootstrap.min.css dan bootstrap.bundle.min.js kedalam folder (contoh, assets/css and assets/js).
  3. Pada file functions.php, enqueue Bootstrap CSS and JS:
function bootstrap_tutorial_theme_enqueue_styles() {
    // Enqueue Bootstrap CSS
    wp_enqueue_style('bootstrap-css', get_template_directory_uri() . '/assets/css/bootstrap.min.css');
    // Enqueue custom styles
    wp_enqueue_style('custom-style', get_stylesheet_uri());
}
add_action('wp_enqueue_scripts', 'bootstrap_tutorial_theme_enqueue_styles');

function bootstrap_tutorial_theme_enqueue_scripts() {
    // Enqueue Bootstrap JS
    wp_enqueue_script('bootstrap-js', get_template_directory_uri() . '/assets/js/bootstrap.bundle.min.js', array('jquery'), null, true);
}
add_action('wp_enqueue_scripts', 'bootstrap_tutorial_theme_enqueue_scripts');

1. Buat Halaman Header

Buat file header.php dan tambahkan code berikut:

<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
    <meta charset="<?php bloginfo('charset'); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
    <header class="bg-primary text-white py-3">
        <div class="container">
            <div class="d-flex justify-content-between align-items-center">
                <h1 class="h4 mb-0"><?php bloginfo('name'); ?></h1>
                <?php
                wp_nav_menu(array(
                    'theme_location' => 'primary',
                    'menu_class'     => 'navbar-nav d-flex flex-row',
                    'container'      => false,
                ));
                ?>
            </div>
        </div>
    </header>

2. Buat Halaman Footer

Buat file footer.php dan tambahkan code berikut:

<footer class="bg-dark text-white py-4">
    <div class="container">
        <p class="mb-0 text-center">&copy; <?php echo date('Y'); ?> <?php bloginfo('name'); ?></p>
    </div>
</footer>
<?php wp_footer(); ?>
</body>
</html>

Register menu dalam file functions.php

function bootstrap_tutorial_theme_register_menus() {
    register_nav_menus(array(
        'primary' => __('Primary Menu', 'bootstrap-tutorial-theme'),
    ));
}
add_action('init', 'bootstrap_tutorial_theme_register_menus');

Buat Primary Menu pada wordpress kita.

3. Buat Halaman Landing Page

Buat landing halaman front-page.php

Jika kita ingin membuat halaman utama wordpress kita adalah landing page.

<?php get_header(); ?>

<main class="py-5">
    <div class="container">
        <div class="row">
            <div class="col-md-8">
                <h1 class="display-4">Welcome to Our Tutorial Website</h1>
                <p class="lead">Learn the latest technologies with our step-by-step tutorials.</p>
                <a href="<?php echo get_permalink(get_option('page_for_posts')); ?>" class="btn btn-primary btn-lg">Explore Tutorials</a>
            </div>
        </div>
    </div>
</main>

<?php get_footer(); ?>

4. Buat Page Index

Page ini digunakan untuk menampilkan semua Post yang telah kita buat index.php

<?php
/**
 * The main template file.
 *
 * This is the most generic template file in a WordPress theme
 * and one of the two required files for a theme (the other being style.css).
 * It is used to display a page when nothing more specific matches a query.
 */
get_header(); // Include the header
?>

<main class="container py-5">
    <div class="row">
        <div class="col-md-8">
            <?php
            if (have_posts()) :
                while (have_posts()) : the_post();
                    // Display post content
                    get_template_part('template-parts/content', get_post_type());
                endwhile;

                // Pagination
                the_posts_pagination(array(
                    'prev_text' => __('Previous', 'bootstrap-tutorial-theme'),
                    'next_text' => __('Next', 'bootstrap-tutorial-theme'),
                ));
            else :
                // If no posts are found
                get_template_part('template-parts/content', 'none');
            endif;
            ?>
        </div>
        <div class="col-md-4">
            <?php get_sidebar(); // Include the sidebar ?>
        </div>
    </div>
</main>

<?php
get_footer(); // Include the footer
?>

5. Buat Post Page

Page ini digunakan untuk halaman post yang kita buat, buat file single.php

<?php get_header(); ?>

<main class="py-5">
    <div class="container">
        <div class="row">
            <div class="col-md-8">
                <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
                    <article>
                        <h1 class="display-4"><?php the_title(); ?></h1>
                        <div class="my-4"><?php the_content(); ?></div>
                    </article>
                <?php endwhile; endif; ?>
            </div>
        </div>
    </div>
</main>

<?php get_footer(); ?>

6. Buat Part Page Content

Page ini digunakan sebagai dynamic content:

  1. Membuat folder baru dengan nama template-parts
  2. Buat file dengan nama content.php
<article id="post-<?php the_ID(); ?>" <?php post_class('mb-5'); ?>>
    <header class="entry-header">
        <?php
        if (is_singular()) :
            the_title('<h1 class="entry-title">', '</h1>');
        else :
            the_title('<h2 class="entry-title"><a href="' . esc_url(get_permalink()) . '" rel="bookmark">', '</a></h2>');
        endif;
        ?>
        <div class="entry-meta">
            <?php
            bootstrap_tutorial_theme_posted_on();
            bootstrap_tutorial_theme_posted_by();
            ?>
        </div>
    </header>

    <div class="entry-content">
        <?php
        the_content(sprintf(
            wp_kses(
                __('Continue reading<span class="screen-reader-text"> "%s"</span>', 'bootstrap-tutorial-theme'),
                array('span' => array('class' => array()))
            ),
            get_the_title()
        ));

        wp_link_pages(array(
            'before' => '<div class="page-links">' . esc_html__('Pages:', 'bootstrap-tutorial-theme'),
            'after'  => '</div>',
        ));
        ?>
    </div>

    <footer class="entry-footer">
        <?php bootstrap_tutorial_theme_entry_footer(); ?>
    </footer>
</article>

Tambahkan code berikut pada file functions.php

function bootstrap_tutorial_theme_posted_on() {
    $time_string = '<time class="entry-date published updated" datetime="%1$s">%2$s</time>';
    if (get_the_time('U') !== get_the_modified_time('U')) {
        $time_string = '<time class="entry-date published" datetime="%1$s">%2$s</time><time class="updated" datetime="%3$s">%4$s</time>';
    }

    $time_string = sprintf(
        $time_string,
        esc_attr(get_the_date(DATE_W3C)),
        esc_html(get_the_date()),
        esc_attr(get_the_modified_date(DATE_W3C)),
        esc_html(get_the_modified_date())
    );

    echo '<span class="posted-on">' . $time_string . '</span>';
}

function bootstrap_tutorial_theme_posted_by() {
    echo '<span class="byline"> by ' . esc_html(get_the_author()) . '</span>';
}

function bootstrap_tutorial_theme_entry_footer() {
    if ('post' === get_post_type()) {
        $categories_list = get_the_category_list(esc_html__(', ', 'bootstrap-tutorial-theme'));
        if ($categories_list) {
            echo '<span class="cat-links">' . $categories_list . '</span>';
        }

        $tags_list = get_the_tag_list('', esc_html__(', ', 'bootstrap-tutorial-theme'));
        if ($tags_list) {
            echo '<span class="tags-links">' . $tags_list . '</span>';
        }
    }
}

7. Membuat Sidebar

  1. Buat file sidebar.php dalam folder tema
  2. Tambahkan code php berikut
<aside id="secondary" class="widget-area">
    <?php dynamic_sidebar('sidebar-1'); ?>
</aside>

Selanjutnya buat function dynamic sidebar pada file functions.php

function bootstrap_tutorial_theme_widgets_init() {
    register_sidebar(array(
        'name'          => __('Sidebar', 'bootstrap-tutorial-theme'),
        'id'            => 'sidebar-1',
        'description'   => __('Add widgets here to appear in your sidebar.', 'bootstrap-tutorial-theme'),
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
        'after_widget'  => '</section>',
        'before_title'  => '<h2 class="widget-title">',
        'after_title'   => '</h2>',
    ));
}
add_action('widgets_init', 'bootstrap_tutorial_theme_widgets_init');

8. Akses Index Page

  1. Akses wordpress local http://localhost/wordpress (sesuaikan dengan url local). dan masuk ke halaman Admin http://localhost/wordpress/wp-admin.
  2. Masuk keemun Settings->Reading
  3. Pastikan templare action index.php

File-file yang telah kita buat adalah file utama dari sebuah tema WordPress agar bisa digunakan atau di install di wordpress. Kita bisa mengembangkan lebih langue sesuai dengan kebutuhan atau tema Wordrpress yang akan kita buat. selain Bootstrap kita juga bisa menggunakan CSS Framework / Library dan Utilities lainnya seperti Tailwind dll. Selain Framework CSS kita juka bisa menggunakan Framework / Library JS lainnya seperti JQuery, React JS dll.

Berikut contoh file-file yang dibutuhkan :

Kode sumber bisa di download di github pada link berikut hyvercode-boots

hyvercode

React Native create project without expo 

Pastikan kita menggunakan Node.js versi LTS cek versi : https://nodejs.org

1. Install Watchman (untuk pengguna macOS)

brew install watchman

2. Install React Native CLI

Install React Native CLI secara global dengan perritah berikut :

npm install -g react-native-cli

3. Buat project baru React Native Project

npx react-native init MyApp

4. Masuk dalam folder project yang telah dibuat

cd MyApp

5. Install Dependencies

Jika kita penguna macOS dan ingin membuat aplikasi untuk iOS, maka kita harus install CocoaPods, pastikan Xcode yang digunakan versi terbaru

cd ios && pod install && cd ..

6. Run the Project

Untuk menjalankan Android patikán JAVA_HOME, ANDROID_SDK, sudah terpasang, termásuk tersedia Android Emulator tau device Android

npx react-native run-android

Untuk mejalankan iOS patikán Xcode sudah tersedia:

npx react-native run-ios

hyvercode

SSO Laravel API + Keycloack

Langkah 1: Instalasi Laravel dan Library Keycloak-Guard

  1. Buat proyek Laravel baru dengan perintah laravel new namaproyek.
  2. Masuk ke direktori proyek dengan perintah cd namaproyek.
  3. Instal library Keycloak-Guard dengan Composer menggunakan perintah composer require laravel/keycloak-guard.

Langkah 2: Konfigurasi Keycloak

  1. Buka file .env dan tambahkan konfigurasi Keycloak berikut ini:
makefile
KEYCLOAK_SERVER_URL=https://alamat-keycloak/auth
KEYCLOAK_REALM=nama-realm
KEYCLOAK_CLIENT_ID=nama-client
KEYCLOAK_CLIENT_SECRET=rahasia-client

Pastikan untuk mengganti nilai-nilai sesuai dengan konfigurasi Keycloak Anda.

  1. Buka file config/auth.php dan ubah driver ke 'keycloak':
arduino
'guards' => [
    'api' => [
        'driver' => 'keycloak',
        'provider' => 'users',
    ],
],
  1. Tambahkan konfigurasi Keycloak ke dalam file config/services.php:
bash
'keycloak' => [
    'base_url' => env('KEYCLOAK_SERVER_URL'),
    'realm' => env('KEYCLOAK_REALM'),
    'client_id' => env('KEYCLOAK_CLIENT_ID'),
    'client_secret' => env('KEYCLOAK_CLIENT_SECRET'),
],

Langkah 3: Migrasi Database dan Routing

  1. Jalankan perintah php artisan migrate untuk membuat tabel pengguna default Laravel.

Langkah 4: Routing dan Implementasi Autentikasi

  1. Buka file routes/api.php dan tambahkan rute berikut ini sebagai contoh:
php
Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Route::middleware('auth:api')->get('/protected', function () {
    return response()->json([
        'message' => 'This is a protected route.',
    ]);
});

Langkah 5: Uji Autentikasi

  1. Jalankan aplikasi Laravel dengan perintah php artisan serve.
  2. Buka Postman atau alat serupa untuk menguji API.
  3. Buat permintaan GET ke http://localhost:8000/api/user dan atur header Authorization dengan nilai Bearer <access_token>. Gantilah <access_token> dengan token akses yang diterima setelah autentikasi Keycloak.
  4. Anda harus menerima respons JSON yang berisi informasi pengguna terautentikasi.

Dengan langkah-langkah di atas, aplikasi Laravel API Anda harus terhubung dengan Keycloak dan mampu melakukan autentikasi menggunakan Keycloak. Pastikan untuk mengganti nilai-nilai konfigurasi dengan yang sesuai dengan konfigurasi Keycloak Anda.

hyvercode

Guest Books CRUD spring-boot + mysql+thymeleaf

Hai hyvercoder! semua kali ini kita akan membuat aplikasi CRUD (Create Read Update Delete ) Guest-Book dimana aplikasi ini berisikan data tamu atau member, aplikasi kali ini akan mengunakan :

  • Spring-boot
  • Maven
  • Mysql
  • Java 1.8
  • Thymeleaf

Buat project spring-boot Structure project seperti ini :

Buat database dengan nama guest_books

create database guest_books;

Buat table dengan nama guest

CREATE TABLE guest_books.guest
(
  id integer PRIMARY KEY NOT NULL,
  name character varying(30),
  phone_number character varying(15)
);

 

Buat class entity dalam package entity dengan Nama Guest.java, Isi file class terse but seperti berikut

import javax.persistence.*;
import java.io.Serializable;

@Table(name = "guest")
@Entity
public class Guest implements Serializable {
    @Id
    @Column(name = "id_guest")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer idGuest;
    @Column(name = "name",length = 30)
    private String name;
    @Column(name = "phone_number",length = 15)
    private String phoneNumber;

    public Integer getIdGuest() {
        return idGuest;
    }

    public void setIdGuest(Integer idGuest) {
        this.idGuest = idGuest;
    }

    public String getName() {
        return name;
    }

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

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

}

Buat class GuestRepository.java Pada package repository

package com.alfazid.guestbooks.repository;

import com.alfazid.guestbooks.model.Guest;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface GuestRepository extends JpaRepository<Guest,Integer> {
    List<Guest> findByName(String name);
}

Buat class GuestController.java dalam package controller

package com.alfazid.guestbooks.controller;

import com.alfazid.guestbooks.model.Guest;
import com.alfazid.guestbooks.repository.GuestRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Optional;


@Controller
public class GuestController {
    @Autowired
    private GuestRepository guestRepository;

    @GetMapping("/")
    public ModelAndView getList(Model model){
        List<Guest> list = guestRepository.findAll();
        model.addAttribute("list", list);
        return new ModelAndView ("index");
    }

    @GetMapping("/param")
    public ModelAndView getListByName(Model model, @Param("name") String name){
        List<Guest> list;
        if(name.isEmpty()){
            list= guestRepository.findAll();
        }else{
            list= guestRepository.findByName(name);
        }
        model.addAttribute("list", list);
        return new ModelAndView ("index");
    }

    @GetMapping("/create")
    public ModelAndView create(Guest guest){
        return new ModelAndView ("create");
    }

    @PostMapping("/create")
    public ModelAndView insert(Guest guest){
        guestRepository.save(guest);
        return new ModelAndView ("redirect:/");
    }

    @GetMapping("/update/{id}")
    public ModelAndView edit(Model model,@PathVariable("id") Integer id){
        Optional<Guest> guestBooks = guestRepository.findById(id);
        if(guestBooks.isPresent()){
            model.addAttribute("guest",guestBooks.get());
            return new ModelAndView ("update");
        }
        return new ModelAndView ("redirect:/");

    }

    @PostMapping("/update/{id}")
    public ModelAndView update(@PathVariable("id") Integer id, Guest guest){
        guestRepository.save(guest);
        return new ModelAndView ("redirect:/");
    }

    @GetMapping("/delete/{id}")
    public ModelAndView delete(@PathVariable("id") Integer id){
        guestRepository.deleteById(id);
        return new ModelAndView ("redirect:/");
    }
}

Buat file html pada folder resources/templates

file index.html adalah halaman utama web saat aplikasi dijalankan

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Guest Books</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" type="text/css" th:href="@{/css/bootstrap.min.css}" />
</head>
<body>
<div class="container" style="margin-top:30px;">
    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3">
        <h2>Guest Books</h2>
        <div class="btn-toolbar mb-5 mb-md-0">
            <div class="btn-group mr-2">
                <input type="text" placeholder="Input name" name="name" id="name" onsubmit="name"
                       class="form-control input-sm form-control-sm"/>
                <button class="btn btn-sm btn-secondary" onclick="onSearch()">Cari</button>
            </div>
            <a class="btn btn-sm btn-secondary" href="/create">
                Tambah Data
            </a>
        </div>
    </div>
    <div class="table-responsive">
        <table class="table table-striped table-sm table-hover">
            <thead>
            <tr>
                <th>Guest ID</th>
                <th>Name</th>
                <th>Phone</th>
                <th style="text-align: center">#</th>
            </tr>
            </thead>
            <tbody>
            <tr th:each="data,iter : ${list}">
                <td th:text="${data.idGuest}"></td>
                <td th:text="${data.name}"></td>
                <td th:text="${data.phoneNumber}"></td>
                <td style="width: 100px;">
                    <a class="btn btn-sm btn-secondary" th:href="@{/update/{id}(id=${data.idGuest})}" style="padding: 3px;">Edit</a>
                    <a class="btn btn-sm btn-secondary" th:href="@{/delete/{id}(id=${data.idGuest})}" style="padding: 3px;">delete</a>
                </td>
            </tr>
            </tbody>
        </table>
    </div>
    <script>
    function onSearch() {
        var name = document.getElementById("name").value;
        if (name !="") {
            window.location = "/param?name="+name;
        } else {
            window.location = "/"
        }
    }
    </script>
</div>
</body>
</html>

Buat file create.html , ini adalah halaman untuk membuat data tamu / member baru

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Guest Books</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" type="text/css" th:href="@{/css/bootstrap.min.css}" />
</head>
<body>
<div class="container">
    <div class="row">
        <main role="main" class="col-md-9 ml-sm-auto col-lg-10 px-4">
            <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3">
                <h2>Guest Books</h2>
            </div>
            <div class="col-sm-8 col-md-8 col-lg-8 col-xs-12">
                <form action="#" th:action="@{/create}" th:object="${guest}" method="POST">
                    <div class="form-group row has-success">
                        <label class="control-label col-sm-3" for="name">Name</label>
                        <div class="col-sm-6">
                            <input class="form-control form-control-sm" type="text" th:field="*{name}" id="name"
                                   name="name" placeholder="Input name" required>
                        </div>
                    </div>
                    <div class="form-group row has-success">
                        <label class="control-label col-sm-3" for="phoneNumber">Phone</label>
                        <div class="col-sm-6">
                        <input class="form-control form-control-sm" type="text" th:field="*{phoneNumber}" id="phoneNumber"
                               name="name" placeholder="Input Phone Number" required>
                        </div>
                    </div>
                    <div class="">
                        <div class="col-sm-6" style="float: right;">
                            <a class="btn btn-sm btn-secondary" href="/">
                                Cancel
                            </a>
                            <input type="submit" class="btn btn-secondary btn-sm" value="Save"/>
                        </div>
                    </div>
                </form>
            </div>
        </main>
    </div>
</div>
</body>
</html>

Buat file update.html , ini adalah halaman untuk merubah data tamu / member

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Guest Books</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" type="text/css" th:href="@{/css/bootstrap.min.css}" />
</head>
<body>
<div class="container">
    <div class="row">
        <main role="main" class="col-md-9 ml-sm-auto col-lg-10 px-4">
            <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3">
                <h2>Guest Books</h2>
            </div>
            <div class="col-sm-8 col-md-8 col-lg-8 col-xs-12">
                <form action="#" th:action="@{/update/{id}(id=${guest.idGuest})}" th:object="${guest}" method="POST">
                    <div class="form-group row has-success">
                        <div class="col-sm-6">
                            <input class="form-control form-control-sm" th:field="*{idGuest}" type="text" id="idGuest"
                                   name="idGuest"  hidden style="background-color: transparent;border: gray solid 1px;">
                        </div>
                    </div>

                    <div class="form-group row has-success">
                        <label class="control-label col-sm-3" for="name">Name</label>
                        <div class="col-sm-6">
                            <input class="form-control form-control-sm" type="text" th:field="*{name}" id="name"
                                   name="name" placeholder="Input name" required>
                        </div>
                    </div>
                    <div class="form-group row has-success">
                        <label class="control-label col-sm-3" for="phoneNumber">Phone</label>
                        <div class="col-sm-6">
                        <input class="form-control form-control-sm" type="text" th:field="*{phoneNumber}" id="phoneNumber"
                               name="name" placeholder="Input Phone Number" required>
                        </div>
                    </div>
                    <div class="">
                        <div class="col-sm-6" style="float: right;">
                            <a class="btn btn-sm btn-secondary" href="/">
                                Cancel
                            </a>
                            <input type="submit" class="btn btn-secondary btn-sm" value="Update"/>
                        </div>
                    </div>
                </form>
            </div>
        </main>
    </div>
</div>
</body>
</html>

Pastikan semua dependencies yg aplikasi butuhkan pada file pom.xml sama seperti berikut :

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.4.0</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.alfazid</groupId>
	<artifactId>guestbooks</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>tes1</name>
	<description>Guest Books</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

Setup database yang terdapat pada file resources/application.yml sesuikan database , username dan password sesuai dengan local mesin kalian

spring:
  datasource:
    driverClassName:
    url: jdbc:mysql://localhost:3306/guest_books?createDatabaseIfNotExist=true&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Jakarta&useSSL=false
    username: root
    password: 
  jpa:
    show-sql: true
    hibernate:
      ddl-auto: update
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL5Dialect
        format_sql: true

Untuk menjalankan aplikasi gunakan perintah

- mvn clean install
- mvn spring-boot:run

jika aplikasi tidak terjadi kesalahan saat running maka tampilan aplikasi yang kita buat superti berikut:

Halaman utama

Halaman tambah data

Halaman ubah data

The project source code can be downloaded on the GitHub  guest-books

hyvercode

Pick Number Java Application

Hallo semua, kali ini saya akan membuat sebuah aplikasi pick-number, ini adalah program sederhana dimana user dan system berlomba untuk mendapatkan nilai tertinggi dari random number yang tersedia.

Buat sebuah file java App.java kemudian tulis syntax atau script java berikut:

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;

public class App {
    public static void main( String[] args ) {
        Scanner keyboard = new Scanner(System.in);
        Random r = new Random();
        System.out.println( "Pick a number between 10 - 20");
        int pickNumber = keyboard.nextInt();
        List<Integer> result = new ArrayList<>();
        if(pickNumber <10 || pickNumber >20){
            System.out.println( "\n==== Please pick a number between 10 - 20 !");
            System.exit(1);
        }
        for(int i=0;i<10;i++){
            result.add(r.nextInt(21-pickNumber)+pickNumber);
        }

        int userPick;
        int aiPick;
        int sumUser=0;
        int sumAi=0;
        int ai;
       while(result.size()!=0){
            System.out.println("List "+result.toString().replace(","," ").replace("[","").replace("]",""));
            System.out.println("Pick a number from most left ot right ");
            userPick = keyboard.nextInt();
            try {
                aiPick =result.indexOf(userPick);
                if(result.size()<aiPick){
                    System.out.println("Left");
                    aiPick =result.indexOf(userPick-2);
                }
                result.remove(Integer.valueOf(userPick));
                if(result.size()==aiPick){
                    ai=result.get(aiPick-1);
                    System.out.println("Rigth "+aiPick);
                }else{
                    ai=result.get(aiPick);
                }

                result.remove(Integer.valueOf(ai));
                sumUser =sumUser+userPick;
                sumAi = sumAi+ai;
                System.out.println("Your pick "+userPick);
                System.out.println("AI pick "+ai);
                System.out.println("Sum User "+sumUser);
                System.out.println("Sum AI "+sumAi);
                System.out.println("");
            }catch (Exception e){
                System.out.println("\n==== Please pick number from list!\n");
                System.exit(1);
            }
        }

        String win = sumUser<sumAi?"Game Over, You Lose":"Congratulation ! You win\n";
        System.out.println(win);
    }
}

untuk menjalankanya masuk ke terminal ketik perintah

$javac App.java
$java App

masukan angka antara 10 dan 20 maka system akan membuat list random angka, kemudian pilih salah satu angka yang terdapat pada list, seperti berikut:

Pick a number between 10 - 20
10
List 10  10  20  11  18  14  12  18  20  16
Pick a number from most left ot right 
10
Your pick 10
AI pick 10
Sum User 10
Sum AI 10

List 20  11  18  14  12  18  20  16
Pick a number from most left ot right 
20
Your pick 20
AI pick 11
Sum User 30
Sum AI 21

List 18  14  12  18  20  16
Pick a number from most left ot right 
12
Your pick 12
AI pick 18
Sum User 42
Sum AI 39

List 14  18  20  16
Pick a number from most left ot right 
18
Your pick 18
AI pick 20
Sum User 60
Sum AI 59

List 14  16
Pick a number from most left ot right 
16
Rigth 1
Your pick 16
AI pick 14
Sum User 76
Sum AI 73

Congratulation ! You win

Process finished with exit code 0

Source code project bisa didownload di GitHub pick-number

hyvercode