Monday, March 28, 2011

Select text file data based on length

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

public class select {
    public static void main(String[] args) {
        int j=0,i=0,loc=0,col=0;
        String line;int []a=new int[15];
        try {
            FileReader fr = new FileReader("D:\\abc.txt");
            BufferedReader br = new BufferedReader(fr);
            while ((line = br.readLine()) != null) {
                StringTokenizer st2 = new StringTokenizer(line, " ");
                col=0;
                while(st2.hasMoreTokens()){
                    a[j]=st2.nextToken().length();
                    j++;
                    col++;
                }
                i++;
            }
            br.close();
            //First value
            int max1=a[0];
            for(int l=col-3;l<=a.length-1;l=l+3){
                if(max1<a[l]){
                    max1=a[l];
                    loc=l;
                }
            }
            int sp1=loc/col;
            FileReader fr1 = new FileReader("D:\\abc.txt");
            BufferedReader br1 = new BufferedReader(fr1);

            for(int k=0;k<sp1;k++){
                br1.readLine();
            }
            if((line = br1.readLine()) != null) {
                System.out.println(line);
            }
            br1.close();
            //Second value
            int max2=a[1];
            for(int l=col-2;l<=a.length-1;l=l+3){
                if(max2<a[l]){
                    max2=a[l];
                    loc=l;
                }
            }
            int sp2=loc/col;
            FileReader fr2 = new FileReader("D:\\abc.txt");
            BufferedReader br2 = new BufferedReader(fr2);

            for(int k=0;k<sp2;k++){
                br2.readLine();
            }
            if((line = br2.readLine()) != null) {
                System.out.println(line);
            }
            br2.close();
            //Third value
            int max3=a[1];
            for(int l=col-1;l<=a.length-1;l=l+3){
                if(max3<a[l]){
                    max3=a[l];
                    loc=l;
                }
            }
            int sp3=loc/col;
            FileReader fr3 = new FileReader("D:\\abc.txt");
            BufferedReader br3 = new BufferedReader(fr3);

            for(int k=0;k<sp3;k++){
                br3.readLine();
            }
            if((line = br3.readLine()) != null) {
                System.out.println(line);
            }
            br3.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

Wednesday, March 16, 2011

sorting in javascript

<html>
<head>
<script>
    function countInputs() {
        var arr=new Array();
        arr[0]=document.frm.data1.value;
        arr[1]=document.frm.data2.value;
        arr[2]=document.frm.data3.value;
        arr[3]=document.frm.data4.value;
        arr.sort();
        document.getElementById('m1').innerHTML=arr[0];
        document.getElementById('m2').innerHTML=arr[1];
        document.getElementById('m3').innerHTML=arr[2];
        document.getElementById('m4').innerHTML=arr[3];


           
    }
</script>
</head>
<body><center>
    <br><br><br><br><br><br>
<form name="frm">
    <input type="text" name="data1"/><br><br>
    <input type="text" name="data2"/><br><br>
    <input type="text" name="data3"/><br><br>
    <input type="text" name="data4"/><br><br>
    <input type="button" value="send"  onclick="countInputs()"/>
</form>
<p id="m1"></p>
<p id="m2"></p>
<p id="m3"></p>
<p id="m4"></p>
</center>
</body>
</html>

Monday, March 7, 2011

Major Differences


Feature Struts 1 Vs Struts 2
Action classes
Ø Struts 1 require Action classes to extend an abstract base class. A common problem in Struts 1 is programming to abstract classes instead of interfaces.
Ø A Struts 2 Action may implement an Action interface, along with other interfaces to enable optional and custom services. Struts 2 provide a base Action Support class to implement commonly used interfaces. Albeit, the Action interface is not required. Any POJO object with a execute signature can be used as an Struts 2 Action object.
Threading Model
Ø Struts 1 Actions are singletons and must be thread-safe since there will only be one instance of a class to handle all requests for that Action. The singleton strategy places restrictions on what can be done with Struts 1 Actions and requires extra care to develop. Action resources must be thread-safe or synchronized.
Ø Struts 2 Action objects are instantiated for each request, so there are no thread-safety issues. (In practice, Servlets containers generate many throw-away objects per request, and one more object does not impose a performance penalty or impact garbage collection.)
Servlet Dependency
Ø Struts1 Actions have dependencies on the servlet API since the HttpServletRequest and HttpServletResponse is passed to the execute method when an Action is invoked.
Ø Struts 2 Actions are not coupled to a container. Most often the servlet contexts are represented as simple Maps, allowing Actions to be tested in isolation. Struts 2 Actions can still access the original request and response, if required. However, other architectural elements reduce or eliminate the need to access the HttpServetRequest or HttpServletResponse directly.
Testability
Ø A major hurdle to testing Struts 1 Actions is that the execute method exposes the Servlet API. A third-party extension, Struts Test Case, offers a set of mock object for Struts 1.
Ø Struts 2 Actions can be tested by instantiating the Action, setting properties, and invoking methods. Dependency Injection support also makes testing simpler.
Harvesting Input
Ø Struts 1 uses an ActionForm object to capture input. Like Actions, all ActionForms must extend a base class. Since other JavaBeans cannot be used as ActionForms, developers often create redundant classes to capture input. DynaBeans can used as an alternative to creating conventional ActionForm classes, but, here too, developers may be red scribing existing JavaBeans.
Ø Struts 2 uses Action properties as input properties, eliminating the need for a second input object. Input properties may be rich object types which may have their own properties. The Action properties can be accessed from the web page via the taglibs. Struts 2 also support the ActionForm pattern, as well as POJO form objects and POJO Actions. Rich object types, including business or domain objects, can be used as input/output objects. The ModelDriven feature simplifies taglib references to POJO input objects.
Expression Language
Ø Struts 1 integrate with JSTL, so it uses the JSTL EL. The EL has basic object graph traversal, but relatively weak collection and indexed property support.
Ø Struts 2 can use JSTL, but the framework also supports a more powerful and flexible expression language called "Object Graph Notation Language" (OGNL).
Binding values into views
Ø Struts 1 uses the standard JSP mechanism for binding objects into the page context for access.
Ø Struts 2 use a "ValueStack" technology so that the taglibs can access values without coupling your view to the object type it is rendering. The ValueStack strategy allows reuse of views across a range of types which may have the same property name but different property types.
Type Conversion
Ø Struts 1 ActionForm properties are usually all Strings. Struts 1 uses Commons-Beanutils for type conversion. Converters are per-class, and not configurable per instance.
Ø Struts 2 uses OGNL for type conversion. The framework includes converters for basic and common object types and primitives.
Validation
Ø Struts 1 supports manual validation via a validate method on the ActionForm, or through an extension to the Commons Validator. Classes can have different validation contexts for the same class, but cannot chain to validations on sub-objects.
Ø Struts 2 supports manual validation via the validate method and the XWork Validation framework. The Xwork Validation Framework supports chaining validation into sub-properties using the validations defined for the properties class type and the validation context.
 Control of Action Execution
Ø Struts 1 supports separate Request Processors (lifecycles) for each module, but all the Actions in the module must share the same lifecycle.
Ø Struts 2 supports creating different lifecycles on a per Action basis via Interceptor Stacks. Custom stacks can be created and used with different Actions, as needed.
Hibernate Vs JDBC
Ø With JDBC, developer has to write code to map an object model's data representation to a relational data model and its corresponding database schema.
Ø Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this mapping using XML files so developer does not need to write code for this. 
Ø With JDBC, the automatic mapping of Java objects with database tables and vice versa conversion is to be taken care of by the developer manually with lines of code.  
Ø Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS.  
Ø JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to access database, i.e. to select effective query from a number of queries to perform same task.  
Ø Hibernate provides a powerful query language Hibernate Query Language (independent from type of database) that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries. Hibernate also supports native SQL statements. It also selects an effective way to perform a database manipulation task for an application.
Ø Application using JDBC to handle persistent data (database tables) having database   specific code in large amount. The code written to map table data to application objects and vice versa is actually to map table fields to object properties. As table changed or database changed then it’s essential to change object structure as well as to change code written to map table-to-object/object-to-table. 
Ø Hibernate provides this mapping itself. The actual mapping between tables and application objects is done in XML files. If there is change in Database or in any table then the only need to change XML file properties.  
Ø With JDBC, it is developer’s responsibility to handle JDBC result set and convert it to Java objects through code to use this persistent data in application. So with JDBC, mapping between Java objects and database tables is done manually.  
Ø Hibernate reduces lines of code by maintaining object-table mapping itself and returns result to application in form of Java objects. It relieves programmer from manual handling of persistent data, hence reducing the development time and maintenance cost.
Ø With JDBC, caching is maintained by hand-coding.  
Ø Hibernate, with Transparent Persistence, cache is set to application work space. Relational tuples are moved to this cache as a result of query. It improves performance if client application reads same data many times for same write. Automatic Transparent Persistence allows the developer to concentrate more on business logic rather than this application code.  
Ø In JDBC there is no check that always every user has updated data. This check has to be added by the developer.  
Ø Hibernate enables developer to define version type field to application, due to this defined field Hibernate updates version field of database table every time relational tuple is updated in form of Java class object to that table. So if two users retrieve same tuple and then modify it and one user save this modified tuple to database, version is automatically updated for this tuple by Hibernate. When other user tries to save updated tuple to database then it does not allow saving it because this user does not have updated data.  
Application Server vs Web Server
Ø Application servers and web servers are common terminologies when discussing the World Wide Web. Many of us have already encountered a web server, even though most people do not know it. A web server refers to the software or hardware that is used to serve content, like HTML pages and other media, to end users. This is what your web browser communicates with and gets information from. On the other hand, an application server refers the software or hardware that runs specific applications. These applications do not have a GUI and only supplies data to clients.
Ø Application servers and web servers have many uses and it is not uncommon for a site to have both of these servers. The web server delivers the primary content while the application server runs the applications that provide additional content. Both can exist without the other though. Web servers for simple content do not need application servers. Applications servers that target non web-based networks do not need to have web servers.
Ø Application servers are a lot more flexible than web servers because of the way they are set-up; applications have a lot more resources and freedom in execution. This may open-up the server to certain vulnerabilities that attackers can exploit. The limited things that can be done on a web server make it easier to secure.
Summary:
1. An application server is a platform for running specific applications while a                web server is a platform for delivering content over the internet
2. Application servers are often deployed in support of a web server
3. Application servers are more flexible than web servers
4. Application servers are less secure than web servers
5. An application server and web server can reside in the same machine

What the difference between hibernate and spring

Spring provides hibernate template and it has many advantages like
1) It removes boiler plate code like getting connection from data source try/catch block for closing connection. So that developer can focus on writing business logic rather than writing boiler plate code everywhere.

2) Spring hibernate Template also throws Runtime exception compared to checked exception which allows to remove writing try/catch block in each DAO.

3) It also gives richer template class using which developer can write query code easily. This template class also allows getting session explicitly so if developer wants to get session object and work on it then it's possible.
4) Spring provides support for both hibernate and JDBC. It provides template classes which contains all common code. But JDBC as we all know is not an ORM tool it does not represent rows as objects whereas Hibernate does that

