3. Struts2 default configuration, centralized mode of data processing, request data encapsulation, date converter

Source: Internet
Author: User

Struts2 Default configuration

1, global View jump configuration, configuration of the default values
This is configured in CONFIG.

    <!-- 配置全局跳转视图 -->        <global-results>            <result name="success">/index.jsp</result>        </global-results>
 <!--Configure each of the default values --         <!--name only configures the access path name class by default the action that is executed in Struts-default has the configuration <default-c Lass-ref class= "Com.opensymphony.xwork2.ActionSupport"/> method defaults to execute default methods execute return value is Su          ccess, the corresponding page to go to the global view to find. -         <action name="Test"></Action>        <!--What happens when class is not configured? That is processed Aciton--        <!--answer: When you just need to jump to web-inf resources. -         <action name="Test2">            <result name="Success" type="redirect">/web-inf/index.jsp</result>         </Action>

2, structs2 the centralized way of data processing

1) Get Servletapi directly
2) through the Actioncontext class
3) How to implement the interface

 Public  class dataaction_bak extends actionsupport{    @Override     PublicStringExecute()throwsException {//1. Request data encapsulation; 2. Call service to process business logic and get result data        //3. Data is saved to the domain        /* *//data manipulation in struts, Mode 1: Get Servletapi directly, perform operation HttpServletRequest request = Servletactioncontex        T.getrequest ();        HttpSession session = Request.getsession ();        ServletContext application = Servletactioncontext.getservletcontext ();        Operation Request.setattribute ("Request_data", "request_data1");        Session.setattribute ("Session_data", "session_data1");        Application.setattribute ("Application_data", "application_data1"); */        //"Recommended: decoupled way to manipulate data"        //Struts in data manipulation, Mode 2: Through the Actioncontext classActioncontext AC = Actioncontext.getcontext ();//Get struts to encapsulate the HttpServletRequest object as a map        //Get a map representing the request objectmap<string,object> request = Ac.getcontextmap ();//Get a map representing the session objectMap<string, object> session = Ac.getsession ();//Get a map representing the ServletContext objectmap<string, object> application = Ac.getapplication ();//DataRequest.put ("Request_data","Request_data1_actioncontext"); Session.put ("Session_data","Session_data1_actioncontext"); Application.put ("Application_data","Application_data1_actioncontext");returnSUCCESS; }
/** * Data processing, Mode 3: Ways to Implement Interfaces * */ Public  class dataaction extends actionsupport  implements  Requestaware, sessionaware, applicationaware{    PrivateMap<string, object> request;PrivateMap<string, object> session;PrivateMap<string, object> Application;//When struts runs, it injects the map object representing the request    @Override     Public void setrequest(map<string, object> request) { This. request = Request; }//Inject session    @Override     Public void setsession(Map<string, object> session) { This. session = Session; }//Injection application    @Override     Public void setapplication(map<string, object> application) { This. application = Application; }@Override     PublicStringExecute()throwsException {//DataRequest.put ("Request_data","Request_data1_actionaware"); Session.put ("Session_data","Session_data1_actionaware"); Application.put ("Application_data","Application_data1_actionaware");//              returnSUCCESS; }}

3. Request Data Encapsulation
regist.jsp

<body>    <form Action="${pagecontext.request.contextpath}/user_register.action"  Method="POST">User name:<input type="text" name="User.Name"><br/>Password:<input type="text" name="User.pwd"><br/>Age:<input type="text" name="User.age"><br/>Birthday:<input type="text" name="User.birth"><br/>        <input type="Submit" value="register">    </form>  </body>

User

 Public classUser {//Encapsulate Request data    PrivateString name;//must give Set/get can not give    PrivateString pwd;Private intAgePrivateDate birth; Public void SetName(String name) { This. name = name; } Public void setpwd(String pwd) { This. pwd = pwd; } Public void Setage(intAge) { This. Age = Age; } Public void Setbirth(Date birth) { This. Birth = Birth; } PublicStringGetName() {returnName } PublicStringgetpwd() {returnPwd } Public int Getage() {returnAge } PublicDateGetbirth() {returnBirth }}

Useraction

/** * Struts core business: Request data Auto-encapsulation and type conversion * */ Public  class useraction {     //object type, be sure to give the Get method    PrivateUser user; Public void SetUser(User user) { This. user = user; } PublicUserGetUser() {returnUser }//Processing registration requests     PublicStringRegister() {System.out.println (User.getname ());        System.out.println (User.getpwd ());        System.out.println (User.getage ()); System.out.println (User.getbirth ());return "Success"; }}

4. Structs2 Date Converter
The date is supported by default only YYYY-MM–DD

Converter class

/** * Custom type converter class * */ Public  class myconverter extends strutstypeconverter {    //New requirement: Requires the format to be supported in the project, such as: yyyy-mm-dd/yyyymmdd/yyyy MM month DD Day .    //define the format of the transformations supported in the projectDateformat[] df = {NewSimpleDateFormat ("Yyyy-mm-dd"),NewSimpleDateFormat ("YyyyMMdd"),NewSimpleDateFormat ("yyyy year mm DD Day") };/** * Converts a string to the specified type "string to Date" * @param Context * Current context * @pa Ram Values * The value of the string submitted by the JSP form * @param Toclass * The target type to be converted to */    @Override     PublicObjectconvertfromstring(Map context, string[] values, Class toclass) {//Judgment: Content cannot be empty        if(Values = =NULL|| Values.length = =0) {return NULL; }//Judgment type must be date        if(Date.class! = Toclass) {return NULL; }//Iteration: Conversion failed to continue the conversion of the next format; the conversion succeeds and returns directly         for(intI=0; i<df.length; i++) {Try{returnDf[i].parse (values[0]); }Catch(ParseException e) {Continue; }        }return NULL; }@Override     PublicStringconverttostring(Map context, Object O) {return NULL; }}

Local

Global

3. Struts2 default configuration, centralized mode of data processing, request data encapsulation, date converter

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.