Showing posts with label JSP. Show all posts
Showing posts with label JSP. Show all posts

Friday, June 6, 2014

Java - To Load a property file

Property files are used to store static information in a key-value pair. Things that you do not want to hard code in your Java code, which tend to change in future goes into properties files. Also as it is a static information you do not want to load the property file for each and every request as it may hamper performance. You may need it to be loaded only once at the begining of the loading of application.

You can load properties file using below methods. You can provide absolute path as well as relative path however mostly relative path is preferred.

prop.load(AppProperties.class.getClassLoader().getResourceAsStream("app.properties"));
OR
prop.load(new FileInputStream(new File("C:/temp/app.properties")));

Please see the self explanatory java code below - 

Wednesday, January 29, 2014

Monday, February 18, 2013

JSP example - Google Recaptcha validation using jquery (AJAX)


Below is the example for Google Recaptcha validation using jquery(AJAX).

What is reCAPTCHA?

reCAPTCHA is a free CAPTCHA service that protects your site against spam, malicious registrations and other forms of attacks where computers try to disguise themselves as a human; a CAPTCHA is a Completely Automated Public Turing test to tell Computers and Human Apart. reCAPTCHA comes in the form of a widget that you can easily add to your blog, forum, registration form, etc.

To know more about Google recaptcha, please see below links
http://www.google.com/recaptcha
https://developers.google.com/recaptcha/

Please see self explanatory JSP code below. To run below example add recaptcha4j-0.0.7.jar file in your applications classpath.

test.jsp

Wednesday, January 23, 2013

JavaScript - onscroll function not working


Today I faced a weird issue, when I add below DOCTYPE in HTML or JSP file onscroll function stops working

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

Also I saw that, document.body.scrollTop is always coming as 0 and document.body.scrollHeight & document.body.clientHeight are always same no matter where my scroll bar is.

I didn't get much time to do research on it however to resolve this I modified DOCTYPE as shown below. If you need quick fix please add below DOCTYPE in your HTML or JSP file.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

If I find more info on it, I will update the post.

Friday, January 11, 2013

Javascript - Unterminated string constant


If you receive below error, check at the specified line. As the error suggest, most probably you have added a line break or some incorrect syntax. To resolve the error just remove the line break or check for proper syntax and the error would go off.

Message: Unterminated string constant
Line: 443

 If you are using Linux, check for line break using below command in vi editor. It will show you symbol '$' at the end of each line. Just remove the line break at the specified line.

 :se list

As the error suggest 'Unterminated string constant', mostly it may occur due to some incorrect syntax.

Tuesday, January 8, 2013

JavaScript - How to get random numbers and random alpha-numeric numbers?


In this article we will see how to generate random numbers and alpha-numeric numbers in JavaScript  We will use JavaScript Math.random function to generate random numbers.

Math.random function returns a floating-point, pseudo-random number in the range [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive), which you can then scale to your desired range.

Please see the below function.


1. Get random numbers

//get random numbers
function getRandomNumber() {
var max = 10;
var randomnumber = Math.floor(Math.random()*max)
return randomnumber;
}

2. Get random numbers between minimum and maximum range

//get random numbers between minimum and maximum range
function getRandomNumber() {
var min = 10;
var max = 20;
var randomnumber = Math.floor((Math.random()*(max - min + 1))+min);
return randomnumber;
}


Tuesday, November 6, 2012

MySQL - JDBC example for BLOB storage

A blob (binary large object) is a collection of binary data stored as a single entity in a database. Blobs can be used to store images, audio or other multimedia files. There are four variation of blob datatype -
  • TINYBLOB - Maximum length of 255 (2^8 - 1) characters i.e 25 bytes
  • BLOB - Maximum length of 65535 (2^16 - 1) characters i.e 64 KB
  • MEDIUMBLOB - Maximum length of 16777215 (2^24 - 1) characters i.e 16 MB
  • LONGBLOB - Maximum length of 4294967295 (2^32 - 1) characters i.e 4GB

About the example: We will create a table in mySql and see how to insert/reterive an image using JDBC.

First lets create a table in MySQL. Please see the syntax below, we have used MEDIUMBLOB as it would be sufficient for medium size object stotage. You can use any other as per your requirement. We have just 3 columns pic_id as a auto increment primary key, pic_name will hold the picture name and pic_file a blob which will store actual picture.

CREATE TABLE blobtest (
pic_id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (pic_id),
pic_name VARCHAR(100) NOT NULL,
pic_file MEDIUMBLOB
);


