1.完全解耦合的方式 如果使用该种方式,Struts2框架中提供了一个类,ActionContext类,该类中提供一些方法,通过方法获取Servlet的API 一些常用的方法如下
Static Actioncontext GetContext () -- Get Actioncontext object instance * java.util.map<java.lang.string, Java.lang.object> getparameters () -- GET request parameters, equivalent to Request.getparametermap (); * java.util.map<java.lang.string,java.lang.object> getsession () -- Gets the Map collection representing the session field, is equivalent to manipulating the session field. * java.util.map<java.lang.string,java.lang.object> getapplication () -- get a Map collection representing the application domain void put (java.lang.String key, Java.lang.Object value) --Note: The value is stored in the request domain.
/*** Fully decoupled way, using Servlet's API *@authorAdministrator*/ Public classDemo1actionextendsactionsupport{Private Static Final LongSerialversionuid = -7255855724015241518l; PublicString Execute ()throwsException {//the way to fully connect the couplingActioncontext context =Actioncontext.getcontext (); //gets the parameters to the request, encapsulating all the requested parametersmap<string, object> map =context.getparameters (); //Traverse Fetch Dataset<string> keys =Map.keyset (); for(String key:keys) {//through key, to get the valueString [] Vals =(string[]) map.get (key); SYSTEM.OUT.PRINTLN (Key+" : "+arrays.tostring (Vals)); } //if the value is stored in the request objectContext.put ("msg", "Little Dongdong")); //get additional Map collectionsContext.getsession (). Put ("msg", "Small Cang"); Context.getapplication (). Put ("MSG", "Ozawa"); returnSUCCESS; }}
2.使用原生Servlet的API的方式--简单方便 * Struts2框架提供了一个类,ServletActionContext,该类中提供了一些静态的方法 * 具体的方法如下 * getPageContext() * getRequest() * getResponse() * getServletContext()
/*** Native API *@authorAdministrator **/ Public classDemo2actionextendsactionsupport{Private Static Final LongSerialversionuid = -864657857993072618l; PublicString Execute ()throwsException {//get to request objectHttpServletRequest request =servletactioncontext.getrequest (); Request.setattribute ("MSG", "Little Dongdong"); Request.getsession (). SetAttribute ("MSG", "Meimei"); Servletactioncontext.getservletcontext (). SetAttribute ("MSG", "Xiao Feng"); HttpServletResponse Response=Servletactioncontext.getresponse (); //use output stream, output content returnSUCCESS; }}
How SERVLETAPI in the 5.STRUTS2 framework gets