Struts 2对Servlet API进行了封装,是业务层更加独立,如果需要调用Request、Response等Servlet API有两种途径
利用ServletActinContext的静态方法
Struts 2利用ServletActinContext来维护Servlet对象,ServletActinContext利用ThreadLocal来维护不同线程的Servlet对象,因此可以使用ServletActinContext来获得Servlet的各种对象
import org.apache.struts2. ServletActinContext; public class LoginActin extends ActionSupport{ public String login(){ HttpServletRequest request = ServletActinContext.getRequest(); HttpServletResponse response = ServletActinContext.getResponse(); HttpServletContext context = ServletActinContext.getServletContext(); HttpSession session = request.getSession(); …… } }
利用相关的Aware接口
Struts 2在实例化一个Action实例时,如果发现它实现了相关的Aware接口,会把相应的资源通过Aware接口方法注射进去,Aware接口其实是一种拦截器
Servlet API常用对象application、request、response、session对应的Aware接口分别为ServletContextAware、ServletRequestAware、ServletResponseAware、SessionAware
public class ServletAwareActionextends ActionSupport implementsServletContextAware,ServletRequestAware,ServletResponseAware,SessionAware{ private HttpServletRequest request ; private HttpServletResponse response; private HttpServletContext application; private HttpSession session ; //相应的setter方法 public void setServletRequest(HttpServletRequest request ){ this.request = request; } public void setServletResponse(HttpServletResponse response ){ this.reponse = reponse; } public void setServletContext(HttpServletContext application ){ this. application = application; } public void setSession(Map sessionValues){ this.session = sessionValues; } //然后可以在Action中直接使用这些对象 public String execute(){ request.getRemoteAddr(); response.getContentType() session.get(“account”); return SUCCESS; } }
相关文章
- 09-12Struts2之Action的编写与访问
- 09-12Struts学习之路-第二天(Action与Servlet API)
- 09-12【学习笔记】Struts2之配置文件struts.xml
- 09-12struts2的action访问servlet API的三种方法
- 09-12Detectron2 API 之 config | 十五
- 09-12Struts2注解错误之There is no Action mapped for namespace /
- 09-12Servlet_Struts2
- 09-12struts2不兼容servlet、COS
- 09-12struts2 servlet之间通信
- 09-12Struts2_API