Struts2 servlet access API

Source: Internet
Author: User

Struts2 servlet access API

1. As a controller, struts usually accesses servlet APIs. Common functions:
(1). GET Request Parameters and control page Jump
(2) store the shared data in request, session, and servletContext to obtain the data in the scope.

Generally, there are three access methods.

2. First: implement the interface to complete the injection when accessing the Action
ServletContextAware
Void setServletContext (javax. servlet. ServletContext context)

ServletRequestAware
Void setServletRequest (javax. servlet. http. HttpServletRequest request)

ServletResponseAware
Void setServletResponse (javax. servlet. http. HttpServletResponse response)

The above method: the coupling between Action and ServletAPI is too deep.

Simple sample code:

Package cn. wwh. www. web. servletapi; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import org. apache. struts2.interceptor. servletRequestAware; import org. apache. struts2.interceptor. servletResponseAware; import com. opensymphony. xwork2.Action; import com. opensymphony. xwork2.ActionSupport;/*** function: *** @ author yiye banzhou * @ version 1.0 * @ Creation Time: 07:54:05 */public class ParamAction1 extends ActionSupport implements ServletRequestAware, servletResponseAware {private static final long serialVersionUID = 1L; private HttpServletRequest request; private HttpServletResponse response; @ Overridepublic String execute () throws Exception {String name = request. getParameter ("name"); String age = request. getParameter ("age"); System. out. println ("name:" + name); System. out. println ("age:" + age); response. getWriter (). write (name +"
"); Response. getWriter (). write (age); // no effect, very strange request. getRequestDispatcher ("/views/servletapi/result. jsp "). forward (request, response); return Action. NONE;} public void setServletRequest (HttpServletRequest request) {this. request = request;} public void setServletResponse (HttpServletResponse response) {this. response = response ;}}


 

3. type 2: Use ServletActionContext (many are used in development, because it is simple and intuitive) ServletActionContext: Provides the ServletAPI environment through this class, and obtains the Servlet API Information static PageContext getPageContext () static HttpServletRequest getRequest () static HttpServletResponse getResponse () static ServletContext getServletContext ()

This solution avoids the Action class from implementing the XxxAware interface, but the Action is still directly coupled with the Servlet API, but this method is also coupled with the ServletApi.

Simple instance code:

Package cn. wwh. www. web. servletapi; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import javax. servlet. http. httpSession; import org. apache. struts2.ServletActionContext; import com. opensymphony. the role of the xwork2.ActionSupport;/*** class: *** @ author yiye banzhou * @ version 1.0 * @ Creation Time: 09:09:02 */public class ParamAction2 extends ActionSupport {private static final long serialVersionUID = 1L; public String execute () throws Exception {HttpServletRequest req = ServletActionContext. getRequest (); String name = ServletActionContext. getRequest (). getParameter ("name"); String age = ServletActionContext. getRequest (). getParameter ("age"); HttpSession session = req. getSession (); session. getServletContext (); System. out. println (name); System. out. println (age); HttpServletResponse resp = ServletActionContext. getResponse (); return NONE ;}}

4. Method 3: Use the ActionContext class (not coupled with ServletApi, recommended for development)
The context of the Action, which provides the environment for the Action, that is, the Action-related data can be obtained through this class.

ActionContext
GetContext () returns the ActionContext Instance Object
Get (key) is equivalent to the getAttribute (String name) method of HttpServletRequest.
Put (String, Object) is equivalent to the setAttribute method of HttpServletRequest
GetApplication () returns a Map object and accesses the ServletContext attribute.
GetSession () returns a Map object and accesses the HttpSession attribute.
GetParameters () is similar to calling the getParameterMap () method of HttpServletRequest.
SetApplication (Map) saves the key-value in the Map instance as the attribute name and attribute value of ServletContext.
SetSession (Map) keeps the key-value in the Map instance as the attribute name and attribute value of HttpSession.
Get the ActionContext object: ActionContext context = ActionContext. getContext ();

Simple sample code:

Package cn. wwh. www. web. servletapi; import java. lang. reflect. array; import java. util. map; import com. opensymphony. xwork2.ActionContext; import com. opensymphony. the role of the xwork2.ActionSupport;/*** class: *** @ author yiye banzhou * @ version 1.0 * @ Creation Time: 09:31:42 */public class ParamAction3 extends ActionSupport {private static final long serialVersionUID = 1L; public String execute () throws Exception {ActionContext ctx = ActionContext. getContext (); Map
 
  
ParamMap = ctx. getParameters (); System. out. println (paramMap); // remove paramMap. the value of the element 0 in the get ("name") array. out. println (Array. get (paramMap. get ("name"), 0); // set sharing data ctx to request. put ("name", ""); // request. setAttribute (key, Object) Object requestValue = ctx. get ("name"); System. out. println (requestValue); // set shared data to the Session // Map
  
   
GetSession () Map
   
    
SessionMap = ctx. getSession (); sessionMap. put ("sessionKey", "sessionValue"); // set shared data to ServletContext //. Map
    
     
GetContextMap () Map
     
      
ContextMap = ctx. getContextMap (); contextMap. put ("appKey", "appValue"); return SUCCESS ;}}
     
    
   
  
 
Note that the data read in jsp is:
$ {RequestScope. name}

$ {SessionScope. sessionKey}

$ {AppKey}


5. Get the Map of the request, session, and application decoupling through ActionContext

(1) operations on the request domain
ActionContext. put ("name", "") --> equal to request. setAttribute ("name", "");
Object o = actionContext. get ("name"); --> equivalent to Object o = request. getAttribute ("name ");
(2). operations on the session domain
Map SessionMap = ActionContext. getContext (). getSession ();
SessionMap. put ("name", "") --> equivalent to session. setAttribute ("name", "");
Object o = sessionMap. get ("name") --> equivalent to Object o = session. getAttribute ("name ");
(3). Operation on the application domain
Map AppMap = ActionContext. getContext (). getApplication ();
AppMap. put ("name", "") --> equivalent to servletContext. setAttribute ("name", "");

Object o = appMap. get ("name") --> is equivalent to Object o = servletContext. getAttribute ("name ");

(4). Operation on Request Parameters
Map ParamMap = ActionContext. getContext (). getParameters ();
Object o = paramMap. get ("username ");
String [] values = (String []) o;
String username = values [0];

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.