Sunday, August 28, 2011

adding youtube video to html pages

This code will add YOUTUBE videos to you HTML pages.

<html>
<body>
<h2>abhishek kumar rathur</h2>
<object width="425" height="350">
             <param name="movie" value="http://www.youtube.com/v/rxUm-2x-2dM"/>
             <param name="wmode" value="transparent" />
             <param name="allowFullScreen" value="true" />
             <embed src="http://www.youtube.com/v/rxUm-2x-2dM"
                      type="application/x-shockwave-flash"
                      wmode="transparent" width="425" height="350"
                      allowFullScreen="true">
              </embed>
</object>
</body>
</html>

The above code will embed a you tube video to your html page. The attributes, value and src of param with name movie and embed tags respectively holds the url to the video, which is being embedded. The last segment of the url is the video ID (which is used to identify a video). The ID in the following example is rxUm-2x-2dM.

OutPut:-
Write the above given code in a notepad save it as xyz.html ,it will create a webpage that is a HTML page ,double click that xyz.html page ,wait for some time ,video will appear in your HTML page.
To play the video ,you have to host that page.


Thursday, August 4, 2011

left join and right join, inner join

Provided DataBase

mysql> select * from demo_people;

+------------+--------------+------+

| name       | phone        | pid  |

+------------+--------------+------+

| Mr Brown   | 01225 708225 |    1 |

| Miss Smith | 01225 899360 |    2 |

| Mr Pullen  | 01380 724040 |    3 |

+------------+--------------+------+

3 rows in set (0.00 sec)



mysql> select * from demo_property;

+------+------+----------------------+

| pid  | spid | selling              |

+------+------+----------------------+

|    1 |    1 | Old House Farm       |

|    3 |    2 | The Willows          |

|    3 |    3 | Tall Trees           |

|    3 |    4 | The Melksham Florist |

|    4 |    5 | Dun Roamin           |

+------+------+----------------------+---------------------------+------------------------+-------------------------
If I do a regular JOIN (with none of the keywords INNER, OUTER, LEFT or RIGHT), then I get all records that match in the appropriate way in the two tables, and records in both incoming tables that do not match are not reported:

mysql> select name, phone, selling
from demo_people join demo_property

on demo_people.pid = demo_property.pid;

+-----------+--------------+----------------------+

| name      | phone        | selling              |

+-----------+--------------+----------------------+

| Mr Brown  | 01225 708225 | Old House Farm       |

| Mr Pullen | 01380 724040 | The Willows          |

| Mr Pullen | 01380 724040 | Tall Trees           |

| Mr Pullen | 01380 724040 | The Melksham Florist |

+-----------+--------------+----------------------+---------------+-------------------+----------------------------+
If I do a LEFT JOIN, I get all records that match in the same way and IN ADDITION I get an extra record for each unmatched record in the left table of the join - thus ensuring (in my example) that every PERSON gets a mention:


mysql> select name, phone, selling

from demo_people left join demo_property

on demo_people.pid = demo_property.pid;

+------------+--------------+----------------------+

| name       | phone        | selling              |

+------------+--------------+----------------------+

| Mr Brown   | 01225 708225 | Old House Farm       |

| Miss Smith | 01225 899360 | NULL                 |

| Mr Pullen  | 01380 724040 | The Willows          |

| Mr Pullen  | 01380 724040 | Tall Trees           |

| Mr Pullen  | 01380 724040 | The Melksham Florist |
-+---------------------+-------------------------------------+-----------------------+----------------
If I do a RIGHT JOIN, I get all the records that match and IN ADDITION I get an extra record for each unmatched record in the right table of the join - in my example, that means that each property gets a mention even if we don't have seller details:
mysql> select name, phone, selling 
from demo_people right join demo_property 
on demo_people.pid = demo_property.pid;
+-----------+--------------+----------------------+
| name      | phone        | selling              |
+-----------+--------------+----------------------+
| Mr Brown  | 01225 708225 | Old House Farm       |
| Mr Pullen | 01380 724040 | The Willows          |
| Mr Pullen | 01380 724040 | Tall Trees           |
| Mr Pullen | 01380 724040 | The Melksham Florist |
| NULL      | NULL         | Dun Roamin           |
+-----------+--------------+----------------------+
-+--------------------------------------------+--------------------------+------------



 

