This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Struts and the fly likes Struts2 newB: some simple questions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Frameworks » Struts
Bookmark "Struts2 newB: some simple questions" Watch "Struts2 newB: some simple questions" New topic
Author

Struts2 newB: some simple questions

Matt Cooke
Greenhorn

Joined: Jun 16, 2006
Posts: 10
Trying to get my head around struts 2 and am hoping that someone may be able to help me and answer a few basic questions for me. Apologies for the "basicness" of these questions.

The scenario is that I have two pages A and B. I select/enter some values on page A and press a button which takes me to B. When I am finished on page B I will be pressing a button which will take me back to page A. My question is:-

What method do I use to maintain the values in the form fields that I entered on page A before going to page B ie. I want them to be present when I revisit page A.

I have a number of buttons on page A. Dependant on which button is pressed, I want a different action to be invoked. How do I do that?

Thanks in advance for any help.
suresh sai
Ranch Hand

Joined: Jul 16, 2007
Posts: 62
First of all,I will tell about your second question that is based on different buttons different actions to be performed.This can be achieved by following some steps, as described below.

1) Donot use execute method in your action class.

2)Instead of that execute method,you need to use your own methods for each button respectively .Give your method name as exactly same name as your button name. This is very important.But signature of your own method is same as execute method.

3)And your action class needs to extend DispatchAction not Action.

4)For each button give a property name which you likes ,generally people gives it as "method". If you have given otherthan method,then you need to provide setters and getters for your property in your bean class.

5)Give the same property name (or "method") for all of your buttons.

6)In sturts-config file you need to mention the attribute parameter of <action> element as "method" or the name you have given.

Thats it you have to do.This process of creating your action class is known as DiapathcAction class.

Iam giving abstract code for the steps above.

1) Iam eliminating execute method.

2)public ActionForward addition(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
{



}

public ActionForward subtraction(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
{



}


3)public class MyAction extends DispatchAction
{

}

4)<html:submit property="method" value="addition" />
5)<html:submit property="method" value="subtraction" />

6)<action parameter="method" />

I have given abstractly,remaining procedure is same as other struts application.
For your first question,you can get by one of the following.

1)By changing your scope to session.
2)By saving your properties in session and then retriveing by session.getAttribute("someThing"); and write these value to fields by using <bean:write>.
Matt Cooke
Greenhorn

Joined: Jun 16, 2006
Posts: 10
Thanks Chinna,

I will study your reply and try out your solutions. Will probably have some more questions.

Thanks again,

Matt
Matt Cooke
Greenhorn

Joined: Jun 16, 2006
Posts: 10
I am trying to find the DispatchAction entry in the Struts 2 API but can't find it. Does it exist in that library?

Thanks.
Merrill Higginson
Ranch Hand

Joined: Feb 15, 2005
Posts: 4864
Matt,

It looks like chinna has steered you in the wrong direction. The method he describes will work fine with a Struts 1 application, but it will not work with Struts 2.

For Struts 2, you have the ability to specify a separate action for each submit button. Here's an example:
config file

dispatch.jsp

Dispatch Action


Merrill
Consultant, Sima Solutions
Merrill Higginson
Ranch Hand

Joined: Feb 15, 2005
Posts: 4864
Regarding your question about how to retain values: Just make sure that any Action classes that you're using have a property for the field you wish to preserve. As long as there is an input control on every page for that property, the value will get passed along from page to page. If you don't want to display the property on a particular page, but still want it to get passed forward, use the <s:hidden> tag to create a hidden input field.
Matt Cooke
Greenhorn

Joined: Jun 16, 2006
Posts: 10
Merrill,

Your fanstastic, thanks very much. Just what I wanted.

Matt
Matt Cooke
Greenhorn

Joined: Jun 16, 2006
Posts: 10
-----Just make sure that any Action classes that you're using have a property for the field you wish to preserve. As long as there is an input control on every page for that property, the value will get passed along from page to page.----

I would be grateful if you could give me an example of this as I am having a bit of trouble with this still.

Many thanks.
Matt Cooke
Greenhorn

Joined: Jun 16, 2006
Posts: 10
I've managed to pass the values through on the URL when I redirect dependant on the button pressed (action xml below). However, I don't like it. There must be a better way of doing it ie. not on the URL?


<action name="Dispatch_*" class="net.uaps.regression.Dispatch" method="{1}">
<!-- <result name="configure" type="redirect-action">RegressionConfigure?BaselineDb=${getBaselineDb()}&ProjectDb=${getProjectDb()}&CompareTables=${getCompareTables()}</result> -->
<result name="configure" type="redirect-action">RegressionConfigure?BaselineDb=${getBaselineDb()}</result>

