Struts2 one class with 2 result bug? - java

i use struts 2 , definen 2 results for 1 class to output 2 pages code:
public String init() throws SystemException {
return "index";
}
public String emailVerify() throws SystemException {
return "emailVerify";
}
and on struts xml
<action name="RegisterAction_*" class="com.app.action.RegisterAction" method="{1}">
<result name="index">/WEB-INF/jsp/app/user_register.jsp</result>
<result name="emailVerify">/WEB-INF/jsp/app/user_email_verify.jsp</result>
</action>
init with result "success does work,but the emailVerify only work 1 time , if i reload the page it shows struts error, is this a bug?

fixed, this mvc has a Interceptor blocks non-init request

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!

Passing a key value in query string from one page to another in a project using Struts 2

I am trying to pass a key value in query string from one page to another in a project using the Struts 2 framework.
URL Mapping:
<struts>
<package name="default" namespace="/" extends="struts-default">
<!-- Line -->
<action name="line" class="com.example.a.b.action.LineAction">
<result name="success">/line.jsp</result>
</action>
</package>
</struts>
URL For HTML Anchor Link:
http://localhost/line?key=value
When it goes to LineAction I want to get the query string key value part but could find anything online for it.
If I understand you correctly. In your action class create Getters and Setters for key. You will get a value in your action class.
May be You try this way..
try{
URL url = new URL("http://www.google.com?gender=male&name=jagga");
System.out.println(url.getQuery());
}catch(MalformedURLException e)
{
e.printStackTrace();
}
You build your URL of that Action
You can get parameters from the action context like
Map<String, Object> parameters = ActionContext.getContext().getParameters();
But a better way is to implement ParameterAware
private Map<String, String[]> parameters;
public void setParameters(Map<String, String[]> parameters){
this.parameters = parameters;
}

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>

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