For smart Primates & ROBOTS (oh and ALIENS ).

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

Friday, March 13, 2015

Generate excel file in jsp java quickly

When you want to generate excel file in jsp java then you have lot of options,
for ex: jexcelapi, Apache POI,other paid library.
The problem is that the file; first will be created on hard disk then after read it and download to the user’s system.
We all know that the .csv files open in excel software, so we can generate .csv file without any third party library.
It is very simple, quickly, fast and easy to use.

Use listed below code.

showdata.jsp
============================================================
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.Date" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.text.*" %>
<%@ page import="java.util.StringTokenizer" %>
<%
// made cdb connection here
PreparedStatement psTestUser = conn.prepareStatement("SELECT *from emp");
ResultSet rsTestUser=psTestUser.executeQuery();
String test_login_id,skills_text,desig_text;
ArrayList<String> l1 = new ArrayList<String>();
l1.add("Login,Skills,Design.");
%>
<body>
<a href="download_excel.jsp">download_excel</a>
<table width="100%"  height="600" align="left" border="0">
  <tr>
    <td><strong>User Name</strong></td>
    <td><strong>Designation</strong></td>
    <td><strong>Skills</strong></td>
  </tr>
<%
while (rsTestUser.next()){
%>
  <tr>
    <td><%=rsTestUser.getString("login") %></td>
    <td><%=decryptA(rsTestUser.getString("skills")) %></td>
    <td><%=rsTestUser.getString("design") %></td>
  </tr>
  <%
StringBuilder sb=new StringBuilder();
sb.append(rsTestUser.getString("login")+","+rsTestUser.getString("skills")+",");
sb.append(decryptA(rsTestUser.getString("design")));
l1.add(sb.toString());
}
session.setAttribute("listResult",l1);
%>
</table>
</body>
</html>
<%
// close database connection here
%>


download_excel.jsp
=========================
<%@ page import="java.util.ArrayList"%>
<%
response.setContentType("application/csv");
response.setHeader("content-disposition","filename=test.csv");
ArrayList<String> list = (ArrayList<String>)session.getAttribute("listResult");
for(int i = 0; i < list.size(); i++) {
    String myString = (String)list.get(i);
    out.println(myString);
}
out.flush();
out.close();
%>
Share:

Wednesday, November 12, 2014

How to show place in Google map

How to show place in Google map
-----------------------------------


























1) Create a table "latandlon" in Mysql/Oracle/Sqlserver/DB2 in which you feel easy.

CREATE TABLE latandlon (
  id int(11) NOT NULL auto_increment,
  lat decimal(10,6) NOT NULL default '0.000000',
  lon decimal(10,6) NOT NULL default '0.000000',
  address varchar(255) NOT NULL default '',
  PRIMARY KEY  (id)
);


2) feed the listed below data.
----------------------------------------------------------
id,     lat,            lon,            address
----------------------------------------------------------
1    23.402800    78.454100    Madhya Pradesh
2    26.280000    80.210000    Kanpur
3    31.122027    77.111664    Himanchal Pradesh
4    22.533000    88.367000    Kolkata
5    28.350000    77.120000    Delhi
6    17.230000    78.290000    Hyderabad
----------------------------------------------------------


3) put youe google map key in the index.jsp.


 <%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.*" %>
<%
// How to show place in google map
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">  
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
<script src="http://maps.google.com/maps?file=api&v=2&key=YOURKEYHERE" type="text/javascript">
</script>
<body>
<p><strong>locations in India</strong></p>
<div id="map" style="width: 800px; height: 600px"></div>

<script type="text/javascript">
//<![CDATA[
var map = new GMap2(document.getElementById("map"));
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
map.addControl(new GScaleControl());
map.setCenter(new GLatLng(23.402800, 78.454100), 5, G_NORMAL_MAP);
function createMarker(point, number)
{
var marker = new GMarker(point);
var html = number;
GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(html);});
return marker;
};
<%
    String userName = "root";
    String password = "";
    String url = "jdbc:mysql://localhost:3306/test";
    try{
        String driver = "com.mysql.jdbc.Driver";
        Class.forName(driver).newInstance();
        Connection conn;
        conn = DriverManager.getConnection(url, "root","");
        Statement s = conn.createStatement ();
        s.executeQuery ("SELECT *from latandlon");
        ResultSet rs = s.getResultSet ();
        int count = 0;
        while (rs.next ()) {
            String lat = rs.getString ("lat");
            String lon = rs.getString ("lon");
            String address=rs.getString ("address");
            out.print("var point = new GLatLng("+lat+","+lon+");\n");
            out.print("var marker = createMarker(point, '"+address+"');\n");
            out.print("map.addOverlay(marker);\n");
            out.print("\n");
        }
        rs.close ();
        s.close ();
    }
    catch(Exception ee){
        System.out.println(ee.toString());  
    }
