Monday, October 8, 2012

Simple code for Ajax with Hibernate

1. Create one dynamic application in eclipse and add below jar file in class path as well in WEB-INF\lib folder:
antlr-3.1.jar
cglib-nodep-2.1_3.jar
commons-collections-3.2.jar
commons-logging-1.1.jar
dom4j-1.1.jar
hibernate-3.2.5.ga.jar
hibernate-annotations-3.4.0.GA.jar
hibernate-commons-annotations-3.3.0.ga.jar
log4j-1.2.15.jar
mysql-connector-java-3.1.12-bin.jar
persistence-api-1.0.jar
slf4j-api-1.5.10.jar
slf4j-log4j12-1.5.10.jar
transaction-api-1.1.jar

2. Create one servlet Login.java


package com.novell;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;



public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
private SessionFactory sessionFactory = null;
private Session session;
 
    public Login() {
        super();
        sessionFactory  = new AnnotationConfiguration().configure().buildSessionFactory();
       
        System.out.println("IT IS SESSION :"+session);
     }

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("It is get method ..........");
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userName = request.getParameter("userName");
String password = request.getParameter("password");
 HttpSession httpSession = request.getSession();
int userid = checkCredential(userName,password);
if(userid==0){
   httpSession.setAttribute("message", "Your Credential is wrong ........");
 RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
 rd.forward(request, response);
}else{
httpSession.setAttribute("message", "You are welcome ..........");
CalculatorState temp = getCalState(userid);
if(temp == null){
temp = new CalculatorState();
temp.setUserId(userid);
temp.setFirstValue(0);
temp.setSecondValue(0);
}
httpSession.setAttribute("state", temp);
RequestDispatcher rd = request.getRequestDispatcher("ucalc.jsp");
rd.forward(request, response);
}

}

private int checkCredential(String userName, String password){
session =sessionFactory.openSession();
List users = session.createQuery("from User where userName = '"+userName+"' and password= '"+password+"'").list();
session.close();
if(users.size()>0){return users.get(0).getId();}
else{return 0;}
}

private CalculatorState getCalState(int id){
session =sessionFactory.openSession();
List calculatorState = session.createQuery("from CalculatorState where userId = "+id).list();
System.out.println("Size of state POJO :"+calculatorState.size());
session.close();
if(calculatorState.size()==0){return null;}
else {return calculatorState.get(0);}

}

}

3. Other Servlet : Calculator.java

package com.novell;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

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



import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;



public class Calculator extends HttpServlet {
private static Logger logger = Logger.getLogger(Calculator.class.getName());
private static final long serialVersionUID = 1L;
Map stragetyMap = new HashMap();
    private SessionFactory sessionFactory = null;
  private Session session;


    public Calculator() {
        super();
        sessionFactory  = new AnnotationConfiguration().configure().buildSessionFactory();
        logger.info("Servlet constructor is calling ...........");
        stragetyMap.put("add", new MainStrategy(new AddCalc()));
        stragetyMap.put("sub", new MainStrategy(new SubCalc()));
        stragetyMap.put("multi", new MainStrategy(new MultiCalc()));
        stragetyMap.put("div", new MainStrategy(new DivideCalc()));
       
    }

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
logger.info("Hitting to server ............");
String first = request.getParameter("first");
String second = request.getParameter("second");
String operation = request.getParameter("operation");
String useridUI = request.getParameter("userid");
logger.info("First Number :"+first);
logger.info("Second Number :"+second);
logger.info("User id :"+useridUI);
saveLatestData(useridUI,first,second);
// int result = calculation(Integer.parseInt(first),Integer.parseInt(second),operation);
int result = ((MainStrategy)stragetyMap.get(operation)).cal(Integer.parseInt(first),Integer.parseInt(second));
saveLatestData(useridUI,first,result+"");
response.setContentType("text/html");
response.getWriter().write(result+"");
}
 