<!-- <result name="configure" type="redirect-action">RegressionConfigure</result> -->
<result name="submit" type="redirect-action">Submit</result>
<result name="cancel" type="redirect-action">Cancel</result>
</action>

Any help would be gratefully accepted.
Merrill Higginson
Ranch Hand

Joined: Feb 15, 2005
Posts: 4864
Matt,

The problem here is that you're using type="redirect-action". When you redirect, all the data that is stored in the request is lost, making it so that you can only pass data through the HTTPSession or by doing as you're doing and passing parameters in the URL. Is it really important to your application that a redirect is done? If not, I'd say just remove the type="redirect-action" and the data will get passed without putting it in the URL.
Matt Cooke
Greenhorn

Joined: Jun 16, 2006
Posts: 10
Merrill, thanks once again for more of your help.

If I take off the redirect it doesn't result in the correct action being called. Therefore I must have something not quite right. I hope that you can be of more assistance as I am determined not to be beaten by this!!


The way I envisage this to work is

On pressing the Configure button on the Regression.jsp page, it calls the Dispatch_* action which sends it off to Dispatch.java. This returns "configure" to the action which should then call the "result" of that action ie. telling the process to next call the RegressionConfigure action. This is where I must have it wrong as it is not calling that action.

The resulting URL from pressing the configure button is http://axuapdev01:8080/uapstools2/uaps/Dispatch_configure.action

I would be grateful again, for any help that you or anyone can be in helping me to solve this "should be" simple thing.

Many thanks in advance.


Struts.xml -----------------------------------------------

<?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>
<constant name="struts.enable.DynamicMethodInvocation" value="true" />
<constant name="struts.devMode" value="true" />

<package name="uaps" namespace="/uaps" extends="struts-default">

<!-- Add actions here -->

<action name="HelloWorld" class="net.uaps.Struts2HelloWorld">
<result>/pages/HelloWorld.jsp</result>
</action>

<action name="Regression" class="net.uaps.regression.Regression">
<result>/pages/regression/Regression.jsp</result>
</action>

<action name="Dispatch_*" class="net.uaps.regression.Dispatch" method="{1}">
<result name="configure">RegressionConfigure</result>
<result name="submit">Submit</result>
<result name="cancel">Cancel</result>
</action>

<action name="RegressionConfigure" class="net.uaps.regression.RegressionConfigure">
<result>/pages/regression/RegressionConfigure.jsp</result>
</action>

<action name="Submit" class="net.uaps.Struts2HelloWorld">
<result>/pages/HelloWorld.jsp</result>
</action>

<action name="Cancel" class="net.uaps.Struts2HelloWorld">
<result>/pages/HelloWorld.jsp</result>
</action>


</package>

<!-- Add packages here -->

</struts>

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

Regression.jsp -------------------------------------------


<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Regression Testing</title>
</head>
<body bgcolor="#C0C0C0">
<br>
<h2>Regression Testing v7</h2>

<s:form action="Dispatch_configure" tooltipConfig="%{'jsTooltipEnabled':'true'}" method="post">

<s:select
tooltip="Select the schema for the baseline"
label="Baseline Schema"
list="getSchemas()"
name="BaselineDb"
emptyOption="false"
headerKey="None"
headerValue="None"/>

<s:select
tooltip="Select the schema for the project"
label="Project Schema"
list="getSchemas()"
name="ProjectDb"
emptyOption="false"
headerKey="None"
headerValue="None"/>

<s:textarea
label="Compare Tables"
name="CompareTables"
cols="50" rows="20"
tooltip="(Cut and paste the list of tables with differences into this text box) eg:-
annnuity
contracted_benefit
contact
..."
value="%{getInputTables()}"/>

<s roperty value="getButton()" />


<s:submit action="Dispatch_configure" value="Configure"/>
<s:submit action="Dispatch_submit" value="Submit"/>
<s:submit action="Dispatch_cancel" value="Cancel"/>


</s:form>
</body>
</html>

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

package net.uaps.regression;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;
import java.util.Date;
import java.util.*;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.*;
import java.math.*;

import net.uaps.database.*;

public class Regression extends ActionSupport
{
static Connection con = null;

HashMap<String, String> optionListMap = new HashMap<String, String>();
HashMap<String, String> schemaListMap = new HashMap<String, String>();
String output;
String input;

public String execute() throws Exception
{
setSchemas();

input = ServletActionContext.getRequest().getParameter("config_submit_button");

return SUCCESS;

}//end execute

public void setSchemas() throws Exception
{
Connection con = DbConnection.getOracleJDBCConnection();
// Create a statement
Statement stmt = con.createStatement();
String query = "select * from database_schemas";
ResultSet rset = stmt.executeQuery(query);

// Dump the result
while (rset.next())
{
schemaListMap.put(rset.getString(1), rset.getString(2));
}
}


public HashMap getSchemas()
{
return schemaListMap;
}

public String getSchemas2()
{
return output;
}

//public HashMap getSchemas()
public String getButton()
{
//return schemaListMap;
return input;
}

}

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


