Wednesday, 28 November 2012

J2ee Tutorial 15 :- Creation of custom tag using BodyTagSupport

//  Creation of custom tag using BodyTagSupport example in this example we will take user gross salary,tax allowance and tax percentage and caliculate the net salary using tag lib

Step 1 :- Create a dynamic web project

Step 2 :- Create a html page were we can take the inputs from user as given bellow
//income.html
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.w3.org/1999/xhtml
                          http://www.w3.org/2002/08/xhtml/xhtml1-strict.xsd">
  <head><title>Input Income &amp; Tax Details</title></head>
  <body>
    <h1>Enter Income &amp; Tax Figures</h1>
    <form action="taxation.jspx">//transferring control to taxation.jspx
      <table>
        <tr>//user enterring details
          <td>Enter gross income:</td>
          <td><input type="text" name="gross" /></td>
        </tr>
        <tr>
          <td>Enter tax allowance:</td>
          <td><input type="text" name="allowance" /></td>
        </tr>
        <tr>
          <td>Enter tax rate (percentage):</td>
          <td><input type="text" name="rate" /></td>
        </tr>
        <tr>
          <td colspan="2"><input type="submit" value="Calculate Net Income" /></td>
        </tr>
      </table>
    </form>
  </body>
</html>

Step 3 :- Now create the taxation.jspx were we will be having our tag used to caliculate the result salary

<html xmlns:mytags="http://www.xyz.com/taglibs/mytags"
      xmlns:jsp="http://java.sun.com/JSP/Page">//declaring our tag in xhtml format if you want you can follow jsp format
  <jsp:output omit-xml-declaration="true" />
  <jsp:directive.page contentType="text/html" />
  <head><title>Taxation, Taxation, Taxation</title></head>
  <body>
    <h1>Calculated Net Income</h1>
    <p>My net income is:
    <mytags:netincome grossIncome="${param.gross}"
                      allowance="${param.allowance}"
                      taxRate="${param.rate}"
                      currency="GBP" />//our custom tag
    </p>
  </body>
</html>

Step 4 :- Now create the myTags.tld wnder the webcontent by creating a folder name tags and place in  it

<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
  http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
  version="2.0">

  <tlib-version>1.0</tlib-version>
  <short-name>MyTagLib</short-name>
  <uri>http://www.osborne.com/mytags.tld</uri>
  <tag>
    <name>netincome</name>//our tagname implementation
    <tag-class>web.prac.TaxationTag</tag-class>
    <body-content>empty</body-content>
    <attribute>
      <name>grossIncome</name>
      <required>true</required>
      <rtexprvalue>true</rtexprvalue>
    </attribute>
    <attribute>
      <name>allowance</name>
      <required>true</required>
      <rtexprvalue>true</rtexprvalue>
    </attribute>
    <attribute>
      <name>taxRate</name>
      <required>true</required>
      <rtexprvalue>true</rtexprvalue>
    </attribute>
    <attribute>
      <name>currency</name>
      <required>true</required>
      <rtexprvalue>true</rtexprvalue>
    </attribute>
  </tag>

</taglib>

Step 5 :-  Now create the tag implementation class

package web.prac;

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

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

public class TaxationTag extends BodyTagSupport {

    private String grossIncome;

    private String taxRate;

    private String allowance;
   
    private String currency;
   
    public void setAllowance(String allowance) {
        this.allowance = allowance;
    }

    public void setGrossIncome(String grossIncome) {
        this.grossIncome = grossIncome;
    }

    public void setTaxRate(String taxRate) {
        this.taxRate = taxRate;
    }
    
    public void setCurrency(String currency) {
        this.currency = currency;
    }

