struts 访问servlet api (ServletActionContext 方式)

来源:互联网 发布:如何提高网络延迟 编辑:程序博客网 时间:2024/06/06 11:15

    ServletActionContext  是ActionContext的子类,还实现了StrutsStatics接口,可以说ServletActionContext  就是为了struts 的action获得servlet相关api而设计的。

public class ServletActionContext extends ActionContext implements StrutsStatics
    ServletActionContext  提供了一些静态的方法来获得想要的 api 。

  PageContext :

    public static PageContext getPageContext() {        return (PageContext) ActionContext.getContext().get(PAGE_CONTEXT);    }
  Request:

    public static HttpServletRequest getRequest() {        return (HttpServletRequest) ActionContext.getContext().get(HTTP_REQUEST);    }
  Response:

    public static HttpServletResponse getResponse() {        return (HttpServletResponse) ActionContext.getContext().get(HTTP_RESPONSE);    }
  ServletContext:

    public static ServletContext getServletContext() {        return (ServletContext) ActionContext.getContext().get(SERVLET_CONTEXT);    }
    下面仍然是一个登录测试的小例子:

package com.cd.action;import org.apache.struts2.ServletActionContext;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import java.io.IOException;public class LoginAction {    public String login()  {        //获取request对象        HttpServletRequest request =                (HttpServletRequest) ServletActionContext.getRequest();        Object username = request.getParameter("username");        Object password = request.getParameter("password");        if(username != null && password != null)        {            if("jack".equals(username)&&"jack".equals(password))            {                //获得session对象                HttpSession session = ServletActionContext.getRequest().getSession();                session.setAttribute("username",username);                return  "success";            }            else            {                //获得response对象                HttpServletResponse response = ServletActionContext.getResponse();                try                {                    response.getWriter().write("failed");                }                catch (IOException e)                {                    e.printStackTrace();                }                return  null;            }        }        else        {            //获得response对象            HttpServletResponse response =  ServletActionContext.getResponse();            try            {                response.getWriter().write("check input");            }            catch (IOException e)            {                e.printStackTrace();            }            return null;        }    }}
   xml配置,返回界面和测试结果和上一篇博客一样,这里就不贴出来了。




                                             
0 0
原创粉丝点击