Dispatch.java --------------------------------------------

package net.uaps.regression;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.*;
import java.util.*;

public class Dispatch extends ActionSupport
{

String projectDb;
String baselineDb;
String compareTables;

//Method called when the Configure button pressed.
public String configure() throws Exception
{
System.out.println("In configure");
setBaselineDb(ServletActionContext.getRequest().getParameter("BaselineDb"));
setProjectDb(ServletActionContext.getRequest().getParameter("ProjectDb"));
setCompareTables(ServletActionContext.getRequest().getParameter("CompareTables"));
return "configure";
}

//Method called when the Submit button pressed.
public String submit() throws Exception
{
System.out.println("In submit");
return "submit";
}

//Method called when the Cancel button pressed.
public String cancel() throws Exception
{
System.out.println("In cancel");
return "cancel";
}

public void setBaselineDb(String baselineDb)
{
this.baselineDb = baselineDb;
}

public void setProjectDb(String projectDb)
{
this.projectDb = projectDb;
}

public void setCompareTables(String compareTables)
{
this.compareTables = compareTables;
}

public String getBaselineDb()
{
return this.baselineDb;
}

public String getProjectDb()
{
return this.projectDb;
}

public String getCompareTables()
{
return this.compareTables;
}
}

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

RegressionConfigure.jsp ----------------------------------

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Regression Testing Configuration</title>
</head>
<body bgcolor="#C0C0C0">
<br>
<h2>Regression Testing Configuration</h2>

<s:form action="Regression" tooltipConfig="%{'jsTooltipEnabled':'true'}" method="post">

<s roperty value="getBaselineDb()" />
<s roperty value="getInputTables()" />
<!--
<s:label key="{getInputTables()}" />
<s:label key="{getBaselineDb()}" />
-->
<s:submit name="config_submit_button" value="Submit" />
<s:submit value="%{'Cancel'}" />

</s:form>

</body>
</html>


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

RegressionConfigure.java ---------------------------------

package net.uaps.regression;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;
import java.util.Date;
import java.util.*;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.*;
import java.math.*;

import net.uaps.database.*;

public class RegressionConfigure extends ActionSupport
{
static Connection con = null;

HashMap<String, String> schemaListMap = new HashMap<String, String>();
String baselineDb;
String projectDb;
String inputTables;

public String execute() throws Exception
{

baselineDb = ServletActionContext.getRequest().getParameter("BaselineDb");
projectDb = ServletActionContext.getRequest().getParameter("ProjectDb");
inputTables = ServletActionContext.getRequest().getParameter("CompareTables");

//System.out.print("MATT inputTables = " + inputTables);

//getConfigurationDetails();

//ServletActionContext.setResponse().getParameter("configure_button");

return SUCCESS;

}//end execute

public void getConfigurationDetails() throws Exception
{
//Read the REGRESSION_TEST_RULES table from the baseline database and display its contents
//in a datagrid for editing.

Connection con = DbConnection.getOracleJDBCConnection();
// Create a statement
Statement stmt = con.createStatement();
String query = "select * from database_schemas";
ResultSet rset = stmt.executeQuery(query);

// Dump the result
while (rset.next())
{
schemaListMap.put(rset.getString(1), rset.getString(2));
}
}

//public HashMap getSchemas()
public String getBaselineDb()
{
//return schemaListMap;
return baselineDb;
}

//public HashMap getSchemas()
public String getProjectDb()
{
//return schemaListMap;
return projectDb;
}

//public HashMap getSchemas()
public String getInputTables()
{
//return schemaListMap;
return inputTables;
}

}


----------------------------------------------------------
Merrill Higginson
Ranch Hand

Joined: Feb 15, 2005
Posts: 4864
Just Change

to

There's no need to go through an intermediate action. Just go directly to the action you want.
Matt Cooke
Greenhorn

Joined: Jun 16, 2006
Posts: 10
Merrill,

Thanks once again. Why didn't I think of that!!

Matt
 
 
subject: Struts2 newB: some simple questions
 
Similar Threads
display data on first jsp on start of application
How to get values of first page in second page
Add new text field on each press of a button and retrieve values
Help on jvascript and validation
Servlets