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>