Monday 1 April 2013

Session Example in jsp


Session-exp.jsp

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <p align="center"><%if(request.getParameter("msg")!=null){out.print(request.getParameter("msg"));}%></p>
        <form action="validate.jsp" method="post">
        Name<input type="text" name="userid"/><br>
        Password<input type="password" name="pass"/><br>
        <input type="submit" name="submit" value="login"/>
        </form>  
        <h1>Hello World!</h1>
    </body>
</html>

home.jsp

<%
String user=(String)session.getAttribute("user");
if(user==null){
    response.sendRedirect("session-exp.jsp?msg=Invalid session");
}
%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <p><a href="logout.jsp">Logout</a><p>
        <h1>Welocome: <%=user%></h1>
    </body>
</html>

validate.jsp

<%
String userid=request.getParameter("userid");
String pass=request.getParameter("pass");
if(userid.equals("aman") && pass.equals("kumar")){
    session.setAttribute("user", userid);
    response.sendRedirect("home.jsp");
} else{
    response.sendRedirect("session-exp.jsp?msg=Invalid username or password.");
}
%>

logout.jsp

<%
session.invalidate();
response.sendRedirect("session-exp.jsp?msg=Logout successfully");
%>

Mysql Database Connection through jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
  <form action="formAction.jsp" method="get" name="form1" id="form1">
  
     <table>
         <tr>
            <td><strong>UserName:</strong> <input type="text" name="username" id="username" size="30"/></td>
         </tr>
         <tr>
            <td><strong>Password:</strong>   <input type="password" name="password" id="password" size="30"/></td>
         </tr>
         <tr>
            <td><strong>Url:</strong>             <input type="text" name="url" id="url" size="50"/></td>
         </tr>
         <tr><td><input type="submit" value="Submit" name="submit"/>   <input type="reset" name="reset" value="Reset"/><a href="outPut.jsp">Show Database</a> </td></tr>
     </table>

  </form>

</body>
</html>


// Create Mysql Database Connection with jsp//
// Insert Data in Database //


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

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

<%
   
    Connection con = null;
    Statement stmt = null;
    PreparedStatement psmt = null;
    ResultSet rs = null; 

   if((request.getParameter("submit")!=null)&&(request.getParameter("submit")!=""))
   {
     String username = request.getParameter("username");
     String password = request.getParameter("password");
     String url = request.getParameter("url");
  
   try{
      
       String _class = "com.mysql.jdbc.Driver";
       String _driver = "jdbc:mysql://localhost:3306/test";
       String _user = "root";
       String _pass = "public";
      
       int updateQuery;
      
       Class.forName(_class); //Load the driver
       con = DriverManager.getConnection(_driver,_user,_pass); //Create the connection
      
       String Query1 = "Insert into cromext(username,password,url)values(?,?,?)";
       psmt = con.prepareStatement(Query1);
      
       psmt.setString(1,username);
       psmt.setString(2,password);
       psmt.setString(3,url);
      
       updateQuery = psmt.executeUpdate();
      
       if(updateQuery !=0)
       %>
         <TABLE style="background-color: #E3E4FA;" WIDTH="30%" border="1">
                    <tr><th>Data is inserted successfully in database.</th></tr>
        </TABLE>
        <%      
      
   }
   catch(Exception ex) {
      
       out.println("Unable to process the database."+ex);
   }
   finally{
       //rs.close();
       psmt.close();
       con.close();
      
       }
   }
%>


// Show the result of database through 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">

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

<%
   
    Connection con = null;
    Statement stmt = null;
    PreparedStatement psmt = null;
    ResultSet rs = null;

     String username = request.getParameter("username");
     String password = request.getParameter("password");
     String url = request.getParameter("url");
  
   try{
   
       String _class = "com.mysql.jdbc.Driver";
       String _driver = "jdbc:mysql://localhost:3306/test";
       String _user = "root";
       String _pass = "public";
      
       Class.forName(_class);
       con = DriverManager.getConnection(_driver,_user,_pass);
       stmt = con.createStatement();
      
       String Query1 = "select username,url from cromext";
       rs = stmt.executeQuery(Query1);
%>
  <style>
  a:link { color: red; text-decoration: none; }
  a:visited { color: red; text-decoration: none; }
  a:curser {}
  a:hover { color: Green; }
  </style>
  <center><H2>Show Database</H2><h4><a href="index.html">Home</a>  <a href="update.jsp" >Update Data</a>  <a href="delete.jsp">Delete Data</a></h4></center>
  <TABLE  cellpadding="3"  border="1" style="background-color:#e2e8e1; border-collapse:collapse; border-color:Black; border-style:solid;color:black; " align="center">
   <th> No. </th>
   <th> User Name</th>
   <th> Url </th>
    <%
    int i=0;
       while(rs.next()){
       i++;
    %>
    <tr bgcolor="#ffd1d7">
    <td><%out.print(i); %></td>
    <td><%=rs.getString(1)%></td>
    <td><%=rs.getString(2)%></td>
    </tr>
   <%  if(rs.next()){
     i++;  %>
      <tr bgcolor="#f1efe2">
    <td><%out.print(i); %></td>
    <td><%=rs.getString(1)%></td>
    <td><%=rs.getString(2)%></td>
    </tr>
   <% } }%>
  </TABLE>
<%      
      
     }
   catch(Exception ex){
       out.print("Unable to get the Data."+ex);
   }
      
   finally{
       rs.close();
       stmt.close();
       con.close();
   }
  
   %>