%>
//]]>
</script>
</body>
</html>

4) change the database connection string in the index.jsp page, coz I have used MySql.






Share:

Thursday, August 14, 2014

Generate CSV in jsp without third party utility

Generate CSV in jsp without third party utility

There are lot of third party paid and free utility that generate CSV file in JSP/Java. but the problems are to hard to implement. and may utility first create CSV file in the server, so Server space will be consumed.
To overcome all the problem I have created listed below the code. You are free to use it in you project.

<%@ page import="java.util.ArrayList"%>
<%
response.setContentType("application/csv");
response.setHeader("content-disposition","filename=test.csv");
// the session.getAttribute("listResult") is containg of comma sepearte multiple lines as listed below
//aa,10,20,30
//bb,10,20,30
//cc,10,20,30
//dd,10,20,30

ArrayList<String> list = (ArrayList<String>)session.getAttribute("listResult");
out.println("<table border='1'>");
for(int i = 0; i < list.size(); i++) {
    String myString = (String)list.get(i);

    out.println(myString);


}

out.flush();
out.close();
%>
Share:

Saturday, July 19, 2014

Post Xml data without form in JSP and receive

How to post xml data in JSP page without form field and get it's data
in the next JSP page.

The first file post-data.jsp is just taking xml data form xml file and
sending xml data as a post to the get-post.jsp page.

first file is:

post-data.jsp
--------------
< %@ page import="java.net.*" % >
< %@ page import="java.io.*" % >
< %@ page import="java.util.*" % >
< %@ page import="java.text.*" % >
< %
try
{
URL u;
u = new URL("http://localhost:9292/post/get-post.jsp");
// get the xml data from xml file which you want to post
String inputFileName="C:\\temp1.xml";
FileReader filereader =new FileReader(inputFileName);
BufferedReader bufferedreader=new BufferedReader(filereader);
String initial=bufferedreader.readLine();
String finalData=new String();
while(initial!=null)
{
finalData=finalData+initial;
initial=bufferedreader.readLine();
}
String s=(finalData.toString());
HttpURLConnection uc = (HttpURLConnection)u.openConnection();
uc.setRequestMethod("POST");
uc.setDoOutput(true);
uc.setDoInput(true);
uc.setRequestProperty("Content-Type", "text/xml; charset=\"utf-8\"");
uc.setAllowUserInteraction(false);
DataOutputStream dstream = new DataOutputStream(uc.getOutputStream());
dstream.writeBytes(s);
dstream.close();
InputStream in = uc.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuffer buf = new StringBuffer();
String line;
while ((line = r.readLine())!=null) {
buf.append(line);
}
in.close();
out.println(buf.toString());
}
catch (IOException e)
{
out.println(e.toString());
}
% >


Second file is:

get-post.jsp
-----------------

< %@ page import="java.util.*" % >
< %
String postedData = request.getReader().readLine();
///// perform here your operation for postedData
out.println("Posted Data is ");
out.println(postedData);
% > 
Share:

Saturday, December 21, 2013

How to Terminate JSP Process

How to Terminate JSP Process

use:
out.close();
Share:

Sunday, November 10, 2013

Post multiple and return values from JSON in JSP

JSON is very lightweight than XML. Here is the some hard JSON example with multiple values post and
multiple return values.
I have used "json-simple-1.1.1.jar" , so you need to download it.

index.jsp
---------------------
<%@ page import="org.json.JSONObject"%>
<%@ page import="java.io.PrintWriter"%>
<script src="jquery-1.10.2.js" type="text/javascript"></script>
<input type="button" value="send" onclick="dook();"/>
<script>
function dook() {
    var article = new Object();
    article.title = "Title Name";
    article.url = "Url Name";
    article.categories ="Categories  Name";
    article.tags = "Tags Name";
    var jsonobj=JSON.stringify(article);
    $.ajax({
        data: {para:jsonobj},
        dataType: 'json',
        url: 'newjsp1.jsp',
        type: 'POST',
        success: function(jsonObj){
            alert(jsonObj.title);
            alert(jsonObj.url);
            alert(jsonObj.categories);
            alert(jsonObj.tags);
            alert(jsonObj.rate); 
        },
        error: function() {
            alert('readyState: '+xhr.readyState+'\nstatus: '+xhr.status + ' ' + err);
        }
    });
}
</script>



