Tuesday, 25 August 2015

Online Book Store Website Using Java

===============================================
Login.html:-
================================================
<html>
    <title>|| Login Page ||</title>
    <body class="bod">
        <form action='login.action'  method="post">
            <table align='center'>
                <tr><td colspan='2' align='center'>
                        <br></br>
                        <h2 style="color: black; font-size: 30px; padding-top: 1%;" class="Head">User Login</h2></td></tr>

                <tr>
                    <td><h2>UserName</h2></td>
                    <td><input type='text' name='UserName' placeholder="UserName" autocomplete="off" required=""/></td></tr>
                <tr>
                    <td><h2>password</h2></td>
                    <td><input type='password' name='Password' placeholder="password" autocomplete="off" required=""/></td></tr>
                <tr>
                    <td align="center" colspan=2><input type='submit' value='Submit' style="background-color: indianred" class="But"/></td></tr>
            </table>
            <div id="footerbottom">
                <div class="footerwrap">
                    <div id="copyright">2015 - Designed By -Anand Dwivedi.<a href="http://learnjavabyanand.blogspot.in/" target="_blank"><img src="test.png" width="150" height="28" border="0"  /></a></div>

                </div>
            </div>
        </form>
        <style type="text/css">

            .formd{
                background-color: darkcyan;
                text-align: center;
                alignment-adjust: center;
                margin-left: 42%;

            }
            .bod{
                background-color:darkcyan;
                text-align: center;
                margin-top: 13%;
            }
            .tb{
                alignment-adjust: center;
                alignment-baseline: central;
            }
            .But{
                margin-top: 9%;
            }
            .footerwrap{
                background-color: #7a7a7a;
                position:absolute;
                bottom:0;
                width:100%;
                left:  -0.5px;
                height:50px; 
                text-align: center;

            }
            .Head{
                background-color: #7a7a7a;
                position:absolute;
                top: -23px;
                width: 100%;
                left: -0.5;
                height: 50px;
                text-align: center;

            }

        </style>
    </body>
</html>
================================================
Session.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.
-->
<html>
  
    <body>
        <form action="TestBook.action" method="post" >
        <input type="button" name="Click Here to Check Session" value="Click Here to Check Session"/>
    </form>
        </body>
   
</html>
================================================
Index.jsp
================================================
<%--
    Document   : newjspTest
    Created on : Aug 7, 2015, 3:15:17 PM
    Author     : ananddw
--%>


<html>
    <body class="bod">
        <title>|| Select Book || </title>
    <center>
        <h1 style="color: black; font-size: 30px; padding-top: 1%;" class="Head"> BookStore</h1>

        <form action="searchbook.action" method="post" class="formd" >
            <table class="tb">
                <tr>
                    <td style="alignment-adjust: center; text-align:center; color: darkgrey;"><h2>Select Category</h2>
                    </td>
                </tr>
                <tr>
                    <td><select name="category" style="background-color: mediumpurple">
                            <option value="Select">Select</option>
                            <option value="Java">Java</option>
                            <option value="Testing">Testing</option>
                            <option value=".NET">.NET</option>
                            <option value="SAP">SAP</option>
                        </select></td>
                </tr>
                <br></br>
                <tr>
                    <td><input type="submit" value="SearchBooks"  style="background-color: indianred" class="But">
                    </td>
                </tr>
            </table>


            <table class="tb" align="right">
                <tr>
                    <td>
                        <h1>
                            Total Visited :<%=application.getAttribute("TV")%>
                        </h1></td>
                </tr>
                <tr>
                    <td>
                        <h1>
                            Total Active :<%=application.getAttribute("TA")%>
                        </h1></td>
                </tr>
            </table>

            <a href="logout.action" class="logout">LOGOUT</a>






            <div id="footerbottom">
                <div class="footerwrap">
                    <div id="copyright">2015 - Designed By -Anand Dwivedi.<a href="http://learnjavabyanand.blogspot.in/" target="_blank"><img src="test.png" width="150" height="28" border="0"  /></a></div>

                </div>
            </div>
        </form>
        <style type="text/css">
            .formd{
                background-color: darkcyan;
                text-align: center;
                alignment-adjust: center;
                margin-left: 42%;

            }
            .bod{
                background-color:darkcyan;
                text-align: center;
                margin-top: 5%;
            }
            .tb{
                alignment-adjust: center;
                alignment-baseline: central;
            }
            .But{
                margin-top: 20%;
            }
            .footerwrap{
                background-color: #7a7a7a;
                position:absolute;
                bottom:0;
                width:100%;
                left:  -0.5px;
                height:50px; 
                text-align: center;

            }
            .Head{
                background-color: #7a7a7a;
                position:absolute;
                top: -23px;
                width: 100%;
                left: -0.5;
                height: 50px;
                text-align: center;
            }
            .logout{

                position:absolute;
                top: -23px;
                width: 10%;
                left: -0.5;
                height: 50px;
               text-decoration-color: aqua;
                margin-left: 88%;
            margin-top: 4%;
            }
        </style>
    </center>
