Struts

Purpose: Provides information on how to create struts and tiles projects in WASD 5.1.2. Document is useful for practical purpose for theoretical information go through the books in References and Books section:

Prerequisites:

1)Go through the basic definitions of action class, action forward, struts-config etc.

2)Basic WASD, jsp, servlet concepts.

References and Books (free PDF):

First struts program using WSAD 5.1.2

1)file->new->dynamic web project-> give project name and check “configure Advanced options” click on next ( my project name is strutsProject2)

2)Click on next.

3)Check “Add Struts support” and “jsp tag libraries” (WASD will automatically copy the required jar files and set up the struts configurations ) .Click next

4)Click next.

5)Click finish.

INFO

The project structure and web.xml was created by the editor. Now we need to create a jsp which just displays a message “hello world. Welcome to my site”.

For that we need welcomeAction.java , welcome.jsp,index.jsp

Index.jsp: (webcontent/index.jsp)This is called by the server when we try to access the application like ( .

This is because the web.xml will declare welcome list like below by default(WASD)

welcome-file-list

welcome-fileindex.html</welcome-file

welcome-fileindex.htm</welcome-file

welcome-fileindex.jsp</welcome-file

welcome-filedefault.html</welcome-file

welcome-filedefault.htm</welcome-file

welcome-filedefault.jsp</welcome-file

</welcome-file-list

From this jsp weare forwarding the control to another jsp welcome.jsp which is under webcontent/jsp through welcomeAction.

Create action class

1)right click the java resources folder ->new->other->Web(Struts)->Action class->next

2) give action class name->next

3) finish.

INFO

Go to welcomeAction.java .we should see execute method with try/catch blocks

That method can be replaced like the below as we don’t need try/catch blocks for this example

publicActionForwardexecute(

ActionMappingmapping,

ActionFormform,

HttpServletRequestrequest,

HttpServletResponseresponse)

throwsException{

ActionErrorserrors=newActionErrors();

ActionForwardforward=newActionForward();// return value

forward=mapping.findForward("welcomeForward");

return(forward);

}

Change the forward name to welcomeForward and we need to update struts config to declare the forward name.

Create index.jsp

1)under webcontent create a new jsp file with name index.jsp

The jsp looks like below

<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>

jsp:forward page="/welcome.do?dispatcher=welcomeMethod" />

</html:html

Create welcome.jsp

Create a new folder jsp under webContent and create new jsp file welcome.jsp like this

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>

<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>

html:html

BODY

Hello World.Welcome to my site.

</BODY

</html:html

Change the struts-config.xml like this. We are mapping the action forward “welcomeForward” to “/jsp/Welcome.jsp”

action path="/welcome" type="com.lavanya.strutsproject2.actions.welcomeAction"

forward name="welcomeForward" path="/jsp/welcome.jsp"/>

</action

Finally restart the server and click on “run on server” by right clicking the project. The output will look like

What is happening when we click on ?

1)Go to WEB.xml

The controller first goes to web.xml as usual and dispatches to index.jsp

2) Go to index.jsp

Here we are forwarding the control to /welcome.do?dispatcher=welcomeMethod"

3) Go to Web.xml again

In web.xml the controller will find only one servlet that is ActionServlet with url-pattern .do . So it is forwarded to ActionServlet to dispatch the request to jsp.

servlet-nameaction</servlet-name

servlet-classorg.apache.struts.action.ActionServlet</servlet-class

init-param

param-nameconfig</param-name

param-valueWEB-INF/struts-config.xml</param-value

</init-param

url-pattern*.do</url-pattern

4) Go to Struts-config.xml

action path="/welcome" type="com.lavanya.strutsproject2.actions.welcomeAction"

forward name="welcomeForward" path="/jsp/welcome.jsp"/>

</action

Find the action mapping for “welcome” and enter the welcomeAction.java class

5) Go to welcomeAction.java

In the action class we only had an execute method so that method will get executed and finally forwarded the control to “welcomeForward”

6) The control will go the struts config and finds the forward name”welcomeForward” under welcome action mapping and forwards to welcome.jsp

Struts + Tiles + DispatcherAction

References and Books (free PDF) :

First tiles program (enhancement to previous project “strutsProject2”):

We are going to display a webpage with header and footer

