Struts2中对Servlet API的访问详解编程语言

1 通过接口进行对象注入,action必须是实现相应的接口,struts就可以将指定的对象传递给action类
ServletContextAware接口:可以获得ServletContext对象
ServletResponseAware接口:可以获得ServletResponse对象
ServletRequestAware接口:可以获得ServletRequest对象
request.getSession获得session对象

public class ServletAction extends ActionSupport implements ServletRequestAware{ 
 
    private HttpServletRequest request; 
 
    @Override 
    public void setServletRequest(HttpServletRequest request) { 
        this.request = request; 
    } 
    @Override 
    public String execute() throws Exception { 
        System.out.println(request.getContextPath()); 
        return SUCCESS; 
    }    
} 

执行结果:
这里写图片描述

2 ServletActionContext 工具类,struts 的action类中获得servlet的api
获得servlet 对象,可以操作域数据,可以调用其他api
HttpServletRequest ServletActionContext.getRequest();
HttpSession ServletActionContext.getRequest().getSession();
ServletContext ServletActionContext.getServletContext();

public class ServletAction extends ActionSupport {   
 
    @Override 
    public String execute() throws Exception { 
        ServletActionContext.getResponse(); 
        ServletActionContext.getRequest().setAttribute("sac", "ServletActionContext_request"); 
        ServletActionContext.getRequest().getSession().setAttribute("sac", "ServletActionContext_session"); 
        ServletActionContext.getServletContext().setAttribute("sac", "ServletActionContext_application"); 
 
        return SUCCESS; 
    } 
 
} 

jsp代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
  <body> 
   <h3>获得3作用域内容 -- ServletActionContext</h3> 
    ${requestScope.sac} <br/> 
    ${sessionScope.sac} <br/> 
    ${applicationScope.sac} <br/> 
  </body> 
</html> 

执行结果:
这里写图片描述

3 通过Action上下文对象ActionContext,可以间接对servlet 域数据进行操作,实现了解耦,不依赖于servlet api
获得ActionContext实例:ActionContext.getContext()
间接操作域数据

public class ServletAction extends ActionSupport { 
    @Override 
    public String execute() throws Exception {       
        ActionContext.getContext().put("ac", "ActionContext_request");   
        ActionContext.getContext().getSession().put("ac", "ActionContext_session"); 
        ActionContext.getContext().getApplication().put("ac", "ActionContext_application"); 
 
 
        return SUCCESS; 
    } 
} 
 

jsp代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
  <body>     
    <h3>获得3作用域内容-- ActionContext</h3> 
    ${requestScope.ac} <br/> 
    ${sessionScope.ac} <br/> 
    ${applicationScope.ac} <br/> 
  </body> 
</html> 

执行结果:
这里写图片描述

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/12077.html

(0)
上一篇 2021年7月19日
下一篇 2021年7月19日

相关推荐

发表回复

登录后才能评论