Wednesday, 15 April 2015

How to populate Drop Down From Database Table in Java

Before create project you have to understand from a JSP file you have to create JDBC Connection with default port 3306  and call HTML Code inside JSP page :--

==========================index.jsp====================================




<%@ page import="java.sql.*" %>
<%ResultSet resultset =null;%>

<HTML>
<HEAD>
    <TITLE>Welcome in Java by Anand,Bangalore</TITLE>
</HEAD>

<BODY BGCOLOR=#66CCFF>

<%
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/Anand";
con = DriverManager.getConnection(url, "root", "pass@123");
    Statement statement = con.createStatement() ;
    resultset =statement.executeQuery("select * from blore") ;
%>

      <center>
    <h1> Welcome in Java by Anand,Bangalore</h1>
        <select>
        <%  while(resultset.next()){ %>
            <option><%= resultset.getString(2)%></option>
        <% } %>
        </select>
     </center>

<%

        }
        catch(Exception e)
        {
             out.println("wrong entry"+e);
        }
%>

</BODY>
</HTML>

======================Create Table Form DB=========================

> Create Database Anand;
> use Anand;
> Create table blore(id int(4), city varchar(30));;
>  insert into blore values('1',"Rewa");
insert into blore values('2',"Pune");
insert into blore values('3',"Bangalore");
insert into blore values('4',"Satna");


Monday, 13 April 2015

Simple Login Form With Servlet Forwarding

For Creating a login form with Servlet we have require some files
For fornt End:-index.html
For Forwarding control: Demo.java (Create as a servlet not a normal java file)
-----
index.html
---
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
@author ananddw
-->
<html><body>

        <form action="welcome" method="get" align="center">
           
                    Enter your name<input type="text" name="name"> <br>
               
           
                    Enter you password<input type="password" name="password"> <br>
 

            <input type="submit" value="login">
        </form>
</html>


============= Demo.java================




import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author ananddw
 */

public class Demo extends HttpServlet{
   
public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
{
   
res.setContentType("text/html");

PrintWriter pw=res.getWriter();

String name=req.getParameter("name");
    System.out.println("Name is "+name);

String password=req.getParameter("password");
    System.out.println("Password is "+password);


pw.println("Welcome :-"+name +",with password:-"+password);

}
}
===============web.xml=======================

<web-app>

<servlet>
<servlet-name>anand</servlet-name>
<servlet-class>Demo</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>anand</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>

</web-app>

============================================
Run this programme on server make sure that while creating a project you create dynamic web project else you will get Error .

Wednesday, 8 April 2015

Basic HTML Tag Used

<!---- 
Author: Anand
-->



<html>
      <head>
            <title> Welcome in the World of HTML </title>
            
      <form align="center">
            
      <body bgcolor="##33CCFF">
    
      <select name="DropDown">
            
          <option  id="1"  value="Anand" > Anand </option>
          
           <option  id="2" value="Antrish" >Antrish </option>
           
          <option  id="3" value="Ajeet" >Ajeet </option>
         
      </select>
      
      <br></br>
      
    DatePicker:  <input type="date" value="date"/>
    
       <br></br>
       
    Name:<input type="text" name="Username" />
    
     <br></br>
     
     Password:<input type="password" name="password" />
     
      <br></br>
      
      Male:<input type="radio" name="Male" value="male" checked="checked" />
      
       Female:<input type="radio" name="Male" value="male" checked="checked" />
       
          <br></br>
          
          ON:<input type="checkbox" name="ON" value="ON" checked="checked" />
          
          OFF:<input type="checkbox" name="OFF" value="OFF" checked="checked" />
          
            <br></br>
            
            <ol>
                  
                  <li>Ajeet</li>
                  
                  <li>Antrish</li>
                  
                  <li>Anand</li>
                  
            </ol>

            
             <br></br>
 <input type="file" name="Browse File" value="" width="50" />
             
              <br></br>
              
              <a href="http://learnjavabyanand.blogspot.in/">Click here</a>
              
            <br></br>
            
            <input type="submit" value="Submit" name="Submit" />

     
      </bdoy>
      
      </form>
      
</head>
  
</html>

             

            

Tuesday, 7 April 2015

How to get client IP address in a servlet

package com.anand;

import java.io.IOException;
import java.io.PrintWriter;

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

public class ClientIP extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

     response.setContentType("text/html");
     PrintWriter out = response.getWriter();
            String name = request.getParameter("name");
           System.out.println("Eneter Name : " + name);
           System.out.println("IP Address of request : </font></b>" +
            request.getRemoteAddr()+"<h3>");

 }
}  

How to Get Client IP Address Using Java Code

/*
 * @author :Anand
 */

package com.anand;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class IP{

public static void main(String[] args) {
 
 InetAddress ip;
 try {
 
ip = InetAddress.getLocalHost();
System.out.println("Your IP is====>" + ip.getHostAddress());
 
 } catch (UnknownHostException e) {
 System.out.println("catch the exception if Error Come ===>"+e);
 
e.printStackTrace();
 
 }
 
}
 
}