Monday, November 5, 2012

How to iterate Java object in JavaScript using JSON?


You may require passing a java object to javascript and iterating through it. Java object could be literally anything whether it List, Map, List of Map, Map of List etc.
For example: ArrayList<String>, Hashtable<String,String>, ArrayList<Hashtable<String,String>>, Hashtable<String,ArrayList<String>> etc.

This can be easily achieved using JSON. To run below JSP you need to include json-simple-1.1.1.jar in classpath. Download the JAR file from http://code.google.com/p/json-simple/

About the example: In below example I have created a java object i.e. HashMap<String, ArrayList<String>>. Add some values to the object. Convert the object into JSON string using method JSONValue.toJSONString(). In JavaScript pass the JSON string to JSON.parse() and get the corresponding JavaScript object. Now you are ready to iterate it using below syntax. Please see the self explanatory example below.

Thursday, November 1, 2012

JSTL: How to access fmt:message from Javascript


You might have seen How to use fmt:message and ResourceBundle from JSP and Java in my earlier post, click here.

Now we will see how to use fmt:message from Javascript. Its very simple to use JSTL's fmt tag in JavaScript to localize alert messages.

I found two ways in which you can access values from a property file in javascript. Please see the sample codes below.

Method 1.

<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<script type="text/javascript">
<!--
var msg = {
prop1: "<fmt:message key="prop1" />",
prop2: "<fmt:message key="prop2" />"
};

function test() {  
 alert(msg.prop1);
alert(msg.prop2);
}

//-->
</script>

Method 2.

<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<script type="text/javascript">
<!--
<fmt:message key="prop1" var="prop1"/>    
var prop1 = "${prop1}";

function test() {  
 alert(prop1);
}

//-->
</script>

Saturday, September 8, 2012

How to create a Jigsaw puzzle using JSP and Javasacript?


What is Jigsaw puzzle?
A Jigsaw puzzle is a tiling puzzle that requires the assembly of numerous small pieces. Each piece usually has a small part of a picture on it; when complete, a jigsaw puzzle produces a complete picture.

In this article we will see how to create a Jigsaw puzzle using javascript. Initially you will require to cut an image into various pieces, that can be done using a simple java program.

Please see the below Java program that will cut an image into number of pieces for a Jigsaw puzzle. Just provide the desire number of rows and column, it will automatically cut an image into that number of pieces.

Please see the self explanatory Java program below

Sunday, September 2, 2012

Java / JSP : Simple image cropping example


In this article we will see how to crop an image in Java. You are in this page then u might surely know what exactly the Image cropping is, it is nothing but removal of the outer parts of an image  to improve framing, to change aspect ratio etc.

Image cropping can be implemented easily using Java. First lets see the basic example of image cropping. In the below code we have used getSubimage() function of BufferedImage to achive image cropping feature. No need to add any Jar file directly you can run below code and see the output.

Please see the self explanatory java code below.

Monday, June 18, 2012

DWR Hello World example

DWR - Direct Web Remoting

DWR is a Java library that enables Java on the server and JavaScript in a browser to interact and call each other as simply as possible. In simple words DWR is Easy Ajax for Java. Unlike AJAX you don't have to write codes to get XHTML object or check for state change etc. To know more about DWR, click here.

DWR is supported by almost all browsers like Firefox,Internet Explorer,Opera and Safari. To know more, click here.

About the example

We will create a simple java class (i.e HelloWorld.java) with a method sayHello() which will accept a name and print Hello name. We can call this java fuction with JavaScript in a browser. Same as Ajax call without refreshing the whole page.

Below are the steps to run the example.

1. For running the below example you need to add below mentioned JAR file in lib folder of your web project.

  • dwr.jar
  • commons-logging-1.1.1.jar 

For downloading dwr.jar, click here
commons-logging-1.1.1.jar, click here.


2. Add the DWR servlet definition and mapping to your application's web.xml. This is just like defining a normal servlet.


<servlet>
  <display-name>DWR Servlet</display-name>
  <servlet-name>dwr-invoker</servlet-name> 
  <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
  <init-param>
     <param-name>debug</param-name>
     <param-value>true</param-value>
  </init-param>
</servlet>
 