We need tiles-definitions.xml, header.jsp,footer.jsp,body.jsp,BasicLayout.jsp

JSP changes:

Create header.jsp

Header.jsp just contains a titlebar .(I choose google logo for that). The code looks like

<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>

html:html

HEAD

TITLE</TITLE

</HEAD

body

img src="/strutsProject/images/mothers_day06.gif" border="0"

</body

</html:html

Create Footer.jsp

It will generally contain the copyrights info, footer links, etc(I choose another google logo) the code looks like

<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>

html:html

HEAD

TITLE</TITLE

</HEAD

BODY

img src="/strutsProject/images/persian_newyear06.gif"

</BODY

</html:html

Create body.jsp.

It is just a Place holder which we are going to replace with our jsps.

BODY

hello

</BODY

Create layout basicLayout.jsp

The layout defines the page with header as header.jsp , footer as footer.jsp etc

<%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %>

tiles:insert attribute="header"/>

br

tiles:insert attribute="body" />

br

tiles:insert attribute="footer"/>

Modifications to welcome.jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>

<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>

html:html

HEAD

<%@ page

language="java"

contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"

%>

METAhttp-equiv="Content-Type" content="text/html; charset=ISO-8859-1"

METAname="GENERATOR" content="IBM WebSphere Studio"

METAhttp-equiv="Content-Style-Type" content="text/css"

LINK href="../theme/Master.css" rel="stylesheet"

type="text/css"

TITLE</TITLE

</HEAD

BODY

html:form action="/welcome.do?dispatcher=helloUserMethod">

Welcome to my site.Please enter your name

html:text property="user" name="welcomeForm"</html:text

html:submit</html:submit

</html:form

</BODY

</html:html

1) here we are giving the dispatcher name as helloUserMethod so that if we submit the page it will go to helloUserMethod and from there it will forwarded to helloUSer.jsp.

Add hello.jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>

<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>

html:html

HEAD

<%@ page

language="java"

contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"

%>

METAhttp-equiv="Content-Type" content="text/html; charset=ISO-8859-1"

METAname="GENERATOR" content="IBM WebSphere Studio"

METAhttp-equiv="Content-Style-Type" content="text/css"

TITLE</TITLE

</HEAD

BODY

PHello bean:write property="user" name="welcomeForm"/> .Welcome to my site</P

</BODY

</html:html

1)here we are displaying the name of the user entered in previous page by using the form bean. This will help a lot if we have so many input fields on the screen.

2)formbean was declared in struts config in such a way that it will exist in request scope.

3)If we do not use form bean then we have to manually place the name in request before forwarding to app page and on the page we need to display the name from request object.

Change to index.jsp

<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>

jsp:forward page="/welcome.do?dispatcher=welcomeMethod" />

</html:html

1) The dispatcher name is welcomeMethod so the control goes to this method in action class

Action class and action form changes

Change welcomeAction

packagecom..strutsproject.actions;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

importorg.apache.struts.action.Action;

importorg.apache.struts.action.ActionError;

importorg.apache.struts.action.ActionErrors;

importorg.apache.struts.action.ActionForm;

importorg.apache.struts.action.ActionForward;

importorg.apache.struts.action.ActionMapping;

importorg.apache.struts.actions.DispatchAction;

importcom..strutsproject.forms.WelcomeForm;

/**

*@version1.0

*@author

*/

publicclassWelcomeActionextendsDispatchAction{

publicActionForwardwelcomeMethod(

ActionMappingmapping,

ActionFormform,

HttpServletRequestrequest,

HttpServletResponseresponse)

throwsException{

ActionErrorserrors=newActionErrors();

ActionForwardforward=newActionForward(); WelcomeFormwForm=(WelcomeForm)form;

forward=mapping.findForward("welcomeForward");

return(forward);

}

publicActionForwardhelloUserMethod(

ActionMappingmapping,

ActionFormform,

HttpServletRequestrequest,

HttpServletResponseresponse)

throwsException{

ActionErrorserrors=newActionErrors();

ActionForwardforward=newActionForward();

forward=mapping.findForward("helloUserForward");

return(forward);

}

}

Here we are extending DispatchAction instead of Action class. So that we can write our own methods (other than execute) and call appropriate method from jsp based on the action(button clicks).

WelcomeMethod is same as previous one