What is the difference between Hibernate and EJB
Ø hibernate is a ORM(object relation mapping ) tool which can be used for creating a mapping between plain java bean objects (POJO) and a persistent storage (rdbms).The EJB 3.0 specification is divided into two parts the first which deals with session and MDBs and the second which deals with persistence and entity beans. The latter part is called JPA(java persistence API ). Hibernate 3.0 implements the JPA specification.EJB 2.1 is a specification for defining loosely coupled reusable business components.
Ø EJB 2.1 and hibernate serve two different purposes. Hibernate can be co related with the entity beans in EJB 2.1.HIbernate offers far more extensive features then plain entity beans. Still there are no containers (application servers) available which fully implement the EJB 3.0 specification. Depending upon the business needs hibernate framework can be used in conjunction with EJB2.1 to achieve the JPA abstraction.

Swing table

import javax.swing.*;
import javax.swing.table.*;
import java.io.File;
import java.util.Date;

public class FileTableDemo {
  public static void main(String[] args) {
    // Figure out what directory to display
    File dir;
    if (args.length > 0) dir = new File(args[0]);
    else dir = new File(System.getProperty("user.home"));

    // Create a TableModel object to represent the contents of the directory
    FileTableModel model = new FileTableModel(dir);

    // Create a JTable and tell it to display our model
    JTable table = new JTable(model);

    // Display it all in a scrolling window and make the window appear
    JFrame frame = new JFrame("FileTableDemo");
    frame.getContentPane().add(new JScrollPane(table), "Center");
    frame.setSize(600, 400);
    frame.setVisible(true);
  }
}
class FileTableModel extends AbstractTableModel {
      protected File dir;
      protected String[] filenames;