newjsp1.jsp
=======================
<%@ page import="java.io.PrintWriter"%>
<%@ page import="org.json.simple.JSONObject"%>
<%@ page import="org.json.simple.JSONValue"%>
<%
request.setCharacterEncoding("utf8");
response.setContentType("application/json");
PrintWriter outt = response.getWriter();
JSONObject jsonObj = (JSONObject) JSONValue.parse(request.getParameter("para"));
String title=jsonObj.get("title").toString();
String url=jsonObj.get("url").toString();
String categories=jsonObj.get("categories").toString();
String tags=jsonObj.get("tags").toString();
String rate="450.00";
System.out.println(jsonObj.get("title"));
JSONObject obj = new JSONObject();
obj.put("title", title);
obj.put("url", url);
obj.put("categories", categories);
obj.put("tags", tags);
obj.put("rate", rate);
out.print(obj);
%>



Share:

Simple JSON in JSP

Simple JSON in JSP

JSON is very lightweight than XML.Here is the simple example of JSON with java.
I have used "json-simple-1.1.1.jar" , so you need to download it.

index.jsp
---------------------
<%@ page import="org.json.JSONObject"%>
<%@ page import="javax.json.Json"%>
<%@ page import="java.io.PrintWriter"%>
<script src="jquery-1.10.2.js" type="text/javascript"></script>
<input type="button" value="send" onclick="dook();"/>
<script>
function dook() {
    var datas = ({"msg":'Test Message'});
    var jsonobj=JSON.stringify(datas);
    $.ajax({
        data: {para:jsonobj},
        dataType: 'json',
        url: 'newjsp.jsp',
        type: 'POST',
        success: function(ans){
            alert(ans.res);    
        },
        error: function() {
            alert('Ajax readyState: '+xhr.readyState+'\nstatus: '+xhr.status + ' ' + err);
        }
    });
}
</script>


newjsp.jsp
-------------------
<%@ page import="java.io.PrintWriter"%>
<%@ page import="org.json.simple.JSONObject"%>
<%@ page import="org.json.simple.JSONValue"%>
<%
request.setCharacterEncoding("utf8");
response.setContentType("application/json");
PrintWriter outt = response.getWriter();
JSONObject jsonObj = (JSONObject) JSONValue.parse(request.getParameter("para"));
System.out.println(jsonObj.get("msg"));
JSONObject obj = new JSONObject();
obj.put("res", "hello...");
out.print(obj);
%>


Share:

Friday, October 25, 2013

ALTERNATE OF OR ANY OTHER LOGIC TAG IN STRUTS

ALTERNATE OF <logic:equal> OR ANY OTHER LOGIC TAG IN STRUTS
----------------------------------------------------------------------------------------
We need to write very much <logic:equal name> if there are lot of if conditions in you page...so how we use native if condition in struts. I have faced the same problem and find the solution. the solution is in listed below code.


=======================================================
Using  <logic:equal name> 

<logic:notEmpty name="myProductList" scope="request">
<table>
<logic:iterate id="prodIterateId" name="myProductList">
<tr>
    <logic:equal name="prodIterateId" property="catId" value="1">
        <td  align="center"><html:text name="prodIterateId" property="catId" value="DESKTOP COMPUTER"/></td>
    </logic:equal>
    <logic:equal name="prodIterateId" property="catId" value="2">
        <td align="center"><html:text name="prodIterateId" property="catId" value="LAPTOP"/></td>
    </logic:equal>
    <logic:equal name="prodIterateId" property="catId" value="3">
        <td  align="center"><html:text name="prodIterateId" property="catId" value="PAMTOP"/></td>
    </logic:equal>
     <logic:equal name="prodIterateId" property="catId" value="4">
        <td  align="center"><html:text name="prodIterateId" property="catId" value="PAD"/></td>
    </logic:equal>
        <td  align="center"><html:text name="prodIterateId" property="productName" readonly="true" size="33"/></td>
        <td  align="center"><html:text name="prodIterateId" property="productPrice" readonly="true" size="33"/></td>
        <td  align="center"><html:text name="prodIterateId" property="productCode" readonly="true" size="33"/></td>
    </tr>
    </logic:iterate>
    </table>
</logic:notEmpty>
============================================================

Using native IF condition