    public int doStartTag() throws JspException {

        JspWriter out = pageContext.getOut();

        double gross;
        double rate;
        double allow;

        try {
            /* Convert string input to numerics */
            gross = Double.parseDouble(grossIncome);
            rate = Double.parseDouble(taxRate);
            allow = Double.parseDouble(allowance);
        } catch (NumberFormatException nfe) {
            try {
                out.write("Bad Input Figures");
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
            return super.doStartTag();
        }
       
        double taxToPay = ((gross - allow) * rate / 100);
        double net = (gross - taxToPay);
        NumberFormat nf = NumberFormat.getInstance();
        Currency c = Currency.getInstance(currency);

        nf.setCurrency(c);
        nf.setMinimumFractionDigits(c.getDefaultFractionDigits());
        nf.setMaximumFractionDigits(c.getDefaultFractionDigits());
       
        try {            
            out.print(c.getSymbol() + nf.format(net));
        } catch (IOException e) {
            e.printStackTrace();
        }
       
        return super.doStartTag();
    }
}


Step 5 :- Now map it in web.xml
<?xml version="1.0" ?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <jsp-config>
        <taglib>//declare our tag lib
            <taglib-uri>http://www.x.y.z.com/taglibs/mytags</taglib-uri>
            <taglib-location>/WEB-INF/tags/mytags.tld</taglib-location>
        </taglib>
    </jsp-config>
</web-app>

Step 6 :- Clean build and run the project

output :-Enter values an submit it



























Tuesday, 27 November 2012

J2ee Tutorial 13 :-Parsing csv in j2ee

// Parsing csv in j2ee 

Step1 ;- Create a dynamic web project

Step2 :- Chang the content in the web.xml as given bellow

<?xml version="1.0" ?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <servlet>
      <servlet-name>CSVReader</servlet-name>
      <servlet-class>web.prac.CSVReader</servlet-class>//our reader servlet
      <init-param>
        <param-name>jsp</param-name>
        <param-value>/csvRenderer.jsp</param-value>//declarring the jsp to be loaded
      </init-param>
    </servlet>
    <servlet-mapping>
      <servlet-name>CSVReader</servlet-name>
      <url-pattern>/CSVReader/*</url-pattern>
    </servlet-mapping>

</web-app>

Step 3:- Create a bean which will store the data andparse the csv

/*
 * Created on 25-Jan-2005
 *
 */
package web.prac;

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

public class CSVBean {
    private int rowCount; // Number of rows (excluding header row)

    private int fieldCount; // Number of fields in each row

    private String[] headers; // Field names (assumed to be in first row)

    private List rows = new ArrayList(); // The data

    public CSVBean() {
        // Must have a no-argument constructor as a bean.
    }

    public void parseFile(File f) {

        BufferedReader br;
        try {
            br = new BufferedReader(new FileReader(f));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return;
        }
        String line;
        boolean firstRow = true;
        try {
            while ((line = br.readLine()) != null) {
                if (firstRow) {
                    headers = tokenize(line);
                    setFieldCount(headers.length);
                    firstRow = false;
                } else {
                    String[] row = tokenize(line);
                    rows.add(row);   
                    rowCount++;
                }
            }
        } catch (IOException e1) {
            e1.printStackTrace();
            return;
        }
    }

    protected String[] tokenize(String line) {
        StringTokenizer st = new StringTokenizer(line, ",");
        int tokenCount = st.countTokens();
        String[] record = new String[tokenCount];
        for (int i = 0; i < tokenCount; i++) {
            record[i] = (String) st.nextToken();
        }
        return record;
    }

    public int getFieldCount() {
        return fieldCount;
    }

    public void setFieldCount(int fieldCount) {
        this.fieldCount = fieldCount;
    }

    public String[] getHeaders() {
        return headers;
    }

    public void setHeaders(String[] headers) {
        this.headers = headers;
    }

    public int getRowCount() {
        return rowCount;
    }

    public void setRowCount(int rowCount) {
        this.rowCount = rowCount;
    }

    public List getRows() {
        return rows;
    }

    public void setRows(List rows) {
        this.rows = rows;
    }
   
    public String toString() {
        StringBuffer sb = new StringBuffer();
        sb.append("Headers: ");
        addStringArray(headers, sb);
        Iterator it = rows.iterator();
        int rowCount = 0;
        while (it.hasNext()) {
            rowCount++;
            sb.append("Row " + rowCount + ": ");
            String[] row = (String []) it.next();
            addStringArray(row, sb);
        }
        return sb.toString();
    }
   
