Spring MVC 4 and Simple Ajax Call

To understand this tutorial, I assume that you are already aware with Spring MVC and how it works. I will demonstrate here a simple Ajax call in Spring MVC where form data are posted and sent to the controller. The output of the ajax call is plain string text.

Step 1: Create Form

Step 2: Add Ajax Script

Step 3: Create Spring MVC Controller

Step 4: Create Model

Step 1 & 2 : Create Form & Add Ajax Script

Screenshots:

Screen 1: Loading the form and filling information

1_springmvc_ajax

Screen 2: Displaying data after clicking on submit

2_springmvc_ajax

Create a jsp file with name studentForm.jsp and add the following code:

<%@taglib uri=”http://www.springframework.org/tags/form” prefix=”form”%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>

<h2>Student Information</h2>
<form:form id=”form” method=”POST” action=”addStudent.htm” >
<table>
<tr>
<td><form:label path=”name”>Name</form:label></td>
<td><form:input path=”name” /></td>
</tr>
<tr>
<td><form:label path=”age”>Age</form:label></td>
<td><form:input path=”age” /></td>
</tr>
<tr>
<td><form:label path=”id”>id</form:label></td>
<td><form:input path=”id” /></td>
</tr>
<tr>
<td colspan=”2″>
<input type=”submit” value=”Submit” id=”submitButton” />
</td>
</tr>
</table>
</form:form>

<div id=”result”>
</div>

