Tuesday, December 25, 2012

Upload/Download Image in MySQL using JDBC


Upload/Download Image in MySQL using JDBC 
  

 PreRequisites :


Database Setting
1. MySql Database with username 'root' and password 'root'
2. create a database named 'test1'.
3. create a table 'stu' with 3 columns naming roll, name and photo. 
 
File Required:
Place a image named image.jpg into C:\practice folder.


Upload

  1. Create a column in table whose datatype is BLOB(64 KB) or MEDIUMBLOB(16MB).
Exp:

CREATE TABLE  `stu` (
  `roll` int(11) default NULL,
  `name` varchar(10) default NULL,
  `photo` mediumblob NOT NULL
);

  1. To insert image into DB through JDBC you should first get the FileInputStream for the image file. Follow the below Steps….

    a. Get the File Object for the input file.
                File f=new File(“d:/pactice/image.jpg”)
b. Get the FileInputStream Using above File object
            FileInputStream fis=new FIleInputStream(f);

      3. Prepare a statement for SQL Query. 

pst=con.prepareStatement("insert into stu values (?,?,?)");
            pst.setInt(1, 20);
            pst.setString(2, "Sushil");
            pst.setBinaryStream(3, fis,(int)f.length());

4. Execute the Query and your image is uploaded.    
                        int s=pst.executeUpdate();

Download image from MYSQL using JDBC

  1. Get the contents of DB Row in a ResultSet.
pst=con.prepareStatement("select * from stu where name='Sushil'");
            rs=pst.executeQuery();

   2. To access the first row do