</body>
</html>
================================================
logout.jsp
================================================
<%@ page session="false"%>
<html>
    <body class="bod">
        <table align="right" class="tb">
            <tr>
                <td>
                    <h3>
                        Total Visited :<%=application.getAttribute("TV")%>
                    </h3></td>
            </tr>
            <tr>
                <td>
                    <h3>
                        Total Active :<%=application.getAttribute("TA")%>
                    </h3></td>
            </tr>
        </table>
        <br />
        <br />
        <h2>You have logged out successfully</h2>
        <br />
        <br />
        <a href="Login.html">Go To Login Page</a>

        <div id="footerbottom">
            <div class="footerwrap">
                <div id="copyright">2015 - Designed By -Anand Dwivedi.<a href="http://learnjavabyanand.blogspot.in/" target="_blank"><img src="test.png" width="150" height="28" border="0"  /></a></div>

            </div>
        </div>
    </body>
    <style type="text/css">
        .formd{
            background-color: darkcyan;
            text-align: center;
            alignment-adjust: center;
            margin-left: 42%;

        }
        .bod{
            background-color:darkcyan;
            text-align: center;
            margin-top: 5%;
        }
        .tb{
            alignment-adjust: center;
            alignment-baseline: central;
        }

        .footerwrap{
            background-color: #7a7a7a;
            position:absolute;
            bottom:0;
            width:100%;
            left:  -0.5px;
            height:50px; 
            text-align: center;

        }
        .Head{
            background-color: #7a7a7a;
            position:absolute;
            top: -23px;
            width: 100%;
            left: -0.5;
            height: 50px;
            text-align: center;
        }

    </style>
</html>
==============================================
placeorder.jsp
==============================================
<%--
    Document   : newjspTest
    Created on : Aug 7, 2015, 3:50:05 PM
    Author     : ananddw
--%>

<%@ page import="java.util.*"%>
<html>
    <title>|| Place Order ||</title>
    <body  class="bod">
    <center>

        <h2 class="Head">Book Search</h2>
        <h1 class="Header">Your order has been Done !</h1>
        <%
            session.invalidate();
        %>
        <br /> <a href="index.jsp">GO TO SEARCH PAGE</a>

    </center>
    <div id="footerbottom">
        <div class="footerwrap">
            <div id="copyright">2015 - Designed By -Anand Dwivedi.<a href="http://learnjavabyanand.blogspot.in/" target="_blank"><img src="test.png" width="150" height="28" border="0"  /></a></div>

        </div>
    </div>
        <style type="text/css">
            .Head{
                background-color: #7a7a7a;
                position:absolute;
                top: -29px;
                width: 100%;
                left: -0.5;
                height: 50px;
                text-align: center;
                color: black;
                font-size: 30px;
                padding-top: 1%;
                margin-left: -13px;
            }
            .footerwrap{
                background-color: #7a7a7a;
                position:absolute;
                bottom:0;
                width:100%;
                left:  -0.5px;
                height:50px; 
                text-align: center;

            }
            .Header{
                text-align: center;
                text-decoration-color: deeppink;
                margin-top: 17%;
            }
            .bod{
                background-color:darkcyan;
                text-align: center;
                margin-top: 20%;
            }
        </style>
    </body>