/*public int calculation(int first,int second,String operation){
MainStrategy mainStrategy = null;
if(operation.equals("add")){mainStrategy = new MainStrategy(new AddCalc());}
if(operation.equals("sub")){mainStrategy = new MainStrategy(new SubCalc());}
if(operation.equals("multi")){mainStrategy = new MainStrategy(new MultiCalc());}
if(operation.equals("div")){mainStrategy = new MainStrategy(new DivideCalc());}
return mainStrategy.cal(first, second);
}*/

private void saveLatestData(String useridUI,String first,String second){
int firstNumber  = Integer.parseInt(first);
int secondNumber = Integer.parseInt(second);
int id = Integer.parseInt(useridUI);
CalculatorState cs = new CalculatorState();
cs.setUserId(id);
cs.setFirstValue(firstNumber);
cs.setSecondValue(secondNumber);
updateCalState(cs);
}

private void updateCalState(CalculatorState cs){
try{
session =sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
session.saveOrUpdate(cs);
transaction.commit();
session.flush();
   session.close();
}catch(Exception e){
e.printStackTrace();
System.out.println("Some issue while saving new data .......");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
logger.info("It is Post Method ............");
doGet(request,response);
}

}


4. login.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>Calculator Login</title>
<script src="jquery.js"></script>
<script src="login.js" type="text/javascript"></script>
</head>
<body>
<h2>Please login to open your calculator</h2>
<%
 String message = (String)session.getAttribute("message");
 if(message!=null){
  out.println(message);
 }
%>
<form action="Login" method="post">
<table>
<tr><td>Please Enter User Name :</td><td><input type="text" id="userName" name="userName" /></td></tr>
<tr><td>Please Enter Password  :</td><td><input type="password" id="password" name="password"/></td></tr>
<tr><td><input type="submit" id="loginButtonSubmit" value="Submit"/></td><td><input type="button" value="Clear" id="clear"/></td></tr>
</table>
</form>
</body>
</html>


5. ucalc.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>Simple Calculator</title>
<script type="text/javascript" src="ucal.js"></script>
<jsp:useBean id="state" class="com.novell.CalculatorState" scope="session"/>
</head>
<body>
It is simple Calculator
<br>
<input type="hidden" id="hiddenId" value="${state.userId}"/>
<input type="text" id="firstNumber" value="${state.firstValue}"/>
<input type="button" id="addButton" value="Add" onclick="addAction()"/>
<input type="text" id="secondNumber" readonly="readonly" value="${state.secondValue}"/>
<input type="button" id="clearButton" value="Clear" onclick="clearInput()"/>
</body>
</html>

6. ucal.js
var request;

function getRequest(){
      if(window.ActiveXObject){
        request = new ActiveXObject("Microsoft.XMLHTTP"); 
       }else if(window.XMLHttpRequest){
        request = new XMLHttpRequest(); 
      } 
    }

function addAction(){
 var first = document.getElementById("firstNumber").value;
 if(first==null||first==""){
alert("Please enter first number");
return null;
 }
 var second = document.getElementById("secondNumber").value;
 if(second==null||second==""){
second = 0;
 }
 var id = document.getElementById("hiddenId").value;
 //alert("Id :"+id);
 calculation(first, second, "add",id);
}

function calculation(first, second, operation,userid){
 getRequest();
 var url = "http://localhost:8080/Calculator/Calculator?first="+first+"&second="+second+"&operation="+operation+"&userid="+userid;
 //alert(url);
 request.open("POST",url,false);
 request.onreadystatechange = showResult;
 request.send();
}

function calculation2(first, second, operation){
getRequest();
var url = "http://localhost:8080/Calculator/Calculator";
     request.open("POST",url,false);
request.onreadystatechange = showResult;
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send("first="+first+"&second="+second+"&operation="+operation); // Why Null
 }

function showResult(){

if(request.readyState == 4){
        var result = request.responseText;
        document.getElementById("secondNumber").value = result;
   }

}
function clearInput(){
document.getElementById("firstNumber").value="";
document.getElementById("secondNumber").value="";
}

7. User.java
package com.novell;

