Struts2的Action并未直接与任何Servlet API偶合,这也是Struts2的一个改良的地方。但如何进行访问?
方法一:.[一般推荐使用](只能获得request,而response则得不到)
Struts2提供了一个ActionContext类,Struts2中的Action可以通过它进行访问。
其方法有:get(),getApplication(),getContext(),getParameters(),getSession(),setApplication(),setSession()
- /**
* @作者 Jcuckoo
* @创建日期 2008-12-02
* @版本 V 1.0
*/ - public class LoginAction implements Action
- {
- private String username;
- private String password;
- public String getPassword()
- {
- return password;
- }
- public void setPassword(String password)
- {
- this.password = password;
- }
- public String getUsername()
- {
- return username;
- }
- public void setUsername(String username)
- {
- this.username = username;
- }
- public String execute() throws Exception
- {
- //获取静态方法,获取系统的ActionContext实例
- ActionContext ctx = ActionContext.getContext();
- //获取servletContext里的counter属性
- Integer counter = (Integer)ctx.getApplication().get("counter");
- if (counter == null)
- {
- counter = 1;
- }
- else
- {
- counter = counter + 1;
- }
- //将增加1后的counter值设置成counter属性
- ctx.getApplication().put("counter" , counter);
- ctx.getSession().put("user" , getUsername());
- if (getUsername().equals("scott")&& getPassword().equals("tiger") )
- {
- //直接设置HttpServletRequest属性
- ctx.put("tip" , "服务器提示:您已经成功的登陆");
- return SUCCESS;
- }else{
- //直接设置HttpServletRequest属性
- ctx.put("tip" , "服务器提示:登陆失败");
- return ERROR;
- }
- }
- }
虽然Struts2提供了ActionContext来访问Servlet API,但这种访问毕竟不能直接获得Servlet API,为了在Action中直接访问Servlet API,Struts2还提供了一下接口:ServletContextAware,ServletRequestAware,ServletResponseAware
下面以ServletResponseAware为例。
- /**
* @作者 Jcuckoo
* @创建日期 2008-12-02
* @版本 V 1.0
*/ - //实现ServletResponseAware
- public class LoginAction implements Action , ServletResponseAware
- {
- //需要访问的HttpServletResponse对象
- private HttpServletResponse response;
- private String username;
- private String password;
- public String getPassword(){
- return password;
- }
- public void setPassword(String password){
- this.password = password;
- }
- public String getUsername(){
- return username;
- }
- public void setUsername(String username){
- this.username = username;
- }
- //实现ServletResponseAware接口必须实现的方法
- public void setServletResponse(HttpServletResponse response) {
- this.response = response;
- }
- public String execute() throws Exception{
- Cookie c = new Cookie("user" , getUsername());
- c.setMaxAge(60 * 60);
- response.addCookie(c);
- return SUCCESS;
- }
- }
Struts2还提供了一个ServletActionContext,其静态方法有:getPageContext(),getRequest(),getResponse(),getServletContext()
- HttpServletRequest request = ServletActionContext.getRequest();
- HttpServletResponse response = ServletActionContext.getResponse();
- request.getSession().setAttribute("username","admin");
- request.setAttribute("password", "1234");