</html>
===============================================
showBooks.jsp
===============================================
<%--
    Document   : newjspTest
    Created on : Aug 7, 2015, 3:42:52 PM
    Author     : ananddw
--%>


<%@ page import="java.util.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <title>|| Show Books ||</title>
    <body class="bod">
        <center>
            <h2 class="Head">Book Search</h2>
            <br></br>
            <font color="lightblue" size="6"> ${ADDED} </font>
        </center>
        <br />
        <%
            Object obj = request.getAttribute("MSG");
            if (obj != null) {
        %>
        <br />
        <center>
            <font color="lightgreen" size="6"><%=obj%></font> <br />
            <a href="index.jsp"> <h2>Go To Search Page</h2>
            </a>
        </center>
        <%
        } else {
            obj = session.getAttribute("Books");
            ArrayList<String> blist = (ArrayList<String>) obj;
            for (String bnm : blist) {
        %>
        <form action="addtocart.action" method="post">
            <input type="hidden" name="bname" value="<%=bnm%>" /> <font size="5"><%=bnm%>
                <input type="submit" value="Add to Cart" class="add">
            </font>
        </form>
        <%
            }
        %>
        <br />
        <form action="showcart.action">
            <input type="submit" value="Show Cart" class="But"/>
        </form>
        <%
            }
        %>

        <div id="footerbottom">
            <div class="footerwrap">
                <div id="copyright">2015 - Designed By -Anand Dwivedi.<a href="http://learnjavabyanand.blogspot.in/" target="_blank"><img src="test.png" width="150" height="28" border="0"  /></a></div>

            </div>
            <style type="text/css">
                .footerwrap{
                    background-color: #7a7a7a;
                    position:absolute;
                    bottom:0;
                    width:100%;
                    left:  -0.5px;
                    height:50px; 
                    text-align: center;

                }
                .Head{
                    background-color: #7a7a7a;
                    position:absolute;
                    top: -29px;
                    width: 100%;
                    left: -0.5;
                    height: 50px;
                    text-align: center;
                    color: black;
                    font-size: 30px;
                    padding-top: 1%;
                    margin-left: -13px;
                }
                .bod{
                    background-color:darkcyan;
                    text-align: center;
                    margin-top: 5%;
                }
                .But{
                    margin-top: 5%;
                    background-color: indianred;
                }
                .add{
                    background-color: lightskyblue;
                }
            </style>
    </body>
</html>
==============================================
showcart.jsp
==============================================
<%--
    Document   : newjspTest
    Created on : Aug 7, 2015, 3:48:02 PM
    Author     : ananddw
--%>

<%@ page import="java.util.*"%>
<html>
    <title>|| Show Cart||</title>
    <body  class="bod">
    <center>

        <h2 class="Head">Book Search</h2>
    </center>
    <%Object obj = request.getAttribute("MSG");
        if (obj != null) {
    %>
    <br/><center><font color="red" size="6"><%=obj%> </font></center>
        <%
        } else {
            obj = request.getAttribute("CART");
            ArrayList<String> blist = (ArrayList<String>) obj;
            for (String bnm : blist) {
        %>
    <form action="removefromcart.action" method="post">
        <input type="hidden" name="bname" value="<%=bnm%>"/>
        <font size="5"><%=bnm%><input type="submit"  value="Remove from CART" class="But"/></font>
    </form>
    <%
        }
    %>
    <br/>
    <center><a href="placeorder.jsp">PLACE ORDER</a></center>
        <%
            }
        %><center>
        <br/><a href="showbooks.jsp">ADD TO CART</a>
    </center>

    <div id="footerbottom">
        <div class="footerwrap">
            <div id="copyright">2015 - Designed By -Anand Dwivedi.<a href="http://learnjavabyanand.blogspot.in/" target="_blank"><img src="test.png" width="150" height="28" border="0"  /></a></div>

        </div>
        <style type="text/css">
            .Head{
                background-color: #7a7a7a;
                position:absolute;
                top: -29px;
                width: 100%;
                left: -0.5;
                height: 50px;
                text-align: center;
                color: black;
                font-size: 30px;
                padding-top: 1%;
                margin-left: -13px;
            }
            .footerwrap{
                background-color: #7a7a7a;
                position:absolute;
                bottom:0;
                width:100%;
                left:  -0.5px;
                height:50px; 
                text-align: center;

            }
            .bod{
                background-color:darkcyan;
                text-align: center;
                margin-top: 5%;
                float: left;
                padding-left: 38%;
                padding-top:10%;
            }
            .But{
                margin-top: 5%;
                background-color: indianred;
            }
        </style>
    </body>