public class User {

private int id;
private String userName;
private String password;
 
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
 
 
}


8. CalculatorState.java
package com.novell;

public class CalculatorState {
private int userId;
private int firstValue;
private int secondValue;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getFirstValue() {
return firstValue;
}
public void setFirstValue(int firstValue) {
this.firstValue = firstValue;
}
public int getSecondValue() {
return secondValue;
}
public void setSecondValue(int secondValue) {
this.secondValue = secondValue;
}

}


9. Cal.hbm.xml
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="com.novell.CalculatorState" table="calculator">
<id name="userId" column="id">
<generator class="assigned" />
</id>
<!-- Both property are optional here as property name and column name are same -->
<property name="firstValue" column="firstValue" />
<property name="secondValue" column="secondValue" />
</class>
</hibernate-mapping>


10. User.hbm.xml
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="com.novell.User" table="login">
<id name="id" column="id">
<generator class="increment" />
</id>
<!-- Both property are optional here as property name and column name are same -->
<property name="userName" column="userName" />
<property name="password" column="password" />
</class>
</hibernate-mapping>


11. hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"          
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:mysql://localhost/sumandb</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.username">root</property>
<property name="connection.password">mysql</property>
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<!-- this will show us all sql statements -->
<property name="hibernate.show_sql">true</property>
<!-- mapping files -->
<mapping resource="Cal.hbm.xml" />
<mapping resource="User.hbm.xml" />
</session-factory>
</hibernate-configuration>





Sunday, September 27, 2009

Ant Script for JBOSS Server Start and Stop

<property name="JBOSS_HOME" value="C:\jboss-4.2.2.GA" />

<target name="serverON">
<exec executable="cmd">
<arg value="/c" /> <
arg value="${JBOSS_HOME}/bin/run.bat" />
</exec>
</target>

<target name="serverOFF">
<exec executable="cmd">
<arg value="/c" />
<arg value="${JBOSS_HOME}/bin/shutdown.bat -S" />
</exec>
</target>

Wednesday, June 24, 2009

How to set wait in javascript, JavaScript Delay, JavaScript wait, JavaScript pause



You can use setTimeout() method or false loop to acheive wait functionlity in JavaScript. There is no such wait() or sleep() methods are here in JavaScript.

1. First Example with setTimeout()
Write one Time1.html and paste below code

<html>
CHECK FOR WAIT IN JAVA SCRIPT
<script type="text/javascript" language="javascript1.2">

function waitCheck(){
alert("Binod Kumar Suman");
setTimeout(function(){secondMethod()},2000);
}

function secondMethod(){
alert("Target Corporation");
}

</script>
<br>

<input type="button" value="Check" onClick="waitCheck()"/>
</html>

Just do double click on Time1.html you will get one alert immedialty but only after 2 seconde you will next alert message.

2. Second Example with false loop
Write one Time2.html and paste below code

<html>
CHECK FOR WAIT IN JAVA SCRIPT
<script type="text/javascript" language="javascript1.2">
function waitCheck(){
alert("Binod Kumar Suman");
pauseJS(1500);
secondMethod();
}

function secondMethod(){
alert("Target Corporation");
}

function pauseJS(timeInMilliS) {
var date = new Date();
var curDate = null;
do { curDate = new Date(); }
while(curDate-date < timeInMilliS);
}

</script>
<br>
<input type="button" value="Check" onClick="waitCheck()"/>
</html>

Just do double click on Time2.html you will get one alert immedialty but only after 2 seconde you will next alert message. :)

Monday, May 11, 2009

Download the image from Servlet usign core java code