<logic:notEmpty name="myProductList" scope="request">
<table>
    <logic:iterate id="prodIterateId" name="myProductList">
        <tr>
            <bean:define id="catId_Value" name="prodIterateId" property="catId"  type="java.lang.Integer" />
            <%
                int c_id=catId_Value.intValue();
                String cat_Name="";
                if(c_id==1) {cat_Name="DESKTOP COMPUTER";}
                if(c_id==2) {cat_Name="LAPTOP"; }
                if(c_id==3) {cat_Name="PAMTOP"; }
                if(c_id==4) {cat_Name="PAD"; }
            %>
        <td  align="center"><html:text name="prodIterateId" property="catId" value="<%=cat_Name%>"/></td>
        <td  align="center"><html:text name="prodIterateId" property="productName" readonly="true" size="33"/></td>
        <td  align="center"><html:text name="prodIterateId" property="productPrice" readonly="true" size="33"/></td>
        <td  align="center"><html:text name="prodIterateId" property="productCode" readonly="true" size="33"/></td>
    </tr>
    </logic:iterate>
    </table>
</logic:notEmpty>


Share:

Ajax in struts

How to use ajax in struts and hibernate.

Ajax is very important in website coding.
Here I am demonstrating how to use jquery ajax in struts and hibernate.


struts-config.xml
--------------------------
<action input="/" path="/amittest" scope="request" type="com.test.actions.AmitTestAction" parameter="method">
<forward name="success" path="/Webs/Input/amittest.jsp"/>
</action>
====================================================


query.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>
  <sql-query cache-mode="ignore" cacheable="false" flush-mode="always" name="chkBook"> SELECT COUNT(*) FROM book_master WHERE code_id=:code AND serial_id>=:serial </sql-query>
</hibernate-mapping>
====================================================

MyUtilDao.java
------------------------------
package dao;
import org.hibernate.CacheMode;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import plugins.HibernateSessionFactory;
public class MyUtilDao {
    public int chkBook(int code,int serial){
        Session ssn = null;
        ssn = HibernateSessionFactory.getSession();
        ssn.setCacheMode(CacheMode.GET);
        Query qry = ssn.getNamedQuery("chkBook");
        qry.setParameter("code", code);
        qry.setParameter("serial", serial);
        Object tot = qry.uniqueResult();
        int total = 0;
        if (tot != null) {
            total = Integer.parseInt(tot.toString());
        } else {
            total = 0;
        }
        return total;
    }
 
}
====================================================

AmitTestAction.java
-------------------------
package mytest.actions;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import dao.MyUtilDao;
import plugins.HibernateSessionFactory;

public class AmitTestAction  extends org.apache.struts.actions.DispatchAction {
     private final static String SUCCESS = "success";
     public ActionForward showForm(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
       
         MyUtilDao myUtiDaoObj=new MyUtilDao();
       
         String ffor= request.getParameter("ffor");
         if(ffor.compareTo("chkBook")==0) {
            int code= Integer.parseInt(request.getParameter("code"));
            int erial= Integer.parseInt(request.getParameter("serial"));
            int total=myUtiDaoObj.chkBook(code,serial);
            request.setAttribute("total", total);
            request.setAttribute("ffor", "chkBook");
         }
         return mapping.findForward(SUCCESS);
      }
}
====================================================
amittest.jsp
<%
if(request.getAttribute("ffor")!=null) {
    if(request.getAttribute("ffor").toString().compareTo("chkBook")==0) {
        out.print(request.getAttribute("total"));
    }
}
%>
====================================================
BookAdd.jsp

<input type="button" name="btn1" value="Button" onclick="dotest();"/>
<html:button property="button" value="Save" onclick="do_save()"/>
<script>

 var code=222;
var serial=111;
function do_save() {
        var ajaxans="";
        $.ajax({
                    url: "amittest.do?method=showForm",
                    type: "POST",
                    async: false,
                    cache: false,
                    data:   { 'ffor':'chkBook',
                              'code':code,
                              'serial':serial},
                    success: function(html) {
                             ajaxans=html;
                            }
                }
             );
       if(ajaxans=="1" || parseInt(ajaxans)==1) {
           alert("This is already exists");
           return;
       }    
        var r=confirm("Do you want to save?");
        if (r==true) {
            document.forms[0].action="BookMasterAdd.do?method=processForm";
            document.forms[0].submit();
        }
    }

   function dotest() {
       /*$.post("http://localhost:8080/mytest/amittest.do?method=showForm",{'method':'showForm'},function(ans) {
alert(ans);
});*/
      /*// done
       *$.post("amittest.do?method=showForm",{'method':'showForm'},function(ans) {
alert(ans);
});*/
      /* done
       * $.post("amittest.do?method=showForm",function(ans) {
alert(ans);
});*/
      /* $.get("amittest.do?method=showForm",function(ans) {
alert(ans);
});*/
     
      /* $.get("amittest.do?method=showForm",{'val1':'Hi'},function(ans) {
alert(ans);
});*/  
   
      /*   $.post("amittest.do?method=showForm",{'val1':'Hi'},function(ans) {
alert(ans);
});*/
    /*  $.post("amittest.do?method=showForm",{'ffor':'chkExistReceiptBookMaster',
                                            'zone_code':'8004500',
                                            'frm_serial':'11'
                                           },function(ans) {
alert(ans);
});*/
}
</script>
====================================================