      protected String[] columnNames = new String[] {
        "name", "size", "last modified", "directory?", "readable?", "writable?"
      };

      protected Class[] columnClasses = new Class[] {
        String.class, Long.class, Date.class,
          Boolean.class, Boolean.class, Boolean.class
      };

      // This table model works for any one given directory
      public FileTableModel(File dir) {
        this.dir = dir;
        this.filenames = dir.list();  // Store a list of files in the directory
      }

      // These are easy methods
      public int getColumnCount() { return 6; }  // A constant for this model
      public int getRowCount() { return filenames.length; }  // # of files in dir

      // Information about each column
      public String getColumnName(int col) { return columnNames[col]; }
      public Class getColumnClass(int col) { return columnClasses[col]; }

      // The method that must actually return the value of each cell
      public Object getValueAt(int row, int col) {
        File f = new File(dir, filenames[row]);
        switch(col) {
        case 0: return filenames[row];
        case 1: return new Long(f.length());
        case 2: return new Date(f.lastModified());
        case 3: return f.isDirectory() ? Boolean.TRUE : Boolean.FALSE;
        case 4: return f.canRead() ? Boolean.TRUE : Boolean.FALSE;
        case 5: return f.canWrite() ? Boolean.TRUE : Boolean.FALSE;
        default: return null;
        }
      }
    }