rs.next();
   
  1. Suppose image is in 3rd column than to access 3rd column do below           
    Blob b=rs.getBlob(3);  ( b contains Bytes only)

  1. convert b into array of Bytes
                 byte barr[]=new byte[(int)b.length
           barr=b.getBytes(1,(int)b.length());

  1. Finally take FileOutputStream Object and write the file into it.
FileOutputStream fout=new FileOutputStream("c:/dbPhoto.jpg");
            fout.write(barr);
            fout.close();
           
  1. Check your C: Drive you will find a image named dbPhoto.jpg which is same image you previously uploaded for Sushil
 -----------------------------------------------------------------------------------------------------------------------


Full Code for Image Upload/Download.
*********************************

package in.ibm;

import java.io.*;
import java.sql.*;

public class ImageInsertion {

    public static void main(String[] args) {

    FileInputStream fis;
    Connection con=null;
    PreparedStatement pst=null;
    ResultSet rs=null;

    try{
        
           Class.forName("com.mysql.jdbc.Driver");
           con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test1","root","root");
       
        File image= new File("d:/practice/image.jpg");
        pst=con.prepareStatement("insert into stu values (?,?,?)");
        pst.setInt(1, 20);
        pst.setString(2, "Sushil");
       
        fis=new FileInputStream(image);
       
        pst.setBinaryStream(3, fis,(int)image.length());
        int s=pst.executeUpdate();
   
    if(s>0){
        System.out.println("Uploaded");

       // DownLoading the same Image

        pst=con.prepareStatement("select * from stu where name='Sushil'");
        rs=pst.executeQuery();
        rs.next();
        Blob b=rs.getBlob(3);
        byte barr[]=new byte[(int)b.length()];//an array is created but contains no data
        barr=b.getBytes(1,(int)b.length());
                   
        FileOutputStream fout=new FileOutputStream("c:/dbPhoto.jpg");
        fout.write(barr);
                   
        fout.close();
        System.out.println("ok");

       
    }else{
        System.out.println("Failed");
    }
       
           
    }catch(Exception e){
        e.printStackTrace();
    }finally{
        try{
        con.close();
        pst.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
   
    }
}


                                                          

33 Java String Interview Questions


1. What is immutable object in Java? Can you change values of an immutable object?
Ans. By immutable, we mean that the value stored in the object cannot be changed.

2. How to create a immutable object in Java? Does all property of immutable object needs to be final?
Ans. Follow the below steps:
1.  make class final so it can’t be inherited to make changes.
2. make every property private so nobody from outside can access them you can declare every property also as final, so kind of u r saying that every property is constant and you can not change it.
3. define parameterized constructor to set the value of various properties.
4. Only define getter methods so value can be accessed only.
5. no setter methods or any other method so no modification possible.

3. What is difference between String, StringBuffer and StringBuilder? When to use them?
Ans. The most important difference between String and StringBuffer/ StringBuilder in java is that String object is immutable whereas StringBuffer/ StringBuilder objects are mutable.

StringBuffer and StringBuilder have the same methods with one difference and that’s of synchronization. StringBuffer is synchronized (which means it is thread safe and hence you can use it when you implement threads for your methods) whereas StringBuilder is not synchronized (which implies it isn’t thread safe).

So, if you aren’t going to use threading then use the StringBuilder class as it’ll be more efficient than StringBuffer due to the absence of synchronization.

4. What are the benefits of immutable object?
Ans. At least 3 great benefits of immutable objects:
  • They simplify multithreaded programming.
  • They can be used as hashtables key.
  • They simplify state comparison.

5. What is String pool  in Java ?
Ans. String Pool is memory available along with object heap memory. It contains all String Literal created.

6. What does intern method do in String?
Ans. you can call intern() on a String object. This will put the String object in the pool if it is not already there, and return the reference to the pooled string.

7. What is special about String Class in Java?
8. Why String is popular HashMap key in Java,?
Ans. Being immutable String in Java caches its hashcode and do not calculate every time we call hashcode method of String, which makes it very fast as hashmap key to be used in hashmap in Java.  In short because String is immutable, no one can change its contents once created which guarantees hashCode of String to be same on multiple invocation.

9. Does String is thread-safe in Java?
Ans. Since String is immutable it can safely shared between many threads,
which is very important for multi-threaded programming and to avoid any synchronization issues in Java, Immutability also makes String instance thread-safe in Java, means you don't need to synchronize String operation externally

10. How to compare two String in Java?
Ans. str1.compareTo(str2).

11. How SubString works in Java?
Ans. it will create a separate string and if u will provide any reference to it, it will be available otherwise will be lost in heap and available to GC. 

12. Why char array is preferred over String for passwords?
Ans. Strings are immutable. That means once you've created the string, if another process can dump memory, there's no way (aside from reflection) you can get rid of the data before GC kicks in.
With an array, you can explicitly wipe the data after you're done with it: you can overwrite the array with anything you like, and the password won't be present anywhere in the system, even before garbage collection.
So yes, this is a security concern - but even using char[] only reduces the window of opportunity for an attacker, and it's only for this specific type of attack.

13. Give name of five very useful methods in String other than length(), equals(), toString(), concate() methods.

14. Why String class is final or immutable?
Ans. String has been widely used as parameter for many java classes e.g. for opening network connection you can pass hostname and port number as string , you can pass database URL as string for opening database connection, you can open any file in Java by passing name of file as argument to File I/O classes.

In case if String is not immutable, this would lead serious security threat, I mean some one can access to any file for which he has authorization and then can change the file name either deliberately or accidentally and gain access of those file. This is some time asked as Why Char array is better than String for Storing password in Java in interviews as well.

The absolutely most important reason that String is immutable is that it is used by the class loading mechanism, and thus has profound and fundamental security aspects.

15. Why String class is Final?
Ans. If String is not final, you can always extend it so that it is no longer immutable.

16. Is there any other class in Java beside String which is Immutable?
Ans. Yes. Wrapper classes.

17. How will you make a class emp immutable, it has some member variable, and another member variable say Salary, on which you don't have any control. In the sense the interviewer said the methods in salary class, can actually change the state of class salary?
Ans. While creating Object for Immutable class you should only provide the complete detail of mutable member, kind of saying before giving object to anybody completely make it mutable, if object contains reference of any other object than make the copy of original object and share the copy, it will ensure nothing is remaining which can be changed.

18. Can you write a function that will replace all tokens delimited by @ with a given String?
Ans.     
      str = “Hello @name@, where are you @name@?”
Ans : String tok[]=str.split(“@”)

19. What would you use to compare two String variables – the operator == or the method equals()?
Or
How is it possible for two String objects with identical values not to be equal under the == operator?
Ans. public class EqualsTest {

            public static void main(String[] args) {

                        String s1 = "abc";
                        String s2 = s1;
                        String s5 = "abc";
                        String s3 = new String("abc");
                        String s4 = new String("abc");
                        System.out.println("== comparison : " + (s1 == s5));
                        System.out.println("== comparison : " + (s1 == s2));
                        System.out.println("Using equals method : " + s1.equals(s2));
                        System.out.println("== comparison : " + s3 == s4);
                        System.out.println("Using equals method : " + s3.equals(s4));
            }
}

20. How to convert String to Number in java program?
Ans. The valueOf() function of Integer class is is used to convert string to Number. Here is the code example:
String numString = “1000″;
int id=Integer.valueOf(numString).intValue();

21. What is difference between String and StringTokenizer?
Ans. A StringTokenizer is utility class used to break up string.
For one thing, StringTokenizer returns one substring at a time whereas the split method returns an array of substrings. Best to use String's split(...) method. The StringTokenizer class is a legacy class. StringTokenizer can split strings based on single characters, split() takes regular expressions.

22. Is it possible to extend the java.lang.String class?
Ans. No

23. Is String a Wrapper Class or not?
Ans. A wrapper class in Java is one of those eight classes that wrap a (=one) primitive value. String wraps a char[] so according to this it is not a (primitive) wrapper class.
Furthermore, String is not designed to wrap or decorate a character array. String has been designed to model a string, a character sequence and the current implementation uses an internal char[]. But Sun could also have chosen to use a byte[] a long with a character encoding hint, a collection or something native. That doesn't matter.
That's different for the primitive wrappers: they have been designed only to wrap a primitive, to adapt a java primitive to java.lang.Object.

24. How many objects are in the memory after the execution of following code segment?
Ans. String str1 = “ABC”;
String str2 = “XYZ”;
String str1 = str1 + str2;
Ans. 0

25. What will trim () method of String class do?

26. What is the possible runtime exception thrown by substring() method?
Ans. ArrayOutofBoundException.

27. In Java, you can create a String object as below :
String str = “abc”; &
String str = new String(“abc”);
Why can’t a button object be created as : Button bt = “abc”?
Why is it compulsory to create a button object as:
Button bt = new Button(“abc”);
Why this is not compulsory in String’s case?
Ans. It is because "abc" is a literal string (something slightly different than a String object, by-the-way) and bt1 is a Button object. The only object in Java that can be assigned a literal String is java.lang.String

28. How to make any class Immutable?
Ans.
 Follow the below steps:
1.  make class final so it can’t be inherited to make changes.
2. make every property private so nobody from outside can access them you can declare every property also as final, so kind of u r saying that every property is constant and you can not change it.
3. define parameterized constructor to set the value of various properties.
4. Only define getter methods so value can be accessed only.
5. no setter methods or any other method so no modification possible.

29. == Vs equals() ?
Ans. It is important to understand that the equals( ) method and the == operator perform two different operations. As just explained, the equals( ) method compares the characters inside a String object. The == operator compares two object references to see whether they refer to the same instance. The following program shows how two different String objects can contain the same characters, but references to these objects will not compare as equal:

30. What is the difference between creating String as new() and literal?
Ans. When we create string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in PermGen area of heap.

String s = new String("Test");

does not  put the object in String pool , we need to call String.intern() method which is used to put  them into String pool explicitly. its only when you create String object as String literal e.g. String s = "Test" Java automatically put that into String pool.

31. What will happen if beginIndex is equal to length in SubString(int beginIndex)

32. Can we say String is a character array?
Ans. No.

33. Why new String() is not added into constant String pool?
Ans.

Struts1 Forms: ValidatorForm, DynaValidatorForm, ValidatorActionForm, DynaValidatorActionForm

The Attached code will provide you a complete code which has used all types of forms available in struts1(except than action form).

In this single application I tried to use all types of Struts1 Form with basic validation using Struts1 Validation Framework and custom validations which are registerd with validation framework.

Hope it will be useful:

1. Directory structure




2. Jars and tlds Required





Source Code


Presentaion Files(JSPs)

1.EmployerDetails.jsp
-----------------------------

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/WEB-INF/tld/struts-html.tld"  prefix="html"%>
<%@ taglib uri="/WEB-INF/tld/struts-bean.tld"  prefix="bean"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Employer Details</title>
</head>
<body><center>

<table align="center" bgcolor="#ffffff">
<tr><td colspan="3" align="center"><h2>ValidatorActionForm</h2></td></tr>
<tr>
<td colspan="4" align="center"><bean:message key="lable.employer.detail"/></td>
</tr>
<tr></tr>
<tr><th></th><th>Name</th><th>Year Of Exp</th></tr>

<html:form action="/employer">
<tr>
<td><bean:message key="lable.employer.first"/></td>
<td><html:text property="fename"/></td>
<td><html:text property="fnoyrs"/></td>
<td><html:errors property="fename"/></td>
</tr>

<tr>
<td><bean:message key="lable.employer.second"/></td>
<td><html:text property="sename"/></td>
<td><html:text property="snoyrs"/></td>
<td><html:errors property="sename"/></td>
</tr>

<tr>
<td><bean:message key="lable.employer.third"/></td>
<td><html:text property="tename"/></td>
<td><html:text property="tnoyrs"/></td>
<td><html:errors property="tename"/></td>
</tr>



<tr>
<td align="center" colspan="4">
<html:submit value="Submit"/>
</td>
</tr>

</html:form>

</table>
</center>
</body>
</html>


2. enquiry.jsp
----------------

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" import="in.ibm.strurts.*"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/WEB-INF/tld/struts-html.tld" prefix="html"%> 
<%@ taglib uri="/WEB-INF/tld/struts-bean.tld" prefix="bean"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<table align="center">
<tr><td colspan="3" align="center"><h2>ValidatorForm</h2></td></tr>
<tr><td colspan="3" align="center"><h1>
<bean:message key="Lable.enquiry.Header"/></h1></td></tr>
<html:form action="/info">
<tr>
<td>Name</td>
<td><html:text property="name"/></td>
<td><html:errors property="name"/></td>
</tr>

<tr>
<td>Mobile No</td>
<td><html:text property="phone"/></td>
<td><html:errors property="phone"/></td>
</tr>

<tr>
<td>Batch</td>
<td><html:text property="batch"/></td>
<td><html:errors property="batch"/></td>
</tr>

<tr>
<td>DateOfBirth</td>
<td><html:text property="dob"/></td>
<td><html:errors property="dob"/></td>
</tr>

<tr>
<td>Email</td>
<td><html:text property="email"/></td>
<td><html:errors property="email"/></td>
</tr>

<tr>
<td>Gender</td>
<td>Male<html:radio property="gender" value="Male"/>
    Female<html:radio property="gender" value="Female"/></td>
<td><html:errors property="gender"/></td>
</tr>

<tr>
<td>City</td>
<td><html:select property="city">
<html:option value="">-----Select------</html:option>
<html:option value="Bangalore">Bangalore</html:option>
<html:option value="Pune">Pune</html:option>
<html:option value="Kolkata">Kolkata</html:option>
<html:option value="Mumbai">Mumbai</html:option>
</html:select></td>
<td><html:errors property="city"/></td>
</tr>

<tr>
<td>Subjects</td>
<td>JSF<html:checkbox property="sub" value="JSF"></html:checkbox>
JSP<html:checkbox property="sub" value="JSP"></html:checkbox>
Java<html:checkbox property="sub" value="Java"></html:checkbox>
Struts<html:checkbox property="sub" value="Struts"></html:checkbox></td>
<td><html:errors property="sub"/></td>
</tr>

<tr>
<td>Query Relevant Topic</td>
<td><html:select property="top" multiple="true">
<html:option value="">-----Select------</html:option>
<html:option value="Java">Java</html:option>
<html:option value="DataBase">DataBase</html:option>
<html:option value="Location">Location</html:option>
<html:option value="teacher">teacher</html:option>
</html:select></td>
<td><html:errors property="top"/></td>
</tr>

<tr>
<td>Write Your Query</td>
</tr>
<tr>
<td colspan="3" align="left"><html:textarea property="query"></html:textarea></td>
</tr>
<tr><td colspan="3" align="center"><html:submit value="register"></html:submit>
</tr>

</html:form>
</table>

</body>
</html>

3. expectations.jsp
------------------------

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" import="in.ibm.strurts.*"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/WEB-INF/tld/struts-html.tld" prefix="html"%> 
<%@ taglib uri="/WEB-INF/tld/struts-bean.tld" prefix="bean"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Expectation</title>
</head>
<body>
<table align="center">
<tr><td colspan="3" align="center"><h2>DynaValidatorActionForm</h2></td></tr>
<tr><td colspan="3" align="center"><h1>
<bean:message key="Lable.expectations.Header"/></h1></td></tr>
<html:form action="/expectations">
<tr>
<td>Expected Salary</td>
<td><html:text property="esalary"/></td>
<td><html:errors property="esalary"/></td>
</tr>

<tr>
<td>Location</td>
<td><html:text property="eloc"/></td>
<td><html:errors property="eloc"/></td>
</tr>

<tr>
<td>Project Type</td>
<td><html:text property="ptype"/></td>
<td><html:errors property="ptype"/></td>
</tr>

<tr>
<td colspan="3" align="center"><html:submit value="Done"></html:submit>
</tr>

</html:form>
</table>

</body>
</html>

4. home.jsp
-----------------

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/WEB-INF/tld/struts-html.tld" prefix="html" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<html:link forward="enquiry"><h1>enquiry</h1> </html:link><br>
</body>
</html>

5. logoff.jsp
--------------

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
 <%@taglib uri="/WEB-INF/tld/struts-html.tld" prefix="html"%>  
    <%@ taglib uri="/WEB-INF/tld/struts-logic.tld" prefix="logic" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<html:errors/>
<center>
<h1>Congratulations, You have learned Struts1 Form Types very well</h1>
</center>
</body>
</html>

6. PersonalDetail.jsp
--------------------------
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/WEB-INF/tld/struts-html.tld"  prefix="html"%>
<%@ taglib uri="/WEB-INF/tld/struts-bean.tld"  prefix="bean"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Personal Details</title>
</head><center><tr><td colspan="3" align="center"><h2>ValidatorForm</h2></td></tr>
<body>
<bean:message key="lable.personal.detail"/><br>
<html:form action="/submit">
<bean:message key="lable.personal.mname"/>
<html:text property="mname"/><html:errors property="mname"/> <br>

<bean:message key="lable.personal.salary"/>
<html:text property="salary"/><html:errors property="salary"/> <br>
<bean:message key="lable.personal.yoe"/>
<html:text property="yoe"/><html:errors property="yoe"/> <br>
<bean:message key="lable.personal.age"/>
<html:text property="age"/><html:errors property="age"/> <br>
<html:submit value="Submit"/>

</html:form>
</center>

</body>
</html>

7.QualificationDetails.jsp
--------------------------------

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/WEB-INF/tld/struts-html.tld"  prefix="html"%>
<%@ taglib uri="/WEB-INF/tld/struts-bean.tld"  prefix="bean"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Qualification Details</title>
</head>
<body><center>
<table align="center" bgcolor="#ffffff">
<tr><td colspan="3" align="center"><h2>ValidatorActionForm</h2></td></tr>
<tr><td colspan="6" align="center"><bean:message key="lable.qualification.detail"/></td></tr>
<tr></tr>
<tr><th></th><th>Percentage</th><th>Passing Year</th><th>College Name</th><th>Univercity</th></tr>

<html:form action="/qualifiction">
<tr>
<td><bean:message key="lable.qualification.ssc"/></td>
<td><html:text property="sscper"/></td>
<td><html:text property="sscyop"/></td>
<td><html:text property="ssccol"/></td>
<td><html:text property="sscuni"/></td>
<td><html:errors property="sscper"/></td>
</tr>

<tr>
<td><bean:message key="lable.qualification.pu"/></td>
<td><html:text property="puper"/></td>
<td><html:text property="puyop"/></td>
<td><html:text property="pucol"/></td>
<td><html:text property="puuni"/></td>
<td><html:errors property="puper"/></td>
</tr>

<tr>
<td><bean:message key="lable.qualification.grad"/></td>
<td><html:text property="gradper"/></td>
<td><html:text property="gradyop"/></td>
<td><html:text property="gradcol"/></td>
<td><html:text property="graduni"/></td>
<td><html:errors property="gradper"/></td>
</tr>

<tr>
<td><bean:message key="lable.qualification.pg"/></td>
<td><html:text property="pgper"/></td>
<td><html:text property="pgyop"/></td>
<td><html:text property="pgcol"/></td>
<td><html:text property="pguni"/></td>
<td><html:errors property="pgper"/></td>
</tr>

<tr>
<td align="center" colspan="6">
<html:submit value="Submit"/>
</td>
</tr>
</html:form>
</table>
</center>
</body>
</html>

8. Skills.jsp
----------------

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" import="in.ibm.strurts.*"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/WEB-INF/tld/struts-html.tld" prefix="html"%> 
<%@ taglib uri="/WEB-INF/tld/struts-bean.tld" prefix="bean"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Skills</title>
</head>
<body>
<table align="center">
<tr><td colspan="3" align="center"><h2>DynaValidatorActionForm</h2></td></tr>

<tr><td colspan="3" align="center">
<h1><bean:message key="Lable.skill.Header"/></h1></td></tr>
<html:form action="/skills">
<tr>
<td>PrimarySkills</td>
<td><html:text property="pskills"/></td>
<td><html:errors property="pskills"/></td>
</tr>

<tr>
<td>Secondary Skills</td>
<td><html:text property="sskills"/></td>
<td><html:errors property="sskills"/></td>
</tr>

<tr>
<td>Web Skills</td>
<td><html:text property="wskills"/></td>
<td><html:errors property="wskills"/></td>
</tr>

<tr>
<td colspan="2" align="center">Your Hobbies and Interests</td>
</tr>
<tr>
<td colspan="3" align="center"><html:textarea property="hobby"></html:textarea></td>
</tr>
<tr><td colspan="3" align="center"><html:submit value="Submit"></html:submit>
</tr>

</html:form>
</table>

</body>
</html>

COnfiguration Files(XMLs)


8. struts-config.xml
-------------------------

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


<form-beans>

<form-bean name="perForm" type="org.apache.struts.validator.DynaValidatorForm">
<form-property name="mname" type="java.lang.String"/>
<form-property name="salary" type="java.lang.String"/>
<form-property name="yoe" type="java.lang.String"/>
<form-property name="age" type="java.lang.String"/>
</form-bean>

<form-bean name="skExpForm" type="org.apache.struts.validator.DynaValidatorActionForm">
<form-property name="pskills" type="java.lang.String"/>
<form-property name="sskills" type="java.lang.String"/>
<form-property name="wskills" type="java.lang.String"/>
<form-property name="hobby" type="java.lang.String"/>
<form-property name="esalary" type="java.lang.String"/>
<form-property name="eloc" type="java.lang.String"/>
<form-property name="ptype" type="java.lang.String"/>

</form-bean>

<form-bean name="enqForm" type="in.ibm.strurts.EnquiryForm"/>

<form-bean name="qualempForm" type="in.ibm.strurts.Qualification_EmployerForm"/>

</form-beans>




<global-exceptions>
<exception key="exception.error" type="java.lang.Exception" path="/logoff.jsp"/>
</global-exceptions>

<global-forwards>
<forward name="enquiry" path="/enquiry.jsp"/>
<forward name="logoff" path="/logoff.jsp"/>
</global-forwards>

<action-mappings>
<action path="/info" name="enqForm" type="in.ibm.strurts.EnquiryAction" validate="true" scope="request" input="/enquiry.jsp">
<exception key="exception.user" type="in.ibm.strurts.IllegalException" path="/logoff.jsp"/>
<forward name="success" path="/PersonalDetail.jsp"/>
</action>

<action path="/submit" name="perForm" type="in.ibm.strurts.PersonalAction" validate="true" scope="request" input="/PersonalDetail.jsp">
<exception key="exception.user" type="in.ibm.strurts.IllegalException" path="/logoff.jsp"/>
<forward name="success" path="/QualificationDetails.jsp"/>
</action>

<action path="/qualifiction" name="qualempForm" type="in.ibm.strurts.QualificationAction" validate="true" scope="request" input="/QualificationDetails.jsp">
<exception key="exception.user" type="in.ibm.strurts.IllegalException" path="/logoff.jsp"/>
<forward name="success" path="/EmployerDetails.jsp"/>
</action>

<action path="/employer" name="qualempForm" type="in.ibm.strurts.EmployerAction" validate="true" scope="request" input="/EmployerDetails.jsp">
<exception key="exception.user" type="in.ibm.strurts.IllegalException" path="/logoff.jsp"/>
<forward name="success" path="/Skills.jsp"/>
</action>

<action path="/skills" name="skExpForm" type="in.ibm.strurts.SkillsAction" validate="true" scope="request" input="/Skills.jsp">
<exception key="exception.user" type="in.ibm.strurts.IllegalException" path="/logoff.jsp"/>
<forward name="success" path="/expectations.jsp"/>
</action>

<action path="/expectations" name="skExpForm" type="in.ibm.strurts.ExpectationAction" validate="true" scope="request" input="/expectations.jsp">
<exception key="exception.user" type="in.ibm.strurts.IllegalException" path="/logoff.jsp"/>
<forward name="success" path="/logoff.jsp"/>
</action>

</action-mappings>


<message-resources parameter="in.ibm.strurts.messages"/>
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property value="/WEB-INF/validator-rules.xml,/WEB-INF/validations.xml" property="pathnames"/>
</plug-in>
</struts-config>

9. validations.xml
---------------------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE form-validation PUBLIC
 "-//Apache Software Foundation
//DTD Commons Validator Rules Configuration 1.0.1//EN" "http://jakarta.apache.org/commons/dtds/validator_1_0_1.dtd">
<form-validation>
<formset>

<form name="/employer">
<field property="fename" depends="required">
<arg0 key="EMployerName" resource="false"/>
</field>

<field property="sename" depends="required">
<arg0 key="EMployerName" resource="false"/>
</field>

<field property="tename" depends="required">
<arg0 key="EMployerName" resource="false"/>
</field>
</form>

<form name="/skills">
<field property="pskills" depends="required">
<arg0 key="Primary Skill" resource="false"/>
</field>

<field property="sskills" depends="required">
<arg0 key="Secondary Skill" resource="false"/>
</field>

<field property="wskills" depends="required">
<arg0 key="Web Skill" resource="false"/>
</field>
</form>


<form name="/expectations">
<field property="esalary" depends="required">
<arg0 key="Expected Salary Field" resource="false"/>
</field>

<field property="ptype" depends="required">
<arg0 key="Project Type Field" resource="false"/>
</field>

</form>

<form name="/qualifiction">
<field property="sscper" depends="required">
<arg0 key="10th Percentage " resource="false"/>
</field>

<field property="puper" depends="required">
<arg0 key="12th Percentage" resource="false"/>
</field>

<field property="gradper" depends="required">
<arg0 key="Graduation Percentage" resource="false"/>
</field>
</form>

<form name="enqForm">

<field property="name" depends="required,maxlength,minlength">
<arg0 key="lable.user" resource="true"/>
<arg1 key="${var:minlength}" resource="false"/>
<arg2 key="${var:maxlength}" resource="false"/>

<var>
<var-name>minlength</var-name>
<var-value>5</var-value>
</var>
<var>
<var-name>maxlength</var-name>
<var-value>10</var-value>
</var>
</field>

<field property="email" depends="required,email">
<arg0 key="lable.email" resource="true"/>
<arg1 key="lable.email" resource="true"/>
</field>


<field property="phone" depends="long,mask">
<arg0 key="lable.phone" resource="true"/>
<var>
<var-name>mask</var-name>
<var-value>^[0-9]{10}$</var-value>
</var>

</field>


<field property="sub" depends="lengthRequired">
<arg0 key="lable.subject" resource="true"/>
</field>

<field property="dob" depends="required,date">
<arg0 key="Date" resource="false"/>

<var>
<var-name>datePattern</var-name>
<var-value>dd/MM/yyyy</var-value>
</var>
</field>

</form>


<form name="perForm">
<field property="mname" depends="required">
<arg0 key="lable.personal.mname" resource="true"/>
</field>
<field property="salary" depends="required,float">
<arg0 key="lable.personal.salary" resource="true"/>
</field>

<field property="age" depends="required,integer,intRange">
<arg0 key="lable.personal.age" resource="true"/>
<arg1 name="intRange" key="${var:min}" resource="false"/>
<arg2 name="intRange" key="${var:max}" resource="false"/>
<var>
<var-name>min</var-name>
<var-value>18</var-value>
</var>
<var>
<var-name>max</var-name>
<var-value>65</var-value>
</var>
</field>

<field property="yoe" depends="required,integer,range">
<arg0 key="lable.personal.yoe" resource="true"/>
<arg1 name="range" key="${var:min}" resource="false"/>
<arg2 name="range" key="${var:max}" resource="false"/>
<var>
<var-name>min</var-name>
<var-value>3</var-value>
</var>
<var>
<var-name>max</var-name>
<var-value>10</var-value>
</var>
</field>

</form>
</formset>
</form-validation>

10. web.xml
-----------------

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>FormElementWithValFram</display-name>
  <welcome-file-list>
    <welcome-file>home.jsp</welcome-file>
    </welcome-file-list>
   
    <servlet>
    <servlet-name>hi</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
        <param-name>config</param-name>
        <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    </servlet>
   
    <servlet-mapping>
    <servlet-name>hi</servlet-name>
    <url-pattern>*.do</url-pattern>
    </servlet-mapping>
</web-app>

11. validator-rules.xml
------------------------------
Download from net ( GOOGLE-struts1 validation-rules.xml)


JAVA CODE



12. EmployerAction
--------------------------

package in.ibm.strurts;

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 EmployerAction extends Action {
   
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest req, HttpServletResponse res)
            throws Exception {
       
        System.out.println("in Employer Action");
       
        ActionForward af= mapping.findForward("success");
       
        return af;
    }
   

}

13. EnquiryAction
------------------------
package in.ibm.strurts;

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 EnquiryAction extends Action {
   
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest req, HttpServletResponse res)
            throws Exception {
        System.out.println(req.getAttribute("enqForm"));
       
       
        ActionForward af= mapping.findForward("success");
       
        return af;
    }
   

}

14. EnquiryForm
-----------------------

package in.ibm.strurts;

import javax.servlet.http.HttpServletRequest;


import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;

import org.apache.struts.action.ActionMapping;
import org.apache.struts.validator.ValidatorForm;

public class EnquiryForm extends ValidatorForm {
   
    private String name;
    private String batch;
    private String gender;
    private String city;
    private String[] sub;
    private String[] top;
    private String query;
    private String email;
    private long phone;
    private String dob;
   
   
   
    /*@Override
    public ActionErrors validate(ActionMapping mapping,
            HttpServletRequest request) {
        ActionErrors err=new ActionErrors();
        if(!batch.equals("b33")){
            err.add("batch",new ActionError("error.batch.required"));
        }
        return err;
    }*/
   
   
    public String getDob() {
        return dob;
    }
    public void setDob(String dob) {
        this.dob = dob;
    }
    public long getPhone() {
        return phone;
    }
    public void setPhone(long phone) {
        this.phone = phone;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getBatch() {
        return batch;
    }
    public void setBatch(String batch) {
        this.batch = batch;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public String[] getSub() {
        return sub;
    }
    public void setSub(String[] sub) {
        this.sub = sub;
    }
    public String[] getTop() {
        return top;
    }
    public void setTop(String[] top) {
        this.top = top;
    }
    public String getQuery() {
        return query;
    }
    public void setQuery(String query) {
        this.query = query;
    }
   
   
   
    public void reset(ActionMapping mapping, HttpServletRequest request) {
        this.name="sushil";
        this.city="Bangalore";
       
    }
   
   

}

15. EnquirySubjectValidation
----------------------------------------

package in.ibm.strurts;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.validator.*;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;

public class EnquirySubjectValidation {
   
    public void validateSubject(ActionErrors err,HttpServletRequest req){
        System.out.println("in Custom Validation");
        String[] sub=req.getParameterValues("sub");
        System.out.println(sub.length);
       
        if(sub.length>2){
            err.add("sub",new ActionError("error.sub.length"));
        }
    }

}

16. ExpectationAction
-----------------------------

package in.ibm.strurts;

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 ExpectationAction extends Action {
   
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest req, HttpServletResponse res)
            throws Exception {
       
        System.out.println("in Employer Action");
       
        ActionForward af= mapping.findForward("success");
       
        return af;
    }
   

}

17. IllegalException
------------------------
package in.ibm.strurts;

public class IllegalException extends Exception {

}

18. PersonalAction
-------------------------

package in.ibm.strurts;

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 PersonalAction extends Action {
   
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest req, HttpServletResponse res)
            throws Exception {
        System.out.println(req.getAttribute("perForm"));
       
       
        ActionForward af= mapping.findForward("success");
       
        return af;
    }
   

}

19. Qualification_EmployerForm
------------------------------------------

package in.ibm.strurts;

import org.apache.struts.validator.ValidatorActionForm;

public class Qualification_EmployerForm extends ValidatorActionForm {
   
    private String fename;
    private String fnoyrs;

    private String sename;
    private String snoyrs;

    private String tename;
    private String tnoyrs;
   
    private String sscper;
    private String sscyop;
    private String ssccol;
    private String sscuni;

    private String puper;
    private String puyop;
    private String pucol;
    private String puuni;

    private String gradper;
    private String gradyop;
    private String gradcol;
    private String graduni;

    private String pgper;
    private String pgyop;
    private String pgcol;
    private String pguni;
    public String getFename() {
        return fename;
    }
    public void setFename(String fename) {
        this.fename = fename;
    }
    public String getFnoyrs() {
        return fnoyrs;
    }
    public void setFnoyrs(String fnoyrs) {
        this.fnoyrs = fnoyrs;
    }
    public String getSename() {
        return sename;
    }
    public void setSename(String sename) {
        this.sename = sename;
    }
    public String getSnoyrs() {
        return snoyrs;
    }
    public void setSnoyrs(String snoyrs) {
        this.snoyrs = snoyrs;
    }
    public String getTename() {
        return tename;
    }
    public void setTename(String tename) {
        this.tename = tename;
    }
    public String getTnoyrs() {
        return tnoyrs;
    }
    public void setTnoyrs(String tnoyrs) {
        this.tnoyrs = tnoyrs;
    }
    public String getSscper() {
        return sscper;
    }
    public void setSscper(String sscper) {
        this.sscper = sscper;
    }
    public String getSscyop() {
        return sscyop;
    }
    public void setSscyop(String sscyop) {
        this.sscyop = sscyop;
    }
    public String getSsccol() {
        return ssccol;
    }
    public void setSsccol(String ssccol) {
        this.ssccol = ssccol;
    }
    public String getSscuni() {
        return sscuni;
    }
    public void setSscuni(String sscuni) {
        this.sscuni = sscuni;
    }
    public String getPuper() {
        return puper;
    }
    public void setPuper(String puper) {
        this.puper = puper;
    }
    public String getPuyop() {
        return puyop;
    }
    public void setPuyop(String puyop) {
        this.puyop = puyop;
    }
    public String getPucol() {
        return pucol;
    }
    public void setPucol(String pucol) {
        this.pucol = pucol;
    }
    public String getPuuni() {
        return puuni;
    }
    public void setPuuni(String puuni) {
        this.puuni = puuni;
    }
    public String getGradper() {
        return gradper;
    }
    public void setGradper(String gradper) {
        this.gradper = gradper;
    }
    public String getGradyop() {
        return gradyop;
    }
    public void setGradyop(String gradyop) {
        this.gradyop = gradyop;
    }
    public String getGradcol() {
        return gradcol;
    }
    public void setGradcol(String gradcol) {
        this.gradcol = gradcol;
    }
    public String getGraduni() {
        return graduni;
    }
    public void setGraduni(String graduni) {
        this.graduni = graduni;
    }
    public String getPgper() {
        return pgper;
    }
    public void setPgper(String pgper) {
        this.pgper = pgper;
    }
    public String getPgyop() {
        return pgyop;
    }
    public void setPgyop(String pgyop) {
        this.pgyop = pgyop;
    }
    public String getPgcol() {
        return pgcol;
    }
    public void setPgcol(String pgcol) {
        this.pgcol = pgcol;
    }
    public String getPguni() {
        return pguni;
    }
    public void setPguni(String pguni) {
        this.pguni = pguni;
    }
}




20. QualificationAction
--------------------------------
package in.ibm.strurts;

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 QualificationAction extends Action {
   
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest req, HttpServletResponse res)
            throws Exception {
        System.out.println("in Qualification Action");
       
       
        ActionForward af= mapping.findForward("success");
       
        return af;
    }
   

}