Share:

Saturday, October 19, 2013

java.lang.OutOfMemoryError: PermGen space in netbeans

java.lang.OutOfMemoryError: PermGen space in netbeans

How to solve it in netbeans:
1- Right click on server
2- properties
3- select platform
4-in VM option paste as : -Xmx512m -Xms512m -XX:MaxPermSize=512m

java.lang.OutOfMemoryError: PermGen space in netbeans

Share:

Thursday, October 10, 2013

DispatchMapping does not define a handler property




You may face this error while working on java struts:

"DispatchMapping[/login] does not define a handler property"




Answer of this issue is "parameter attribute mention in struts-config for method of Action class"
Share:

Cannot retrieve definition for form bean on action

javax.servlet.jsp.JspException: Cannot retrieve definition for form bean stdname on action regist 

Ans:spelling mistake in tags, so check it and correct it in struts-config.xml file
Share:

Action missing resource in key method map

Action missing resource in key method map

Ans:It means the you have put some spaces in .properties file or missing some property key and its value
Share:

Cannot find ActionMappings or ActionFormBeans collection

org.apache.jasper.JasperException: javax.servlet.
ServletException: javax.servlet.jsp.JspException: Cannot find ActionMappings or ActionFormBeans collection
root cause
javax.servlet.ServletException: javax.servlet.jsp.JspException: Cannot find ActionMappings or ActionFormBeans collection
root cause
javax.servlet.jsp.JspException: Cannot find ActionMappings or ActionFormBeans collection


Ans: One of the most common error is that .. that you have missed struts-config file path in web.xml file.

for Ex: <param-value>/WEB_INF/struts-config.xml</param-value>
so change it as <param-value>/WEB-INF/struts-

config.xml</param-value>
Share:

message No action instance for path / could be created error in struts

message No action instance for path /getcity could be created in struts
description The server encountered an internal error (No action instance for path /getcity could be created) that prevented it from fulfilling this request.

Ans: it means that you miss-spelled class information just see [type="con.test.action.DoLogin"] it must be 
type="com.test.action.DoLogin"

<action name="logform" path="/getcity"  type="con.test.action.DoLogin" scope="request" parameter="action">
            <forward name="cityyyy" path="/city_confirm.jsp"/>
        </action>
Share:

Action does not contain specified method (check logs)

javax.servlet.ServletException: java.lang.
NoSuchMethodException: Action[/salary] does not contain specified method (check logs)
java.lang.NoSuchMethodException: Action[/salary] does not contain specified method (check logs)

Ans: This means "salary" method must be a text in the .jsp file:
public ActionForward salary(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) throws Exception {
        LoginForm lfm=(LoginForm)form;
        request.setAttribute("empName", lfm.getAname());
        return mapping.findForward("salary");
    }

<html:form action="/salary" method="post">
Salary: <html:text property="salary"/><br/>
Emp code <html:text property="empcode"/><br/>
<html:submit value="salary" property="action"/>
</html:form>struts-config.xml
 
Share:

Cannot find message resources under key org.apache.struts.action.MESSAGE

Cannot find message resources under key org.apache.struts.action.MESSAGE

 javax.servlet.jsp.JspException: Cannot find message resources under key org.apache.struts.action.
MESSAGE
javax.servlet.ServletException: javax.servlet.jsp.JspException: Cannot find message resources under key org.apache.struts.action.MESSAGE

 
Ans:
1- create a package: com.test.properties
2- under that package create a "Common.properties" file with this contents or just empty it:

#common module error message
error.common.name.required = Name is required.

#common module label message
label.common.name = UserName
label.common.button.submit = Submit
label.common.button.reset = Reset


3- just add the message-resource tag in struts-config.xml file as listed below:
<message-resources parameter="com.test.properties.Common"></message-

resources> 
Share:

Cannot cast from ActionForm to form error in struts

I was working in struts and faced "Cannot cast from ActionForm to StudentForm" error.

to solve follow the steps:

Ans: It means you have not import
"import org.apache.struts.action.ActionForm;" int Form class
and can not extends "ActionForm" in that class
for ex:

import org.apache.struts.action.
ActionForm;
public class StudentForm  extends ActionForm {
Share:

Ads Inside Post

Powered by Blogger.

Archive