一个action类,必须在action包,
第一步:
1.1、建类,UserAction(必须建在action包下),
1.2、要给这个类加上一个注解,否则会报错。(@ParentPackage,value 是第3步的 name),
1.3、在浏览器中访问test.action,根据temp 方法的返回值确定跳转的指定的页面。 代码如下:
package com.shadow.action;
@ParentPackage(value="shadow")
public class UserAction {
@Action(value="testl",results={
@Result(name="success",location="/WEB-INF/html/user.html"),
@Result(name="fail",location="/WEB-INF/html/login.html"),
},
interceptorRefs={@InterceptorRef("customValidata")}
)
public String test() {
//拦截器如果返回的是一个fail 则不会进入此方法。
System.out.println("useraction");
//当拦截器返回的值没有了意义由现在的方法的返回值来控制展示页面
return "success";
}
}
第二步:
2.1、建一个拦截器包,(interceptors)
2.2、建一个自定义拦截器的类。(CustomValidataInterceptor)
package com.shadow.action.interceptor;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class CustomValidataInterceptor extends AbstractInterceptor {
private static final long serialVersionUID = 1L;
public String intercept(ActionInvocation invocation) throws Exception {
ActionContext actionContext = ActionContext.getContext();
//从session 取值 actionContext.getSession();
//假设一个用户
String user = "user";
if(user == "" && user == null){//如果不是null
return "fail";//已经登录了-----------------> 返回 一个 fail 到 UserAction
}else{
invocation.invoke();// 没有登录 ------------------> 跳过此方法 返回的值便没有了意义
}
return "fail";
}
}
第三步:
struts2的资源文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<constant name="struts.devMode" value="false" />
<!--允许方法可以被动态调用 -->
<constant name="struts.enable.DynamicMethodInvocation" value="true" />
<package namespace="/" name="shadow" extends="struts-default"><!-- name 是第一步的value -->
<interceptors>
<interceptor name="customValidata"
class="com.zhuyue.action.interceptor.CustomValidataInterceptor">
</interceptor>
</interceptors>
</package>
</struts>
struts获取session与获取req/resp
ActionContext actionContext = ActionContext.getContext();
actionContext.getSession();
HttpServletRequest request = ServletActionContext.getRequest();