解耦的方式获取web资源的途径有两种:
- 使用ServletActionContext
- 实现ServletXxxAware接口
通过耦合方式获取web资源,可以只用很多原生API而不局限于,非耦合只能获得Map集合。
第一种方法:
package com.atguigu.struts2.actions;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
public class TestServletActionContextAction {
public String execute(){
/**
* ServletActionContext:可以从中获取到当前Action对象需要的一切Servlet相关API
* 常用的方法:
* 1.获取HttpServletRequest:ServletActionContext.getRequest();
* 2.获取HttpSession:ServletActionContext.getRequest().getSession();
* 3.获取ServletContext:ServletActionContext.getServletContext();
*
*/
HttpServletRequest request= ServletActionContext.getRequest();
HttpSession session = ServletActionContext.getRequest().getSession();
ServletContext setvletContext = ServletActionContext.getServletContext();
System.out.println("execute...");
return "success";
}
}
第二种方法:是实现接口的方式获取(public class TestServletxxxAware implements ServletContextAware,ServletRequestAware,ServletResponseAware)
package com.atguigu.struts2.actions;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.util.ServletContextAware;
/**
* 通过实现ServletXxxAware接口的方式可以由Struts2注入需要的Servlet相关的对象
* 常用的方法:
* 1.ServletRequestAware:注入HttpServletRequest对象(比较常用)
* 2.ServletContextAware:注入ServletRequest对象(比较常用)
* 3.ServletResponseAware:注入HttpServletSponse对象
*
*/
public class TestServletxxxAware implements ServletContextAware,ServletRequestAware,ServletResponseAware{
@Override
public void setServletResponse(HttpServletResponse response) {
System.out.println(response);
}
@Override
public void setServletRequest(HttpServletRequest request) {
System.out.println(request);
}
private ServletContext context;
@Override
public void setServletContext(ServletContext context) {
System.out.println(context);
this.context=context;
}
public String execute(){
System.out.println("ServletContext:"+ context);
return "success";
}
}
实现代码:
index.jsp
<body>
<a href="TestServletActionContext">TextServletActionContext</a></br>
<a href="TestServletAware">TestServletAware</a></br></br>
</body>
Struts.xml
<package name="default" namespace="/" extends="struts-default">
//action-class:action所在的路径(包名+类名);默认值为:com.opensymphony.xwork2.ActionSupport,可不写
<action name="TestServletActionContext" class="com.atguigu.struts2.actions.TestServletActionContext">
<result>/success.jsp</result>
</action>
<action name="TestServletAware" class="com.atguigu.struts2.actions.TestServletAware">
<result>/success.jsp</result>
</action>
</package>