Java @ Desk: Javascript | Java at your desk

Angular JS Spring MVC Rest CRUD JSON Example using $http

Angular JS Spring MVC Rest CRUD JSON Example using $http

In this example, we will learn how to get the json data from rest service controller from Spring and display using the ng-model attribute of angular JS.

Spring RestController returns the Customer java object in JSON format and data is displayed on UI using angular JS. Call to the rest api is done using the $http of angular JS.

Following components will be used
1) Spring RestController
2) Angular JS ng-app
3) Angular JS ng-controller
4) Angular JS ng-model
5) Angular JS $http

Here are the files that are used.

Customer.java
package com.accenture.restviability.pojo;

public class Customer {

 private String name;
 
 private String id;

 public String getName() {
  return name;
 }

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

 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }
}


SpringRestController
package com.accenture.restviability.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.accenture.restviability.pojo.Customer;
import com.google.gson.Gson;

@RestController()
@CrossOrigin(maxAge = 3600)
public class SpringRestController {

 @RequestMapping(method = RequestMethod.GET, path = "/customers", produces = MediaType.APPLICATION_JSON_VALUE)
 public ResponseEntity<Customer> getCustomers() {
  System.out.println("Entered in Get Customers");
  List<Customer> customers = new ArrayList<Customer>();
  Customer customer = new Customer();
  customer.setName("Kumar");
  customer.setId("1");
  Gson gson = new Gson();
  return new ResponseEntity<Customer>(customer, HttpStatus.OK);
 }
}




customer.jsp
<!DOCTYPE html>
<html ng-app="customerApp">
<head>
<title>Customer App</title>
<script src="js/angular.js"></script>
<script src="js/customerController.js"></script>
<script src="js/jquery.min.js"></script>
</head>

<body>
 <div ng-controller="customerController">
  <p>
   Customer Id - <input type="text" ng-model="customer.id" />
  </p>
  <p>
   Customer Name - <input type="text" ng-model="customer.name" />
  </p>
 </div>
</body>
</html>


customerController.js
var app = angular.module('customerApp', []);
app.controller("customerController", function($scope, $http) {
 $http.get('http://localhost:8070/customers').then(
   function successCallback(response) {
          $scope.customer = {name: response.data.name, id: response.data.id};
   }, function errorCallback(response) {
   });
});


Jquery pass Json data from HTML to Servlet in Ajax

Jquery pass Json data from HTML to Servlet in Ajax

In order to pass JSON data from HTML to servlet, javascript object is created and values are set into user defined properties of the object. Data is passed in String json format using JSON.stringify(jsonData).

Data is passed using the data attribute of ajax service.

Below example is to illustrate the same. Value of a textbox is passed to a servlet in JSON String format.

HTML File:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.min.js"></script>
<script src="js/common.js"></script>
<script src="js/jquery-ui.min.js"></script>

</head>
<body>
 <form id="inputform">
  <div style="height: 40px;"></div>

  <input type="text" id="textBox" name="textBox"> <input
   type="button" value="Identify" onclick="submitJsonPostData()" />
 </form>
</body>
</html>


JS File:
function submitJsonPostData() {
 var text = $("#textBox").val();
 var jsonData = new Object();
 jsonData.text = text;
 $.ajax({
  url : 'JsonPostDataServlet',
  type : 'POST',
  data : {
   jsonPostRequest : JSON.stringify(jsonData)
  },
  success : function(response) {
  },
  error : function(response) {
   alert("Error: Timeout please try again later");
  },
 });
}




Servlet:
package com.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/JsonPostDataServlet")
public class JsonPostDataServlet extends HttpServlet {
 @SuppressWarnings("unchecked")
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  String jsonPostRequest = request.getParameter("jsonPostRequest");
  System.out.println("Json Post Request received from JSP - " + jsonPostRequest);
 }
}


Output:
Json Post Request received from JSP -
{"text":"TextValue"}

Change label in HTML using Jquery

Change label in HTML using Jquery

Changing the label or a message is often required in an application. For example, on a registration page there is a validation required to fill all the fields on click of a button. Instead of showing an alert message, a message in a label looks quiet good in the form. Its more user frieldly.

To update a label, for property is used and a new html is appended to the for property name of the label.

To use the inbuilt function in JS, following library must be included in the HTML file
1) jquery.min.js