    protected StringBuffer addStringArray(String[] array, StringBuffer buffer) {
        for (int i = 0; i < array.length; i++) {
            buffer.append(array[i] + ",");
        }
        buffer.append("\n");
        return buffer;
    }
   
}

Step 4 :- Now create the servletwhichcontrols the flow

package web.prac;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class CSVReader extends HttpServlet {
   
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String path = request.getPathInfo();
        ServletContext context = getServletContext();
        String fullPath = context.getRealPath(path);
        File f = new File(fullPath);
        CSVBean csvBean = new CSVBean();
        csvBean.parseFile(f);
        request.setAttribute("csv", csvBean);
        String jsp = getInitParameter("jsp");
        RequestDispatcher rd = context.getRequestDispatcher(jsp);
        rd.forward(request, response);
    }
   
}

Step5 :- Final output page displaying csv data using scripletes

<html><head><title>CSV File Renderer</title></head>
<jsp:useBean id="csv" scope="request" type="webcert.ch07.ex0703.CSVBean" />
<%@ page import="java.util.*" %>
<body>
<h1>CSV File Presented As HTML Table</h1>
<h2>JSP Syntax Version</h2>
<h3>There are
<jsp:getProperty name="csv" property="rowCount" />
 rows of data, and
 <jsp:getProperty name="csv" property="fieldCount" />
  columns.</h3>
<table border="1">
  <tr>
    <th>&nbsp;</th>
    <% String[] headers = csv.getHeaders();
    for (int i = 0; i < headers.length; i++) { %>
      <th><b><%= headers[i] %></b></th>
    <% } %>
  </tr>
  <% List rows = csv.getRows();
     Iterator it = rows.iterator();
     int rowNumber=0;
     while (it.hasNext()) {
  %>
  <tr>
     <td>Row <%= ++rowNumber %></td>
  <% String[] fields = (String[]) it.next();
    for (int i = 0; i < fields.length; i++) { %>
      <td><%= fields[i] %></td>
    <% } %>
  </tr>
  <% } %>
</table>

</body></html>


Step6 :- Final output page displaying csv data usingjsp standard actions

<html xmlns:jsp="http://java.sun.com/JSP/Page" >
<head><title>CSV File Renderer</title></head>
<jsp:output omit-xml-declaration="true" />
<jsp:directive.page contentType="text/html" />
<jsp:directive.page import="java.util.*" />
<jsp:useBean id="csv" scope="request" type="web.prac.CSVBean" />
<body>
<h1>CSV File Presented As HTML Table</h1>
<h2>JSP Document (XML) Version</h2>
<h3>There are
<jsp:getProperty name="csv" property="rowCount" />
 rows of data, and
 <jsp:getProperty name="csv" property="fieldCount" />
  columns.</h3>
<table border="1">
  <tr>
    <th><![CDATA[&nbsp;]]></th>
    <jsp:scriptlet> String[] headers = csv.getHeaders();
    for (int i = 0; i &lt; headers.length; i++) { </jsp:scriptlet>
      <th><b><jsp:expression>headers[i]</jsp:expression></b></th>
    <jsp:scriptlet>}</jsp:scriptlet>
  </tr>
  <jsp:scriptlet>List rows = csv.getRows();
     Iterator it = rows.iterator();
     int rowNumber=0;
     while (it.hasNext()) {
  </jsp:scriptlet>
  <tr>
     <td>Row <jsp:expression>++rowNumber</jsp:expression></td>
  <jsp:scriptlet>String[] fields = (String[]) it.next();
    for (int i = 0; i &lt; fields.length; i++) { </jsp:scriptlet>
      <td><jsp:expression>fields[i]</jsp:expression></td>
    <jsp:scriptlet> } </jsp:scriptlet>
  </tr>
  <jsp:scriptlet> } </jsp:scriptlet>
</table>
</body></html>

J2ee Tutorial 12 :- Jsp standard actions

// Jsp standard actions  example

Step 1 :- Create a dynamic web project

Step 2 :- Create a html as given bellow which will be our first page to load

<html><head><title>Music CD</title></head>
<body>
<h2>Music CD Details</h2>
<p>Type in the details of a music CD below...<p>
<form action="musicCDsummary.jsp">
<br />Title: <input type="text" name="title" />
<br />Artist: <input type="text" name="artist" />
<br />Year of Release: <input type="text" name="year" />
<br />Favorite Track: <input type="text" name="track" />
<br /><input type="submit" value="Continue..." />
</form></body></html>