For download the image from Servlet usign core java code
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class Download {

public static void main(String args[]) throws Exception {
String url = "http://localhost:9080/mYWebApp/sendImage/Fashion/shirt.jpg";
URL u = new URL(url);
URLConnection uc = u.openConnection();
String contentType = uc.getContentType();
int contentLength = uc.getContentLength();
if (contentType.startsWith("text/")|| contentLength == -1) {
throw new IOException("This is not a binary file.");
}
InputStream raw = uc.getInputStream();
InputStream in = new BufferedInputStream(raw);
byte[] data = new byte[contentLength];
int bytesRead = 0;
int offset = 0;
while (offset < contentLength) {
bytesRead = in.read(data, offset, data.length - offset);
if (bytesRead == -1)
break;
offset += bytesRead;
}
in.close();

if (offset != contentLength) {
throw new IOException("Only read " + offset + " bytes; Expected " + contentLength + " bytes");
}

System.out.println("DATA :: "+u.getFile());
String filename = u.getFile().substring(u.getFile().lastIndexOf('/') + 1);
System.out.println("FILE NAME :: "+filename);
FileOutputStream out = new FileOutputStream(filename);
out.write(data);
out.flush();
out.close();
}
}

Wednesday, February 11, 2009

How to show Image on JSP page from My Computer Folder