Here is the sample html code to change the label value on click of a button

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.min.js"></script>

<script type="text/javascript">

function changeLabel() {
    $("label[for='LabelName']").html("Label On Load Changed");
}
</script>

</head>
<body>
 <div style="height: 40px;"></div>

 <p><strong><label for="LabelName">Label On Load</label></strong></p>

 <div>
  <button onclick="changeLabel();">Change Label</button>
 </div>

 <div style="height: 40px;"></div>

</body>
</html>

Jquery show hide by id in Javascript

Jquery show hide in Javascript

show and hide the UI elements using the id attribute of the html element.
hide() - Jquery method to hide the field
show() - Jquery method to show the field

To use the inbuilt function in JS, following library must be included in the HTML file
1) jquery.min.js

Here is the sample html code to show hide the image

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.min.js"></script>

<script type="text/javascript">

function showImage() {
 $("#processNewImage").show();
}
function hideImage() {
 $("#processNewImage").hide();
}
</script>

</head>
<body>
 <div style="height: 40px;"></div>

 <div>
  <button onclick="showImage();">Show Image</button>
  <button onclick="hideImage();">Hide Image</button>
 </div>

 <div style="height: 40px;"></div>

 <div>
  <img src="images/giphy.gif" id="processNewImage"
   name="processNewImage">
 </div>
</body>
</html>

Redirect a Page or URL using javascript

Redirect a Page or URL using javascript

What is Redirect?
Redirect is something, the user requests for some JSP page but internally the user gets redirected to some other page within the application or outside the application.

Reasons for redirect:
1) Domain Name change - There arise a case where a registered domain need to be changed. In that case, the JSP pages that are build up need to be redirected to a new domain so that users do not see the old website.

2) Single Domain Usage - Every application uses domain region wise. Like for India, URL will end with ".in". In order to keep all the users at ".com" domain, redirect comes into usage

3) Payment Gateways - During online bill payments, the application needs to be redirected to third party payment sites. Consider you want to pay Vodafone Bill. So as soon as you fill in all the details and proceed to payment, the website redirects to a third party website for payment process. Here redirects comes into picture.

This side of redirection is termed as Client Side Redirect since it happens through Javascript which occurs at browser side.

There are different ways to implement the Redirection using Javascript:
1) window.localtion.replace - The replace method on the other hand navigates to the URL without adding a new record to the history. You cannot click the back button in this case
2) window.localtion.href - Work like assign
3) window.localtion.assign - The assign method does add a new record to the history.
4) window.location - Work like assign

Sample implementation for JSP:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div id="redirect">
<h2>Redirecting to another Page</h2>
</div>
<script>
 // JavaScript using localtion.replace
 window.location.replace("http://javacodeimpl.blogspot.com");
 // JavaScript using localtion.href
 //window.location.href="http://javacodeimpl.blogspot.com";
 // JavaScript using localtion.assign
 //window.location.assign("http://javacodeimpl.blogspot.com");
</script>
</body>
</html>

Difference between substr() and substring() in javascript

var stringVar = "substr_vs_substring";
stringVar.substr(start, length);
stringVar.substring(start, stop);

substring(start, stop):It returns string from index position [start] i.e. 1 to index position [stop-1] i.e. 3

Difference between slice() and substring() in javascript

Difference between slice() and substring() in javascript

slice() works like substring() works the same way for string in javascript.

var stringVar = "slice_vs_substring";
stringVar.slice(start, stop);
stringVar.substring(start, stop);

substring():

start==stop: It returns an empty string.
if(start==stop){ 
 return ""
}

How to create map/array in javascript?















var keyOne = "keyOne";
var keyTwo = "keyTwo";
var valueOne = "valueOne";
var valueTwo = "valueTwo";
// Map with two keys and two values
var map = {keyOne:valueOne,keyTwo:valueTwo}

// Get function to get the value from key
function get(k){
  return map[k];
}

How to get domain/sub-domain/extension from URL in javascript?

Consider the following URL:
http://www.google.com/
This URL has 3 parts

1) www - subdomain
2) google - domain
3) com - extension

In javascript, use the below code to get the complete URL
document.domain
var tokens = document.domain.split('.');//[www,google,com]
var subdomain = tokens[tokens.length - 3];//www
var domain = tokens[tokens.length - 2];//google
var extension = tokens[tokens.length - 1];//com