Step 3 :- Now create  musicCDsummary.jsp were we will be using jsp standard actions to store the data

<html><head><title>Music CD</title></head>
<body>
<h2>Music CD Summary</h2>
<jsp:useBean id="musicCD" class="web.prac.MusicCD" />
<jsp:setProperty name="musicCD" property="*" />//storring the data to bean
<jsp:setProperty name="musicCD" property="yearOfRelease" param="year" />//storring param
<jsp:setProperty name="musicCD" property="favoriteTrack" param="track" />
<p>These are the details you entered...</p>
<br />Title: <b><jsp:getProperty name="musicCD" property="title" /></b>
<br />Artist: <b><jsp:getProperty name="musicCD" property="artist" /></b>
<br />Year of Release: <b><jsp:getProperty name="musicCD" property="yearOfRelease" /></b>
<br />Favorite Track: <b><jsp:getProperty name="musicCD" property="favoriteTrack" /></b>
</body></html>


Step 4 :- Now create the MusicCD bean  should strictly follow javabean standards

package web.prac;

public class MusicCD {
    private String title;
    private String artist;
    private String favoriteTrack;
    private int yearOfRelease;
    public MusicCD() {
       super();
    }
   
    public String getArtist() {
        return artist;
    }
    public void setArtist(String artist) {
        this.artist = artist;
    }
    public String getFavoriteTrack() {
        return favoriteTrack;
    }
    public void setFavoriteTrack(String favoriteTrack) {
        this.favoriteTrack = favoriteTrack;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public int getYearOfRelease() {
        return yearOfRelease;
    }
    public void setYearOfRelease(int yearOfRelease) {
        this.yearOfRelease = yearOfRelease;
    }
}

Step 5 :- Clean build the project and run the html file

//output:-


After enterring the data click on continue the data will be stored to the usebean and the will also be displayed in the jsp



 

J2ee Tutorial 11 ;- Tic tac toe using jsp

//Tic tac toe example using jsp

<%@ page language="java" %>
<%
if (session.isNew()) {
   int[] squareValues = {-1, -1, -1, -1, -1, -1, -1, -1, -1};
   session.setAttribute("squareValues", squareValues);
}
int[] squareValues = null;
for (int i = 0; i < 9; i++) {
  squareValues = (int[]) session.getAttribute("squareValues");
  String s = request.getParameter("square" + i);
  if ((s != null) && s.toLowerCase().equals("x")) {
    squareValues[i] = 1;
  }
  if ((s != null) && s.toLowerCase().equals("o")) {
    squareValues[i] = 0;
  }
  session.setAttribute("squareValues", squareValues);
}
%>

<%!
private int getChoice(int squareNo, int[] squareValues) {
   return squareValues[squareNo];
}
%>
<html>
<head>
<title>Tic Tac Toe</title>
</head>
<body bgcolor="#FFFFFF">
<h1>A basic version of Tic-tac-toe (Noughts and Crosses)</h1>
<form action="tictactoe.jsp">
<table>
<% /* Establish a loop for 9 squares in 3 rows of 3 */
   for (int counter=0; counter < 9; counter++) {
      /* A row every three squares */
      if (counter % 3 == 0) { %>
         <tr><td width="15">
   <% } else { %>
         <td width="15">
   <% }
      /* Each cell should have an O, an X or an input field */
      switch (getChoice(counter, squareValues)) {
         case 0: %>
            O
         <% break;
         case 1: %>
            X
         <% break;
         default: %>
            <input type="text" size="1" length="1" name="square<%= counter %>" />
         <% break;
      }
      /* Finish row every three squares */
      if ((counter + 1) % 3 == 0) { %>
         </td></tr>
   <% } else { %>
         </td>
   <% }
   } %>


</table>
<input type="submit" value="Confirm Choice" />
</form>
</body>
</html>

//output

J2ee Tutorial 10 :- Life cycle of jsp and explanation of scriplets,expressions and declarations in jsp

//Base concept of jsp

<%@ page language="java" %>
<html>
<head>
<title>JavaServer Page Lifecycle</title>
</head>
<body bgcolor="#FFFFFF">
<h1>To illustrate JavaServer Page lifecycle</h1>
<p>Look at your server console for System.out.println() output.</p>
</body>
</html>
<%!

public void init() {
  // Illegal?
  System.out.println("Actually OK to override GenericServlet's init() convenience method");
}

public void jspInit() {
  try {
    throw new Exception();
  } catch (Exception e) {
    StackTraceElement[] st = e.getStackTrace();
    System.out.println(st[0]);
  }
 
  // Show inheritance hierarchy and implementing interfaces
  Class c = this.getClass();
  System.out.println("\nClass " + c.getName());
  while ((c = c.getSuperclass()) != null) {
    System.out.println("subclass of " + c.getName());
    Class[] ifaces = c.getInterfaces();
    for (int i = 0; i < ifaces.length; i++) {
      if (i == 0) {
        System.out.print(" which implements interfaces: "
        + ifaces[0]);
      } else {
        System.out.print(", " + ifaces[i].getName());
      }
    }
    System.out.println();
  }
}


public void jspDestroy() {
  try {
    throw new Exception();
  } catch (Exception e) {
    StackTraceElement[] st = e.getStackTrace();
    System.out.println(st[0]);
  }
}

%>

<%
  // The scriptlet code below finds its way into the _jspService() method
  try {
    throw new Exception();
  } catch (Exception e) {
    StackTraceElement[] st = e.getStackTrace();
    System.out.println(st[0]);
  }

%>

//explanation of scriplets,expressions and declarations in jsp
<%!
private String convert(int miles) {
  java.text.DecimalFormat formatter = new java.text.DecimalFormat("###.##");
  String value = formatter.format(1.6 * miles);
  return value;
}
%>
<%
int[] mileValues = {1,2,3,5,10,15,20,50,100,200,500};
%>
<html>
<head><title>Miles to Kilometers</title></head>
<body>
<table border="1">
  <tr>
    <th><b>Miles</b></th>
    <th><b>Kilometers</b></th>
  </tr>
<% for (int i = 0; i < mileValues.length; i++) { %>
  <tr>
    <td><%=mileValues[i]%></td>
    <td><%=convert(mileValues[i])%></td>
  </tr>
<% } %>
</table>
</body>
</html>

Output:-



Monday, 26 November 2012

J2ee tutorial part 9:- Listeners in servlet

//listeners concept in servlet with example


Step1 :- Declare your listeners in web.xml as given bellow

<?xml version="1.0" ?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<listener>
  <listener-class>web.prac.MyContextListener</listener-class>
</listener>

<listener>
  <listener-class>web.prac.MyContextAttributeListener</listener-class>
</listener>


<servlet>
  <servlet-name>SetContextAttributes</servlet-name>
  <servlet-class>webcert.ch04.ex0403.SetContextAttributes</servlet-class>
</servlet>

<servlet-mapping>
  <servlet-name>SetContextAttributes</servlet-name>
  <url-pattern>/SetContextAttributes/*</url-pattern>
</servlet-mapping>

</web-app>

Step2 :-  Create the servlet which generates events so thant we can implement them

package web.prac;

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

import javax.servlet.*;
import javax.servlet.http.*;

public class SetContextAttributes extends HttpServlet {

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

        PrintWriter out = response.getWriter();
        response.setContentType("text/html");
        out.write("<HTML><HEAD>");
        out.write("<TITLE>Set and Display Context Attributes</TITLE>");
        out.write("</HEAD><BODY>");

        ServletContext context = getServletContext();
       
        // Add, replace & remove some context attributes
        context.setAttribute("attribute1", "first attribute");
        context.setAttribute("attribute2", "second attribute");
        context.setAttribute("attribute1", "changed first attribute value");
        context.setAttribute("attribute2", "changed second attribute value");
        context.removeAttribute("attribute2");
       
        // Display context attributes

        Enumeration e = context.getAttributeNames();
        out.write("<H2>Context Attributes</H2>");
        while (e.hasMoreElements()) {
            String name = (String) e.nextElement();
            String value = "" + context.getAttribute(name);
            out.write("<BR />Name: " + name + ", value: " + value);
        }
       
       
        // Conclude page
        out.write("</BODY></HTML>");
        response.flushBuffer();

    }

    public void init() throws ServletException {
        super.init();
        System.out.println("In SetContextAttributes init() method.");
        ServletContext context = getServletContext();
        context.setAttribute("servletInitAttribute", "This attribute value added in servlet init() method.");
    }
}

Step 3 :- Now create your listeneres which were declared in the web.xml

package web.prac;

import javax.servlet.*;
public class MyContextAttributeListener implements
        ServletContextAttributeListener {//this listenes for change of context attributes
    public void attributeAdded(ServletContextAttributeEvent event) {
        String name = event.getName();
        String value = "" + event.getValue();
        System.out.println("Added context attribute: " + name + ", " + value);
    }

    public void attributeReplaced(ServletContextAttributeEvent event) {
        ServletContext context = event.getServletContext();
        String name = event.getName();
        String oldValue = "" + event.getValue();
        String newValue = "" + context.getAttribute(name);
        System.out.println("Replaced context attribute: " + name
                + ", old value: " + oldValue + ", new value: " + newValue);
    }

    public void attributeRemoved(ServletContextAttributeEvent event) {
        String name = event.getName();
        String value = "" + event.getValue();
        System.out.println("Removed context attribute: " + name + ", " + value);
    }
}

Step 4 :- The other listener declared in the web.xml

package webcert.ch04.ex0403;

import javax.servlet.*;

public class MyContextListener implements ServletContextListener {//this listenes for context initilization and destroying

    public void contextInitialized(ServletContextEvent event) {
        System.out.println("In MyContextListener contextInitialized() method.");
        ServletContext context = event.getServletContext();
        context.setAttribute("contextInitAttribute", "Made in the ServletContextListener");
    }

    public void contextDestroyed(ServletContextEvent event) {
        System.out.println("In MyContextListener contextDestroyed() method.");
        ServletContext context = event.getServletContext();
        context.removeAttribute("contextInitAttribute");
    }

}

Sunday, 25 November 2012

J2ee tutorial part 8 ;- Filter concept in j2ee

// Filter concept in j2ee with example

Step1 :- Create a Dynamic web Project

Step 2 :- Create a filter with name MicroPaymentFilter as given bellow

package web.prac;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

/**
 * Using a filter to suffix information to a servlet response.
 */
public class MicroPaymentFilter implements Filter {

