How to get form data after action chaining in last action - java

Here i am chaining action then want to get data on last preview action
My First action call first.jsp. I Enter some value here I want to get that value on next Action call
<action name="first">
<result name="success">/first.jsp</result>
</action>
<action name="second" class="com.ved.action.FirstAction">
<result name="success">/second.jsp</result>
</action>
<action name="preview" class="com.ved.action.SecondAction">
<result name="success">/preview.jsp</result>
</action>
I want to display first.jsp data on preview.jsp
first.jsp
<s:form action="second">
<s:textfield name="username" label="UserName"/>
<s:submit name="next" value="Next"/>
</s:form>
second.jsp
<s:form action="preview">
<s:textfield name="address"/>
<s:submit name="priview" value="priview"/>
preview.jsp
<s:property value="username"/>
<s:property value="address"/>
i want display both page data on preview
my Action is as
public class FirstAction extends ActionSupport{
private String firstname;
public String execute() throws Exception {
return SUCCESS;
}
//setter getter for firstname
}
public class SecondAction extends ActionSupport{
private String address;
public String execute() throws Exception {
return SUCCESS;
}
//setter getter for address
}

HTTP is stateless.
Solution:
1) You have to use session to persist the data.
2) During transition from first to second, the data should be in second.jsp. Use html hidden element to store the data of first.jsp. So, you have to restore the data in request scope.

Related

struts2 form submit not hitting method

