Wednesday 13 November 2013

Sorting ArrayList with custom fields by Id, Name , City , Age using Comparator Interface in java


package TestCollection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

class SetData{
  public Integer id;
  private String name;
  private String city;
  private Integer age;
  
  public SetData (Integer id, String name, String city, Integer age) {
this.id = id;
this.name = name;
this.city = city;
this.age = age;
}
  
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String nity) {
this.city = city;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}

public String toString(){

return "[" + " ID: " + this.getId() + " Name: "+ this.getName() + " City: " + this.getCity() + " Age: " + this.getAge() +"]";
}

}

class Sample2{
public static void main(String args[]){
   new Sample2();
Scanner scan  = new Scanner(System.in);
SetData setdata1 = new SetData(101,"Aman","Noida",28);
SetData setdata2 = new SetData(119,"Vijay","Delhi",25);
SetData setdata5 = new SetData(204,"chetan","Noida",28);
SetData setdata3 = new SetData(601,"Rajesh","Ghaziabad",27);
SetData setdata4 = new SetData(701,"Brijesh","Noida",26);
List <SetData> l1 = new ArrayList <SetData>();
List  l2 = new ArrayList();
l1.add(setdata1);
l1.add(setdata2);
l1.add(setdata3);
l1.add(setdata4);
l1.add(setdata5);
//l2.add(l1);
         
Iterator itr = l1.iterator();
while(itr.hasNext()){
Object o = itr.next();
//System.out.println(o);
}
Collections.sort(l1,new MyIdComparable1());
itr = l1.iterator();
System.out.println("------------------Sort By ID----------------------");
while(itr.hasNext()){
Object o = itr.next();
System.out.println(o);
}
Collections.sort(l1,new MyNameComparable2());
System.out.println("------------------Sort By Name----------------------");
for(Object name : l1){
System.out.println(name);
}
Collections.sort(l1,new MyCityComparable3());
System.out.println("------------------Sort By City----------------------");
for(Object city : l1){
System.out.println(city);
}
Collections.sort(l1,new MyAgeComparable4());
System.out.println("------------------Sort By Age----------------------");
for(Object age : l1){
System.out.println(age);
}
}
}

