Tuesday, March 15, 2016

How to Stored images into a table?
Public class img
{
public static void main(String args[])
{
class.forName();
Connection con=Drivermanager.getConnection();
PreparedStatement pstmt=con.prepareStatement(“insert into image value(?)”);
FileInutStream fis=new FileInputStream(“a.gif”);
Pstmt.setBinaryStream (1,fis,fis.available);
int i=pstmt.executeUpdate();
}
}

How to retrieve image from a table?
public class img
{
public static void main(String args[])
{
class.forName();
Connection con=Drivermanager.getConnection();
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(“select * from img”);
rs.next();
InputStream is=rs.getBinaryStream(1);
FileOutPutStream fos=new FileOutPutStream(“g2.gif”);
int ch;
while(ch=is.read(1)!=!-1)
{
fos.write(ch);
}
}

What are the methods() to retrieve very large values from database?
getAsciiStream () àread values which are character in nature.
getBinaryStream()àused to read images.
What is a Transaction in java ?

A transaction is a set of operations that should be completed as a unit. If one operation fails then all the other operations fail as well. For example if you transfer funds between two accounts there will be two operations in the set
1. Withdraw money from one account.
2. Deposit money into other account.
These two operations should be completed as a single unit. Otherwise your money will get lost if the withdrawal is successful and the deposit fails. There are four characteristics (ACID properties) for a Transaction.
  
Atomicity
Consistence
Isolation
Durability
All the individual
operations should
either complete or fail.
The design of the
transaction should
update the database
correctly.
Prevents data being corrupted by concurrent
access by two different sources. It keeps
transactions isolated or separated from each
other until they are finished.
Ensures that the database is definitely updated once the Transaction is completed.

Transactions maintain data integrity. A transaction has a beginning and an end like everything else in life. The setAutocommit(….), commit() and rollback() are used for marking the transactions (known as transaction demarcation). When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and will be automatically committed immediately after it is executed. The way to allow two or more statements to be grouped into a transaction is to disable auto-commit mode:

try{
Connection myConnection = dataSource.getConnection();
// set autoCommit to false
myConnection .setAutoCommit(false);
withdrawMoneyFromFirstAccount(.............); // operation 1
depositMoneyIntoSecondAccount(.............); // operation 2
myConnection .commit();
}
catch(Exception sqle){
try{
myConnection .rollback();
}catch( Exception e){}
}
finally{
try{if( conn != null) 
      {
        conn.close();}
      } catch( Exception e) {}
    }

The above code ensures that both operation 1 and operation 2 succeed or fail as an atomic unit and consequently leaves the database in a consistent state. Also turning auto-commit off will provide better performance.

Monday, August 22, 2011

Login Form Application Using Strus Framework


In this example we will see how to create a login application using ActionForm. The following files are required for the login application.
  • login.jsp
  • success.jsp
  • failure.jsp
  • web.xml
  • struts-config.xml
  • LoginAction.java
  • LoginForm.java
  • ApplicationResource.properties

web.xml

The first page that will be called in the login application is the login.jsp page. This configuration should be done in web.xml as shown below.
 <welcome-file-list>
     <welcome-file>login.jsp</welcome-file>
 </welcome-file-list>

login.jsp

We use Struts HTML Tags to create login page. The form has one text field to get the user name and one password field to get the password. The form also has one submit button, which when clicked calls the login action. <html:errors /> tag is used to display the error messages to the user.
 <%@taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
 <html>
 <head>
 <title>Login Page</title>
 </head>
 <body>
     <div style="color:red">
         <html:errors />
     </div>
     <html:form action="/Login" >
         User Name :<html:text name="LoginForm" property="userName" />
         Password  :<html:password name="LoginForm" property="password" />
         <html:submit value="Login" />
     </html:form>
</body>
</html>
The user enters the user name and password and clicks the login button. The login action is invoked.

struts-config.xml

The validate method in the LoginForm class is called when the Form is submitted. If any errors are found then the control is returned back to the input page where the errors are displayed to the user. The input page is configured in the action tag of strut-config file. <html:errors /> tag is used to display the errors in the jsp page.
 <struts-config>
     <form-beans>
         <form-bean name="LoginForm" type="com.om.LoginForm"/>
     </form-beans>
     <action-mappings>
         <action path="/Login" name="LoginForm"   input="/login.jsp" scope="session" type="com.om.LoginAction">
             <forward name="success" path="/success.jsp" />
             <forward name="failure" path="/failure.jsp" />
         </action>
     </action-mappings>
 </struts-config>
Here the action is "/Login" , the input page is "login.jsp" and the corresponding action class is LoginAction.java. Now the validate method in the LoginForm class will be invoked.

LoginForm.java

Inside the validate method, we check whether the user name and password is entered. If not the corresponding error message is displayed to the user. The error messages are configured in the ApplicationResource.properties file.
 public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
     ActionErrors errors = new ActionErrors();
     if (userName == null || userName.length() < 1) {
         errors.add("userName", new ActionMessage("error.userName.required"));
     }
     if (password == null || password.length() < 1) {
         errors.add("password", new ActionMessage("error.password.required"));
     }
     return errors;
 }

ApplicationResource.properties

The ApplicationResource.properties file contains the error messages. The key "error.userName.required" is used in the validate function to add a new error. Since the error messages are configured in a seperate properties file they can be changed anytime without making any changes to the java files or the jsp pages.
 error.userName.required = User Name is required.
 error.password.required = Password is required.
If either user name or password is not entered then the corresponding error message will be added to the ActionErrors. If any errors are found then the control is returned back to the input jsp page, where the error messages are displayed using the <html:errors /> tag. The validate method is used to perform the client-side validations. Once when the input data is valid the execute method in the LoginAction class is called.

LoginAction.java

The execute method contains the business logic of the application. Here first we typecast the ActionForm object to LoginForm, so that we can access the form variables using the getter and setter methods. If the user name and password is same then we forward the user to the success page else we forward to the failure page.
public class LoginAction extends org.apache.struts.action.Action {
   private final static String SUCCESS = "success";
    private final static String FAILURE = "failure";

    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
         LoginForm loginForm = (LoginForm) form;
         if (loginForm.getUserName().equals(loginForm.getPassword())) {
             return mapping.findForward(SUCCESS);
         } else {
             return mapping.findForward(FAILURE);
         }
     }
 }
Lets enter the user names and password as "Eswar". Since the user name and password is same the execute method will return an ActionForward "success". The corresponding result associated with the name "success" will be shown to the user. This configuration is done in struts-config.xml file.
<action-mappings>
    <action path="/Login" name="LoginForm "   input="/login.jsp" scope="session" type="com.om.LoginAction">
        <forward name="success" path="/success.jsp" />
        <forward name="failure" path="/failure.jsp" />
    </action>
</action-mappings>
So according to the configuration in struts-config.xml the user will be forwarded to success.jsp page.
If the user name and password did not match the user will be forwarded to the failure pag.