<script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js”> </script>
<script>
$(function(){

$(“#form”).submit(function(){

formData = $(“#form”).serialize();
alert(formData);
$.ajax({
type: “POST”,
url: “addStudent.htm”,
data : formData,
success : function(callback){
alert(callback);
$(“#result”).html(callback);
},
error : function(){
$(“#result”).html(“Error!”);
}
});

return false;
});
});
</script>

</body>
</html>

 

Step 3: Create Spring Controller

Create a java file with name studentController.java and add the following code:
package com.StudentController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
//import org.springframework.web.portlet.ModelAndView;
@Controller
public class StudentController {
@RequestMapping(value = “/student”, method = RequestMethod.GET)
public ModelAndView student() {
return new ModelAndView(“studentForm”, “command”, new Student());
}

@RequestMapping(value = “/addStudent”, method = RequestMethod.POST)
public @ResponseBody String addStudent(@ModelAttribute(“SpringWeb”)Student student) {

String studentStr = “{name:”+student.getName()+”,age:”+student.getAge()+”,id:”+student.getId()+”}”;

return studentStr;
}

}

 

The first method in the controller loads the form and the later one is executed when the submit button is clicked.

Step 4: Create Model

In this step data binding takes place which helps to bind the form data and transact via the controller. You must have already done this step while implementing spring custom controller. Create file Student.java and paste the following code:
package com.StudentController;

public class Student {
private Integer age;
private String name;
private Integer id;

public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}

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

public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}

Finally, run the project and call the student form by typing localhost:8080/project_name/student at the address bar of your browser. Fill some data into the form fields and there your are.

 

 

#SignMyTL – A Complete Microblog using PHP & MySQL (Facebook Like Timeline)

#Website:

A website is a location to the internet that maintains one or more webpages.

#Microblog: 

Microblog is a social media site to which a user makes short, frequent posts.

#SignMyTL

#SignMyTL is a digital autobiograph for one who wants to create log of the key activities of their daily life on the Web. The key feature to this application is that user can share blog post, upload images, youtube videos, facebook timline layout, share immediate comments, smiley support, infinite scroll of website.

Why #SignMyTL?
1. I want my private TimLine public.
2. I want to make a history of my life.
3. I want to connect with my friends differently.
4. I am what my friends talk about me.
5. I want to say something silently.
6. Social Networks are getting fake day by day.
7. I want to be true to myself.

How to get #SignMyTL?

Click here to download #SignMyTL
Click here to view Live Demo

How to install #SignMyTL?

1. Extract and upload SignMyTL directory using ftp client software.

Directory Structure :

SignMyTL 1.0

  • assets
    images
    javascripts
    smileys
    stylesheets
  • imagecache
  • includes
  • uploads

2. Use signmytl.sql to create database & tables.
3. Modify the database credentials in the SignMyTL/config.php.
4. Access your SignMyTL using http://your.domain.name/SignMyTL.

How to implement Heatmap on Websites using PHP, MySQL, jQuery and Ajax?

I was assigned a task when an Interviewer interviewed me and that was a Technical question. I was asked to design a system that can gather click data from a webpage and show it later in form of a Heatmap.

[dfads params=’groups=-1′]

This system can be integrated into any website which records visitor clicks on the page. The goal of of this will be to track visitor’s mouse clicks on various elements of the page and later show them accurately in form a Heatmap. The owner should be able to see aggregated click data in form of an overlay on top of his webpage. The areas in the heatmap that are red more clicks compared to the areas that are white.

After googling through the internet I found some resources which were very interesting. I devoted some time and tried to implement a demo. Please follow the following Steps:

1. Client Code : Create a file index.php and include the following code below. This is the page where users make clicks.

[code]
<script type=’text/javascript’ src="js/jquery-lib.js"></script> <!– jQuery library –>
<script type=’text/javascript’ src="js/hm-dev.js"></script> <!– Log JS –>

<title>99-Websites.com Labs</title>
<body>
<div style="text-align:center">
<img src="99-ws-labs.jpg" />
</div>
</body>

[/code]

2. The Ajax Call : Create a JS file named as hm-dev.js. This file is included in the above index.php page. Add the snippet below:

[code]
/*
Author : Dev
Date : 12/06/2015
*/

jQuery(document).ready(function() {
jQuery(document).click(function(e){
//alert(window.location.href.toString().split(window.location.host)[1]+" — "+e.pageX+" — "+e.pageY);
log_click(window.location.href.toString(), e.pageX, e.pageY);
});
var canvas = document.getElementsByTagName(‘canvas’)[0];
canvas.style.display = "none";
});

function log_click(page, x, y){ // log clicks for heatmap
jQuery.ajax({
type: ‘POST’,
url: ‘log_click.php’,
crossDomain: true,
data: "x_coord="+x+"&y_coord="+y+"&page="+page,
dataType: ‘json’,
success: function(responseData, textStatus, jqXHR)
{
if (responseData== 1){
console.log("Click logged: " + x + ", " + y);

}
else{
console.log("Error – click not logged " + x + ", " + y);
}
},
error: function (responseData, textStatus, errorThrown)
{
console.warn(responseData, textStatus, errorThrown);
alert(‘CORS failed – ‘ + textStatus);
}
});
}
[/code]

3. Log the Clicks : Create a PHP file named with log_click.php and add the following snippet.

[code]

<?php
header(‘Access-Control-Allow-Origin: *’);
header(‘Access-Control-Allow-Methods: POST, GET, OPTIONS’);
header(‘Access-Control-Max-Age: 1000’);
header(‘Access-Control-Allow-Headers: Content-Type’);

//echo json_encode(array("your_request_was" => $_POST[‘page’].$_POST[‘x_coord’].$_POST[‘y_coord’]));

include(‘config.php’); //Create config.php file and define $dbuser, $dbpass & $dbname

if(isset($_POST[‘x_coord’])){
$page = htmlentities($_POST[‘page’]);
if($page == "/"){ $page = "/index.php"; }
$xcoord = htmlentities($_POST[‘x_coord’]);
$ycoord = htmlentities($_POST[‘y_coord’]);
$time = date( ‘Y-m-d H:i:s’);

$conn = mysql_connect(‘localhost’, $dbuser, $dbpass);
mysql_select_db($dbname, $conn);
$page = mysql_real_escape_string($page);
$xcoord = mysql_real_escape_string($xcoord);
$ycoord = mysql_real_escape_string($ycoord);

mysql_query("INSERT INTO clicks (timestamp, page, x, y) VALUES (‘$time’, ‘$page’, $xcoord, $ycoord)");
mysql_close($conn);
echo "1";
}
else
{
echo ‘0’;
}

?>

[/code]

4. Create MySQL Table : Create table with following fields:

[code]

CREATE TABLE IF NOT EXISTS `clicks` (
`timestamp` datetime NOT NULL,
`page` varchar(200) NOT NULL,
`x` int(255) NOT NULL,
`y` int(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

[/code]

That’s it, the first part is over. After implementing the above steps you will be able to log clicks on the MySQL Table. The next and the main part is viewing the heat maps.

5. Create the Admin Page : Create PHP page named with admin.php. This page will lists out all the domains on which the client side code is added. When the links are clicked, their respective heatmaps will be displayed below the same page.  Admin Code is listed below:

[code]

<?php
/*
Author : Dev
Date : 12/06/2015
*/
include("config.php");
$con2 = mysql_connect(‘localhost’, $dbuser, $dbpass);
mysql_select_db($dbname, $con2);
$query = "SELECT distinct page FROM `clicks` WHERE 1";
$result = mysql_query($query);
?>
<html>
<head>
<title>Heatmap Admin</title>
<script type=’text/javascript’ src="js/jquery-lib.js"></script>

<script type=’text/javascript’ src="js/heatmap.js"></script>
<script>
jQuery(document).ready(function(){
var heatmapInstance = h337.create({
container: document.querySelector(‘.display’),
radius: 25
});

jQuery(".showcanvas").click(function(){
//location.reload();
//alert(jQuery(this).attr(‘value’));
var timescale = "day";
var page = jQuery(this).attr(‘value’);
//alert(page);
var postData = "timescale="+timescale+"&page="+page;
jQuery.ajax({
type:"POST",
dataType: "json",
data: postData,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/json;charset=UTF-8");
}
}, url: ‘heatmap.php’,
success: function(data) {

if (data.amount > 0){
for (i=0; i<data.amount; i++){
heatmapInstance.addData({
x: data[i].x,
y: data[i].y,
value: 2
});
}
}
}
});

});
});
</script>
</head>
<body >
<div style="width:100%; border:1px solid; black;">
[Click on the Websites below to View their respective HeatMaps]<br>
<ul style="font-size:12px;">
<?php
while($row = mysql_fetch_assoc($result)){
?>
<li><a href="#" class="showcanvas" value="<?=$row["page"]?>"> <?=$row["page"]?></a></li> <br/>

<?php

}
?>
</ul>
</div>
<div class="display" style="width:100%;height:100%;border:1px solid; black;float:right;">
</div>

</body>
</html>

[/code]

The main logic behind the code is the heatmap.js library. In order to understand in detail you can explore the following references:

1. http://www.patrick-wied.at/static/heatmapjs/example-click-heatmap.html

2. http://rossmarks.co.uk/blog/?p=683

3. http://www.d-mueller.de/blog/cross-domain-ajax-guide/

You can view the Demo here: 

1. Client / Users Page : http://99labs.net where you can make some clicks on the webpage.

2. Admin Page : http://dewendra.com.np/labs/hm/admin.php where you can view the Heatmap.

Also, You can download the whole code from here : Download

[dfads params=’groups=-1′]

PS : The client code can be installed into any website and their logs can be maintained on the remote server. If you go through the client side code you can see the ajax code implemented with CORS (Cross Origing Resource Sharing) using jQuery.

Check whether current time lies between start hour and end hour (PHP)

I started to think of a function in PHP that checks the current time whether it lies between start hour and end hour. This was a task from my boss a couple of weeks ago. He asked this function to write in order to turn down our web application from 900PM to 400AM and display an appropriate message. I googled for a few minutes and compiled the code below:

[dfads params=’groups=-1′]

[code]
function checkTime($current_time, $start, $end){
/* $current_time = "9:00 pm";
$start = "9:00 pm";
$end = "4:00 am"; */

$date1 = DateTime::createFromFormat(‘H:i a’, $current_time);
$date2 = DateTime::createFromFormat(‘H:i a’, $start);
$date3 = DateTime::createFromFormat(‘H:i a’, $end);

//echo $date1;
if ($date1 &gt;= $date2 || $date1 &lt; $date3)
{
return 1;
}
else{
return 0;
}
}

$curTime = date(‘h:i a’);
$curTime = "9:00 pm";
//echo $curTime;
if(checkTime($curTime, "9:00 pm", "4:00 am")==1){
echo "Server Under Maintenance !!
<div style="color: #cc503f; border: 2px solid red; border-radius: 6px; margin-left: auto; margin-right: auto; width: 600px; height: 200px; padding: 10px; text-align: center;">
<h2>Notice!!!</h2>
<h3>Portal under Maintenance from 9PM to 4AM. Please visit back soon.</h3>
</div>
";
exit;
}
[/code]

[dfads params=’groups=-1′]

ORA-24408: could not generate unique server group name

After continuous google for more than 10 hours, I finally came to a conclusion that the problem “ORA-24408: could not generate unique server group name” was not with oracle instanclient or the connection string oci_connect(). The only problem was with the mis-match of the hostnames of the application server defined in /etc/sysconfig/network & /etc/hosts.

[dfads params=’groups=-1′]

After modifying the hostnames in both the file to a single name, the problem was solved.

 $ vi /etc/sysconfig/network

NETWORKING=yes
HOSTNAME=RHEL65
$vi /etc/hosts

$ vi /etc/hosts
#127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
127.0.0.1    RHEL65

$service network restart

The above steps helped me save my valuable time. Thanks to the bloggers.

I hope these information would help you too. Best wishes!

[dfads params=’groups=-1′]

[Source: http://ahmadzainuddinzakaria.blogspot.in/2012/06/warning-ociconnect-functionoci-connect.html]

Unable to save changes to menu in Drupal 6

[dfads params=’groups=-1′]

On the menu-customize page, after

1) dragging a menu item, or

2) checking/unchecking an enable checkbox,

