Html5 DateTime + Ajax Jquery + SpringBoot @JsonFormat example

In the tutorial, JavaSampleApproach will show you how to build an web application with Html5 DateTime + Jquery Ajax + SpringBoot @JsonFormat.

Related posts:
Ajax Jquery post List JavaScript Objects to SpringBoot server | BootStrap

I. Technologies

– Java 1.8
– Maven 3.6.1
– Spring Tool Suite – Version 3.8.1.RELEASE
– Html 5
– JQuery Ajax
– Bootstrap
– Spring Boot – 1.5.7.RELEASE

II. Html5 DateTime + Ajax Jquery + SpringBoot

For working with time input, Html5 support a set of new Input Types:

  • date
  • datetime-local
  • time
  • week

– To bind data from Html5 date input with JQuery, we use new Date():


    $("#taskForm").submit(function(event) {
		// Prevent the form from submitting via the browser.
		event.preventDefault();
		
		// get data from submit form
		var formTask = {
    			taskName : $("#taskName").val(),
    			startTime : new Date($("#startTime").val()),
    			endTime : new Date($("#endTime").val())
    	}

– To display Date object with customized format, we can use some Date methods as below code


function timeFormat(date){
	if(date instanceof Date){
		var isoDate = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
		var time = date.toLocaleString('en-US', { hour: 'numeric',minute:'numeric', hour12: true });
		return isoDate + ' @ ' + time;	
	}else{
		return "";
	}
}

– When exchange data between client to server, Json format is used by JSON.stringify(), and Date objects will be converted to String type with UTC standard format.


// DO POST
function ajaxPost(){
	$.ajax({
		type : "POST",
		contentType : "application/json",
		accept: 'text/plain',
		url : window.location + "api/logtime/save",
		data : JSON.stringify(listTasks),
		dataType: 'text',
		success : function(result) {

Html5 DateTime - JqueryAjax - SpringBoot RestAPIs - post tasks

– When receiving Json data from Server, we need change objects to Date for working:

Html5 DateTime - JqueryAjax - SpringBoot RestAPIs - get tasks logs


// DO GET
function ajaxGet(){
	$.ajax({
		type : "GET",
		url : window.location + "api/logtime/all",
		success: function(result){
				$('#resultGetAllTaskDiv ul').empty();
				
				$.each(result, function(i, task){
					var strTask = "task: " + task.taskName + 
					", startTime: " + timeFormat(new Date(task.startTime)) +
					", endTime: " + timeFormat(new Date(task.endTime));

– With SpringBoot code, we use @JsonFormat annotation of Jackson to convert Date format:


public class LogTime {
	private String taskName;
	
	@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", timezone="GMT")
	private Date startTime;
	
	@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", timezone="GMT")
	private Date endTime;

GOAL:

– Create SpringBoot project as below:

Html5 DateTime - JqueryAjax - SpringBoot RestAPIs - project structure

Run and check results:

-> adding form:

Html5 DateTime - JqueryAjax - SpringBoot RestAPIs - adding task form

Html5 DateTime - JqueryAjax - SpringBoot RestAPIs - add tasks

-> post data:

Html5 DateTime - JqueryAjax - SpringBoot RestAPIs - post task view

-> get data:

Html5 DateTime - JqueryAjax - SpringBoot RestAPIs - get all view

III. Practice

Step to do:
– Create Spring Boot project
– Create data model
– Create Web Controller to provide web view
– Create RestController for GET/POST request
– Create an index.html view
– Implement Jquery Ajax GET/POST data

1. Create Spring Boot project

Use SpringToolSuite to create a SpringBoot project SpringBootHtmlDateTimeJQueryAjax with dependencies:

<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>

2. Create data model

– Create LogTime model with JsonFormat:


import java.util.Date;
 
import com.fasterxml.jackson.annotation.JsonFormat;
 
public class LogTime {
	private String taskName;
	
	@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", timezone="GMT")
	private Date startTime;
	
	@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", timezone="GMT")
	private Date endTime;
	
	public LogTime(){}
	
	public LogTime(String taskName, Date startTime, Date endTime){
		this.taskName = taskName;
		this.startTime = startTime;
		this.endTime = endTime;
	}
	
	public void setTaskName(String taskName){
		this.taskName = taskName;
	}
	
	public String getTaskName(){
		return this.taskName;
	}
	
	public void setStartTime(Date startTime){
		this.startTime = startTime;
	}
	public Date getStartTime(){
		return this.startTime;
	}
	
	public void setEndTime(Date endTime){
		this.endTime = endTime;
	}
	
	public Date getEndTime(){
		return this.endTime;
	}
}

3. Create Web Controller to provide web view


package com.javasampleapproach.html5datetime.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
 
@Controller
public class WebController {
	@GetMapping(value="/")
    public String homepage(){
        return "index";
    }
}

4. Create RestController for GET/POST request


package com.javasampleapproach.html5datetime.controller;
 
import java.util.ArrayList;
import java.util.List;
 
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.RestController;
 
import com.javasampleapproach.html5datetime.model.LogTime;
 
@RestController
@RequestMapping("/api/logtime")
public class RestWebController {
	
	List cust = new ArrayList();
	
	@GetMapping(value = "/all")
	public List getResource(){
			return cust;
	}
	
	@PostMapping(value="/save")
	public String postCustomer(@RequestBody List logtimes){
		cust.addAll(logtimes);
		return "Post Successfully!";
	}
}

5. Create an index.html view

<!DOCTYPE HTML>
 
<html>
<head>
	  <title>HTML5 - DateTime - JQuery Ajax - LogTime sample</title>
	  <meta charset="utf-8" />
	  <meta name="viewport" content="width=device-width, initial-scale=1" />
	  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
	  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
	  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
	  <script src="/js/jqueryAjaxGetPost.js"></script>
</head>
<body>
 
<div class="container">
 
	<h3 style="color:blue">HTML5 - DateTime - JQuery Ajax - LogTime sample</h3>
	
	<div class="row col-md-7">
		<form id="taskForm">
			<div class="form-group">
				<label for="taskName">Task:</label>
				<input type="text" class="form-control" id="taskName" placeholder="Enter Task"/>
			</div>
			<div class="form-group">
				<label for="startTime">StartTime:</label>
				<input type="datetime-local" class="form-control" id="startTime" placeholder="Enter StartTime"/>
			</div>
			<div class="form-group">
				<label for="endTime">EndTime:</label>
				<input type="datetime-local" class="form-control" id="endTime" placeholder="Enter EndTime"/>
			</div>
			<button style="margin-bottom:10px" type="submit" class="btn btn-default">Add Task</button>
		</form>
		
		<!-- Table of Adding Task -->
		<table id="taskTable" class="table table-bordered table-hover">
			<thead>
				<tr>
					<th>No</th>
					<th>Task</th>
					<th>StartTime</th>
					<th>EndTime</th>
				</tr>
			</thead>
			<tbody>
			</tbody>
		</table>
		
		<!-- DIV Submit task  -->
		<!-- SUBMIT Task Button to Server -->
		<button id="postTasksBtn" style="margin-bottom:10px" type="submit" class="btn btn-default">Post Tasks</button>
		
		<!-- Message result from server -->
		<div id="postResultDiv" style="margin:10px 0px 10px 0px;">
		</div>
		
		
		<!-- Get All Tasks from back-end -->		
		<button id="getAllTasksBtnId" type="button" class="btn btn-primary" style="margin:10px 0px 10px 0px;">Get All Tasks</button>
		<div id="resultGetAllTaskDiv">
	        <ul class="list-group">
	    	</ul>
    	</div>
	</div>
</div>
</body>
</html>

6. Implement Jquery Ajax GET/POST data


$( document ).ready(function() {
	
	var listTasks = [];

	/**
	 * Using JQuery for hiding some elements in view when bootstrap app
	 */
	// Hide task table when starting
	// we just show it if having any adding-task
	$('#taskTable').hide();
	$('#postTasksBtn').hide();
	
	// Task-Form submit
    $("#taskForm").submit(function(event) {
		// Prevent the form from submitting via the browser.
		event.preventDefault();
		
		// get data from submit form
		var formTask = {
    			taskName : $("#taskName").val(),
    			startTime : new Date($("#startTime").val()),
    			endTime : new Date($("#endTime").val())
    	}
		
		// store task
		listTasks.push(formTask);
		
		// re-render task table by append new task to table
		console.log(formTask);
		var taskRow = '' +
							'' + listTasks.length + '' +
							'' + formTask.taskName + '' +
							'' + timeFormat(formTask.startTime) + '' +
							'' + timeFormat(formTask.endTime) + '' +
					        '' +
					        	'' +
					        	'' +
					  				'' +
								'' +
					        '' +
						  '';

		$('#taskTable tbody').append(taskRow);

		// just how task table and POST button
		$('#taskTable').show();
		$('#postTasksBtn').show();
		
		// Reset FormData after Posting
    	resetData();
	});
    
	// Do DELETE a Task via JQUERY AJAX
	$(document).on("click","a",function() {
		var taskId = $(this).parent().find('input').val();
		$(this).closest("tr").remove()
	});
	
	// POST REQUEST
	$('#postTasksBtn').click(function(){
		ajaxPost();
	});
	
	// GET REQUEST
	$("#getAllTasksBtnId").click(function(event){
		event.preventDefault();
		ajaxGet();
	});

	// DO POST
    function ajaxPost(){
    	$.ajax({
			type : "POST",
			contentType : "application/json",
			accept: 'text/plain',
			url : window.location + "api/logtime/save",
			data : JSON.stringify(listTasks),
			dataType: 'text',
			success : function(result) {
				// clear task body
				$('#taskTable tbody').empty();
				$('#taskTable').hide();
				
				// re-set task table list
				listTasks = [];
				
				// fill successfully message on view
				$("#postResultDiv").html("

" + result + "

"); }, error : function(e) { alert("Error!") console.log("ERROR: ", e); } }); } // DO GET function ajaxGet(){ $.ajax({ type : "GET", url : window.location + "api/logtime/all", success: function(result){ $('#resultGetAllTaskDiv ul').empty(); $.each(result, function(i, task){ var strTask = "task: " + task.taskName + ", startTime: " + timeFormat(new Date(task.startTime)) + ", endTime: " + timeFormat(new Date(task.endTime)); $('#resultGetAllTaskDiv .list-group').append("
  • " + strTask + "
  • "); }); // just re-css for result-div $('#resultGetAllTaskDiv').css({'background-color':'#D16953', 'color':'white', 'padding':'20px 20px 5px 30px'}); // just hide POST button if($('#taskTable').is(":hidden")){ $('#postTasksBtn').hide(); } }, error : function(e) { $("#getResultDiv").html("Error"); console.log("ERROR: ", e); } }); } /** * format string to display date in view */ function timeFormat(date){ if(date instanceof Date){ var isoDate = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate(); var time = date.toLocaleString('en-US', { hour: 'numeric',minute:'numeric', hour12: true }); return isoDate + ' @ ' + time; }else{ return ""; } } function resetData(){ $("#taskName").val(""); $("#startTime").val(""); $("#endTime").val(""); } })

    IV. Sourcecode

    SpringBootHtml5DateTimeJQueryAjax



    By grokonez | November 15, 2017.

    Last updated on April 29, 2021.



    Related Posts


    Got Something To Say:

    Your email address will not be published. Required fields are marked *

    *