21. SkillsAction
----------------------

package in.ibm.strurts;

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 SkillsAction extends Action {
   
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest req, HttpServletResponse res)
            throws Exception {
       
        System.out.println("in Employer Action");
       
        ActionForward af= mapping.findForward("success");
       
        return af;
    }
   

}


PROPERTIES FILE

22. messages.properties
-----------------------------

#lables
lable.user=Username
lable.email=Email
lable.phone=Mobile no
Lable.enquiry.Header=Fill Enquiry Form
lable.subject=Subject
lable.personal.detail=Personal Deatils are required
lable.personal.yoe= Year of Experience
lable.personal.salary=Salary
lable.personal.mname=Mother's Name
lable.personal.age=Age
lable.qualification.detail=<h1>Qualification Details</h1>
lable.qualification.ssc=10th details
lable.qualification.pu=12th details
lable.qualification.grad=Graduation details
lable.qualification.pg=PG details
Lable.expectations.Header=<h1>Your Expectations</h1>
Lable.skill.Header=<h1>Your Skills</h1>


lable.employer.detail=<h1>Previous Employer Details</h1>
lable.employer.first=<h3>First EMployer</h1>
lable.employer.second=<h3>Second EMployer</h1>
lable.employer.third=<h3>Third EMployer</h1>


#errors
errors.header=<font size="4"><UL>
errors.prefix=<LI><span style="color: red">
errors.suffix=</span></LI>
errors.footer=</UL></font>

errors.required= {0} is required.
errors.maxlength={0} length should be max {2} character
errors.minlength={0} length should be min {1} character
errors.email={1} is not in proper format
errors.long={0} should be long
errors.invalid={0} should contains 10 digits
error.batch.required=Batch should be B33
error.sub.length= you should select minimum two {0}
errors.date=date pattern should be dd/MM/yyyy
errors.float={0} should be float
errors.integer={0} should be integer.
errors.range={0} should be between {1}-{2}


exception.user=Exception is thrown


---------------------------------------------------------------------------------