Webpage NEVER allow the to access any local files. Means if you write <img src="c:\ImageFolder\Binod.jpg"/> in the jsp file, it will NOT work. (It can work only in some editor, but it will not work using internet explorer)
first.jsp
<html>
<head>
<title>Binod Show Image</title>
</head>
<body>
<h1> BINOD FROM IMAGE SHOW PROJECT </h1>
<img src="c:\ImageFolder\Binod.jpg" width="100" height="100"/></body>
</html>
It will not work.
Then how to show Image on JSP page from local computer drive.
SOLUTION: You have to use servlet to show image on jsp file
1. Servlet SendImage.java
2. first.jsp
3. Change in web.xml
SendImage.java
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SendImage extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
static final long serialVersionUID = 1L;
String image_name = "";
ResourceBundle props = null;
String filePath = "";
private static final int BUFSIZE = 100;
private ServletContext servletContext;
public SendImage() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("FROM SERVLET");
sendImage(getServletContext(), request, response);
}
public void sendImage(ServletContext servletContext,
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.servletContext = servletContext;
String reqUrl = request.getRequestURL().toString();
StringTokenizer tokens = new StringTokenizer(reqUrl, "/");
int noOfTokens = tokens.countTokens();
String tokensString[] = new String[noOfTokens];
int count = 0;
while (tokens.hasMoreElements()) {
tokensString[count++] = (String) tokens.nextToken();
}
String folderName = tokensString[noOfTokens - 2];
image_name = tokensString[noOfTokens - 1];
filePath = "/" + folderName + "/" + image_name;
String fullFilePath = "c:/ImageFolder" + filePath;
System.out.println("FULL PATH :: "+fullFilePath);
// doShowImageOnPage(fullFilePath, request, response);
doDownload(fullFilePath, request, response);
}
private void doShowImageOnPage(String fullFilePath,
HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.reset();
response.setHeader("Content-Disposition", "inline");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Expires", "0");
response.setContentType("image/tiff");
byte[] image = getImage(fullFilePath);
OutputStream outputStream = response.getOutputStream();
outputStream.write(image);
outputStream.close();
}
private void doDownload(String filePath, HttpServletRequest request,
HttpServletResponse response) throws IOException {
File fileName = new File(filePath);
int length = 0;
ServletOutputStream outputStream = response.getOutputStream();
// ServletContext context = getServletConfig().getServletContext();
ServletContext context = servletContext;
String mimetype = context.getMimeType(filePath);
response.setContentType((mimetype != null) ? mimetype
: "application/octet-stream");
response.setContentLength((int) fileName.length());
response.setHeader("Content-Disposition", "attachment; filename=\""
+ image_name + "\"");
byte[] bbuf = new byte[BUFSIZE];
DataInputStream in = new DataInputStream(new FileInputStream(fileName));
while ((in != null) && ((length = in.read(bbuf)) != -1)) {
outputStream.write(bbuf, 0, length);
}
in.close();
outputStream.flush();
outputStream.close();
}
private byte[] getImage(String filename) {
byte[] result = null;
String fileLocation = filename;
File f = new File(fileLocation);
result = new byte[(int)f.length()];
try {
FileInputStream in = new FileInputStream(fileLocation);
in.read(result);
}
catch(Exception ex) {
System.out.println("GET IMAGE PROBLEM :: "+ex);
ex.printStackTrace();
}
return result;
}
}
2. first.jsp
<html><head><title>Binod Show Image</title></head><body><h1> BINOD FROM IMAGE SHOW PROJECT </h1>
<img src="http://localhost:8080/ImageShow/SendImage/12/Binod.jpg" width="100" height="100"/>
</body></html>
3. Update in web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd%22&gt;
<display-name> ImageShow</display-name>
<servlet>
<description> </description> <display-name> SendImage</display-name>
<servlet-name>SendImage</servlet-name>
<servlet-class> SendImage</servlet-class>
</servlet> <servlet-mapping> <servlet-name>SendImage</servlet-name>
<url-pattern>/SendImage/*</url-pattern> </servlet-mapping>
</web-app>

use this URL, now its work. :)
http://localhost:8080/ImageShow/first.jsp

Tuesday, December 16, 2008

How to make servlet for dowload image option

Suppose you have to write one serlvet, who would be give the download the image as save or open option.

This servelt should pick up the image as per the URL parameter from local drive and give the option of save or option image on your disk.

1. Make one Servlet SendImage

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SendImage extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

private SendImageHelper sendImageHelper;

public SendImage() {
super();
sendImageHelper = new SendImageHelper();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
sendImageHelper.sendImage(getServletContext(),request,response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}

}
2. One java file SendImageHelper.java

package com.tgt.image.sendimage.service;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.StringTokenizer;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SendImageHelper {

String image_name = "";
List imageTypes = new ArrayList();
List numbers = new ArrayList();
ResourceBundle props = null;
String filePath = "";

private static final int BUFSIZE = 100;
private ServletContext servletContext;

public void sendImage(ServletContext servletContext,HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
this.servletContext = servletContext;
String reqUrl = request.getRequestURL().toString();
StringTokenizer tokens = new StringTokenizer(reqUrl,"/");
int noOfTokens = tokens.countTokens();
String tokensString[] = new String[noOfTokens];
int count=0;
while(tokens.hasMoreElements()){
tokensString[count++] = (String)tokens.nextToken();
}

String folderName = tokensString[noOfTokens-2];
image_name = tokensString[noOfTokens-1];
filePath="/"+folderName+"/"+image_name;
fullFilePath = "c:/ImageFolder"+filePath;
//doShowImageOnPage(fullFilePath, request, response);
doDownload(fullFilePath, request, response);
}

private void doShowImageOnPage(String fullFilePath,HttpServletRequest request, HttpServletResponse response) throws IOException {
response.reset();
response.setHeader("Content-Disposition", "inline" );
response.setHeader("Cache-Control","no-cache");
response.setHeader("Expires","0");
response.setContentType("image/tiff");
byte[] image = getImage(fullFilePath);
OutputStream outputStream = response.getOutputStream();
outputStream.write(image);outputStream.close();
}

private void doDownload(String filePath,HttpServletRequest request, HttpServletResponse response) throws IOException {
File fileName = new File(filePath);
int length = 0;
ServletOutputStream outputStream = response.getOutputStream();
//ServletContext context = getServletConfig().getServletContext();
ServletContext context = servletContext;
String mimetype = context.getMimeType(filePath);

response.setContentType( (mimetype != null) ? mimetype : "application/octet-stream" );
response.setContentLength( (int)fileName.length() );
response.setHeader( "Content-Disposition", "attachment; filename=\"" + image_name + "\"" );

byte[] bbuf = new byte[BUFSIZE];
DataInputStream in = new DataInputStream(new FileInputStream(fileName));
while ((in != null) && ((length = in.read(bbuf)) != -1)){
outputStream.write(bbuf,0,length);
}

in.close();
outputStream.flush();
outputStream.close();
}

}