Traffic Example in swing

import java.applet.*;
import java.awt.*;

public class Traffic extends Applet implements Runnable {

  
    static int i = 0;
    Thread t1, t2, t3;

    public void paint(Graphics g)
         {
        g.drawOval(50,350,30,30);
        g.drawOval(50,300,30,30);
        g.drawOval(50,250,30,30);
        
                if(i == 0)
        {
                        g.setColor(Color.RED);
                        g.fillOval(50,250,30,30);
                        try{
                        t1.sleep(5000);
                        }catch(Exception e){}
            repaint();
            i=1;
                }   else if(i==1)
        {
                        g.setColor(Color.YELLOW);
            g.fillOval(50,300,30,30);
                        try{
                        t2.sleep(1000);
                        }catch(Exception e){}
            repaint();
            i=2;
                }   else if(i==2)
        {
                        g.setColor(Color.GREEN);
                        g.fillOval(50,350,30,30);
                        try{
                        t3.sleep(4000);
                        }catch(Exception e){}
            repaint();
            i=0;
               }
       
         }

    @Override
    public void run() {
        // TODO Auto-generated method stub
       
    }
}
/*
 * <APPLET CODE="Traffic" height=700 width=500> </APPLET>
 */

Wednesday, February 23, 2011

Generate PDF

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
public class PDFServlet extends HttpServlet {
 public void init(ServletConfig config) throws ServletException {
  super.init(config);
 }
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  doPost(request, response);
 }
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  String query = null;
  response.setContentType("application/pdf"); // Code 1
   //PrintWriter pw=response.getWriter();
  Document document = new Document();
  try {
   PdfWriter.getInstance(document, response.getOutputStream()); // Code
                   // 2
   document.open();
   try {
    int rcount = 0;
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection conn = DriverManager.getConnection(
      "jdbc:oracle:thin:@localhost:1521", "hr", "tiger");
    query = "SELECT * FROM REGIONS";
    Statement state = conn.createStatement(
      ResultSet.CONCUR_UPDATABLE,
      ResultSet.TYPE_SCROLL_SENSITIVE);
    ResultSet rs = state.executeQuery(query);
    ResultSetMetaData mdata = rs.getMetaData();
    int colcount = mdata.getColumnCount();
    PdfPTable table = new PdfPTable(1);
    while (rs.next()) {
     rcount++;
    }
    rs.beforeFirst();
    rs.next();
    table.addCell(mdata.getColumnName(colcount));
    rs.beforeFirst();
    for (int i = 1; i <= rcount; i++) {
     for (int j = 1; j <= colcount-1; j++) {
    
      table.addCell(rs.getString("region_name"));
     }
    }
    document.add(table);
    document.close();
   } catch (Exception e) {
    e.printStackTrace();
   }
  } catch (DocumentException e) {
   e.printStackTrace();
  }
 }
}

Saturday, February 19, 2011

when click a radio button display related text boxes

<html>
<head>
<script language='javascript'>
function display(){   
     if(document.frmRadio.selType[0].checked){
       document.getElementById('div1').style.display = 'block';
       document.getElementById('div2').style.display = 'block' ;
     }
     else{
       document.getElementById('div2').style.display =  'none';
       document.getElementById('div1').style.display = 'block';
     }       
}
</script>
</head>
<body>
<form name='frmRadio'>
<tr><td><input type=radio name='selType' onclick='display()'> Display dropdown & textbox</td></tr>
<tr><td><input type=radio name='selType' onclick='display()'> Display Textbox Only</td></tr>
<tr height='30'><td>&nbsp;</td></tr>
<div id='div1' style=display:none>
<tr>
  <td><input type='text' name='txtName'></td>
</tr>
</div>
<div id='div2' style=display:none>
<tr>
  <td>
      <select name='selOption'>
         <option value='A'>A</option>
         <option value='B'>B</option>
      </select>
  </td>
</tr>
</div>
</form>
</body>
</html>

Wednesday, February 16, 2011

bat file of project

start firefox "http://localhost:9090/nani/query.html"

Tuesday, February 15, 2011

Swing table with file data

import java.awt.Color;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;

public class InsertFileDataToJTable extends AbstractTableModel {
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    Vector<String> data;
    Vector<String> columns;
    int i = 1;

