原文来自搬砖工,如需转载请注明出处
博主SSH框架专栏请戳这里http://blog.csdn.net/column/details/14227.html
之前学习了Struts2入门和简单的使用,这篇文章学习一下Struts2中重要的部分Action。鉴于内容比较多,就分为上下两部分学习。
一、Action的定义
在struts2中,控制器由两部分组成,配置在web.xml中的控制器和处理业务逻辑的action。action是struts2中重要的组件,绝大部分业务逻辑都在其中实现。那么该如何在struts2中定义一个action?
1.一个简单的类
package com.study.action;
public class LoginAction {
public String execute() throws Exception{
}
}
如上,如果是定义的一个简单的类(未继承或实现任何东西),那么就必须实现execute方法,而且得抛出异常。那么struts2就会执行execute里面的逻辑。格式如:
public String execute() throws Exception{}
2.实现action接口
package com.study.action;
import com.opensymphony.xwork2.Action;
public class LoginAction implements Action{
public String execute() throws Exception{
}
}
如上,实现Action接口。在这里要覆盖execute方法。
3.继承ActionSupport
package com.study.action;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport{
public String execute() throws Exception{
}
}
二、Action如何访问Servlet API
struts2中没有与任何的Servlet API耦合,这样可以不依赖web容器对action进行测试。但是对于web应用来说,访问Servlet API是不可或缺的需求。那么,在Struts2中如何访问Servlet API呢?struts2给出了如下方法:
1.ActionContext
一个操作session的示例
ActionContext ac = ActionContext.getContext();
Map session = ac.getSession();
session.put("", "");
对于ActionContext类,它提供了如下方法来访问Servlet API
1)Object get(Object obj) 它相当于是HttpServletRequest中的getAttribute方法
2)Map getApplication() Map中保存的是ActionContext作用域中的对象
3)static ActionContext getContext() 是获得一个ActionContext 的实例
4)Map getParameters() 相当于HttpServletRequest的getParameterMap方法
4)Map getSession() Map中保存的是session作用域中的对象
2.实现接口
实现ServletResponseAware和ServletRequestAware接口示例
package com.study.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
public class LoginAction implements ServletResponseAware,ServletRequestAware{
HttpServletRequest request;
HttpServletResponse response;
public String execute() throws Exception{
HttpSession session = request.getSession();
return null;
}
public void setServletRequest(HttpServletRequest arg0) {
this.request = arg0;
}
public void setServletResponse(HttpServletResponse arg0) {
this.response = arg0;
}
}
1)ServletContextAware 通过依赖注入可以得到ServletContext对象
2)ServletResponseAware 通过依赖注入可以得到HttpServletResponse对象
3)ServletRequestAware 通过依赖注入可以得到HttpServletRequest对象
3.使用ServletActionContext
利用ServletActionContext获得ActionContext示例
package com.study.action;
import org.apache.struts2.ServletActionContext;
public class LoginAction{
public String execute() throws Exception{
ActionContext ac = ServletActionContext.getContext();
return null;
}
}
1)static PageContext getPageContext() 获得一个PageContext 对象
2)static HttpServletRequest getRequest() 获得一个HttpServletRequest 对象
3)static HttpServletResponse getResponse() 获得一个HttpServletResponse 对象
4)static ServletContext getServletContext() 获得一个ServletContext 对象
5)static ActionContext getContext() 获得一个ActionContext 对象