Div hide Technique on JavaScript

<html>
<head>
<script type="text/javascript">
function hideshow() {

if (document.getElementById("adiv").style.display == "none") {
document.getElementById("adiv").style.display = "block";
} else {
document.getElementById("adiv").style.display = "none";
}
}
</script>
</head>
<body>
<a href="javascript:hideshow()">Working Hours</a>
<div id="adiv" style="font: 24px bold; display: none">
<table color="Red">
<tr>
</tr>
<tr>
<td>I Love Javascript...</td>
</tr>
</table>
</div>
</body>
</html>

Simple Ajax code


<script language="javascript" type="text/javascript">
 var xmlHttp;
 function modifyData(Str) {

   if(document.getElementById("td1").style.display=="none")
         {document.getElementById("td1").style.display="block";}
         else{document.getElementById("td1").style.display="none";}

  var versionIds = [ "Msxml2.XMLHTTP", "Microsoft.XMLHTTP",
    "Microsoft.XMLDOM", "Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.5.0",
    "Msxml2.XMLHTTP.4.0", "Msxml2.XMLHTTP.3.0",
    "Msxml2.XMLHTTP.2.6", "Microsoft.XMLHTTP.1.0",
    "Microsoft.XMLHTTP.1" ];
  if (typeof XMLHttpRequest != "undefined") {
   xmlHttp = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
   for ( var i = 0; i < versionIds.length; i++) {
    try {

     return new ActiveXObject(versionIds[i]);


    } catch (e) {

     alert("Browser does not support XMLHTTP Request");
    }
   }
   new XDomainRequest();
  }
  if (xmlHttp == null) {
   alert("Browser does not support XMLHTTP Request");
   return;
  }

  var url = "outPut.jsp?";
  url += "id=" + Str;
  url += "&sid=" + Math.random();
  xmlHttp.onreadystatechange = stateChange;
  xmlHttp.open("POST", url, true);
  xmlHttp.send(null);

  function stateChange() {
   if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
     document.getElementById("td1").innerHTML=xmlHttp.responseText;
   }
  }
 }

</script>


    <table align="center" >

       <tr>
            <td><input type="text" size="30" maxlength="50" name="search1" value=""/><input type="button"     name="searchbtn" value="Search" onclick='modifyData(this.value);'/></td>
       </tr>
       <tr>
            <td id="td1"></td> 
       </tr>
    </table>

Ajax example using with jsp



// Using this Ajax example you can show data with jsp into text area, text field. 

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

<% 
  Connection con = null;
  ResultSet rs = null;
  Statement stmt = null;
  
  Class.forName("net.sourceforge.jtds.jdbc.Driver");
  con = DriverManager.getConnection("jdbc:jtds:sqlserver://localhost:1433/amantrn", "aman","kumar");
 // stmt = con.createStatement();
%>

<%-- <% --%>
<!--   String Query1="SELECT [id],[username],[password],[email],[profile] FROM [admin]"; -->
<!--   stmt = con.createStatement(); -->
<!--   ResultSet rs1 = stmt.executeQuery(Query1); -->
  
<!-- %> -->