class MyIdComparable1 implements Comparator <SetData>{
public int compare(SetData s1, SetData s2){
return (s1.getId()<s2.getId() ? -1 : (s1.getId()==s2.getId() ? 0 : 1));
}

class MyNameComparable2 implements Comparator <SetData>{
public int compare(SetData s1, SetData s2){
return (s1.getName().compareToIgnoreCase(s2.getName()));
}

class MyCityComparable3 implements Comparator <SetData>{
public int compare(SetData s1, SetData s2){
return (s1.getCity().compareToIgnoreCase(s2.getCity()));
}

class MyAgeComparable4 implements Comparator <SetData>{
public int compare(SetData s1, SetData s2){
return (s1.getAge()<s2.getAge() ? -1 : (s1.getAge()==s2.getAge() ? 0 : 1));
}


// Out Put :

Thursday 7 November 2013

How to create a report using Jasper Report in java

Jasper Report is an open source java reporting engine. It is a Java class library, and is not meant for end users, but rather is targeted towards Java developers who need to add reporting capabilities to their applications.

Here i am showing you, how to create a reaport with Jasper Reporting engine in Eclipse.

Requirements 

jdk 1.6
Eclipse IDE

commons-beanutils-1.8.0.jar
commons-collections-2.1.1.jar
commons-digester-2.1.jar
commons-javaflow-20060411.jar
commons-lang-2.1.jar
commons-logging-1.1.1.jar
iText-2.1.7.js2.jar
jasperreports-5.5.0.jar
mysql-connector-java-3.1.7-bin.jar
servlet-api.jar



//-------------------- Save as ReportGenerator.java ----------------------------

package com.ramsis;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

public class ReportGenerator {

Connection conn;

public void generateReport() {

try {
//Class.forName("oracle.jdbc.driver.OracleDriver");
//conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","ABCD");
Class.forName("com.mysql.jdbc.Driver");
//con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","public");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/gts","root","public");
System.out.println("Loading Report Designs");
InputStream input = new FileInputStream(new File("jrxml/EmployeeReport.jrxml"));
JasperDesign jasperDesign = JRXmlLoader.load(input);

System.out.println("Compiling Report Designs");
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

System.out.println("Creating JasperPrint Object");
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("ReportTitle", "PDF JasperReport");

JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport,null,conn);

//Exporting the report
OutputStream output = new FileOutputStream(new File("Report/EmployeeReport4.pdf"));

JasperExportManager.exportReportToPdfStream(jasperPrint, output);

System.out.println("Report Generation Complete");
conn.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JRException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new ReportGenerator().generateReport();
}

}


//----------------------- Save as EmployeeReport.jrxml ------------------------

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN"
"http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
<jasperReport name="EmployeeReport_aman.kumar">
<queryString>
<![CDATA[select First_Name, Last_Name from employee e]]>
</queryString>
<field name="First_Name" />
<field name="Last_Name" />
<title>
<band height="50">
<staticText>
<reportElement x="0" y="0" width="180" height="15"/>
<textElement/>
<text><![CDATA[Jasper Report - By Java]]></text>
</staticText>
</band>
</title>
<pageHeader>
<band height="30">
<staticText>
<reportElement x="0" y="0" width="69" height="24" />
<textElement verticalAlignment="Bottom" />
<text>
<![CDATA[First Name: ]]>
</text>
</staticText>
<staticText>
<reportElement x="100" y="0" width="79" height="24" />
<text>
<![CDATA[Last Name: ]]>
</text>
</staticText>
</band>
</pageHeader>
<detail>
<band height="30">
<textField>
<reportElement x="0" y="0" width="69" height="24" />
<textFieldExpression>
<![CDATA[$F{First_Name}]]>
</textFieldExpression>
</textField>
<textField>
<reportElement x="100" y="0" width="69" height="24" />
<textFieldExpression>
<![CDATA[$F{Last_Name}]]>
</textFieldExpression>
</textField>
</band>
</detail>
</jasperReport>


Out Put:




//------------------------- Save as HelloJasper.java ---------------------

package com.ramsis;

import java.util.HashMap;
import java.util.Map;

import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
import net.sf.jasperreports.view.JasperViewer;

public class HelloJasper {

public static void main(String args[]){

String reportSource = "jrxml/HelloReportWorld.jrxml";
String reportDest = "jrxml/HelloReportWorld.html";



Map <String, Object> params = new HashMap <String, Object>();

//params.put("reportTitle", "Hello Report World");
//params.put("author", "Craig Conover");
//params.put("startDate", (new java.util.Date()).toString());


try
{
JasperReport jasperReport =
JasperCompileManager.compileReport(reportSource);

JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, new JREmptyDataSource());

JasperExportManager.exportReportToHtmlFile(
jasperPrint, reportDest);
JasperViewer.viewReport(jasperPrint);
}

catch (JRException ex)
{
ex.printStackTrace();
}
}

}

//-------------------------- Save as HelloReportWorld.jrxml ------------------



<jasperReport name="HelloReportWorld">

<detail>
<band height="200">
<staticText>
<reportElement mode="Opaque" x="50" y="10" width="500" height="30" />
<text><![CDATA[ ID Name Phone City ]]></text>
</staticText>

<staticText>
<reportElement x="50" y="20" width="500" height="30" />
<text><![CDATA[101 Aman Kumar 997152663 Noida ]]></text>
</staticText>

<staticText>
<reportElement x="50" y="30" width="500" height="30" />
<text><![CDATA[102 Suraj Kumar 929300440 New Delhi ]]></text>
</staticText>

<staticText>
<reportElement x="50" y="40" width="500" height="30" />
<text><![CDATA[102 Pavan Yadav 9293344550 Noida ]]></text>
</staticText>
</band>
</detail>
</jasperReport>


Out Put:



  

Monday 4 November 2013

How to canvert java object into xml file (Vice Versa)

JAXB, stands for Java Architecture for XML Binding, using JAXB annotation we can convert Java object into XML file and Xml file into java object (Vice versa).
No extra jaxb libraries are required if you are using JDK1.6  


For object that need to convert to / from XML file, it have to annotate with JAXB annotation

//---------------- Save as Customer.java ------------------------

package com.ramsiscode.jaxb;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;


@XmlRootElement
public class Customer {

int id;
String name;
int age;
String address;
public int getId() {
return id;
}
@XmlElement
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
@XmlElement
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
@XmlElement
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
@XmlElement
public void setAddress(String address) {
this.address = address;
}

}


//-----------------------------------------------------------

JAXB marshalling example, for convert customer object into a XML file

//------------------- save as ConvertXML.java -------------------------



package com.ramsiscode.jaxb;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;


public class ConvertXML {

public static void main(String args[]){

Customer customer = new Customer();
customer.setId(101);
customer.setName("Aman");
customer.setAge(28);
customer.setAddress("Noida, Uttar Pradesh India.");

try{

File file = new File("D:\\customer.XML");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(customer, file);
jaxbMarshaller.marshal(customer, System.out);

}
catch (Exception ex){

ex.printStackTrace();

}

}

}


//----------------- output -----------------------------------




//------------------------------------------------------------------------------
JAXB unmarshalling example, convert a XML file content into a customer object

//------------------------- save as CustomerXMLRead.java ------------------------

package com.ramsiscode.jaxb;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;


public class CustomerXMLRead {

public static void main(String args[]){

try {

File file = new File("D:\\customer.XML");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);

Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
System.out.println(customer.getName());
System.out.println(customer.getId());
System.out.println(customer.getAge());
System.out.println(customer.getAddress());


} catch (JAXBException e) {
e.printStackTrace();
}

}

}

 



Monday 28 October 2013

Dynamically Add/Remove Rows In HTML Table Using JavaScript and Jquery