    public void init(FilterConfig config) throws ServletException {
    }

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {

        HttpServletRequestWrapper reqWrapper = new HttpServletRequestWrapper(
                (HttpServletRequest) request);
        String referrerName = reqWrapper.getPathInfo().substring(1);
        if (referrerName != null) {
            System.out.println("Micropayment made to " + referrerName);
            reqWrapper.setAttribute("referrer", referrerName);
        }
        chain.doFilter(reqWrapper, response);//calling the consequitive servlet
        PrintWriter out = response.getWriter();
        out.write("<BR />0.0001c has been paid to referrer " + referrerName);
    }

    public void destroy() {
    }

}

Step3 :- Create a servlet which will be called after filter asgive bellow

package web.prac;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

/**
 * A servlet which reflects back details of the agent
 * referring you to the servlet.
 **/
public class MicroPaymentServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
       
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.write("<HTML><HEAD><TITLE>Sponsor Visit</TITLE></HEAD><BODY>");
       
        out.write("<H1>Thank you for visiting this page!!!</H1>");
       
        String referrer = (String) request.getAttribute("referrer");
        if (referrer != null) {
            out.write("<BR />Your were referred to this page by " + referrer + "</B>");
        }
       
       
        out.write("</BODY></HTML>");
        out.flush();
    }
}