Friday, June 3, 2011

creating a flash,how to include swf in html

creating a flash is very simple.
Things you need.
1.Micromedia Dreamweaver.
2.A swf file,which you can create using Mix-Fix.


Monday, April 18, 2011

DynaAction

Q).what is a DynaAction?
Why actually we need DynaAction Form this is the real question,one proverb is there "necessity is the mother of invention " this proverb is applicable here.

Starting from Struts 1.0 where we are having one jsp page ,one form bean  is there which has all setter() and getter() mehod and one action class is there which has the execute() method,there was a overhead of creating a form bean for ever method, so they came up with the idea of DynaActionForm bean, where all the from properties are defined in the Struts configuration file,so that creation of the concrete class can be avoided.

<form-beans>
    <form-bean name="LoginForm" type="org.apache.struts.action.DynaActionForm">
        <form-property name="userName" type="java.lang.String" />
       <form-property name="password" type="java.lang.String" />
    </form-bean>
</form-beans>
 
Then came Struts2 where there is a single java class, where we are having all the from properties and the execute() method,so if you had noticed there nothing called DynaAction Form in Struts2.0,since all the form properties are defined in the action class it shelf,no need to define the form  properties in the sturts configuration file .



Exapmle of DiapatchAction in Struts2

There is a little bit of difference in DispatchAction Functionality in Struts1.x and Struts2.0.
We would talk about DispatchAction in Struts2.0 since it is somewhat simpler.
Before taking this example I guess  you must be knowing what actually is a DispatchAction if not please go through this,what actually is a DispatchAction and why it is needed is explained in simple words.
http://rathursp.blogspot.com/2011/04/what-is-dispatchaction-in-struts2.html

Guess now you must have little bit of idea about DispatchAction
Its good to start..

we would create a form with multiple buttons on it,such that each button will have different action to perfrom.

index.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="/struts-tags" prefix="s" %>
<html>
<head> 
 
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<s:form action="User" >
<s:submit />
<s:submit action="addUser" value="Add" />
<s:submit action="updateUser" value="Update" />
<s:submit action="deleteUser" value="Delete" />
</s:form>
</body>
</html>
 
 
struts.xml 
Configure struts.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <package name="default" extends="struts-default">
        <action name="User" class="rathur.UserAction">
            <result name="success">/success.jsp</result>
        </action>      
        <action name="addUser" method="add" class="rathur.UserAction"> 
/*will call the add() declared in pkg rathur.UserAction*/
            <result name="success">/success.jsp</result> 
/*it will check if the add() has returned success then it will go to the success.jsp page*/
        </action>
        <action name="updateUser" method="update" class="rathur.UserAction">
            <result name="success">/success.jsp</result>
        </action>
        <action name="deleteUser" method="delete" class="rathur.UserAction">
            <result name="success">/success.jsp</result>
        </action>  
    </package>
</struts>
notice we are having same UserAction for all the action mapping.
when the requested URL is User the execute() of UserAction would be called,
when the requested url is addUser the add() in the UserAction is called.
UserAction.java

package rathur;
import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport{

    private String message;
        public String execute()
       {
        message = "Inside execute method";
        return SUCCESS;   
       }
       public String add()
      {
        message = "Inside add method";
        return SUCCESS;          /* these return would be checked in struts.xml  */ 
      }
      public String update()
      {
        message = "Inside update method";
        return SUCCESS;       
       }
      public String delete()
     {
       message = "Inside delete method";
        return SUCCESS;       
      }
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}



success.jsp

create a success.jsp page
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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>
${message}
</body>
</html>


output





hi if you got the required output please do comment. :-)





Sunday, April 10, 2011

what is dispatchaction in struts

Q)explain dispatchaction.
Q)what is a dispatch action.
Q)dispatchaction in struts

When we talk about struts,when we go for creating a form we need three things.
1.jsp page
2.login form.
3.login action
since we show that for creating a form be need to create three differnt file,if our application involve multiple (x)form there would be overhead of creating 3*x file.Inorder to prevent this we came up with the idea of DispactchAction,where multiple action class is not required,in one action class we can declare the implementation of  i.e business logic of all the form.




Thursday, April 7, 2011

dispatchaction in struts2

Dispatch Action