and clicking “Save configuration”, changes to menu were not saved in Drupal 6. Hence, I started to debug the issue at the Application level. After long head bang, I raised my hand and took some rest. Finally, I googled and found that the problem was not at the Application Level but at System Level. I came to know that while posting the form (i.e. when Save Configuration is clicked) the data sent was of large amount and the system was not able to accept since maximum input size was not defined. Following were the changes made in php.ini file.

; How many GET/POST/COOKIE input variables may be accepted
max_input_vars = 2048

After making above changes I restarted the Apache server. Thus, the problem was resolved and Save Configuration in Menu started working.

[dfads params=’groups=-1′]

Starting web server: apache2(98)Address already in use: make_sock: could not bind to address 0.0.0.0:80

download

$service apache2 restart
[....] Starting web server: apache2(98)Address already in use: make_sock: could not bind to address 0.0.0.0:80
no listening sockets available, shutting down
Unable to open logs
failed!

In order to solve the above issue, type following on your console

fuser -k -n tcp 80

[dfads params=’groups=-1′]

Http Error 0 in Drupal

[dfads params=’groups=-1′]

Http Error 0  is a very common error that occurs in Drupal. There are many reasons behind this error.

htttp-error-0

One of the way to resolve this error is to append the following line in this file : /etc/apache2/mods-available/fcgi.conf

