Struts2 the Action class to access WEB resources

Source: Internet
Author: User

Then the last blog content I continue to share the knowledge I learned, and my learning process encountered problems and solutions. Of course, if the reader finds any questions, please let me know in the comments below, thank you!

Accessing Web resource Web Resources in Action
    • The so-called Web resource refers to the HttpServletRequest、HttpServletResponse、ServletContext native API, the Controller developed as b/S application must have access to the Web resources, such as reading and writing properties to the domain object.
How to access WEB resources
  • and Servletapi decoupling way : in order to avoid coupling with SERVLETAPI, convenient Action to do unit test, Struts2 to Httpservletrequest,httpsession and Servletcon Text is encapsulated, 3 map objects are constructed to replace these 3 objects, and the httpservletrequest,httpservletsession,httpservletcontext corresponding map object can be used in the action to save and read Fetch data
    • using Actioncontext (Method 1): Actioncontext is the context object that the action executes, and all the objects needed to execute the action are saved in Actioncontext, Parameters, Request,session and so on. If you get the map object using HttpSession corresponding method public Map getSession() , context,params corresponding method is the same, but for request need to use public Object get(Object key) Method pass request parameter implementation
    • Implement the Xxxaware Interface (Method 2): such as implementing the Requestaware interface and implementing its setRequest() methods, so that the requestmap can be called in all action methods.
  • to get a code demonstration of a domain object using Actioncontext
    • Send the request to showpage.jsp from the index.jsp page and submit the request to the Struts Action class Objectaction.java process the request
    • In Objectaction.java, the actioncontext gets the domain object and adds the property value to it, forwarding the request to showpage.jsp
    • On the showpage.jsp page we can get the values of the individual domain objects
    • index.jsp

      <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    • Objectaction.java

      Package Com.request.test;import Com.opensymphony.xwork2.actioncontext;import Java.util.map;public class objectaction {public String print () {//get actioncontext actioncontext Actioncontext = Actioncontext.get Context ();//Gets the action domain object corresponding to the map map<string, object> applicationmap = Actioncontext.getapplication ();         Assign a value of Applicationmap.put ("Applicationmap", "Applicationmapvalue") to the application;//Get the map for the Session map<string, object> sessionmap = Actioncontext.getsession ();//Sessionmap Assignment Sessionmap.put ( "Sessionmap", "Sessionmapvalue");//Get the map for the request and there is no corresponding getrequest () method, so use the Get ("Request") method Map<s Tring, object> Requestmap = (map<string, object>) actioncontext.get ("request");//For Requestmap assignment R Equestmap.put ("Requestmap", "Requestmapvalue");//Obtain the params corresponding Map map<string, object> paramsmap = AC Tioncontext.getparameters ();//Get PArams parameter value string[] params = (string[]) paramsmap.get ("name");//print parameter values to console SYSTEM.OUT.PRINTLN (params        [0]);    Return "Success"; }}
    • Struts.xml (only the package node can be displayed)

      <package name="showValue" extends="struts-default">    <action name="showPage" class="com.request.test.ObjectAction" method="print">        <result name="success">/showPage.jsp</result>    </action></package>
    • showpage.jsp(Body tag content only)

      <%--获取到 application 域对象的值--%>${applicationScope.applicationMap}<br><%--获取到 session 域对象的值--%>${sessionScope.sessionMap}<br><%--获取 request 域对象的值--%>${requestScope.requestMap}
    • Details and needs attention (you can drag the picture to the browser's new tab to see a larger image)

  • Accessing WEB resources using the Xxxaware interface
    • As with Actioncontext, the index.jsp page sends requests to Objectaction.java handled by the Print2 () method
    • Assigns a value to the domain object in the Print2 () method in Objectaction.java and gets the value of the passed-in parameter
    • Finally, the value of the domain object is obtained in showpage.jsp, in order to distinguish it from the previous one, we give each output a symbol.
    • index.jsp(Display body tag section)

      <a href="showPage2.action?name=smZyy">ToPage2</a>
    • Objectaction.java

      Package Com.request.test;import Com.opensymphony.xwork2.actioncontext;import Org.apache.struts2.interceptor.applicationaware;import Org.apache.struts2.interceptor.parameteraware;import Org.apache.struts2.interceptor.requestaware;import Org.apache.struts2.interceptor.sessionaware;import Java.util.map;public class Objectaction implements Requestaware, Sessionaware, Applicationaware, parameteraware{Priva    Te map<string, object> requestmap;    Private map<string, object> Sessionmap;    Private map<string, object> Applicationmap; Private map<string, string[]> parametermap;//showpage.action Execute the required method public String Print2 () {Applicat        Ionmap.put ("Applicationmap", "applicationmapval===");        Requestmap.put ("Requestmap", "requestmapval===");        Sessionmap.put ("Sessionmap", "sessionmapval===");        string[] name = Parametermap.get ("name");        System.out.println (name[0] + "= = =");    Return "Success"; } @Override public void SetAPplication (map<string, object> map) {this.applicationmap = map;    } @Override public void Setparameters (map<string, string[]> map) {this.parametermap = map;    } @Override public void Setrequest (map<string, object> map) {this.requestmap = map;    } @Override public void Setsession (map<string, object> map) {this.sessionmap = map; }}
    • Struts.xml(Show package node section)

      <package name="showValue" extends="struts-default">    <action name="showPage2" class="com.request.test.ObjectAction" method="print2">        <result name="success">/showPage.jsp</result>    </action></package>
    • showpage.jsp (ibid., not changed at all)

Selection Suggestions

  Through the two methods of obtaining WEB resources, we can know that the first method if there are many action methods need to call the domain object then each method must be implemented, and the second method only need to be implemented once, so in the actual development, depending on the situation and choose the corresponding method to implement.

    • and Servletapi coupling : more Servletapi can be accessed, and native methods can be called
      • Using Servletactioncontext
      • Implementing the Servletxxxaware Interface

The implementation in this way is similar to the above implementation, I am not verbose.

Struts2 the Action class to access WEB resources

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.