Let's start with an example of a permission interceptor to illustrate a custom interceptor, to access the method in action after logging in, and to prompt the user to log in without logging in
First set up a JSP that sets the login status login.jsp
<%request.getsession (). SetAttribute ("User", "dbq_00");%>
Create a JSP that exits the login state quit.jsp
<%request.getsession.removeattribute ("user");%>
Now to create action
Package com.day05;
public class Demo {
Private String message;
Public String GetMessage () {
return message;
}
public void Setmessage (String messsage) {
This.message = messsage;
}
Public String Addui () {
This.message = "Addui ()";
Return "Success";
}
Public String execute () {
This.message = "execute ()";
Return "Success";
}
}
Configure in action
<package name= "day05" namespace= "/day05" extends= "Struts-default" >
<action name= "demo_*" class= "Com.day05.demo" method= "{1}" >
<result name= "Success" >/show.jsp</result>
</action>
</package>
Access to access
Let's build interceptors to intercept browser access
Package com.day05;
Import Com.opensymphony.xwork2.ActionContext;
Import com.opensymphony.xwork2.ActionInvocation;
Import Com.opensymphony.xwork2.interceptor.Interceptor;
public class Demo1 implements interceptor{
@Override
public void Destroy () {
TODO auto-generated Method Stub
}
@Override
public void init () {
TODO auto-generated Method Stub
}
@Override
Public String Intercept (Actioninvocation arg0) throws Exception {
TODO auto-generated Method Stub
Object user = Actioncontext.getcontext (). GetSession (). Get ("user");
if (user!=null)//If the user is not NULL proof that the user is already logged in
{
return Arg0.invoke (); The return is the view in action success
}
Else
{
Actioncontext.getcontext (). Put ("message", "Sorry you haven't logged in");
return "message"; Jump to Message View
}
Then register the interceptor in struts
}
<interceptors>
<interceptor name= "Demo" class= "Com.day05.demo1" >
</interceptor>
</interceptors>
And then you can use it in action.
<interceptor-ref name= "Demo" ></interceptor-ref>
We are not logged in and will be prompted not to log in
You can access the action after you log in
However, the default interceptor that uses the interceptor struts directly in the action will not be executed, but we can use the interceptor stack.
<interceptors>
<interceptor name= "Demo" class= "Com.day05.demo1"/>
<!--Interceptor Stacks--
<interceptor-stack name= "Mystack" >
<interceptor-ref name= "Defaultstack"/> <!--struts Interceptor Stack--
<interceptor-ref name= "Demo"/> <!--custom Interceptors--
</interceptor-stack>
</interceptors>
<action name= "demo_*" class= "Com.day05.demo" method= "{1}" >
<interceptor-ref name= "Mystack"/> <!--using the interceptor stack directly in action--
<result name= "Success" >/show.jsp</result>
<result name= "Message" >/message.jsp</result>
</action>
Struts Custom Interceptors