Monday, November 28, 2011

Struts 2.2.3 Hello world example with Eclipse


I have been looking for a full flash working example of a struts 2.2.3.1 So I Googled it. And found some examples. But all of them were either uncomplete or using older version of struts. So I decided to make my own.
To make a struts 2 hello world example I created an example in which user simply puts some information on the form submits it and on submission user gets informed that his form has been processed.
Prerequisites:
  •        Any Web/application server : (I used tomcat 6)  Tomcat , JBoss etc.
  •        Struts library : can be downloaded from Here or go to struts official site.
  •               Eclipse IDE for easier configuration of project Europa or above.
  •        Fundamental knowledge of Eclipse is preferable.
      For a newbie it is suggested that to read some struts fundamentals. Like what is the basic structure of Struts application. Basically in a struts Web application you need to configure your bean class, filter dispatcher and actions. Basic structure of a struts application that is made is follows.

 
Struts project structure in eclipse
For those who are familiar with Eclipse’s environment then this structure is easily understandable. For those who are new at this ! don’t worry. Just follow the steps provided and you should get your application running.
Step 1. Open eclipse and create new ‘Dynamic Web Project’ With any suitable name.  I gave Struts Practice3 here. 
Configure your Tomcat server before you proceed building any Web application as we gonna need that to run out application.
Step 2. Fundamental structure of a web application will be created by eclipse. After that you need to copy your necessary struts library files into your application’s lib folder.
Following is the list that are necessary library files required to run struts 2.2.3 application.
After a 2 hour long search and debugging I found the list that is actually required to run a struts application
1. Commons-fileupload-1.2.2.jar
2. Commons-io-2.0.1.jar
3. Commons-logging-1.1.1.jar
4. Commons-logging-api-1.1.jar
5. Freemarker-2.3.1.6.jar
6. Javassist-3.11.0.GA.jar
7. Ognl-3.0.1.jar
8. Struts2-core-2.2.3.1.jar
9. Xwork-core-2.2.3.1.jar
Don’t worry about the exact version names. They are all bundled with struts distribution. Copy those files from the struts distribution package and paste them in to the lib folder . As shown in the picture.
Step3. Next thing is to configure our web.xml file So here is the web.xml code. What we are telling here is that there is an application with the name StrutsPractice3 Which if we run on server then all requests will be filtered through FilterDispatcher. (You can ignore security constraint here its optional. Its just to make sure that Jsp files are not directly accessible.)
<?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>StrutsPractice3</display-name>
 
  <security-constraint>
    <web-resource-collection>
      <web-resource-name>JSPs</web-resource-name>
      <url-pattern>/jsp/*</url-pattern>
    </web-resource-collection>
    <auth-constraint/>
  </security-constraint>
  <login-config>
    <auth-method>BASIC</auth-method>
  </login-config>
  <filter>
    <display-name>struts2</display-name>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>


Step 4. Now our filter dispatcher will look for its struts.xml file. So its time to configure it . So here is the code.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
<package name="app" extends="struts-default" namespace="/">
              <action name="Product_input">
                     <result>/jsp/ProductForm.jsp</result>
              </action>
              <action name="Product_save" class="app.Product">
                     <result>/jsp/ProductDetails.jsp</result>
              </action>
       </package>
</struts>
As you can see It has two actions defined.  Product_input and Product_save. Product_input doesn’t have any class so struts will just forward request to ProductForm.jsp (we’ll make is very soon.) and in Product_details action the class Product in app package is defined. As there is not method specified here so it will find execute method by default defined in Product class.
Setp 5. Next step is to define Product Class. So right click on project and create a package with the name app. Then again right click on package and create new java class with name Package. Define three private variables productName, description, price with getter and setter methods  and a public method execute. Here is the code.  (To create getter setter methods right click on class go to Source -> generate getter setters and eclipse create getter and setter methods for you.)
package app;
import java.io.Serializable;
import com.opensymphony.xwork2.ActionSupport;
public class Product extends ActionSupport implements Serializable {
                private String productName;
                private String description;
                private String price;
                public String execute(){
                                System.out.println("Hello world");
                                return "success";
                }
                public String getProductName() {
                                return productName;
                }
                public void setProductName(String productName) {
                                this.productName = productName;
                }
public String getDescription() {
                                return description;
                }
                public void setDescription(String description) {
                                this.description = description;
                }
                public String getPrice() {
                                return price;
                }
                public void setPrice(String price) {
                                this.price = price;
                }
}
Step 5. Now last step is to create our view part. i.e. the jsp files.
Right click on WebContent folder create new folder with the name jsp (Its not necessary to create files in a folder. If you don’t want to use it then just create jsp files in WebContent. But then adjust jsp path in struts.xml file) inside jsp folder create new jsp files with name
ProductForm.jsp and ProductDetails.jsp

ProductForm.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!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>Product Input Form</title>
</head>
<body>
<h3>Product input form</h3>

<s:form action="Product_save.action" method="post">
<table>
<tr><td><s:textfield name="productName" label="Product Name" /></td></tr>
<tr><td><s:textfield name="description" label="Product Description"/></td></tr>
<tr><td><s:textfield name="price" label="Product Price"/></td></tr>
<tr><td><s:submit align="center" /><s:reset name="Reset" value="Reset"/></td></tr>
</table>
</s:form>
</body>
</html>

ProductDetails.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!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>
<h3>Product Details are follows</h3>
<p>
Product Name: <s:property value="productName"/><br/>
Description: <s:property value="description"/><br/>
Price: $ <s:property value="price"/>
 </p>
</body>
</html>

That’s it ..!! you just created a struts application.
No run the application on server. (Start tomcat, Export project as war file into tomcat’s webapp directory) and try accessing following url

Please give your valuable response if that article was helpful.






Saturday, October 1, 2011

Simple tutorial to Set background image of a button : for beginners
Requirements : An image , An html button on page at least
First of all make a simple html page with a button in it.

<html>
<head>
<style>
#myCustomButton{
background: url("myimage.png") ;
background-repeat : repeat-x; /* repeat-y , no-repeat */
}
</style>
</head>
<body>
<input type="button" value="My Button" id="myCustomButton">
</body>
</html>

Thats it. background image should appear on your button.
Note :

  1. Path should be accurate while giving url of background image. if image file is in same directory where your html page is then there is not need to give path. Just give the file name with extension.
  2. If you don't want to give url you can also use attribute background-color: #123456;
I have used inline style sheet on page style can also be applied using separate css file like style.css
using following tag in your head tag 
<link type="text/css" rel="stylesheet" href="style.css">

href url should be accurate path of your css file.

Monday, September 19, 2011

How to Access JBoss AS 7 on LAN network

Running JBoss AS 7 on Network

The new JBoss 7 Application server has new look and new management interface. And it has new method to start. Instead of starting the server using run.bat user now have to run it through standalone.bat 
Welcome  screen was absent in beta versions but in final version its can be accessed through
http://localhost:8080
A new refreshing look
But then a question arise in mind that if you are connected to network and how to access the server on other computers via network.
As in older versions of JBoss the same can be done using command line with -b 0.0.0.0 option using with run.bat (set broad cast address)

But in JBoss AS 7 how to do the same?
After some Googling i found following solution
open standalone.xml file in notepad (/jbosspath/standalone/configuration) and find following code chunk in it
<interfaces>
        <interface name="management">
            <inet-address value="127.0.0.1"/>
        </interface>
        <interface name="public">
           <inet-address value="127.0.0.1"/>
        </interface>
    </interfaces>

Basically find <interfaces> tag in xml file.
And add a new Interface like :

<interfaces>
        <interface name="management">
            <inet-address value="127.0.0.1"/>
        </interface>
        <interface name="public">
           <inet-address value="127.0.0.1"/>
        </interface>
         <!-- Equivalent of -b 0.0.0.0 -->

          <interface name="any">
               <any-address/>
          </interface>

    </interfaces>

and then find Socket-binding-group and change default-interface value from public to any <socket-binding-group name="standard-sockets" default-interface="any">

Use IP Address of computer on which server is running to access server on network.

Friday, August 12, 2011

Adventure of Spring 3.0

I have been reading book on spring frame work for last few days, got ill every thing left back.
but after coming back i finally managed to run a hello world Web application.
I was trying to read book again. but found too boring and complex to understand.
then Googled (Google has everything) and found some useful links.
Followed the tutorial.
(One question, Why all those big enterprise level Frame works have too much open branches like a tree. this branch will do this. that will do this. to make one simple application you need 29 on hold.)

I bet This question will arise to every newbie who want to learn spring, struts, hibernate etc.
When i'll get fluent on this i'll answer this question.

To make a simple Hello world (Showing hello world on click of a link on webpage) you need
1. index.jsp - This is entry point of the application and this will contain link to hello world.
2. dispacther-servlet.xml - This will contain mapping of the page which will be processed on click of link of index.jsp
3. HelloWorldController.java - This is controller and will give message and filename which should be opened on click of index.jsp link
4. Mapping of DispatcherServlet and url pattern in Web.xml file
Thats all is required.
I know this will add only 5% idea to visitor mind. (if they already know web application structure) so i'll post complete tutorial very soon on this.

Sunday, December 19, 2010

Copy Constructor

In C++ a copy constructor that takes Object reference of the class to which it belongs. Most people think that if there is no copy constructor then we cannot create argument of its own class type while create object. Obviously because there is no matching constructor will be found while calling. but this is partially true.

If we don't make a copy constructor in our class definition then the compiler itself creates a copy constructor itself.
That means if we don't code a copy constructor in our class and make an object with an argument of its own class object that will not give error and will run perfectly...!!!
for example

class Test{
int x,y;
public:
Test(int a,int b){
a = x;
b = y;
}
void display()
{
cout<<"x = "<<x<<"y = "<<y;
}
};
void main()
{
Test obj1(5,19);    // This will call parametrized constructor that we defined in class
Test obj2(obj1);    // This will run perfectly and will not give any error. but copy the contents of obj1 to obj2 exactly                             //  the same.
obj2.display();
}

but if we don't want to exactly copy the contents of one object into other object then we will need to create custom copy constructor.

but there is a problem. consider the following situation
class test
{
int *p;
public:
test()
{
p = new int();        // This will allocate a new memory into p;
}
~test()                // this destructor will deallocate memory of p of concerned object.
{
delete p;
}
};
void main()
{
test obj1;            // creating this object will allocate memory to p into obj1
{                        // a inner block starts here.
test obj2(obj1);      // as this will copy the content of obj1 to obj2 that is memory reference of obj1->p will be copied                            //     to obj2 - > p. now we are dealing with the address of p

}    // at this point destructor will be called and deallocate the memory occupied by obj2. but here is the problem.
      // as p of obj2 has the same address as of p of obj1. that means if obj2 is destroyed then p will also be                  // destroyed. it will also release memory in obj1 ' s p. which should not be done.
       // hence if we are dealing with pointer we have to be very carefull using copy constructor.

}