Step 4 :- Declare the servlet,filter and map them as given bellowin web.xml

<?xml version="1.0" ?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

   
    <servlet>
      <servlet-name>MicroPaymentServlet</servlet-name>
      <servlet-class>web.prac.MicroPaymentServlet</servlet-class>
    </servlet>
    <servlet-mapping>
      <servlet-name>MicroPaymentServlet</servlet-name>
      <url-pattern>/MicroPayment/*</url-pattern>
    </servlet-mapping>

    <filter>
      <filter-name>MicroPaymentFilter</filter-name>
      <filter-class>web.prac.MicroPaymentFilter</filter-class>
    </filter>
    <filter-mapping>
      <filter-name>MicroPaymentFilter</filter-name>
      <servlet-name>MicroPaymentServlet</servlet-name>
    </filter-mapping>

   
</web-app>

 Step 5 :- clean build the project and then run it

Output;-





Saturday, 24 November 2012

J2ee tutorial part 7 :- explorring request session and application scopes

//explorring request session and application scopes
package webcert.ch03.ex0302;

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

import javax.servlet.*;
import javax.servlet.http.*;

public class AttributesAllScopes extends HttpServlet {

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

        /* Set the response type, retrieve the writer */
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out
                .write("<HTML><HEAD><TITLE>Show all the attributes, all scopes</TITLE></HEAD><BODY>");
        out.write("<H1>Show attributes for every scope</H1>");

        String attrName;
        Object attrValue;

        /* Set up a request attribute */

        request.setAttribute("my.request.attribute", "By special request");
       
        /* Set up a session attribute */
        request.getSession().setAttribute("my.session.attribute", "Today's session is about scope");
       
        out.write("<H2>Request Scope</H2>");
        Enumeration enum = request.getAttributeNames();
        while (enum.hasMoreElements()) {
            attrName = (String) enum.nextElement();
            attrValue = request.getAttribute(attrName);
            writeAttribute(out, attrName, attrValue);
        }

        out.write("<H2>Session Scope</H2>");
        HttpSession session = request.getSession();
        enum = session.getAttributeNames();
        while (enum.hasMoreElements()) {
            attrName = (String) enum.nextElement();
            attrValue = session.getAttribute(attrName);
            writeAttribute(out, attrName, attrValue);
        }

        out.write("<H2>Context (Application) Scope</H2>");
        ServletContext context = getServletContext();
        String myAttributeName = "com.osborne.conductor";
        context.setAttribute(myAttributeName, "Andre Previn");

        enum = context.getAttributeNames();
        while (enum.hasMoreElements()) {
            attrName = (String) enum.nextElement();
            attrValue = context.getAttribute(attrName);
            out.write("<BR />Attribute name: <B>" + attrName + "</B>, value: <B>"
                    + attrValue + "</B>");
        }

        // I know I put a String in there, so it's safe to cast my attribute
        // object back to a String

        String conductor = (String) context.getAttribute(myAttributeName);
        out.write("<BR /> Just used getAttribute() to obtain "
                + myAttributeName + " whose value is " + conductor);

        // Get rid of the attribute
        context.removeAttribute(myAttributeName);

        // Could have done this to remove attribute instead;

        // no harm in executing the code even though the attribute has gone.
        context.setAttribute(myAttributeName, null);

        // Check attribute has gone
        out.write("<BR />Value of attribute " + myAttributeName + " is now "
                + context.getAttribute(myAttributeName));

        /* Tidy up */
        out.write("</BODY></HTML>");

    }

    private void writeAttribute(PrintWriter out, String name, Object value) {

        out.write("<BR />Attribute name: <B>" + name + "</B>, value: <B>"
                + value + "</B>");

    }

}

