Struts2 access servlet share

  • 2020-05-30 20:56:32
  • OfStack

1: access or add request/session/application properties

public String scope() throws Exception{
   ActionContext ctx = ActionContext.getContext();
   ctx.getApplication().put("app", " Range of application ");// to ServletContext Put inside app
   ctx.getSession().put("ses", "session The scope of ");// to session Put inside ses
   ctx.put("req", "request The scope of ");// to request Put inside req
   return "scope";


    ${} <br>

2: get the HttpServletRequest/HttpSession/ServletContext/HttpServletResponse object

Method 1, get directly through ServletActionContext. class:

public String rsa() throws Exception{
       HttpServletRequest request = ServletActionContext.getRequest();
       ServletContext servletContext = ServletActionContext.getServletContext();
       HttpServletResponse response = ServletActionContext.getResponse();
       return "scope";

Method 2, implementation of the specified interface, by the struts framework runtime injection:

public class HelloWorldAction implements ServletRequestAware, ServletResponseAware, ServletContextAware{
       private HttpServletRequest request;
       private ServletContext servletContext;
       private HttpServletResponse response;
       public void setServletRequest(HttpServletRequest req) {
       public void setServletResponse(HttpServletResponse res) {
       public void setServletContext(ServletContext ser) {

Related articles: