Showing posts with label servlet. Show all posts
Showing posts with label servlet. Show all posts

Thursday, May 24, 2012

Servlet to export jasper report in excel

Its very important issue to export jasper report to excel format. This can be done through a servlet in JSP application. The servlet code may be as bellow:

In tis case I have used some code as part of many times edit. It can be summarize.


This servlet is able to handle different no. of parameters and different reports.

We just need to call this servlet as below:

link = "/JRExcelExport?rname=candidateList&pname=posiCode=" + posiCode + "@qValue1=" + qValue1 + "@qValue2=" + qValue2 ;
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(link);
dispatcher.forward(request, response);

The value of rname is the name of the report. And all the parameters would be attached after the pname

package dbbl.paul.recruitment.servlets;

import dbbl.paul.recruitment.dal.dbconnector.ConnectionHandler;
import java.io.*;
import java.sql.Connection;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.*;

import net.sf.jasperreports.engine.export.JExcelApiExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import org.apache.log4j.Logger;


public class JRExcelExport extends HttpServlet {

final static Logger logger = Logger.getLogger(ReportManager.class);

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
logger.trace("Trying to Generate report:processRequest");

String mailMessage = "";
String folder = "/reports/";
JasperPrint jasperPrint = null;

String rpt_name = request.getParameter("rname");
String report_name = rpt_name + ".jasper";
String file_name = folder + report_name;

mailMessage = "RPTNAME=" + rpt_name;
System.out.println("Report Name: " + file_name);
try {
HashMap hm = new HashMap();
String param_name = request.getParameter("pname");
System.out.println(param_name);

if (param_name != null) {

if (!param_name.equals("")) {
String split_param[] = param_name.split("@");
String tmp_param[];
for (int i = 0; i < split_param.length; i++) { System.out.println(split_param); tmp_param = split_param[i].split("="); hm.put(tmp_param[0], tmp_param[1].replaceAll("NULL", "")); } } mailMessage = mailMessage + ". PARAMETERS collected successfully"; } ServletOutputStream servletOutputStream = response.getOutputStream(); File reportFile = new File(getServletConfig().getServletContext().getRealPath(file_name)); Connection con = null; try { con = ConnectionHandler.getConnection_OnlineJob(); jasperPrint = JasperFillManager.fillReport(reportFile.getPath(), hm, con); generateXLSOutput(rpt_name, jasperPrint, response); } catch (JRException e) { // display stack trace in the browser logger.error(e); StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); e.printStackTrace(printWriter); response.setContentType("text/plain"); response.getOutputStream().print("Could not display report temporarily..."); //response.getOutputStream().print(stringWriter.toString()); mailMessage = mailMessage + ".ERROR catched when creating report."; } } catch (Exception e) { System.out.println(e.getMessage()); logger.error(e); } finally { logger.info(mailMessage); } } private void generateXLSOutput(String reportname, JasperPrint jasperPrint, HttpServletResponse resp) { String reportfilename = reportname + ".xls"; try { JExcelApiExporter exporterXLS = new JExcelApiExporter(); exporterXLS.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint); exporterXLS.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, Boolean.TRUE); exporterXLS.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE); exporterXLS.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE); exporterXLS.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, resp.getOutputStream()); resp.setHeader("Content-Disposition", "inline;filename=" + reportfilename); resp.setContentType("application/vnd.ms-excel"); exporterXLS.exportReport(); } catch (Exception ex) { logger.trace(ex); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override public String getServletInfo() { return "Short description"; }//
}

Tuesday, November 8, 2011

Difference between sendRedirect and forward

sendRedirect is the marriage which is leagal as both the parties know each other and faithful.
forward: where one of the party cheats and contacts to third party.. a illicit relationship..

Probably this will make a clear concept to us, as all time we like to thinks in different way.

So, from the above we are sure about the family where Hubby and wife don't hide anything from each other. They share to each others every thing. Suppose, coming back from office, Husband request to make a cup of tea to his lovely wife. Wife is busy with her favorite TV serials. So, she tells the maid servant to mak the tea for him. Beside this Wife also inform his hubby about the maker of the tea and request to get tea from the servant. Then hubby will take the update of the tea from the servant.

On the contrary, in another family getting the request of tea from the husband, wife asked to make tea another one but after completion she must provide the tea directly to his wife.

First Family is sendRedirect and the second one is forward.

sendRedirect() sends a redirect response back to the client's browser. The browser will normally interpret this response by initiating a new request to the redirect URL given in the response.

forward() does not involve the client's browser. It just takes browser's current request, and hands it off to another servlet/jsp to handle. The client doesn't know that they're request is being handled by a different servlet/jsp than they originally called.

Sendredirect( ) : javax.Servlet.Http.HttpServletResponce interface
- RequestDispatcher.SendRedirect( ) works on the browser.
- The SendRedirect( ) allows you to redirect trip to the Client.
- The SendRedirect( ) allows you to redirect to any URL.
- After executing the SendRedirect( ) the control will not return back to same method.
- The Client receives the Http response code 302 indicating that temporarly the client is being redirected to the specified location , if the specified location is relative , this method converts it into an absolute URL before redirecting.
- The SendRedirect( ) will come to the Client and go back,.. ie URL appending will happen.





Forward( ) : javax.Servlet.RequestDispatcher interface.

- RequestDispatcher.forward( ) works on the Server.
- The forward( ) works inside the WebContainer.
- The forward( ) restricts you to redirect only to a resource in the same web-Application.
- After executing the forward( ), the control will return back to the same method from where the forward method was called.
- The forward( ) will redirect in the application server itself, it doesn't come back to the client.
- The forward( ) is faster than Sendredirect( ) .

Sunday, August 14, 2011

show Image from database in jsp


We can provide a servlet as the source of the image. ans in the servlet we need to some little cook. This code may help you in the regards.

/*
* This Method Returns the right MIME type for a particular format
*


* @param String format ex: xml or HTML etc.
* @return String MIMEtype
*/
private String getMimeType(String format)
{
if(format.equalsIgnoreCase("pdf")) //check the out type
return "application/pdf";
else if(format.equalsIgnoreCase("audio_basic"))
return "audio/basic";
else if(format.equalsIgnoreCase("audio_wav"))
return "audio/wav";
else if(format.equalsIgnoreCase("image_gif"))
return "image/gif";
else if(format.equalsIgnoreCase("image_jpeg"))
return "image/jpeg";
else if(format.equalsIgnoreCase("image_bmp"))
return "image/bmp";
else if(format.equalsIgnoreCase("image_x-png"))
return "image/x-png";
else if(format.equalsIgnoreCase("msdownload"))
return "application/x-msdownload";
else if(format.equalsIgnoreCase("video_avi"))
return "video/avi";
else if(format.equalsIgnoreCase("video_mpeg"))
return "video/mpeg";
else if(format.equalsIgnoreCase("html"))
return "text/html";
else if(format.equalsIgnoreCase("xml"))
return "text/xml";
else
return null;
}

Step Two
Get the reference to the right OutPutStream. Use ServletOutPutStream, where as for character data you'd use PrintWriter, the java.io class that prints objects to a text-output stream. This following snippet is for binary data:


ServletOutputStream sOutStream = response.getOutputStream();

Step Three
Create BufferedInputStream from the InputStream:


BufferedInputStream bis = null;
InputStream in = urlc.getInputStream();
bis = new BufferedInputStream(in);




Step Four
Create BufferedOutPutStream with a new ServletOutPutStream to which you can write:


BufferedOutputStream bos = null;
bos = new BufferedOutputStream(sOutStream);

Step Five
Read in to the bytes array from BufferedInputStream:


byte[] buff = new byte[length];
int bytesRead;
// Simple read/write loop.
while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}

Step Six
Write on to BufferedOutPutStream from the bytes array, which in turn streams to the client. Use the streamBinaryData() method for binary data streaming:


/*
* This Method Handles streaming Binary data
*


* @param String urlstr ex: http;//localhost/test.pdf etc.
* @param String format ex: pdf or audio_wav or msdocuments etc.
* @param ServletOutputStream outstr
* @param HttpServletResponse resp
*/
private void streamBinaryData(String urlstr,String format,
ServletOutputStream outstr, HttpServletResponse resp)
{
String ErrorStr = null;
try{
//find the right MIME type and set it as contenttype
resp.setContentType(getMimeType(format));
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try{
URL url = new URL(urlstr);
URLConnection urlc= url.openConnection();
int length = urlc.getContentLength();
resp.setContentLength(length);
// Use Buffered Stream for reading/writing.
InputStream in = urlc.getInputStream();
bis = new BufferedInputStream(in);
bos = new BufferedOutputStream(outstr);
byte[] buff = new byte[length];
int bytesRead;
// Simple read/write loop.
while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
ErrorStr = "Error Streaming the Data";
outstr.print(ErrorStr);
} finally {
if( bis != null ) {
bis.close();
}
if( bos != null ) {
bos.close();
}
if( outstr != null ) {
outstr.flush();
outstr.close();
}
}
}
catch(Exception e){
e.printStackTrace();
}
}

N.B In the up coming post, i will try to note a complete sequence to show image from database.

Friday, August 12, 2011

Servlet Life cycle




* The servlet is initialized by calling the init () method.
* The servlet calls service() method to process a client's request.
* The servlet is terminated by calling the destroy() method.
* Finally, servlet is garbage collected by the garbage collector of the JVM.



The life cycle of a servlet can be categorized into four parts:

1. Loading and Inatantiation: The servlet container loads the servlet during startup or when the first request is made. The loading of the servlet depends on the attribute of web.xml file. If the attribute has a positive value then the servlet is load with loading of the container otherwise it load when the first request comes for service. After loading of the servlet, the container creates the instances of the servlet.



2. Initialization: After creating the instances, the servlet container calls the init() method and passes the servlet initialization parameters to the init() method. The init() must be called by the servlet container before the servlet can service any request. The initialization parameters persist untill the servlet is destroyed. The init() method is called only once throughout the life cycle of the servlet.

The servlet will be available for service if it is loaded successfully otherwise the servlet container unloads the servlet.

The init() method :

The init method is designed to be called only once. It is called when the servlet is first created, and not called again for each user request. So, it is used for one-time initializations, just as with the init method of applets.

The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you can also specify that the servlet be loaded when the server is first started.

When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init() method simply creates or loads some data that will be used throughout the life of the servlet.

The init method definition looks like this:

public void init() throws ServletException {
// Initialization code...
}



3. Servicing the Request: After successfully completing the initialization process, the servlet will be available for service. Servlet creates seperate threads for each request. The sevlet container calls the service() method for servicing any request. The service() method determines the kind of request and calls the appropriate method (doGet() or doPost()) for handling the request and sends response to the client using the methods of the response object.

The service() method :

The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client.

Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.

Here is the signature of this method:

public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException{
}

The service () method is called by the container and service method invokes doGe, doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service() method but you override either doGet() or doPost() depending on what type of request you receive from the client.

The doGet() and doPost() are most frequently used methods with in each service request. Here are the signature of these two methods.



4. Destroying the Servlet: If the servlet is no longer needed for servicing any request, the servlet container calls the destroy() method . Like the init() method this method is also called only once throughout the life cycle of the servlet. Calling the destroy() method indicates to the servlet container not to sent the any request for service and the servlet releases all the resources associated with it. Java Virtual Machine claims for the memory associated with the resources for garbage collection.



Wednesday, June 15, 2011

Servlet

Servlets are modules of Java code that run in a server application (hence the name "Servlets", similar to "Applets" on the client side) to answer client requests

Java servlets are becoming increasingly popular as an alternative to CGI(Common Gateway Interface) programs. The biggest difference between the two is that a Java applet is persistent. This means that once it is started, it stays in memory and can fulfill multiple requests. In contrast, a CGI-Common Gateway Interface program disappears once it has fulfilled a request.


It acts as a middlelayer between requests coming from Web browsers or other HTTP clients and databases or applications on the HTTP server. some features are as below

• It is regular Java code. There are new APIs, but no new syntax.

• It has unfamiliar import statements. The servlet and JSP APIs are
not part of the Java 2 Platform, Standard Edition (J2SE); they are a
separate specification (and are also part of the Java 2 Platform,
Enterprise Edition—J2EE).

• It extends a standard class (HttpServlet). Servlets provide a rich
infrastructure for dealing with HTTP.

• It overrides the doGet method. Servlets have different methods to
respond to different types of HTTP commands.

Security is also an important issue related to servlet.


Quickly bookmark the link:
A complete guide to customized j2ee trainning