//Session management example


/*
 * Created on 12-Sep-2004
 */

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

import javax.servlet.*;
import javax.servlet.http.*;

public class SessionDisplayer2 extends HttpServlet {

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

        PrintWriter out = response.getWriter();
        response.setContentType("text/html");
        out.write("<HTML><HEAD>");
        out.write("<TITLE>Session Aspects</TITLE>");
        out.write("</HEAD><BODY>");

        // Only perform session handling code when requested
        if ("true".equals(request.getParameter("getSession"))) {
           
            // Only perform session invalidation code when requested
            String maxInact = request.getParameter("maxinact");
            if (maxInact != null) {
                int timeLimit = Integer.parseInt(maxInact);
                HttpSession session = request.getSession();
                session.setMaxInactiveInterval(timeLimit);
            }
            String invalidate = request.getParameter("invalidate");
            if ("true".equals(invalidate)) {
                request.getSession().invalidate();//invalidating session
            }
           
            doSessionStuff(request, out);
           
        } else {
            out
                    .write("<BR />Session not accessed on this request to SessionDisplayer servlet");
        }

        // Forms to simplify re-calling servlet
       
        // Ensure encoded URLs are used

        String servletURL = response.encodeURL("SessionDisplayer2");
       
        out.write("<FORM action=\"" + servletURL + "\" method=\"GET\">");
        out.write("<input type=\"hidden\" name=\"getSession\" value=\"true\">");
        out.write("<br /><input type=\"submit\" value=\"Recall Servlet: Access Session\"/>");
        out.write("</FORM>");