</html>


======Server Side Code AddToCartServlet================
/*
 * 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.
 */
package com.servlets;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
 *
 * @author ananddw
 */

public class AddToCartServlet extends HttpServlet {
     /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */

    protected void service(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        // Accessing the existing session object
        HttpSession sess = req.getSession(false);
        // Validating session are available or not
        if (sess == null) {
            req.setAttribute("MSG", "Session is Destroyed");
        } else {
            String bnm = req.getParameter("bname");
            // Accessing the client selected Book to session
            sess.setAttribute(bnm, bnm);
            req.setAttribute("ADDED", bnm + " is added to cart");
            System.out.println("Calling ADDtoCart Servlet Class ");
        }
        RequestDispatcher rd = req.getRequestDispatcher("showbooks.jsp");
        rd.forward(req, res);
        System.out.println("Request forward to Showbooks.jsp from Addtocard servlet class");
    }

}

======Server Side Code Loginservlet================

package com.servlets;

import java.io.IOException;
import java.io.Writer;
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 Loginservlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        System.out.println("Calling Method !!");
        //collecting the client submit the data
        String un = req.getParameter("UserName");
        String pwd = req.getParameter("Password");
        String msg = "";
        if (un.equals(pwd)) {
            msg = "<body bgcolor=darkgreen><h1 align=center><font color=red>Login success!!!!!!!!! Welcome to To Book Store </font></h1></body>";

        } else {
            msg = "Invlid login!!!Try again";
        }
       
        RequestDispatcher rd = req.getRequestDispatcher("index.jsp");
       
        rd.forward(req, res);
        System.out.println("Forward Sucessfully ");
        Writer out = res.getWriter();
        out.write(msg);
        HttpSession session = req.getSession();
        System.out.println("Session from Servlet Class===>"+session);
    }
}
======Server Side Code LogoutServlet================
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);
    }

}
======Server Side Code MyContextListener================

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**");
    }
   
}
======Server Side Code MySessionListener================


package com.servlets;

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();
        System.out.println("session Called===>"+sess);
    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);
   
    }
   
}

======Server Side Code RemoveFromCartServlet================

/*
 * 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.
 */
package com.servlets;

import java.io.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;
/**
 *
 * @author ananddw
 */

public class RemoveFromCartServlet extends HttpServlet {
     /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void service(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        HttpSession sess = req.getSession(false);
        if (sess == null) {
            req.setAttribute("MSG", "Session is distroyed");
        } else {
            String bnm = req.getParameter("bname");
            // Removing the client selected book from session
            sess.removeAttribute(bnm);
                        System.out.println("Remove Book form Session");
        }
        RequestDispatcher rd = req.getRequestDispatcher("showcart.action");
        rd.forward(req, res);
                System.out.println("request forward to Showcart using RemoveFormCartServlet Class");
    }
       

}

======Server Side Code SearchBookServlet================

/*
 * 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.
 */
package com.servlets;

import java.io.IOException;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;
/**
 *
 * @author ananddw
 */

public class SearchBookServlet extends HttpServlet {
     /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */

    protected void service(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        String cat = req.getParameter("category");
        if (cat != null && cat.equals("Java")) {
            ArrayList<String> blist = new ArrayList<String>();
            blist.add("Java");
            blist.add("Jdbc");
            blist.add("Servlet");
            blist.add("Jsp");
            blist.add("Ejb");
            blist.add("RMI");
            blist.add("HTML");
            HttpSession sess = req.getSession();
            System.out.println("Session Called?" + sess);
            sess.setAttribute("Books", blist);
            System.out.println("Session After set Attribute?" + sess);
        } else {
            req.setAttribute("MSG", "No books found with category" + cat);
        }
        RequestDispatcher rd = req.getRequestDispatcher("showbooks.jsp");
        rd.forward(req, res);
       
        System.out.println("Request Forward to showbooks.jsp page using SearchBooksServlet class");
    }

}

======Server Side Code SessionTrack================

 package com.servlets;


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

// Extend HttpServlet class
public class SessionTrack extends HttpServlet {

    public void doGet(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {
        // Create a session object if it is already not  created.
        HttpSession session = request.getSession(true);
        // Get session creation time.
        Date createTime = new Date(session.getCreationTime());
        // Get last access time of this web page.
        Date lastAccessTime
                = new Date(session.getLastAccessedTime());

        String title = "Welcome Back to my website";
        Integer visitCount = new Integer(0);
        String visitCountKey = new String("visitCount");
        String userIDKey = new String("userID");
        String userID = new String("ABCD");

        // Check if this is new comer on your web page.
        if (session.isNew()) {
            title = "Welcome to my website";
            session.setAttribute(userIDKey, userID);
        } else {
            visitCount = (Integer) session.getAttribute(visitCountKey);
            visitCount = visitCount + 1;
            userID = (String) session.getAttribute(userIDKey);
        }
        session.setAttribute(visitCountKey, visitCount);

        // Set response content type
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        String docType
                = "<!doctype html public \"-//w3c//dtd html 4.0 "
                + "transitional//en\">\n";
        out.println(docType
                + "<html>\n"
                + "<head><title>" + title + "</title></head>\n"
                + "<body bgcolor=\"#f0f0f0\">\n"
                + "<h1 align=\"center\">" + title + "</h1>\n"
                + "<h2 align=\"center\">Session Infomation</h2>\n"
                + "<table border=\"1\" align=\"center\">\n"
                + "<tr bgcolor=\"#949494\">\n"
                + "  <th>Session info</th><th>value</th></tr>\n"
                + "<tr>\n"
                + "  <td>id</td>\n"
                + "  <td>" + session.getId() + "</td></tr>\n"
                + "<tr>\n"
                + "  <td>Creation Time</td>\n"
                + "  <td>" + createTime
                + "  </td></tr>\n"
                + "<tr>\n"
                + "  <td>Time of Last Access</td>\n"
                + "  <td>" + lastAccessTime
                + "  </td></tr>\n"
                + "<tr>\n"
                + "  <td>User ID</td>\n"
                + "  <td>" + userID
                + "  </td></tr>\n"
                + "<tr>\n"
                + "  <td>Number of visits</td>\n"
                + "  <td>" + visitCount + "</td></tr>\n"
                + "</table>\n"
                + "</body></html>");
    }
}
==================Server Side ShowCartServlet============

/*
 * 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.
 */
package com.servlets;

import java.io.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;
/**
 *
 * @author ananddw
 */

public class ShowCartServlet extends HttpServlet {
     /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */

    protected void service(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        HttpSession sess = req.getSession();
        if (sess == null) {
            req.setAttribute("MSG", "Session is destroyed");
            RequestDispatcher rd = req.getRequestDispatcher("showbooks.jsp");
            rd.forward(req, res);
        } else {
            Enumeration<String> enms = sess.getAttributeNames();
            List<String> selectedlist = Collections.list(enms);
            selectedlist.remove("Books");
            if (selectedlist.size() == 0) {
                req.setAttribute("MSG", "No Books selected");
            } else {
                req.setAttribute("CART", selectedlist);
            }
            RequestDispatcher rd = req.getRequestDispatcher("showcart.jsp");
            rd.forward(req, res);
            System.out.println("Calling ShowCart Class and revert back on showcart.jsp");
        }
    }
   

}
=======================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>Lab18</display-name>
    <welcome-file-list>
        <welcome-file>Login.html</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>SBServ</servlet-name>
        <servlet-class>com.servlets.SearchBookServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>SBServ</servlet-name>
        <url-pattern>/searchbook.action</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>ATocServ</servlet-name>
        <servlet-class>com.servlets.AddToCartServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ATocServ</servlet-name>
        <url-pattern>/addtocart.action</url-pattern>
    </servlet-mapping>
    <servlet>

        <servlet-name>SCServ</servlet-name>
        <servlet-class>com.servlets.ShowCartServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>SCServ</servlet-name>
        <url-pattern>/showcart.action</url-pattern>
    </servlet-mapping>
    <servlet>

        <servlet-name>RemoveFromCartServlet</servlet-name>
        <servlet-class>com.servlets.RemoveFromCartServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>RemoveFromCartServlet</servlet-name>
        <url-pattern>/RemoveFromCartServlet</url-pattern>
    </servlet-mapping>
    <servlet>

        <servlet-name>RFCServ</servlet-name>
        <servlet-class>com.servlets.RemoveFromCartServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>RFCServ</servlet-name>
        <url-pattern>/removefromcart.action</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>loginservlet</servlet-name>
        <servlet-class>com.servlets.Loginservlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>loginservlet</servlet-name>
        <url-pattern>/login.action</url-pattern>

    </servlet-mapping>
    <servlet>
        <servlet-name>logoutServ</servlet-name>
        <servlet-class>com.servlet.LogoutServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>logoutServ</servlet-name>
        <url-pattern>/logout.action</url-pattern>
    </servlet-mapping>
    <listener>
        <listener-class>com.servlet.MyContextListener</listener-class>
    </listener>
    <listener>
        <listener-class>com.servlet.MySessionListener</listener-class>
    </listener>
</web-app>



Thursday, 13 August 2015

How to Create PDF File Using Java Code

package com.anand;

import com.lowagie.text.Document;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;

public class GeneratePDF {

    public static void main(String[] args) {
        try {
            OutputStream file = new FileOutputStream(new File("/home/ananddw/test.pdf"));
            Document document = new Document();
            PdfWriter.getInstance(document, file);
            document.open();
            document.add(new Paragraph("welcome Anand in the World of PDF "));
          
            document.close();
            file.close();

        } catch (Exception e) {

            e.printStackTrace();
        }
    }
}

===============================================
Attach Some Require Jar else you will get error 

Thanks 
Anand Dwivedi

Wednesday, 22 July 2015

How to append Same File name With Date Append in Java?

Please Find Code Below :

==================Append.java=======================
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

/**
 *
 * @author ananddw
 */
public class Append {

