san544 san544 - 6 months ago 16
Java Question

Struts action class properties are getting null after using myinterceptors

I'm new to Struts framework. So seeking some online tutorials and tried to develop a very basic application. Before using interceptors am able to access username and password values in action class but after involving interceptors am getting username and password as null in action class execute method. How can i get the values of username and password inside action class?

login.jsp

<s:form action="login.action">
<s:actionerror cssStyle="color:red"/>
<s:textfield name="username" label="Username"/>
<s:password name="password" label="Password"/>
<s:submit value="Go"/>
</s:form>


Interceptor class

public class MyInterceptors extends AbstractInterceptor {

/**
*
*/
private static final long serialVersionUID = 1L;

public String intercept(ActionInvocation invocation)throws Exception{

/* let us do some pre-processing */
String output = "Pre-Processing";
System.out.println(output);

/* let us call action or next interceptor */
String result = invocation.invoke();

/* let us do some post-processing */
output = "Post-Processing";
System.out.println(output);

return result;
}
}


Action class

public class LoginAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
private String username;
private String password;

public String execute() {

System.out.println("Action Result.."+getUsername());

return "success";
}
//getters and setters
}


struts.xml

.....
<interceptors>
<interceptor name="myinterceptor"
class="com.techm.interceptors.MyInterceptors" />
</interceptors>

<action name="login" class="com.techm.actions.LoginAction">

<interceptor-ref name="myinterceptor"></interceptor-ref>
<result name="success">Success.jsp</result>
<result name="error">Login.jsp</result>
</action>
.....


Result on execution in console is :

Pre-Processing
Action Result..null
Post-Processing

Answer

In the action config you have overridden the interceptors configuration. Struts by default is configured to use a default stack of interceptors even if you don't use any interceptors in the action config. By overriding interceptors you made a mistake. You should add a defaultStack in your specific action config.

<action name="login" class="com.techm.actions.LoginAction">
    <interceptor-ref name="myinterceptor">
    <interceptor-ref name="defaultStack"/>            
    <result name="success">Success.jsp</result>
    <result name="error">Login.jsp</result>        
</action> 
Comments