        out.write("<FORM action=\"" + servletURL + "\" method=\"GET\">");
        out.write("<input type=\"hidden\" name=\"getSession\" value=\"false\">");
        out.write("<br /><input type=\"submit\" value=\"Recall Servlet: Don't Access Session\"/>");
        out.write("</FORM>");

        out.write("<FORM action=\"" + servletURL + "\" method=\"GET\">");
        out.write("<input type=\"hidden\" name=\"getSession\" value=\"true\">");
        out.write("<input type=\"hidden\" name=\"invalidate\" value=\"true\">");
        out.write("<br /><input type=\"submit\" value=\"Invalidate Session Immediately\"/>");
        out.write("</FORM>");

        out.write("<FORM action=\"" + servletURL + "\" method=\"GET\">");
        out.write("<input type=\"hidden\" name=\"getSession\" value=\"true\">");
        out.write("<br />Enter new session time limit in seconds: <input type=\"text\" name=\"maxinact\" />");
        out.write("<br /><input type=\"submit\" value=\"Change Session Time Limit\"/>");
        out.write("</FORM>");

       
       
       
        // Conclude page
        out.write("</BODY></HTML>");
        response.flushBuffer();

    }

    private void doSessionStuff(HttpServletRequest request, PrintWriter out) {
        HttpSession session = request.getSession();
        setAccessAttribute(session);
        displaySessionStuff(request, out);
    }

    private void setAccessAttribute(HttpSession session) {
        Integer accessCount = (Integer) session.getAttribute("accessCount");
        int a;
        if (accessCount == null) {
            a = 1;
        } else {
            a = accessCount.intValue() + 1;
        }
        session.setAttribute("accessCount", new Integer(a));
    }

    private void displaySessionStuff(HttpServletRequest request, PrintWriter out) {
       
        HttpSession session = request.getSession();
        // Display things about the session
        int accessCount = ((Integer) session.getAttribute("accessCount"))
                .intValue();
        out.write("\n<P>Session has been accessed <B>" + accessCount
                + "</B> times</P>");
        out.write("\n<P>Session id is <B>" + session.getId() + "</B>.</P>");
        if (session.isNew()) {
            out.write("\n<P>The session is new.</P>");
        } else {
            out.write("\n<P>The session is old.</P>");
        }
        // Calculate age of session
        long creation = session.getCreationTime();
        long now = (new Date()).getTime();

        // Get difference in seconds
        long diffMilliSecs = now - creation;
        long diffSecs = diffMilliSecs / (1000);
        long minutes = diffSecs / 60;
        long seconds = diffSecs % 60;

        // Write out age in minutes and seconds
        out.write("\n<P>The session is " + minutes + " minutes and " + seconds
                + " seconds old.</P>");

        // Write out maximum inactive interval
        out.write("\n<P>Maximum inactive interval for session is <B>"
                + session.getMaxInactiveInterval() + "</B> seconds.</P>");

        if (request.isRequestedSessionIdFromCookie()) {
            out.write("\n<P>Session id comes from cookie JSESSIONID.</P>");
            Cookie[] theCookies = request.getCookies();
            for (int i = 0; i < theCookies.length; i++) {
                Cookie c = theCookies[i];
                out.write("<H2>Cookie </H2>" + c.getName());
                out.write("<BR />Domain: " + c.getDomain());
                out.write("<BR />Max Age: " + c.getMaxAge());
                out.write("<BR />Path: " + c.getPath());
                out.write("<BR />Value: " + c.getValue());
                out.write("<BR />Version: " + c.getVersion());
            }
        }
       
        if (request.isRequestedSessionIdFromURL()) {
            out.write("\n<P>Session id comes from URL.</P>");
        }
       
        out.write("\n<BR />End of session information");
       
    }


}

Custom single threaded java server

 package com.diffengine.csv; import java.io.*; import java.net.*; import java.util.Date; public class Server { public static void main(Str...