Struts2 Study Notes (5) -- Action access Servlet API, struts2servlet

Source: Internet
Author: User

Struts2 Study Notes (5) -- Action access Servlet API, struts2servlet

There are three methods to access Servlet APIs in Strut2:

1. Using ActionContext to access the Servlet API is recommended. However, this solution does not obtain the actual Servlet API.

Steps:
1) Create an ActionContext

  • ActionContext context = ActionContext. getContext ();

2). Get the Servlet API through the context object

  • Map <String, Object> getApplication () obtains all information stored in the application.
  • Map <String, Object> getParameters () is equivalent to request. getParameterMap ();
  • Map <String, Object> getSession (); obtains all the information stored in the session.
  • Put (String key, Object value); is equivalent to request. setAttribute ();
  • Object get (String key) is equivalent to request. getAttribute ();

2. Inject (real Servlet API)

Use the * Aware interface to obtain the Servlet API, for example:

  • ServletContextAware: injects the ServletContext object
  • ServletRequestAware: injects the request object
  • ServletResponseAware: injects a response object.

For example, to obtain the HttpServletRequest object:

 1 public class TestAction extends ActionSupport implements ServletRequestAware { 2     HttpServletRequest request; 3     @Override 4     public String execute() { 5         request.setAttribute("name", "requestTest"); 6         return "success"; 7     } 8      9     @Override10     public void setServletRequest(HttpServletRequest request) {11         this.request = request;12     }13 14 }

3. Use ServletActionContext (real Servlet API)

Through the static method provided in the ServletActionContext class, you can directly obtain the Servlet API:

1 // obtain request2 HttpServletRequest request = ServletActionContext. getRequest (); 3 // get session4 HttpSession session = request. getSession (); 5 // get context6 ServletContext context = ServletActionContext. getServletContext ();

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.