Saturday, 4 April 2015

"How to Read file Line by line from your system Using java code "

package com.Anand;

/*  
 * Created by : Anand
 * Date: 04-APR-2015       
 *         */



import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Reader {



 
public static void main(String[] args) {
 
try (
BufferedReader br = new BufferedReader(new FileReader("E:\\Anand.txt")))

{
System.out.println("Read file ok ===> "+br);
String LinebyLine;
 
while ((LinebyLine = br.readLine()) != null) {
System.out.println("Read file Line by line===> "+LinebyLine);
}
 
} catch (IOException e) {
e.printStackTrace();

 
}}

Wednesday, 1 April 2015

 ======================================================================
How to See Total Visitors in webpage Using  HTMl front End and Servlet Used for forwarding the Control ?
=======================================================================
For creating this project we need to create Some files like :-
index.jsp :- for front page
logout.jsp:- for log out page
            
________________________________index.jsp________________________________________

<html>
<body bgcolor="#FFCCFF">
<h1 align="center">Welcome to the World of java </h1>
<table align="right">
<tr>
<td>
<h4>
Total Visited :<%=application.getAttribute("TV") %>
</h4></td>
</tr>
<tr>
<td>
<h4>
Total Active :<%=application.getAttribute("TA") %>
</h4></td>
</tr>
</table>
<br />
<br />
<h4 align="center">Home page</h4>
<br />
<br />
<a href="logout.jlc">LOGOUT</a>
</body>
</html>

____________________________________Logout.jsp____________________________________
<%@ page session="false"%>
<html>
<body bgcolor="#FFCCFF">
<h1>Welcome to the World of java </h1>
<table align="right">
<tr>
<td>
<h4>
Total Visited :<%=application.getAttribute("TV") %>
</h4></td>
</tr>
<tr>
<td>
<h1>
Total Active :<%=application.getAttribute("TA") %>
</h1></td>
</tr>
</table>
<br />
<br />
<h4>You have logged out successfully</h4>
<br />
<br />
<a href="index.jsp">Go To Index Page</a>
</body>
</html>

======================================================================
Now for forwarding a Control we have create three servlet classes 
LogoutServlet.java
MyContextListener.java
MySessionListener.java

______________________________LogoutServlet.java ________________________________
package com.servlet;

import java.io.IOException;

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;
public class LogoutServlet extends HttpServlet {
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    HttpSession sess=req.getSession(false);
    if(sess!=null)
    sess.invalidate();
    RequestDispatcher rd=req.getRequestDispatcher("logout.jsp");
    rd.forward(req, res);
}

}

__________________________MyContextListener.java________________________________
package com.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class MyContextListener implements ServletContextListener {
      public void contextInitialized(ServletContextEvent event) {
    System.out.println("**ContextInitialized***");
    ServletContext ctx=event.getServletContext();
    ctx.setAttribute("TV", 0);  
    ctx.setAttribute("TA", 0);  
    }
    public void contextDestroyed(ServletContextEvent arg0) {
    System.out.println("***contextDestroyed**");
    }
}

__________________________MySessionListener.java______________________________
package com.servlet;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class MySessionListener implements HttpSessionListener {
    public void sessionCreated(HttpSessionEvent event) {
    HttpSession sess=event.getSession();
    ServletContext ctx=sess.getServletContext();
    int tv=(Integer) ctx.getAttribute("TV");
    tv++;
    ctx.setAttribute("TV", tv);
    int ta=(Integer) ctx.getAttribute("TA");
    ta++;
    ctx.setAttribute("TA", ta);
    }
    public void sessionDestroyed(HttpSessionEvent event) {
    HttpSession sess=event.getSession();
    ServletContext ctx=sess.getServletContext();
    int ta=(Integer) ctx.getAttribute("TA");
    ta--;
    ctx.setAttribute("TA",ta);
    
    }
}
====================================================================
For mapping
web.xml 

_______________________________web.xml___________________________________
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Lab29</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>logoutServ</servlet-name>
    <servlet-class>com.servlet.LogoutServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>logoutServ</servlet-name>
    <url-pattern>/logout.jlc</url-pattern>
  </servlet-mapping>
  <listener>
    <listener-class>com.servlet.MyContextListener</listener-class>
  </listener>
  <listener>
    <listener-class>com.servlet.MySessionListener</listener-class>
  </listener>
</web-app>



==================================================================
Please find attached image   where we put all these files so it can be accessible  and O/P Console as well .


if any Doubt and suggestion  wanted Contact any time 





Thanks & Regards
Anand Dwivedi
Software Developer 
Email: ananddwivedi92@gmail.com

Map class field to map

 import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; public class AutogeneratedClassMapper {     public static M...