<servlet-mapping>
  <servlet-name>dwr-invoker</servlet-name>
  <url-pattern>/dwr/*</url-pattern>
</servlet-mapping>

Monday, August 15, 2011

JSP page life-cycle phases


JSP page life-cycle phases
Phase Name Description
Page translation The page is parsed and a Java file containing the corresponding servlet is created.
Page compilation The Java file is compiled.
Load class The compiled class is loaded.
Create instance An instance of the servlet is created.
Call jspInit() This method is called before any other method to allow initialization.
Call _jspService() This method is called for each request.
Call jspDestroy() This method is called when the servlet container decides to take the servlet out of service.

Wednesday, February 9, 2011

JSP : According to TLD or attribute directive in tag file, attribute value does not accept any expressions.

While using JSTL in one of my project i was getting an error message According to TLD or attribute directive in tag file, attribute value does not accept any expressions.


Initially i thought there might be some issue with Eclipse or jar file jstl.jar but i was unable to solve it. Latter on a web i found the below code.


<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>

 It really worked. So i wanted to share with u. thanks to whoever discovered it.

Thursday, February 19, 2009

JSP : Write Log Datewise

Writing logs in JSP..

Here is the code you can use to write log Every day Datewise(dd-mm-yyyy).
You can use in in you code JSP or Servlet.

you need to import following

import java.util.*;
import java.text.*;
import java.io.*;

Add following lines in your code accordingly


// open file to write date wise logs
SimpleDateFormat df = new SimpleDateFormat("dd-MMMM-yyyy");
java.util.Date date = new java.util.Date();
String today = df.format(date);

//Provide file in which log to be written
BufferedWriter outlog = outlog = new BufferedWriter(new FileWriter("D:\\Log_"+today+".log", true));

outlog.write("1st Line \n");........... //used "\n" as line seperator
outlog.write("2nd Line ");
outlog.newLine(); .....................//used outlog.newLine() as line seperator
outlog.write("3rd Line ");


//flush BufferedWriter at the end
outlog.flush();
outlog.close();

Saturday, January 24, 2009

JSP : Simple File Uploading Codes.

We will see how to upload a file using JSP, you can upload a file to your desire location with desire name. Please see the simple self explanatory codes below.

Please add below mentioned jar files in your applications classpath.





1st HTML interface (can be used in JSP as well)

FileUploadingInterface.HTML


<HTML>
<HEAD>
<TITLE>File Uploading Interface</TITLE>
</HEAD>
<BODY>
<center>
<h3>Simple File Uploading Example</h3>
<form action="ProcessUploadedFile.jsp" method="post" enctype="multipart/form-data">
Name <input type="text" name="userName"> (optional) </br></br>
File <input type="file" name="file1"> </br></br> <!-- Here You Can Add more numbers of Files For Uploading -->
<input type="submit" value="Submit">
</form>
</center>
</BODY>
</HTML>



2nd JSP code


ProcessUploadedFile.jsp


<%@ page import="java.io.*" %>
<%@ page import="java.util.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%
boolean isMultipart = ServletFileUpload.isMultipartContent(request);

if (!isMultipart)
{
}
else
{
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try
{
items = upload.parseRequest(request);
}
catch (FileUploadException e)
{
e.printStackTrace();
}

Iterator itr = items.iterator();

while (itr.hasNext())
{
FileItem item = (FileItem) itr.next();

//Get Other Form Fileds Values in this Block
if (item.isFormField())
{
String itemName = item.getFieldName();
String itemValue = item.getString();
String name = "";
if (itemName.equals("userName"))
name = item.getString();

out.println("User Name "+name);
}
//Get File type Values Here, it could be one or multiple File
else
{
try
{
String itemName = item.getName();

//userFieldName is what u provided in html file
String userFieldName = item.getFieldName();

if(itemName != null)
{
if(itemName.equals(""))
{
//If Nothing Uploaded
out.println("No File Uploaded");
}
else
{
//Provide Destination Folder, Where Uploaded File to be saved
boolean folderMade = (new File("d:/UploadedFileFolder")).mkdirs();

// This is required to filter out file name from complete file path.
int idx = itemName.lastIndexOf("\\");

String filename = "";

if(idx > -1)
{
//in case of IE, it sends complete path. Hence only file name must be filtered out.
idx=idx+1;
filename = itemName.substring(idx);
}
else
{
//in case of other borwsers, its just filename
filename = itemName;
}

File savedFile = new File("d:/UploadedFileFolder/"+filename);
item.write(savedFile);

//Get path of the saved file
String path = savedFile.getPath();

out.println("File Uploaded Sucessfully "+path);

}
}
}//try
catch(Exception e)
{
e.printStackTrace();
}
}//else
}//while
}//else
%>