Basically Dispatch action is used when you have multiple submit buttons in a single form.
The Dispatch action is a class which extends the Struts DispatchAction,
and encpsulates all the action methods (similar to execute method in Action class)
in one single class.
In the Struts-Config.xml you need to define the DispatchAction class and the parameter name that you passing in the URL.
Based on the parameter the Controller will invoke the action method.

The DispatchAction is a special Action class within Struts
that allows different functions to be called depending on a value of a parameter in a request object

Every Action in the JSP page need not have a different/Separate Action class to handle the request.
Instead one Dispatch Action class can handle all this.
Basing on the action selected a value is passed to the Dispatch Action and the corresponding method gets executed which
would handle the Action. Dispatch Action extends the Action class.
This way the Dispatch Action reduces the Developement time and also eases the process of maintenance.

DispatchAction is another useful built-in Struts Action. However you cannot use it as is.
You will have to extend it to provide your own implementation.

An interesting thing to notice is that the value of the HTTP
request parameter named step is same as the four method names in CreditAppAction
http://localhost:8080/bank/screen-credit-app.do?step=reject&id=2 
http://localhost:8080/bank/screen-credit-app.do?step=approve&id=2    
http://localhost:8080/bank/screen-credit-app.do?step=addComment&id=2

DispatchAction knows what parameter to look for in the incoming URL
request through this attribute named parameter in struts-config.xml.
(the request parameter that will uniquely identify all actions.)
the arguments and their order in these methods is fixed by DispatchAction
the method invocation by reflection at runtime is successful.

uploading image and displaying

FileUploadAction.java


package net.viralpatel.struts2;

import java.io.File;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport implements
        ServletRequestAware {
 private File userImage;
 private String userImageContentType;
 private String userImageFileName;

 private HttpServletRequest servletRequest;

    @Override
  public String execute() {
       try {

           String filePath = servletRequest.getRealPath("/");
           System.out.println("Server path:" + filePath);
           File fileToCreate = new File(filePath, this.userImageFileName);

           FileUtils.copyFile(this.userImage, fileToCreate);
       } catch (Exception e) {
            addActionError(e.getMessage());

         return INPUT;
       }
       return SUCCESS;
 }

   public File getUserImage() {
        return userImage;
   }

   public void setUserImage(File userImage) {
      this.userImage = userImage;
 }

   public String getUserImageContentType() {
       return userImageContentType;
    }

   public void setUserImageContentType(String userImageContentType) {
      this.userImageContentType = userImageContentType;
   }

   public String getUserImageFileName() {
      return userImageFileName;
   }

   public void setUserImageFileName(String userImageFileName) {
       this.userImageFileName = userImageFileName;
 }

   @Override
   public void setServletRequest(HttpServletRequest servletRequest) {
      this.servletRequest = servletRequest;

   }
}





UserImage.jsp


This is done using the struts2.0  framework,you need to have the plugin for it.


<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Upload User Image</title>
</head>
<body>
<h2>Struts2 File Upload & Save Example</h2>
<s:actionerror />
<s:form action="userImage" method="post" enctype="multipart/form-data">
<s:file name="userImage" label="User Image" />

<s:submit value="Upload" align="center" />
</s:form>
</body>
</html>

SuccessUserImage
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Success: Upload User Image</title>

</head>
<body>
   <h2>Struts2 File Upload Example</h2>
  
 User Image: <s:property value="userImage"/>

 Content Type: <s:property value="userImageContentType"/>

 File Name: <s:property value="userImageFileName"/>

 Uploaded Image:


 <img src="<s:property value="userImageFileName"/>"/>
</body>
</html>


struts.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <include file="example.xml"/>
    <!-- Configuration for the default package. -->
    <package name="default" extends="struts-default">
        <action name="userImage"
    class="net.viralpatel.struts2.FileUploadAction">
    <interceptor-ref name="fileUpload">
          <param name="maximumSize">2097152</param>

          <param name="allowedTypes">
              image/png,image/gif,image/jpeg,image/pjpeg
         </param>
     </interceptor-ref>
       <interceptor-ref name="defaultStack"></interceptor-ref>
    <result name="success">SuccessUserImage.jsp</result>

      <result name="input">UserImage.jsp</result>
</action>
    </package>
</struts>
 
output