    public static void main(String[] args) throws IOException {
        /*

         Date date = new Date();
        File file1 = new File("/home/ananddw/Anand.json");
        String file2 = file1.getParent().toString();
        System.out.println("file 2 call ===>" + file2);
        boolean b = false;
        if (!(file1.exists())) {
            b = file1.createNewFile();
        }
        if (b) {
            System.out.println("Empty File successfully created");
        } else {

            String fileContent = "";
              String filename = file1.toString() + date;

            try {
                File f = new File(file1.toString());

                FileInputStream inp = new FileInputStream(f);

                byte[] bf = new byte[(int) f.length()];

                inp.read(bf);

                fileContent = new String(bf, "UTF-8");

                System.out.println("file===>" + fileContent);

            } catch (FileNotFoundException e) {

            } catch (IOException e) {
            }
            System.out.println("file name in else===>" + filename);
            FileWriter fw = new FileWriter(filename, true);
            System.out.println("FileWriter===>"+fw);
            String see = null;
            fw.write("Test");
            fw.close();
            System.out.println("Failed to create File");

        }

    }
}

Friday, 19 June 2015

File Monitoring Using Java API

======================WatchDog.java======================================

package net.codejava.io;

import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;

/**
 * 
 * @author anand
 *
 */
public class WatchDog {

    public static void main(String[] args) {
        try {
            WatchService watcher = FileSystems.getDefault().newWatchService();
            Path dir = Paths.get("F:\\video s\\south indian");
            dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
             
            System.out.println("Registered  dir:===>" + dir.getFileName());
             
            while (true) {
                WatchKey key;
                try {
                    key = watcher.take();
                } catch (InterruptedException ex) {
                    return;
                }
                 
                for (WatchEvent<?> event : key.pollEvents()) {
                    WatchEvent.Kind<?> kind = event.kind();
                     
                    @SuppressWarnings("unchecked")
                    WatchEvent<Path> ev = (WatchEvent<Path>) event;
                    Path fileName = ev.context();
                     
                    System.out.println(kind.name() + ": " + fileName);
                     
                    if (kind == ENTRY_MODIFY &&
                            fileName.toString().equals("Test.java")) {
                        System.out.println(" file has changed!!!======>");
                    }
                }
                 
                boolean valid = key.reset();
                if (!valid) {
                    break;
                }
            }
             
        } catch (IOException ex) {
            System.err.println(ex);
        }
    }
}




Please Find Snapshot For Monitering O/p Console 
Any help mail on :ananddwivedi92@gmail.com




How To Upload File Using Struts

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

<%-- 
    Document   : index
    Created on : Jun 17, 2015, 8:32:59 PM
    Author     : Anand
--%>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>File Upload</title>
</head>
<body>
      <center>
   <form action="upload" method="post" enctype="multipart/form-data">
      <label for="myFile">Upload your file</label>
      <input type="file" name="myFile" />
      <input type="submit" value="Upload" onclick="run()"/>
   </form>
      </center>
</body>
</html>

<script>
    function run(){
        
        alert("Data Have Been Updated Sucessfully ")
    }
    
</script>


============================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_3_0.xsd"
   id="WebApp_ID" version="3.0">
   
   <welcome-file-list>
      <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>
   <filter>
      <filter-name>struts2</filter-name>
      <filter-class>
         org.apache.struts2.dispatcher.FilterDispatcher
      </filter-class>
   </filter>

   <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>/*</url-pattern>
   </filter-mapping>
</web-app>

===============================Struts.xml==============================

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
   <package name="Anand" extends="struts-default">
   <action name="upload" class="Com.Anand.uploadFile">
       <result name="success">/index.jsp</result>
   </action>
   </package>
</struts>

==============================uploadFile.java========================

/*
 * 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 Anand
 */
package Com.Anand;
import java.io.File;
import org.apache.commons.io.FileUtils;
import java.io.IOException; 

import com.opensymphony.xwork2.ActionSupport;

public class uploadFile extends ActionSupport{
    //Declare Prviate Varriable
   private File myFile;
   private String myFileContentType;
   private String myFileFileName;
   private String destPath;

   public String execute() throws IOException
   {
     // uploaded File Data Save on this Path 
      destPath = "F:\\upload";    //create folder on F drive with upload Name or else you can provide any folder name here 

      System.out.println("Src File name: " + myFile);
      System.out.println("Dst File name: " + myFileFileName);
      File destFile  = new File(destPath, myFileFileName);
      FileUtils.copyFile(myFile, destFile);
      
      return SUCCESS;
   }
   
   //Setter and getter method for All varriable 
   public File getMyFile() {
      return myFile;
   }
   public void setMyFile(File myFile) {
      this.myFile = myFile;
   }
   public String getMyFileContentType() {
      return myFileContentType;
   }
   public void setMyFileContentType(String myFileContentType) {
      this.myFileContentType = myFileContentType;
   }
   public String getMyFileFileName() {
      return myFileFileName;
   }
   public void setMyFileFileName(String myFileFileName) {
      this.myFileFileName = myFileFileName;
   }
}


please Find Attached Image for Folder Directroy in NetBeans 

if any Help Needed Mail on :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...