<script language="javascript" type="text/javascript">
 var xmlHttp;
 function modifyData(Str) {
  
  var versionIds = [ "Msxml2.XMLHTTP", "Microsoft.XMLHTTP",
    "Microsoft.XMLDOM", "Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.5.0",
    "Msxml2.XMLHTTP.4.0", "Msxml2.XMLHTTP.3.0",
    "Msxml2.XMLHTTP.2.6", "Microsoft.XMLHTTP.1.0",
    "Microsoft.XMLHTTP.1" ];
  if (typeof XMLHttpRequest != "undefined") {
   xmlHttp = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
   for ( var i = 0; i < versionIds.length; i++) {
    try {

      return new ActiveXObject(versionIds[i]);

     } catch (e) {
     alert("Browser does not support XMLHTTP Request");
    }
   }
   new XDomainRequest();
  }
  if (xmlHttp == null) {
   alert("Browser does not support XMLHTTP Request");
   return;
  }
  
  var url = "modify.jsp?";
  url += "id=" + Str;
  url += "&sid=" + Math.random();
  xmlHttp.onreadystatechange = stateChange;
  xmlHttp.open("POST", url, true);
  xmlHttp.send(null);
  
  function stateChange() {
   if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
    var abc = xmlHttp.responseText.split("~");
    //alert(abc);
    document.getElementById('id').value = abc[0];//id
    document.getElementById('name').value = abc[1];//Username
    document.getElementById('pass').value = abc[2];//Password
    document.getElementById('email').value = abc[3];//Email
    //document.getElementById("id").value = abc[4];//Profile
   }
  }
 }
</script>

<form name="modify.jsp">
<table>
  <tr>
   <td>Id:</td>
     <td><input type="text" name="id" id="id" value="" onblur='modifyData(this.value);'/></td>
  </tr>
    <tr>
   <td>Name:</td> 
    <td><input type="text" name="name" id="name" value=""/></td>
  </tr>
   <tr>
   <td>Password:</td>
   <td><input type="password" name="pass" id="pass" value="" /></td>
  </tr>
   <tr>
   <td>Email:</td>
   <td><input type="text" name="email" id="email" value="" /></td>
  </tr>
  <tr>
  <td><input type="reset" value="Clear"></td>
  <td></td>
  </tr>
</table>
</form>


// modify.jsp 


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

<% 
  Connection con = null;
  ResultSet rs = null;
  Statement stmt = null;
  
  Class.forName("net.sourceforge.jtds.jdbc.Driver");
  con = DriverManager.getConnection("jdbc:jtds:sqlserver://localhost:1433/amantrn", "aman","Kumar");
  stmt = con.createStatement();
%>

<%
  String id = request.getParameter("id").trim();
  String Query1="SELECT [id],[username],[password],[email],[profile] FROM [admin] where id like '"+id+"%' ";
  stmt = con.createStatement();
  ResultSet rs1 = stmt.executeQuery(Query1);
  while(rs1.next()){
%>

<%=rs1.getString("id").trim()%>~<%=rs1.getString("username")%>~<%=rs1.getString("password")%>~<%=rs1.getString("email")%>~
<% }%>

JavaScript alert validation on click

<!-- JavaScript alert validation on click  -->

<html>
<head>
<script type="text/javascript">
function msg()
 {
   var m = document.getElementById('textfield')
   if(m.value !="")
    {
       alert("Your Value is"+textfield.value);
     }
    else
     {
       alert("Enter some Text... ");
     }
 }
</script>
</head>
  <body>
    <input type= 'text' id= 'textfield'>
    <input type='button' onClick="msg()" value='Click Me'>
  </body>
</html>


<!-- Search box validation with JavaScript --> 


<script language="javascript" type="text/javascript">
function clearText(field)
{
    if (field.defaultValue == field.value)
 field.value = '';
    else if (field.value == '')
 field.value = field.defaultValue;
}
</script>
</head>
<body>
<div id="search_bar_wrapper">

 <div id="search_bar">
     <div id="search_box">
            <form action="#" method="get">
                <input type="text" value="Enter keyword here..." name="q" size="20" id="searchfield" title="searchfield" onfocus="clearText(this)" onblur="clearText(this)" />
                <input type="submit" name="Search" value="Search" alt="Search" id="searchbutton" title="Search" />
            </form>
        </div>
    </div>
</div>

<!-- JavaScript value split Example  -->


<html>
<head>
<script type="text/JavaScript">
function sp(){
var name,i;
name = document.getElementById("user").value;
var arraydata = name.split(',');
for(i=0;i<arraydata.length;i++){
alert(i);
//document.write(name);
a = arraydata[0];
b = arraydata[1];
c = arraydata[2];
d = arraydata[3];
}
document.writeln(a);
document.writeln(b);
document.writeln(c);
document.write(d);
return false;
}
</script>
<head>
<form name="s">
<body>
user name <input type="text" value="" name="user" id="user"/>
<input type="button" onclick ="return sp();" value="submit"/>
</body>
</form>
<html>

SQL

SQL