Wednesday, March 9, 2011

Login and Logout in struts2

learn java




login.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page language="java" contentType="text/html"%>

<html>
    <head>
        <title>Insert Data here!</title>
     <link href="<s:url value="/css/main.css"/>" rel="stylesheet"
          type="text/css"/>
  </head>
    <body>
  <s:form action="loginAction1" >
      <s:textfield name="userId" label="Login Id"/><br>
      <s:password name="password" label="Password"/><br>
         <s:submit value="Login" align="center"/>
    </s:form>
  </body>
</html>

loginAction1
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vaannila;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ActionContext;
import java.util.*;

public class loginAction1 extends ActionSupport {

    private String userId;
    private String password;

    @Override
    public String execute() throws Exception {

        if ("admin".equals(userId) && "admin".equals(password)) {
            Map session = ActionContext.getContext().getSession();
            session.put("logged-in", "true");
            return SUCCESS;
        } else {
            return ERROR;
        }
    }

    public String logout() throws Exception {

        Map session = ActionContext.getContext().getSession();
        session.remove("logged-in");
        return SUCCESS;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }
}


struts.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <include file="example.xml"/>
    <!-- Configuration for the default package. -->
    <package name="default" extends="struts-default">
        <action name="loginAction1" class="vaannila.loginAction1" >      
        <result name="success" type="dispatcher">/success2.jsp</result>
       <result name="error" type="redirect">/login.jsp</result>
</action>

<action name="logoutAction" class="vaannila.logoutAction" >
       <result name="success" type="redirect">checkLogin.jsp</result>
</action>

    </package>
</struts>


success2.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page language="java" contentType="text/html" import="java.util.*"%>
<html>
    <head>
        <title>Welcome, you have logined!</title>
  </head>
    <body>
    Welcome, you have logined. <br />
    <b>Session Time: </b><%=new Date(session.getLastAccessedTime())%>
      <br /><br />
      <a href="<%= request.getContextPath() %>/vaannila/logoutAction">Logout</a>
      <br />
    </body>
</html>

logoutAction.java
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package vaannila;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ActionContext;
import java.util.*;

public class logoutAction extends ActionSupport {
    @Override
  public String execute() throws Exception {
    Map session = ActionContext.getContext().getSession();
    session.remove("logged-in");
    return SUCCESS;
    }
}

after logoutAction it wil go to struts.xml and then to

checkLogin.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page language="java" contentType="text/html" import="java.util.*"%>
<html>
    <head>
        <title>Check validate!</title>
  </head>
    <body>
      <s:if test="#session.login != 'admin'">
      <jsp:forward page="login.jsp" />
      </s:if>
    </body>
</html> 


output











starting struts2.0

learn java
index.jsp

<%@taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
    <s:form action="HelloWorld1" >
        <s:textfield name="userName" label="User Name" />
        <s:submit />
    </s:form>
</body>
</html>

helloworld.java
package vaannila;
public class HelloWorld1 {
private String message;
private String userName;


    public String execute() {
        setMessage("Hello " + getUserName());
        return "SUCCESS";
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
}
}



success.jsp
<%@taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
    <h1><s:property value="message" /></h1>
</body>
</html>

struts.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <include file="example.xml"/>
    <!-- Configuration for the default package. -->
    <package name="default" extends="struts-default">
        <action name="HelloWorld1" class="vaannila.HelloWorld1">
            <result name="SUCCESS">/success.jsp</result>
       </action>
    </package>
</struts>


output

Thursday, March 3, 2011

Cookie Example

learn java

index.jsp
 <body>
        <h1>Hello World!</h1>
        <% Cookie cookie = new Cookie ("testcookie","Visualbuilder");
        cookie.setMaxAge(60);
        response.addCookie(cookie);
        response.sendRedirect("getcookie.jsp");
         %>
  </body>  
    



getcookie.jsp
   <body>
<%
   Cookie[] cookies= request.getCookies();
   for(int i=0;i<cookies.length;i++){
   if(cookies[i].getName().equalsIgnoreCase("testcookie")){
          out.println("Cookie Value is "+ cookies[i].getValue());
      }
   }
%>
    </body>

  

Cookie

learn java