I have a .jsp form like so
<s:form action="AuditLogReport">Source IP<br>
<input type="text" class="auditLogSearch" name="sourceIp" value="All">
<input type="submit" value="Submit"/>
</s:form>
And my struts.xml is defined
<action name="AuditLogReport"
class="com.mycom.selfservice.actions.AuditLogAction" method="auditLogReport">
<result name="success">jsp/AuditLog.jsp</result>
<result name="error">jsp/Error.jsp</result>
</action>
Here is my class definition
public class AuditLogAction extends ActionSupport implements Action,ServletRequestAware {
And in my AuditLogAction class there is a method
public String auditLogReport() {
System.out.println("Im in auditLogReport...");
but when I click the button, auditLogReport method does not get hit. What I see in the browser url is http://localhost:7001/BPSelfServicePortal/AuditLogReport.action
It is appending .action which I think is why it doesn't find the method. So I tried putting
<constant name="struts.action.extension" value=""/>
in the struts.xml. That prevented the .action from being appended but the button still didn't work. Plus it caused the .css and images from being found. I have a link that uses the default execute() method and that works ok.
If I simply remove the .action in the url and hit enter, it hits the method but then none of the values in the form get passed.
Suggestions?
The problem turned out to be a Date parameter. Apparently struts2 doesn't like them.
public Date getFromDate() {
return fromDate;
}
public void setFromDate(Date fromDate) {
this.fromDate = fromDate;
}
Changed it to
public String getFromDate() {
return fromDate;
}
public void setFromDate(String fromDate) {
this.fromDate = fromDate;
}
And then it worked!

Checking a session value in Struts 2 web application [duplicate]

This question already has answers here:
Is there a way to redirect to another Action class without using on struts.xml
(2 answers)
Closed 6 years ago.
I am creating a web application using Struts 2. I have a login page in it. As the user click the login button after entering the username and password, the credentials are checked and if the credentials are found correct, then a session is created and its attributes are set and control is redirected to WELCOME JSP.
Now before the welcome.jsp is opened, I want to check, if the session attributes are set. How to do it in Struts 2?
Can anyone clear me the concept of interceptors. I read that we create interceptors to perform any function before or after an action is called. Can I create an interceptor that checks if the session is set, every time before WELCOME JSP is called.
you can use <s:if> tag to test presence of your attribute in Session.I am assuming that you are setting value in your action class and here is how you can do that in jsp page
<s:if test="%{#session.logged_in ==true}">
I am assuming that here i am setting a flag indicating if user is logged in or not on similar way you can test as per your requirements
For Interceptors, They are set of utility classes being provided by Struts2 out of the box to make your life easy.Interceptors are just java classes with certain functionality which is being provide by the framework, some of them are
fileUpload
i18n
params
token etc
These Interceptors are called based on the interceptor stack being configured in your application and they will be called at 2 places
when you send request to your action
when request processing done and view rendered.
in first case they will be called before your action execute or custom method defined by you is called, Interceptors are responsible to provide required data to your action class, some of the work done by interceptors before your action called are
File uploading
Handling i18n
Passing form values to respected fields in your action class
validation of your data
there are certain set of interceptors being provided by struts2 , you can have look at struts-defaultxml.
You can create any number of interceptors and configure them to be executed as per your requirements,a ll you need to extends AbstractInterceptor an provide your custom logic inside intercept(ActionInvocation invocation) method
I suggest you to follow below mentioned links to get more overview
building-your-own-interceptor
Struts2 Interceptors
writing-interceptors
#rickgaurav for your 1st question. make a login action like this
<action name="login_action" class="loginAction class">
<result name="success" type="chain">welcomeAction</result>
<result name="input">/index.jsp</result>
<result name="error">/index.jsp</result>
</action>
wher index.jsp is your login page
and in login interceptor first make a session map in which your session attribute will be store
Map<String, Object> sessionAttributes = invocation
.getInvocationContext().getSession();
after that check using this condition
if (sessionAttributes == null
|| sessionAttributes.get("userName") == null
|| sessionAttributes.get("userName").equals("")) {
return "login";
}else{
if (!((String) sessionAttributes.get("userName")).equals(null)){
return invocation.invoke();
}else{
return "login";
}
for your 2nd question assume you are calling a welcomeAction to go to the welcome.jsp page
so you can add action like this
<action name="welcomeAction" class="class">
<interceptor-ref name="logininterceptor"></interceptor-ref>
<result name="login" type="chain">loginaction</result>
<result name="success" >/welcome.jsp</result>
</action>
hope so this will work for you
In Struts.xml write this:
<interceptors>
<interceptor name="loginInterceptor"
class="com.mtdc.interceptor.LoginInterceptor"></interceptor>
<interceptor-stack name="loginStack">
<interceptor-ref name="loginInterceptor"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
2.Now After aAction which you want to check session put this: <interceptor-ref name="loginStack"></interceptor-ref>
3.Our LoginACtion in struts.xml: `
<action name="login_action" class="com.action.LoginAction">
<result name="success">/welcome.jsp</result>
<result name="input">/login.jsp</result>
<result name="error">/login.jsp</result>
</action>
`
4.Now define LOgin interceptor for that make com,interceptor.LoginInterceptor :
`
public String intercept(ActionInvocation invocation) throws Exception {
Map<String, Object> sessionAttributes = invocation
.getInvocationContext().getSession();
if (sessionAttributes == null
|| sessionAttributes.get("userName") == null
|| sessionAttributes.get("userName").equals("")) {
return "login";
} else {
if (!((String) sessionAttributes.get("userName")).equals(null)
|| !((String) sessionAttributes.get("userName")).equals("")) {
return invocation.invoke();
} else {
return "login";
}
}
}
`
[5]. Now make Login Action class where you assign session:
`
public String execute() {
String result = LOGIN;
UserLogin userlogin;
try {
userlogin = userlogindao.authenticateUser(signin_username, signin_password);
if (userlogin != null && userlogin.getUsername() != null) {
session.put("userID", userlogin.getUserId());
session.put("userName", userlogin.getUsername());
result = SUCCESS;
} else {
result = LOGIN;
}
} catch (Exception e) {
result = LOGIN;
e.printStackTrace();
}
return result;
}
`
[6]. Now final step on your login page on click call action LoginAction.
Yes you can use interceptor.
Make a Action class Which will store UserId / Username of user (after user is authenticated) in session like this.
session.put("userID", userlogin.getUserId());
after that make a Interceptor class which impl. interceptor
public class LoginInterceptor implements **Interceptor** {
public String intercept(ActionInvocation invocation) throws Exception {
get the session attribute using
sessionAttributes.get("userId");
and check it is not null if it is null then return login to forward user to the login page
or else return invocation.invoke(); to continue the action.
and in struts.xml file configure interceptor inside package
<interceptors>
<interceptor name="loginInterceptor" class=".....LoginInterceptor"></interceptor>
<interceptor-stack name="loginStack">
<interceptor-ref name="loginInterceptor"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
and for action you can write
<action name="anything" class="anyclass" method="default">
<interceptor-ref name="loginStack"></interceptor-ref>
<result name="login">/index.jsp</result>
<result name="success" type="redirect">success.jsp</result>
</action>

The form does not submit the selected value of the <s:select>

I have the following dropdown list which correctly shows the options but when I select an item and submit the form it runs into the following error :
'select', field 'list', name 'name': The requested list key 'listnames' could not be
resolved as a collection/array/map/enumeration/iterator type. Example: people or
people.{name} - [unknown location]
My JSP form
<s:form method="POST" action="addNames">
<s:select name="name"
label="Names"
list="listnames"
/>
</s:form>
My Action
#Action
public class Myaction implements ModelDriven{
private MyClass myclass = new MyClass();
private List listnames = new ArrayList();
#Override
public MyClass getModel() {
return this.myclass;
}
public List getListnames() {
return listnames;
}
public void setListnames(List listnames) {
this.listnames = listnames;
}
public MyClass getMyClass() {
return myclass;
}
public void setMyClass(MyClass myclass) {
this.myClass = myclass;
}
}
My Class
public class MyClass {
private String name;
..... getter and setters go here ....
}
struts
<package name="MyUsers" extends="default" namespace="/MyUsers">
<action name="*" method="{1}" class="com.myproject.controller.Myaction">
<result name="uAdd" type="tiles" >uAdd</result>
<result name="uView" type="tiles" >uView</result>
</action>
</package>
STEP 1 :make sure that getter and setter for listnames are done properly
STEP 2 :make sure that you have done the declaration and initialization for listnames List properly
UPDATE 2
Sample Example
struts.xml
<action name="getText" class="commonpackage.ReportsCommonClass" method="getText">
<result name="success">index.jsp</result>
</action>
<action name="myaction" class="commonpackage.ReportsCommonClass" method="myaction">
<result name="success">index2.jsp</result>
</action>
index.jsp
<s:form id="conform" action="myaction" method="post">
<label>NAME</label>
<s:select id="name1" name="name1" list="mylist" headerKey="0" headerValue="--SELECT--"/>
<s:submit value="Click" />
</s:form>
In commonpackage.ReportsCommonClass class
ArrayList mylist=new ArrayList();
public ArrayList getMylist() {
return mylist;
}
public void setMylist(ArrayList mylist) {
this.mylist = mylist;
}
public String getText()
{
mylist.add("NAME 1");
mylist.add("NAME 2");
mylist.add("NAME 3");
mylist.add("NAME 4");
mylist.add("NAME 5");
return SUCCESS;
}
String name1;
public String getName1() {
return name1;
}
public void setName1(String name1) {
this.name1 = name1;
}
public String myaction()
{
System.out.println("NAMEEEEEEEEEEEEEEEEEEEEE:"+name1);
return SUCCESS;
}
change your select tag like this
<s:form method="POST" action="addNames">
<s:select name="myclass.name"
label="Names"
list="listnames"
/>
</s:form>
Edit:
Problem:
I guess you are hitting jsp directly hence there is no any action execution. If there is no any action execution then there is no any list in request.
Solution.
Hit URL in way that action class get executed and list should initialize or populated before rendering the jsp or view.
Create a method like populateView in action class and execute this method rather than directly execution JSP.
Hope you understand what I want to say.
Provide getter setter for name in your action class.
As your select tag name is name <s:select name="name"> when you submit your form it will search for the property name in your action class.
This may be the problem in your case

Result is null with JSON and Struts2

I have created a simple form in Extjs4.1.
I am sending the request to Struts2 framework, and using the Strtus2JSON plugin, i have to recieve the response. But unfortunately, the response is null.
Action class
public String execute()throws Exception{
Employee emp = new Employee();
emp.setAddress(getAddress());
emp.setDepartment(getDepartment());
emp.setName(getName());
emp.setSalary(getSalary());
AddEmployeeService empService = new AddEmployeeService();
boolean flag = empService.addEmployee(emp);
resultJSONobj = new JSONObject();
if(flag == true)
resultJSONobj.put("success","Inserted Successfully");
else
resultJSONobj.put("failure","An error occured");
System.out.println(resultJSONobj);
return SUCCESS;
}
struts.xml
<struts>
<package name="default" extends="struts-default, json-default">
<action name="AddEmp" class = "actions.AddEmpAction">
<result name = "success" type="json">
<param name ="root">resultJSONobj</param>
</result>
</action>
</package>
</struts>
Can anybody tell why iam getting the response as null ?
Do you have a Getter for resultJSONobj like this?:
public JSONObject getResultJSONobj(){
return this.resultJSONobj;
}
Add a namespace to your package, like this:
<package name="default" namespace="/" extends="struts-default, json-default">
And see if something has changed...
EDIT
As described in the guide,
'transient' fields are not serialized
fields without getter method are not serialized
Try like this:
Use a Map instead of your JSONObject. Not every class is accepted, and I'm not sure your JSONObject is serializable (do you implement serializable? do you declare a serialVersionUID? etc)
private Map resultJSONobj = new HashMap(); //instantiated at class level
// accessors
public Map getResultJSONobj() {
return resultJSONobj;
}
public void setResultJSONobj(Map resultJSONobj) {
this.resultJSONobj = resultJSONobj;
}
//...
public String execute()throws Exception{
Employee emp = new Employee();
emp.setAddress(getAddress());
emp.setDepartment(getDepartment());
emp.setName(getName());
emp.setSalary(getSalary());
AddEmployeeService empService = new AddEmployeeService();
boolean flag = empService.addEmployee(emp);
if(flag == true)
resultJSONobj.put("success","Inserted Successfully");
else
resultJSONobj.put("failure","An error occured");
System.out.println(resultJSONobj);
return SUCCESS;
}
And change struts config like this:
<struts>
<package name="default" extends="struts-default, json-default">
<action name="AddEmp" class = "actions.AddEmpAction">
<result name="success" type="json" />
</action>
</package>
</struts>
Success is not necessary, but leave it for a clearer code, you can always remove it later.
Now, you should see this as result (if you doesn't have any other getter):
{
"resultJSONobj": {
"success":"Inserted Successfully"
}
}
or
{
"resultJSONobj": {
"failure":"An error occured"
}
}
in your configuration file struts.xml, please use
<param name="includeProperties">resultJSONobj.*</param>
Instead of
<param name="includeProperties">resultJSONobj</param>
I was facing the same issue before in my project, after I made the above change it works.
There are few things missing in your struts.xml file. After result is success, where are you going?
Create json object instance outside your execute method and inside action class.
Struts2JSON plugin serializes all action variables inside an action class. It might be that since you have only declared JSONobject in action class and actually creating it inside execute, JSON might be getting it {}.
Put
private JSONObject resultJSONobj = new JSONObject();
inside action class and outside execute and see, it might work.
For more information you can go here
http://struts.apache.org/2.2.3/docs/json-plugin.html

Struts ignoring validate method

<form-bean name="RegisterForm" type="com.mysite.form.RegisterForm" />
<action path="/register" type="com.mysite.action.RegisterAction" name="RegisterForm" input="/register.jsp" validate="true">
<forward name="success" path="/welcome.jsp" />
<forward name="failure" path="/register.jsp" />
</action>
RegisterForm
public class RegisterForm extends ActionForm{
private String name;
/**
Constructor
Set+Get
**/
public ActionErrors validate(ActionMapping mapping, ServletRequest request) {
ActionErrors errorList = new ActionErrors();
System.out.println("VALIDATING");
return errorList;
}
}
This is all i have. For some reason it seems that the control flow jumps directly to the ActionForm's execute method because I can't even see the VALIDATING message in the console. Is there something I'm missing? Thanks!
You need to use the other overloaded validate() method that takes HttpServletRequest

Categories