[code]

MaxRequestLen 536870912

[/code]

Increase the number value of the MaxRequestLen until the error stops to continue.

[dfads params=’groups=-1′]

Load Testing on Web Servers using Apache Benchmark

ab

After working on many websites, I found one of my site getting too many traffic bringing down the site. I contacted the technical support who fixed the problem. I had never tested load on any of my site. So, I started studying load testing on web servers. This helped me to understand how many users can be handled by my website so that it can run smoothly.

I found a very light and strong linux tool called Apache Benchmark Tool that can test load on Web Servers. This can benchmark Apache, IIS and other web server with apache benchmarking tool called ab. There are also other open source tools that helps to test load on web servers.

[dfads params=’groups=-1′]

I executed following command on my linux terminal:

[code]

ab -c 1000 -n 1000 -t 60 -k http://ignou.ac.in

[/code]

Option -c : This option says there are 1000 concurrent users logged in on the Web Server.

Option -n : This option sends 1000 requests to the Web Server.

Option -t : This option says users will be logged in for 60 seconds.

Option -k : For Keep Alive On

I logged in to the web server and executed the following command to test the actual load.

[code]

top

[/code]

This command helped to track down the load average, CPU and Memory Utilization of the web server.

[dfads params=’groups=-1′]

How to redirect http requests to https on Debian Linux with Apache Web Server?

securing-apache5-590x277

[dfads params=’groups=-1′]

Do the following to redirect http requests to https running on Debian Linux with Apache Web Server.

File : /etc/apache2/ports.conf

[code]
NameVirtualHost *:80
Listen 80
[/code]

File : /etc/apache2/sites-availabe/default

[code]
<VirtualHost *:80>
ServerName www.example.com
Redirect / https://www.example.com/
</VirtualHost>

<VirtualHost *:443>
ServerName www.example.com
# … SSL configuration goes here
</VirtualHost>
[/code]

Restart Apache Webserver

[code]
/etc/init.d/apache2 restart
[/code]

[dfads params=’groups=-1′]