Struts2's servlet access API, struts2servletapi

Source: Internet
Author: User

Struts2's servlet access API, struts2servletapi

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 + "<br/>"); 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 <String, Object> 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 <String, Object> getSession () Map <String, Object> sessionMap = ctx. getSession (); sessionMap. put ("sessionKey", "sessionValue"); // set shared data to ServletContext //. map <String, Object> getContextMap () Map <String, Object> contextMap = ctx. getContextMap (); contextMap. put ("appKey", "appValue"); return SUCCESS ;}}
Note that the data read in jsp is:
$ {RequestScope. name} <br/>
$ {SessionScope. sessionKey} <br/>
$ {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 <String, Object> 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 <String, Object> 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 <String, Object> paramMap = ActionContext. getContext (). getParameters ();
Object o = paramMap. get ("username ");
String [] values = (String []) o;
String username = values [0];


Struts2 access servlet API Problems

1,
Because ctx. getApplication. get ("counter"); returns the Object type, while counter is defined as the Integer type, it needs to be forcibly converted. So Integer counter = (Integer) ctx. getApplication. get ("counter ");

Now JDK has been able to automatically disassemble the box between Integer (reference type) and int (basic type) types. Simply put, the box can be automatically converted, so there is no problem with this sentence.

2. What is get ("counter? Obtain the value corresponding to the key in the current ActionContext written in the book. Is this the value of the map object? Isn't that value stored using the put method? It should not have started.
Yes, so the following sentence
Integer counter = (Integer) ctx. getApplication. get ("counter ");
If (counter = null)
{
Counter = 1;
}
Else counter = counter + 1;
If you don't have one, assign 1 to it. If you have one, add 1 to it. That's right.

Objects such as sessions and requests obtained by accessing Servlet APIs in struts2

What do you do when you use struts2 to retrieve servlet sessions?
Don't you just want to pass the value to jsp, just use struts2 to pass it, why do you still use session and request.

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.