ServletAction方式,必须要有Servlet容器作支持
package com.hanqi.action;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
public class TestServletAction {
public String testServletAction()
{
//访问原生的web资源
//1得到servletContext,相当于application
ServletContext sc= ServletActionContext.getServletContext();
System.out.println("app1="+sc.getAttribute("app1"));
sc.setAttribute("app2", "原生的方式加入的application");
//2访问Session
HttpServletRequest hsr=ServletActionContext.getRequest();
HttpSession hs=hsr.getSession();
System.out.println("ses1="+hs.getAttribute("ses1"));
hs.setAttribute("ses2", "原生方式放入的session");
//3访问request
System.out.println("req1="+hsr.getAttribute("req1"));
hsr.setAttribute("req2", "原生方式放入的request");
//4 访问parameter
System.out.println("user1="+hsr.getParameter("user"));
System.out.println("user2="+hsr.getParameter("user"));
return "success";
}
}
实现接口方式
package com.hanqi.action;
import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.util.ServletContextAware;
public class TestServletActionAware
implements ServletRequestAware, ServletContextAware {
private ServletContext sc;
private HttpServletRequest hsr;
private HttpSession hs;
@Override
public void setServletContext(ServletContext arg0) {
sc=arg0;
}
@Override
public void setServletRequest(HttpServletRequest arg0) {
hsr=arg0;
hs=arg0.getSession();
}
public String testServletAware()
{
System.out.println("app1="+sc.getAttribute("app1"));
sc.setAttribute("app2", "新的application");
System.out.println("ses1="+hs.getAttribute("ses1"));
hs.setAttribute("ses2","新的session");
System.out.println("user="+hsr.getParameter("user"));
hsr.setAttribute("req2", "新的request");
return "success";
}
}