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

    51 thoughts on “Html5 DateTime + Ajax Jquery + SpringBoot @JsonFormat example”

    1. Thanks for ones marvelous posting! I definitely enjoyed reading it, you will
      be a great author.I will remember to bookmark your blog
      and will eventually come back in the foreseeable future.

      I want to encourage that you continue your great posts, have
      a nice holiday weekend!

    2. Very nice post. I just stumbled upon your weblog and wished to say that I have really enjoyed surfing around your weblog posts.
      In any case I will be subscribing to your feed and I
      hope you write again soon!

    3. Hi, i read your blog from time to time and i own a similar one and i was just
      curious if you get a lot of spam remarks? If so how do you prevent it, any plugin or anything you can advise?
      I get so much lately it’s driving me crazy so any support
      is very much appreciated.

    4. I think that what you wrote made a bunch of sense. However,
      what about this? what if you were to create a awesome headline?
      I am not saying your information is not solid, however suppose you added something
      that grabbed people’s attention? I mean ozenero | Mobile & Web Programming Tutorials is kinda boring.
      You might look at Yahoo’s home page and note how they create article headlines to grab people interested.
      You might try adding a video or a picture or two to get people excited about everything’ve got to say.
      In my opinion, it could bring your posts a little bit more interesting.

    5. Fantastic items from you, man. I’ve take into account
      your stuff prior to and you are just extremely
      excellent. I actually like what you have acquired here,
      really like what you’re stating and the way in which
      through which you assert it. You’re making it entertaining and you continue to take care of
      to stay it sensible. I can’t wait to read far more from you.
      This is really a tremendous web site.

    6. Hey I know this is off topic but I was wondering if you
      knew of any widgets I could add to my blog that automatically tweet my newest twitter
      updates. I’ve been looking for a plug-in like this for quite some time and was
      hoping maybe you would have some experience with something like this.
      Please let me know if you run into anything.
      I truly enjoy reading your blog and I look forward to your
      new updates.

    7. I like the valuable information you supply for your articles.

      I will bookmark your blog and check once more here regularly.
      I am fairly sure I will be informed plenty of new stuff proper
      here! Good luck for the next!

    8. This is really attention-grabbing, You’re an excessively skilled blogger.
      I have joined your feed and look ahead to seeking extra of your great post.
      Additionally, I’ve shared your site in my social networks

    9. After checking out a few of the blog posts on your web site, I honestly appreciate your way of blogging.

      I book marked it to my bookmark site list and will be checking back in the near future.

      Take a look at my website as well and let me know how you feel.

    10. Somebody essentially help to make seriously posts I might state.
      That is the very first time I frequented your web page and to this point?

      I surprised with the analysis you made to make this actual post
      incredible. Great job!

    11. Undeniably believe that which you stated. Your favorite justification appeared to be on the internet the easiest thing to
      be aware of. I say to you, I certainly get irked while people consider worries that they plainly do not know about.
      You managed to hit the nail upon the top and defined out the whole thing without having side-effects , people could take a signal.

      Will probably be back to get more. Thanks

    12. You actually make it seem so easy with your presentation but
      I find this matter to be actually something which I think
      I would never understand. It seems too complex and very
      broad for me. I am looking forward for your next post, I will try
      to get the hang of it!

    13. When someone writes an article he/she retains the idea of a user
      in his/her brain that how a user can understand it. Thus that’s why this piece of writing is great.
      Thanks!

    14. An outstanding share! I’ve just forwarded this onto a coworker who has been doing
      a little homework on this. And he actually ordered me
      dinner because I found it for him… lol.
      So let me reword this…. Thanks for the meal!! But yeah, thanx for spending some time to talk about this topic here on your site.

    15. I like the helpful information you provide to your articles.
      I will bookmark your blog and check again right here regularly.
      I’m relatively certain I’ll be informed many new stuff right here!
      Best of luck for the following!

    16. Its like you read my mind! You seem to know a lot about
      this, like you wrote the book in it or something. I think that you can do with some pics to drive the
      message home a bit, but instead of that, this is excellent blog.

      A fantastic read. I will definitely be back.

    17. My coder is trying to persuade me to move to .net from PHP.

      I have always disliked the idea because of the costs.
      But he’s tryiong none the less. I’ve been using WordPress on various websites for about a year and am anxious about switching to another platform.
      I have heard excellent things about blogengine.net.
      Is there a way I can import all my wordpress posts into it?
      Any help would be greatly appreciated!

    18. Hey There. I discovered your weblog the use of msn. This is a really well
      written article. I’ll be sure to bookmark it and come back to learn extra of your helpful info.
      Thank you for the post. I will definitely comeback.

    19. I was very pleased to uncover this site. I want to to thank you for your time just for this fantastic read!!
      I definitely liked every part of it and I have you book
      marked to see new information in your website.

    20. What you said was very logical. But, think on this, suppose you were to create a killer post
      title? I ain’t suggesting your information isn’t
      solid., but suppose you added a title that grabbed
      a person’s attention? I mean ozenero | Mobile & Web Programming Tutorials
      is a little boring. You could look at Yahoo’s
      front page and see how they create news titles to grab viewers to
      click. You might add a related video or a related picture or two to grab people excited about what you’ve written. In my opinion,
      it could bring your blog a little bit more interesting.

    21. Hi there, just became alert to your blog through Google, and found that it’s truly informative.
      I am gonna watch out for brussels. I will be grateful if you continue this in future.
      A lot of people will be benefited from your writing.
      Cheers!

    22. Pretty part of content. I simply stumbled upon your site and in accession capital to claim that I get
      actually loved account your weblog posts. Anyway I will be
      subscribing in your augment and even I success you get
      entry to persistently rapidly.

    23. Exceptional post but I was wondering if you could write a
      litte more on this topic? I’d be very grateful
      if you could elaborate a little bit more. Cheers!

    24. Usually I do not learn article on blogs, but I would like to say that this write-up very
      compelled me to take a look at and do so! Your writing taste
      has been amazed me. Thanks, very great post.

    25. You can definitely see your enthusiasm within the article you write.
      The world hopes for more passionate writers like you who aren’t afraid to say how they believe.
      All the time go after your heart.

    26. Somebody essentially assist to make significantly posts
      I would state. That is the very first time I frequented your website page and so far?
      I amazed with the analysis you made to create this particular publish
      extraordinary. Wonderful activity!

    27. Hey there are using WordPress for your blog platform?
      I’m new to the blog world but I’m trying to get started
      and create my own. Do you need any coding expertise to make your own blog?
      Any help would be really appreciated!

    28. This design is incredible! You definitely know how to keep a reader amused.
      Between your wit and your videos, I was almost moved
      to start my own blog (well, almost…HaHa!) Excellent job.
      I really loved what you had to say, and more than that, how you presented it.
      Too cool!

    29. Thanks for ones marvelous posting! I actually enjoyed reading it, you can be
      a great author.I will be sure to bookmark your blog and definitely will
      come back down the road. I want to encourage continue your great posts,
      have a nice afternoon!

    30. Hi there very cool blog!! Guy .. Beautiful .. Superb ..
      I’ll bookmark your blog and take the feeds additionally?
      I am happy to find so many useful information right here within the put up, we need work out extra strategies in this regard, thank
      you for sharing. . . . . .

    31. Valuable info. Fortunate me I discovered your website unintentionally, and I
      am shocked why this twist of fate didn’t happened earlier!
      I bookmarked it.

    Leave a Reply

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