使用servletAPI三种方式简单示例

时间:2021-08-03 10:33:30

一、直接实现Action接口或集成ActionSupport类(推荐)

public class HelloAction implements Action {

  @Override
  public String execute() throws Exception {
    Map<String, Object> requestScope = (Map<String, Object>) ActionContext.getContext().get("request");
    Map<String, Object> sessionScope = ActionContext.getContext().getSession();
    Map<String, Object> applicationScope = ActionContext.getContext().getApplication();
    Map<String, Object> params = ActionContext.getContext().getParameters();
    requestScope.put("name", "request");
    sessionScope.put("name", "session");
    applicationScope.put("name", "application");
    String[] strs = (String[]) params.get("name");
    System.out.println(Arrays.toString(strs));
    return SUCCESS;
  }

}

二、使用ServletActionContext对象获得原生的Servlet对象

public class HelloAction implements Action {

  @Override

  public String execute1() {
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpServletResponse response = ServletActionContext.getResponse();
    HttpSession session = request.getSession();
    ServletContext context = ServletActionContext.getServletContext();
    return SUCCESS;
  }

}

三、

public class HelloAction extends ActionSupport implements ServletRequestAware, ServletResponseAware, SessionAware {
  private HttpServletRequest request;
  private HttpServletResponse response;
  private Map<String, Object> session;

  @Override
  public void setSession(Map<String, Object> session) {
    // TODO Auto-generated method stub
    this.session = session;
  }

  @Override
  public void setServletResponse(HttpServletResponse response) {
    // TODO Auto-generated method stub
    this.response = response;
  }

  @Override
  public void setServletRequest(HttpServletRequest request) {
    // TODO Auto-generated method stub
    this.request = request;
  }

  @Override
  public String execute() throws Exception {

    return SUCCESS;
  }

}