Cookie
In JSP cookie are the object of the class javax.servlet.http.Cookie.
The Http protocol is a stateless protocol means that it can't keep a state
i.e. it can't persist values. To maintain a session we used the concept of cookies.
"A token is generated which contains user's information,
By this cookie, the server is able to identify the user."

Cookie is nothing but a name- value pair, which is stored on the client machine.
The cookies are saved to clients hard disk in the form of small text file.
Cookies helps the web servers to identify web users, by this way server tracks the user.
Cookies pay very important role in the session tracking.

Two types of cookies.
1) Non- secure session cookie:
This cookie can flow between the browser and server under the SSL or non- SSL connection.

2) Secure authentication cookie:
It is used to authenticate the data. This cookie flow over SSL.
This type of authenication cookie are used where the information security is very important. 


getComment()
Returns the comment describing the purpose of this cookie.

getMaxAge()

Returns the maximum specified age of the cookie.

getName()

Returns the name of the cookie.

getPath()
Returns the prefix of all URLs for which this cookie is targeted

getValue()

Returns the value of the cookie.

setMaxAge(int)
Sets the maximum age of the cookie.

setPath(String)
This cookie should be presented only with requests beginning with this URL.

setValue(String)
Sets the value of the cookie.

Response Object

learn java
The response object is an instance of a class that implements the javax.servlet.http.HttpServletResponseT
interface.
The response object denotes the HTTP Response data.
The result or the information of a request is denoted with this object.
The response object handles the output of the client.
The response object is generally used by cookies.

The response object is also used with HTTP Headers.

Methods of response Object:
There are numerous methods available for response object. Some of them are:

    setContentType()
    addCookie(Cookie cookie)
    addHeader(String name, String value)
    containsHeader(String name)
    setHeader(String name, String value)
    sendRedirect(String)
    sendError(int status_code)

setContentType()
setContentType() method of response object is used to set the MIME type and character encoding for the page.
response.setContentType("text/html");

addCookie(Cookie cookie):

addCookie() method of response object is used to add the specified cookie to the response.
For example:
response.addCookie(Cookie exforsys);

addHeader(String name, String value):
addHeader() method of response object is used to write the header as a pair of name and value to the response.
If the header is already present, then value is added to the existing header values.
For example:
response.addHeader("Author", "Exforsys");

The output of above statement is as below:
Author: Exforsys

containsHeader(String name):
containsHeader() method of response object is used to check whether the response already includes the header given as parameter.
If the named response header is set then it returns a true value.response.containsHeader(String name)

setHeader(String name, String value):
setHeader method of response object is used to create an HTTP Header with the name and value given as string.
If the header is already present, then the original value is replaced by the current value.
For example:
response.setHeader("Content_Type","text/html");

The above statement would give output as
Content_Type: text/html

sendRedirect(String):

sendRedirect method of response object is used to send a redirect response to the client temporarily by making use of redirect location URL given in parameter. But one must note that if the JSP executing has already sent page content to the client, then the sendRedirect() method of response object will not work and will fail.response.sendRedirect(String)

Implicit Object

These objects are defined as implicit because you do not have to explicitly declare them.
Because implicit objects are declared automatically we need only use the reference
variable associated with a given object to begin calling methods on it.
JSP container will create these objects automatically and
the container makes them available to the developers.
The implicit objects are parsed by the container and
inserted into the generated servlet code. 

1.request

2.response

3.page

4.application

5.session

6.pagecontext

7.exception

8.out

9.config

Ex: request.getElementById("xyz");

here you are using 'request' object without instantiating it because this object
is readily available for you.

Example:
If i want to put my username in the session in JSP.
JSP Page:
<%
String name=request.getParameter("Username");
session.setAttribute("UserName",name);
%>

<%=request.getRequestURI()%>

Wednesday, March 2, 2011

Learn JSP


Example for displaying content from other jsp page.

index.jsp

<body>
        <h1>Hello World!</h1>
        <%=request.getRequestURI()%>
        <%=request.getProtocol()%>          
            <%request.setAttribute("information","This is information passed from outer page");%>
             <jsp:include page="success.jsp"/>      
  </body>  
success.jsp     
   <body>
        <h1>Hello World!</h1>
                <%=request.getAttribute("information")%>
    </body>


  


Monday, January 17, 2011

java-8-streams-map-examples

package com.mkyong.java8; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.List; im...