    public InsertFileDataToJTable() {
        String line;
        data = new Vector<String>();
        columns = new Vector<String>();
        try {
            FileReader fr1 = new FileReader("D:\\abc.txt");
            BufferedReader br = new BufferedReader(fr1);
            StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
            /*while (st1.hasMoreTokens())
                columns.addElement(st1.nextToken());*/
            int f = 4,l=f+4;
            while (i < f) {
                br.readLine();
                i++;
            }
            while (f <= l) {
                if ((line = br.readLine()) != null) {
                    StringTokenizer st2 = new StringTokenizer(line, " ");
                    while (st2.hasMoreTokens())
                        data.addElement(st2.nextToken());
                    f++;
                }
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    protected String[] columnNames = new String[] {"ID", "NAME", "ADD"};
    public int getRowCount() {
        return data.size() / getColumnCount();
    }
    public String getColumnName(int col) { return columnNames[col]; }
    public int getColumnCount() {
        return columns.size();
    }

    public Object getValueAt(int rowIndex, int columnIndex) {
        String name=(String) data.elementAt((rowIndex * getColumnCount())
                + columnIndex);
        return name;
    }

    public static void main(String s[]) {
        InsertFileDataToJTable model = new InsertFileDataToJTable();
        JTable table = new JTable();
        table.setModel(model);
        table.setBackground(Color.orange);
        JScrollPane scrollpane = new JScrollPane(table);
        JPanel panel = new JPanel();
        panel.add(scrollpane);
        JFrame frame = new JFrame();
        frame.add(panel, "Center");
        frame.pack();
        frame.setVisible(true);
      
    }
}

Saturday, December 25, 2010

Mahesh Babu Photos



















Friday, December 24, 2010

how to retrive table data in struts

Action class:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

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

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class tableAction extends Action {
   
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
        try{
            tableForm data = (tableForm) form;
            String s[]=null;
            String uname=data.getUsername();
            String pas=data.getPassword();
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","hr","tiger");
            PreparedStatement ps1=con.prepareStatement("insert into stdval values(?,?)");
            ps1.setString(1,uname);
            ps1.setString(2,pas);
            int i=ps1.executeUpdate();
            if(i==1){
                System.out.println("insert");
            }else{
                System.out.println("fail");
            }
            PreparedStatement ps=con.prepareStatement("select * from stdval");
            ResultSet rs=ps.executeQuery();
            /*ResultSetMetaData rsmd=rs.getMetaData();
            int no=rsmd.getColumnCount();
            for(int count=1;count<=no;count++){
                s[count]=rsmd.getColumnName(count);
            }
            request.setAttribute("count",no);
            request.setAttribute("header",s);*/
            int c=0;
            ArrayList al=new ArrayList();
            while(rs.next()){
                c=1;
                tableForm data1=new tableForm();
                data1.setUsername(rs.getString("use"));
                data1.setPassword(rs.getString("pass"));
                al.add(data1);
            }
            if(c==0){
                return mapping.findForward("fail");
            }else{
                request.setAttribute("res",al);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return mapping.findForward("success");
    }
}
FormBean:
/*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */
import org.apache.struts.action.ActionForm;

/**
 * MyEclipse Struts
 * Creation date: 10-24-2010
 *
 * XDoclet definition:
 * @struts.form name="data"
 */
public class tableForm extends ActionForm {
    /*
     * Generated fields
     */

    /** password property */
    private String password;

    /** username property */
    private String username;

    /*
     * Generated Methods
     */

    /**
     * Returns the password.
     * @return String
     */
    public String getPassword() {
        return password;
    }

    /**
     * Set the password.
     * @param password The password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * Returns the username.
     * @return String
     */
    public String getUsername() {
        return username;
    }

    /**
     * Set the username.
     * @param username The username to set
     */
    public void setUsername(String username) {
        this.username = username;
    }
}
index.jsp:
<%@ page language="java" pageEncoding="ISO-8859-1"%>
<%@page import="java.util.*"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>

    <head>
       
    </head>
    <body><center>
        <html:form action="/data">
            UserName : <html:text property="username" /><br />
            Password : <html:text property="password" /><br />
            <html:submit />
        </html:form></center>
    </body>

<table border="1" align="center">
    <%
        ArrayList as = (ArrayList) request.getAttribute("res");
       
    %>
    <logic:notEmpty name="res" scope="request">
        <tr bgcolor="red">
            <th>UserName</th>
            <th>Password</th>
        </tr>
        <logic:iterate id="id1" collection="<%=as%>">
            <tr>
                <td><center><bean:write name="id1" property="username"/></center></td>
                <td><center><bean:write name="id1" property="password"/></center></td>
            </tr>
        </logic:iterate>
    </logic:notEmpty>

</table>
failure.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'fail.jsp' starting page</title>
   
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">   
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
 
  <body>
    This is my JSP page. <br>
  </body>
</html>

Jsp & Servlet


Question 1: Which of the following is not a standard method called as part of the JSP life cycle?
 Answer: jspService()

Question 2: If you want to override a JSP file's initialization method, within what type of tags must you declare the method?
 Answer: <%! %>

Question 3: Which can not be used as the scope when using a JavaBean with JSP?
 Answer:  Response is not a valid object scope for JavaBeans

Question 4: Why use RequestDispatcher to forward a request to another resource, instead of using a sendRedirect
 Answer: The RequestDispatcher does not require a round trip to the client, and thus is more efficient and allows the server to maintain request state.

Question 5: What is the key difference between using a <jsp:forward> and HttpServletResponse.sendRedirect()?
 Answer: forward executes on the server while sendRedirect() executes on the client.

Question 6: How you  makes your compiled JSP page implement the SingleThreadModel interface?
 Answer: <%@ page isThreadSafe="false" %>

Question 7: What is the difference between doing an include or a forward with a RequestDispatcher?
 Answer: When the forward method is used, the invoking resource does not regain control. Multiple include invocations can be made from the same resource, while the invoking resource maintains execution control.

Question 8: When a JSP page is compiled, what is it turned into?
 Answer: Servlet

Question 9: What is JavaServer Pages technology?
 Answer: JavaServer Pages (JSP) technology provides a simplified, fast way to create web pages that display dynamically generated content. The JSP specification, developed through an industry-wide initiative led by Sun Microsystems, defines the interaction between the server and the JSP page, and describes the format and syntax of the page.

Question 10: How does the JavaServer Pages technology work?
 Answer: JSP pages use XML tags and scriptlets written in the JavaTM programming language to encapsulate the logic that generates the content for the page. It passes any formatting (HTML or XML) tags directly back to the response page. In this way, JSP pages separate the page logic from its design and display.

JSP technology is part of the Java technology family; it uses a Java programming language-based scripting language, and JSP pages are compiled into servlets. JSP pages may call JavaBeansTM components (beans) or Enterprise JavaBeansTM components (enterprise beans) to perform processing on the server. As such, JSP technology is a key component in a highly scalable architecture for web-based applications.

JSP pages are not restricted to any specific platform or web server. The JSP specification represents a broad spectrum of industry input.

Question 11: Why do I need JSP technology if I already have servlets?
 Answer: JSP pages are compiled into servlets, so theoretically you could write servlets to support your web-based applications. However, JSP technology was designed to simplify the process of creating pages by separating web presentation from web content. In many applications, the response sent to the client is a combination of template data and dynamically-generated data. In this situation, it is much easier to work with JSP pages than to do everything with servlets.

Question 12: What is a JSP page?
 Answer: A JSP page is a page created by the web developer that includes JSP technology-specific tags, declarations, and possibly scriptlets, in combination with other static (HTML or XML) tags. A JSP page has the extension .jsp; this signals to the web server that the JSP engine will process elements on this page.

Question 13: How do JSP pages work?
 Answer: A JSP engine interprets tags and scriptlets, and generates the content required - for example, by calling a bean, accessing a database with the JDBCTM API or including a file. It then sends the results back in the form of an HTML (or XML) page to the browser. The logic that generates the content is encapsulated in tags and beans processed on the server. JSP scriptlets let developers tie everything together, and ordinary HTML tags control the formatting and display of the generated page.

Question 14: How is a JSP page invoked and compiled?
 Answer: Pages built using JSP technology are typically implemented using a translation phase that is performed once, the first time the page is called. The page is compiled into a Java Servlet class and remains in server memory, so subsequent calls to the page have very fast response times.

Question 15: Can I create XML pages using JSP technology?
 Answer: Yes, the JSP specification does support creation of XML documents. For simple XML generation, the XML tags may be included as static template portions of the JSP page. Dynamic generation of XML tags occurs through bean components or custom tags that generate XML output. See the white paper Developing XML Solutions with JavaServer Pages Technology (PDF) for details.

Question 16: Can I generate and manipulate JSP pages using XML tools?
 Answer: The JSP 1.1 specification describes a mapping between JSP pages and XML documents.The mapping enables the creation and manipulation of JSP pages using XML tools.

Question 17: How do I use JavaBeans components (beans) from a JSP page?
 Answer: The JSP specification includes standard tags for bean use and manipulation. The useBean tag creates an instance of a specific JavaBeans class. If the instance already exists, it is retrieved. Otherwise, it is created. The setProperty and getProperty tags let you manipulate properties of the given object. These tags are described in more detail in the JSP specification and tutorial.

Question 18: Why are there no try/catch blocks around my JSP scriptlets? I know the code should throw errors.
 Answer: Don't be confused. Scriplets do eventually end up with try/catch blocks around thier code. A JSP will catch any thrown error and display it to a user, or optionally handle it with a error page if specified.

If you would like to see the error handling examine the generated code by your JSP container.

Question 19: How do I call a function in my JSP via client-side JavaScript?
 Answer: It is not possible to do that.

A common misconception about JSP is where it takes place. JSP occurs only on the server-side. As it implies, client-side JavaScript takes place only on the client's computer. You cannont interchange the two.

Question 20: What are Implicit Objects?
Answer. An implicit object is available for a JSP developer to use inside scriptlets and expressions. The implicit objects represent all of the important components of the PageContext. Implicit objects need not be declared. They already exist and an error will be thrown if another variable of the same name is used.

User friendly documentaion of the implicit objects along with code examples is also provided at JSP Insider. Here is a list of the JSP 1.1 implicit objects and links for the documentation provided by JSP Insider.

A. pageContext
B. application
C. out
D. response
E. request
F: Session

 Question 21: Is it possible to pass in any Object other than a String to a taglib?
 Answer. Yes, just use an expression. The value of the expression will not be converted to a string in this case.
 Take the following example
 <example:tag date="<%= new java.util.Date()%>" />
 In the above example, the corresponding tag handler will have the setDate method called with a java.util.Date object passed in as a parameter.
 This is perfectly valid in your JSP assuming the tag's value can be a runtime expression. The TLD for this taglibrary would have to include the following snippet.
  
  <attribute> 
    <name>date</name> 
    <rtexprvalue>true</rtexprvalue> 
  </attribute>
  
Question 22: Both <%!...%> and <%...%> can be used for declaring variables. What is the difference between both and which to use?
 Answer: There is a distinct difference between an declaration, <%!...%>, and a scriptlet, <%...%>.

<%!...%> Declares a variable or method valid in the scripting language used in the JSP page.
<%...%> Contains a code fragment valid in the pages scripting language.

The big difference is that <%...%> is initialized once per each request to the JSP. Often the <%...%> is prefered and recommended for this reason, variables declared by <%!...%> are only loaded once, at the beginning of the JSP's lifecycle.
Question 23: What JSP servers are currently available?
 Answer: Here's a list of JSP servers with which we are familiar. This is only a partial list.
                                Extreme Internet Server
                                IPlanet WebServer 
                                JRun
                                Orion
                                Resin
                                Tomcat
                                WebLogic
                                WebSphere
                                ServletExec
                                LiteWebServer
For a more complete list check out the Java server list at the Java Skyline web site. This list contains more than just JSP servers, but it is a great place to start.
  
Question 24: How do I Pass an Object between a Servlet and a JSP?
 Answer: On the server-side you may forward the request with, pageContext.forward("Relative URI..."); for a JSP, or with getServletConfig().getServletContext().getRequestDispatcher("Relative URI...").forward(request, response); for a Servlet. The same HttpServletRequest object is shared when using these methods. Because of this objects may be stashed and retrieved using the getAttribute() and setAttribute() methods of HttpServletRequest.

Take for example the following Servlet. A java.lang.String object is set in the request object with "text" as the key. The servlet then fowards to a JSP.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ExampleServlet extends HttpServlet
{
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException  
  {
   String text  = new String("Some text to pass...");
   request.setAttribute("text", text);
   getServletConfig().getServletContext().getRequestDispatcher("/test.jsp").forward(request, response);

  }
}

  Using getAttribute(), a JSP can access the object set by the servlet.

1
2
3
4
5
6
7
8
9
10
<html>
 <head><title>Passing an object.</title></head>
 <body>
<%
  String text = (String)request.getAttribute("text");
%>
<%= text %>
 </body>
</html>


 If the result would be a webpage displaying, "Some text to pass..."

Any object may be passed using this method. Just remember to use the appropriate type cast when getting the object from the request. This method may also be used to pass objects between only servlets or JSP.

Question 25: How can I set a cookie in JSP?
 Answer: This should work:

response.setHeader("Set-Cookie", "cookie string");
To give the response-object to a bean, write a method setResponse
(HttpServletResponse response)
- to the bean, and in jsp-file:

<%
bean.setResponse (response);
%>

Question 26: How can I include one JSP inside another JSP?
 Answer: <%@ include="FileName.jsp" %>
  
Question 27: How do I delete a cookie with JSP?
 Answer:
<%
                Cookie killCookie = new Cookie("foo", null);
                killCookie.setPath("/");
                killCookie.setMaxAge(0);
                response.addCookie(killCookie);
%>

Question 28: What is a web application?
 Answer: A web application is a collection of resources that is mapped to a specific Uniform Resource Identifier (URI) prefix. These resources may include JSP pages, Servlets, HTML files, and images.

Question 29: If you want to override a JSP file's initialization method, within what type of tags must you declare the method?
 Answer: <%! %>

Question 30: Why use RequestDispatcher to forward a request to another resource, instead of using a sendRedirect?
 Answer: The RequestDispatcher does not require a round trip to the client, and thus is more efficient and allows the server to maintain request state.

Question 31: What is the key difference between using a <jsp:forward> and HttpServletResponse.sendRedirect()?
 Answer: forward executes on the server while sendRedirect() executes on the client.

Question 32. What is the difference between doing an include or a forward with a RequestDispatcher?
 Answer: When the forward method is used, the invoking resource does not regain control. Multiple include invocations can be made from the same resource, while the invoking resource maintains execution control.

Question 33. What are the elements available in JSP?
 Answer: There are three types of elements: directive elements, scripting elements, and action elements.

Question 34. How do you invoke a JSP page from a servlet?
 Answer:
                ServletContext context = getServletConfig().getServletContext();
                context.getResourceDispatcher(urlpath).forward(request, response);
                                                                                (Or)
                RequestDispatcher rd = request.getRequestDispatcher(urlpath);
                rd.forward(request, response);

Question 35. Can JSP and Servlet share same Session and Beans?
 Answer: Yes

Question 36. What are the different scopes available for usebean tag in JSP?
 Answer: Page, Request, Session and Application.





PHP Form Image Upload

















This tutorial shows you how to upload an image on your server using PHP and html forms. You will also learn how to verify if the uploaded file is an image (checking the extension), if it doesn't overtakes a size limit and how to change the uploaded file name.
Important: You must set the enctype form atribute to "multipart/form-data", otherwise the form will not show you any errors, but it will just not upload your images!

Step 1: Create a folder named images located in the path you are planning to place the php script you are about to create. Make sure it has write rights for everybody or the scripts won't work ( it won't be able to upload the files into the directory).
Step 2: Paste the following code into a php file.
Please read carefuly the comments. All steps are explained there.
<?php
//define a maxim size for the uploaded images in Kb
 define ("MAX_SIZE","100");

//This function reads the extension of the file. It is used to determine if the file  is an image by checking the extension.
 function getExtension($str) {
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
 }

//This variable is used as a flag. The value is initialized with 0 (meaning no error  found) 
//and it will be changed to 1 if an errro occures. 
//If the error occures the file will not be uploaded.
 $errors=0;
//checks if the form has been submitted
 if(isset($_POST['Submit']))
 {
               //reads the name of the file the user submitted for uploading
               $image=$_FILES['image']['name'];
               //if it is not empty
               if ($image)
               {
               //get the original name of the file from the clients machine
                               $filename = stripslashes($_FILES['image']['name']);
               //get the extension of the file in a lower case format
                               $extension = getExtension($filename);
                               $extension = strtolower($extension);
               //if it is not a known extension, we will suppose it is an error and will not  upload the file, 
               //otherwise we will do more tests
 if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
                               {
                               //print error message
                                              echo '<h1>Unknown extension!</h1>';
                                              $errors=1;
                               }
                               else
                               {
//get the size of the image in bytes
 //$_FILES['image']['tmp_name'] is the temporary filename of the file
 //in which the uploaded file was stored on the server
 $size=filesize($_FILES['image']['tmp_name']);

//compare the size with the maxim size we defined and print error if bigger
if ($size > MAX_SIZE*1024)
{
               echo '<h1>You have exceeded the size limit!</h1>';
               $errors=1;
}

//we will give an unique name, for example the time in unix time format
$image_name=time().'.'.$extension;
//the new name will be containing the full path where will be stored (images folder)
$newname="images/".$image_name;
//we verify if the image has been uploaded, and print error instead
$copied = copy($_FILES['image']['tmp_name'], $newname);
if (!$copied)
{
               echo '<h1>Copy unsuccessfull!</h1>';
               $errors=1;
}}}}

//If no errors registred, print the success message
 if(isset($_POST['Submit']) && !$errors)
 {
               echo "<h1>File Uploaded Successfully! Try again!</h1>";
 }

 ?>

 <!--next comes the form, you must set the enctype to "multipart/frm-data" and use an input type "file" -->
 <form name="newad" method="post" enctype="multipart/form-data"  action="">
 <table>
               <tr><td><input type="file" name="image"></td></tr>
               <tr><td><input name="Submit" type="submit" value="Upload image"></td></tr>
 </table>
 </form>