 <link href="Styles/ui-lightness/jquery-ui-1.8.21.custom.css" rel="stylesheet" type="text/css" />
    <script src="Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery-ui-1.8.22.custom.min.js" type="text/javascript"></script>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<script> $(document).ready(function(){ function Reset() { //$("#tblpodetail").empty(); $("#rerID").hide(); $("#lblmsg").html(''); //$("#totalamt").html(''); //$("#container tr").remove(); } function valid() { var id = $('.trdelete').attr('id').split('-')[1]; //alert(id); return false; } $("#addanother").click(function(){ $("#rerID").show(); //validateForm(); var count = 0; $("#container tr").each(function () { count++; }); var str='<tr id ="tr-' + count + '" ><td align="center" height="35px">
<select class="degreeclass" name="degree-' + count + '" id="degree-' + count + '"
style="background-color:#F8FCFC; color:#284D4D;"><option>
</option><option value="10th">10th</option><option value="12th">12th</option>
<option value="B.A">B.A</option> <option value="B.SC">B.SC</option>
<option value="B.COM">B.COM</option> <option value="BBA">BBA</option>
<option value="BCA">BCA</option><option value="B.Tech">B.Tech</option>
<option value="M.A">M.A</option> <option value="M.SC">M.SC</option>
<option value="M.COM">M.COM</option> <option value="MBA">MBA</option>
<option value="MCA">MCA</option><option value="M.Tech">M.Tech</option>
</select></td><td align="center" height="35px">
<input style="background-color:#F8FCFC; color:#284D4D;" type="text"
name="year_of_passing-' + count + '" id="year_of_passing-' + count + '" size="5"/>
</td><td><center><a href="#" class="trdelete" id ="delete-' + count + '">delete</a>
</center> </td></tr>';
$("#container").append(str); }); $("#Reset").live('click', function () { $("#btnshow").show(); $("#btndelete").hide(); Reset(); return false; }); $("#submit").live('click', function () { //valid(); validateForm(); return true; }); $(".trdelete").live('click', function () { var id = $(this).attr('id').split('-')[1]; var trid = "#tr-" + id; //alert(trid); $(trid).remove(); return false; }); $("#btndelete").click(function () { if (confirm('Are you sure want to delete This.') === true) { PoDelete($("#txtpoid").val()); } else { return false; } }); $("#btnok").live('click', function () { var count = 0; var itemcode = ''; $(".item").each(function () { if (this.checked === true) { count++; itemcode = $(this).attr('id'); } }); if (count === 0) { //alert('Please select at least one item.'); $("#rerID").append('<p>Please select at least one item.</p>'); Reset(); } else { $(UniversalId).val(itemcode); if (UniversalId === '#txtpoid') { $("#txtpoid").change(); } else { $(".itemcode").change(); } $(".black_overlay").hide(); $("#div-child").hide(); } return false; }); }); </script> <script> function validateForm() { var x=document.forms["eduform"]["degree"].value; if (x==null || x=="") { document.forms["eduform"]["degree"].focus(); document.forms["eduform"]["degree"].style.borderColor='#FF778B'; document.forms["eduform"]["degree"].style.borderWidth='1px'; document.forms["eduform"]["degree"].style.borderStyle='solid'; alert("Qualification must be filled out"); $("#rerID").html('<p style="color:RED;">Qualification must be filled out.</p>'); $( "#degree" ).focus(); return false; } else{ $("#rerID").html(''); } var y=document.forms["eduform"]["year_of_passing"].value; if (y==null || y=="") { document.forms["eduform"]["year_of_passing"].focus(); document.forms["eduform"]["year_of_passing"].style.borderColor='#FF778B'; document.forms["eduform"]["year_of_passing"].style.borderWidth='1px'; document.forms["eduform"]["year_of_passing"].style.borderStyle='solid'; alert("Year Of Passing must be filled out"); $("#rerID").html('<p style="color:RED;">Year Of Passing must be filled out.</p>'); $( "#year_of_passing" ).focus(); return false; } else{ $("#rerID").html(''); } } </script>

<P align="center" style="color:#386B6B;">
<%
if
(request.getParameter("msg")!=null){out.println(request.getParameter("msg"));}
%></p>
<body>
  <div align="center">
  <div style="border:1px solid #386B6B; background-color:#d7eaea; width:800px; height:auto;">
  <div style="background-color:#d7eaea;width:800px;height:60px;padding-top:10px;font-size:35px;color:#386B6B;">Employee Education</div>
  <form action="emp_edu_action.jsp" method="post" name="eduform" id="eduform" onsubmit="return validateForm();">
    <div>
<table id="container" border="1px" cellpadding="0" style="color:#386B6B; width: 800px; border-collapse: collapse;" >
       <tr>
      <td align="center" height="35px"><strong>Qualification:</strong></td>
<td align="center"height="35px"><strong>Year Of Passing:</strong></td>
<td align="center"height="35px"><b>Operation</b></td>
</tr>
<tr><td align="center"height="35px">
<select name="degree" onClick="this.style.borderColor='#333EFF';this.style.borderStyle='solid';this.style.borderWidth='1px'" style="background-color:#F8FCFC;color:#284D4D;">
<option></option>
<option value="B.A">B.A</option>
<option value="B.SC">B.SC</option>
<option value="B.COM">B.COM</option>
<option value="BBA">BBA</option>
<option value="BCA">BCA</option>
<option value="B.Tech">B.Tech</option>
<option value="M.A">M.A</option>
<option value="M.SC">M.SC</option>
<option value="M.COM">M.COM</option>
<option value="MBA">MBA</option>
<option value="MCA">MCA</option>
<option value="M.Tech">M.Tech</option>
</select></td>           
<td align="center"height="35px"><input style="background-color:#F8FCFC; color:#284D4D;" type="text" name="year_of_passing" id="year_of_passing" size="5" onClick="this.style.borderColor='#333EFF';this.style.borderStyle='solid';this.style.borderWidth='1px'"/></td>
   <td align="center"rowspan="auto"height="35px"><input style="background-color:#9DCCCC; color:#284D4D;" type="button" id="addanother" class="addanother" value="add more" onclick="return validateForm();"></td>
</tr>
</table>
<table>
 <tr>
<td id="rerID">  </td>
 </tr>
<tr height="35px">
         <td ><input style="background-color:#9DCCCC; color:#284D4D;width:60px; height:25px;font-size:15px;"" type="submit" value="Submit" id="submit" name="submit"/>
<input style="background-color:#9DCCCC; color:#284D4D;width:60px; height:25px;font-size:15px;"" type="reset" value="Reset" id="Reset" name="Reset"/>
</td>
</tr>
</table>
  </div>
  </form>
  </div>
  </div>
</body>
</html>

Thursday 10 October 2013

How to convert and download HTML Format into ( MS_Excel, Excel , Xls) Formats in jsp


In this code i am showing you, How to convert any HTML or jsp code into ( MS_Excel, Excel , Xls) formats,
and also you can download same format in to Excel , xls. It is very usefull when you will generating a report with download feature in excel format.

 

//---------------------- Save As "GetExcel.jsp" -------------------//

<table width="60%" cellpadding="5px;" align="center" border="1" style="border-color: RED;"  class="textn">
  <tbody bgcolor="#ffdebf">
   <tr>
 <td colspan="3"><strong>Convert HTML code in to Excel format and also download it </strong></td>
   <br/>
   </tr>
  </tbody>
  </table>

<table width="60%" align="center" border="1" style="border-collapse: collapse; border-color: #df6e00;" bordercolor="#111111" class="textn">
 
  <th style="">Emp Name</th>  
 <th>Emp ID</th>
    <th>Mobile</th>
    <th>City</th>
<tr>
  <td>
      <center>Aman Kumar</center> 
</td>
<td>
      <center>1099</center> 
</td>
<td>
      <center>9918299393</center> 
</td>
<td>
      <center>Noida</center> 
</td> 
  </tr>
<tr>
  <td>
      <center>Nitin Kumar</center> 
</td>
<td>
      <center>1233</center> 
</td>
<td>
      <center>956829937</center> 
</td>
<td>
      <center>Ghaziabad</center> 
</td> 
  </tr>
<tr>
  <td>
      <center>Brijesh Bhagat</center> 
</td>
<td>
      <center>1405</center> 
</td>
<td>
      <center>9338299345</center> 
</td>
<td>
      <center>Lucknow</center> 
</td> 
  </tr>
<tr>
  <td>
      <center>Suraj Kumar</center> 
</td>
<td>
      <center>2035</center> 
</td>
<td>
      <center>9938244340</center> 
</td>
<td>
      <center>New Delhi</center> 
</td> 
  </tr>

</table>

<P align="center"><a href="DownloadExcel.jsp" style="color:Blue;">Download Excel</a></P>



//---------------------- Save As "DownloadExcel.jsp" -------------------//


 <%   
     response.setHeader("Content-Disposition","attachment;filename=Report.xls");   
     response.setContentType("application/vnd.excel");  
 %> 

<table width="60%" align="center" border="1" style="border-collapse: collapse" bordercolor="#111111" class="textn">
<tr>
  
<td colspan="3"><strong>Download Report:</strong></td>
<br/>
</tr>

</table>

<table width="60%" align="center" border="1" style="border-collapse: collapse" bordercolor="#111111" class="textn">
 
  <th style="">Emp Name</th>  
 <th>Emp ID</th>
    <th>Mobile</th>
    <th>City</th>
<tr>
  <td>
      <center>Aman Kumar</center> 
</td>
<td>
      <center>1099</center> 
</td>
<td>
      <center>9918299393</center> 
</td>
<td>
      <center>Noida</center> 
</td> 
  </tr>
<tr>
  <td>
      <center>Nitin Kumar</center> 
</td>
<td>
      <center>1233</center> 
</td>
<td>
      <center>956829937</center> 
</td>
<td>
      <center>Ghaziabad</center> 
</td> 
  </tr>
<tr>
  <td>
      <center>Brijesh Bhagat</center> 
</td>
<td>
      <center>1405</center> 
</td>
<td>
      <center>9338299345</center> 
</td>
<td>
      <center>Lucknow</center> 
</td> 
  </tr>
<tr>
  <td>
      <center>Suraj Kumar</center> 
</td>
<td>
      <center>2035</center> 
</td>
<td>
      <center>9938244340</center> 
</td>
<td>
      <center>New Delhi</center> 
</td> 
  </tr>
</table>

Tuesday 24 September 2013

How to validate username and password from database in jsp



<!-- login.jsp -->

<Body>
<form action="loginAction.jsp" method="GET" name="login" >
<table border="1" style="border-collapse:collapse;" cellpadding="5px">
  <tr>
    <td>
      <Strong>User Name:</strong>
    <input type="text" name="username" id="username" size="30" maxlength="50" />
   </td>
 </tr>
  <tr>
    <td>
      <Strong>Password:&nbsp;&nbsp;&nbsp;</strong>
    <input type="password" name="password" id="password" size="30"  maxlength="50" />
   </td>
 </tr>
  <tr>
    <td>
      <input type="submit" id="submit" name="submit"  value="Submit"></input>
    <input type="reset" id="reset" name="reset" value="Reset"></input>
   </td>
 </tr>
</table>
</form>
</Body>

// ------------------------------------------------------------------------------------------------

<!-- loginAction.jsp -->

<%@ page import="java.util.*"%>
<%@ page import="java.sql.*"%>
<%@ page import="java.io.*"%>
<%@ page import="java.text.*"%>

<%
Statement st=null;
Connection con=null;
ResultSet rs=null;

 
   // JDBC driver name and database URL
     final String DB_URL  = "jdbc:mysql://127.0.0.1:3306/test";
//  Database credentials
      final String DB_USER = "root";
      final String DB_PASS = "public";
String user = request.getParameter("username");
String pass = request.getParameter("password");

try{
 
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(DB_URL,DB_USER,DB_PASS);
st = con.createStatement();

String QueryString = "select username,pass from auth where username='"+user+"' and pass = '"+pass+"'";
rs = st.executeQuery(QueryString);
if(rs.next()){
out.print("Login Successfully."); 
}
else
out.print("User Name and password are not Valid..");
}
catch (Exception e){
  out.print(e);
}
finally{
st.close();
rs.close();
con.close();
}
%>

Friday 13 September 2013

How to calculate text length of Textarea in Jquery




<script type="text/javascript" src="js/jquery-1.8.0.js"></script>
<script type="text/javascript">
$(document).ready(function(){

var TotalLength = 50;

$("#txt-imgdisc").keyup(function(evt){
  var charCode = (evt.which) ? evt.which : event.keyCode;

var textlength = $(this).val().length;
if(textlength > TotalLength)
{
if(charCode === 8)
{
return true;
}
return false;
}
$("#spresult").text(TotalLength-textlength);

});
$("#txt-imgdisc").keydown(function(evt){
  var charCode = (evt.which) ? evt.which : event.keyCode;
var textlength = $(this).val().length;
if(textlength > TotalLength)
{
if(charCode === 8)
{
return true;
}
return false;
}
  $("#spresult").text(TotalLength-textlength);
  });
});
 </script>
<p style="color:red; font-weight:bold;">Enter Text Less then 50</p> <textarea id="txt-imgdisc" name="imgdisc" rows="5" cols="30" class="required require" maxlength="400" validate="Please enter the image discription."></textarea>
 <span id ="spresult" style="color:green; font-weight:bold;" >50</span>