helloUserMethod is called when user click on submit button from welcome.jsp page and forwards it to helloUser.jsp

Create WelcomeForm.java

packagecom..strutsproject.forms;

importjavax.servlet.http.HttpServletRequest;

importorg.apache.struts.action.ActionErrors;

importorg.apache.struts.action.ActionForm;

importorg.apache.struts.action.ActionMapping;

/**

*FormbeanforaStrutsapplication.

*Usersmayaccess1fieldonthisform:

*<ul>

*<li>user-[yourcommenthere]

*</ul>

*@version1.0

*@author

*/

publicclassWelcomeFormextendsActionForm{

privateStringuser=null;

publicStringgetUser(){

returnuser;

}

publicvoidsetUser(Stringu){

this.user=u;

}

publicvoidreset(ActionMappingmapping,HttpServletRequest request){

user=null;

}

publicActionErrorsvalidate(

ActionMappingmapping,

HttpServletRequestrequest){

ActionErrorserrors=newActionErrors();

// Validate the fields in your form, adding

// adding each error to this.errors as found, e.g.

// if ((field == null) || (field.length() == 0)) {

// errors.add("field", new org.apache.struts.action.ActionError("error.field.required"));

// }

returnerrors;

}

}

In the validate method we can validate the name entered on the screen

We can return errors to same page by giving input=”definition name” in struts config

Create tile defintions file under WEB-INF.

This file contains tiles with tile associated with parameters and identified by a name which we can use in jsps or directly give them in struts config as action forwards instead of jsp urls.

The tiles definition looks like this( tiles-definitions.xml)

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE tiles-definitions PUBLIC

"-//Apache Software Foundation//DTD Tiles Configuration//EN"

"

tiles-definitions

definition name="basic.Def" path="/jsp/BasicLayout.jsp"

put name="header" value="/jsp/header.jsp"/>

put name="footer" value="/jsp/footer.jsp"/>

put name="body" value="/jsp/body.jsp"/>

</definition

definition name="welcome.user" extends="basic.Def"

put name="body" value="/jsp/welcome.jsp"/>

</definition

definition name="hello.user" extends="basic.Def"

put name="body" value="/jsp/hello.jsp"/>

</definition

</tiles-definitions

Basic.Def is basic tile definition which we can extend to other definitions and override the body.jsp or header.jsps. if we extend this definition the new definition also gets the same layout and offcourse we can add some more tiles like menu.jsp or change the body content to different jsp other than body.jsp

Welcome.user and hello.user are two examples of tiles definitions which are extending the basic.Def. welcome.user is definition for welcome.jsp and hello.user is definition for hellUser.jsp

Changes in struts-config.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"

"

struts-config

<!-- Form Beans -->

<form-beans>

<form-bean name="welcomeForm" type="com..strutsproject.forms.WelcomeForm">

</form-bean>

</form-beans>

<!-- Global Forwards -->

global-forwards

forward name="welcome" path="/welcome.do" />

</global-forwards

<!-- Action Mappings -->

action-mappings

action path="/welcome" type="com..strutsproject.actions.WelcomeAction" name="welcomeForm"scope="request" parameter="dispatcher"

forward name="welcomeForward" path="welcome.user"/>

forward name="helloUserForward" path="hello.user"/>

</action

action path="/base" type="com..strutsproject.actions.BaseAction"

</action

</action-mappings

<controller processorClass="org.apache.struts.tiles.TilesRequestProcessor" />

<!-- Message Resources -->

message-resources parameter="com..strutsproject.resources.ApplicationResources"/>

<plug-in className="org.apache.struts.tiles.TilesPlugin">

</plug-in>

</struts-config

1) The action /welcome now has two forwards declared and pointing to appropriate tiles

2) Declare the controller as tilesRequestProcessor

3) Insert the tiles plugin.

4) define the form bean and connect the form with action class

5) the parameter=”dispatcher” is used to dispatch request to different methods in action class based on the dispatcher value given on jsp.

Changes to web.xml

init-param

param-namedefinitions-config</param-name

param-value/WEB-INF/tiles-definitions.xml</param-value

</init-param

Define the parameter defintions-config ( we can even change the file name tiles-definitions.xml to another but that should be same as what we are giving here in web.xml)

Restart the server and run on the server

The out put looks like this