cool hit counter SSH framework tour - struts2 (2)_Intefrankly

SSH framework tour - struts2 (2)


struts.jpg

1.Results page configuration


1.1 Global results page configuration

result tag configures the return value of the action method to a different path if the action approachhas the same return value as the, And the path to get there is the same, Then you can use the global results page configuration, All that is required is a package Tag with global-results Tags.action The tag can then be omitted from the result tag now, which achieves code simplification.

Example code generation is as follows.

    <global-results>
      <result name=" Same return value"> Same arrival path</result>
    </global-results>
    <action name="action1" class="cc.wenshixin.action.ActionDemo1">
    </action>
    <action name="action2" class="cc.wenshixin.action.ActionDemo2">
    </action>

1.2 Local results page configuration

If both a global results page configuration and a local results page configuration are set in the configuration file, then the local results page configuration overrides the global results page configuration.

1.3 The type attribute of the result tag

result In addition to the label name In addition to the attributes, there are type attributes.type attribute is used to set how the path is jumped, whether it is a redirect or a forward action, and is further divided into a page jump and an action jump.

  • For page jumps dispatcher: default value, does the forwarding operation. redirect: redirect.

The sample code is as follows.

    <package name="demo1" extends="struts-default" namespace="/">
        <action name="action1" class="cc.wenshixin.action.ActionDemo1">
          <result name="success" type="dispatcher">/success.jsp</result>
        </action>
        <action name="action2" class="cc.wenshixin.action.ActionDemo2">
          <result name="success" type="redirect">/success.jsp</result>
        </action>
    </package>
  • Jump for action chain: forward to another action, generally not used this way because of browser caching issues. redirectAction: redirects to another action in result tag to write another directly in the action tagged name attribute value.

The sample code is as follows.

    <package name="demo1" extends="struts-default" namespace="/">
        <action name="action1" class="cc.wenshixin.action.ActionDemo1">
          <result name="success" type="dispatcher">/success.jsp</result>
        </action>
        <action name="action2" class="cc.wenshixin.action.ActionDemo2">
          <result name="success" type="redirectAction">action1</result>
        </action>
    </package>

2.API for struts2 to access JSP


struts hit the target action class It's the equivalent of a regularjava web Project in servlet kind,servlet In therequest harmonyresponse etc. approach, but (not)action is also provided in the approach ofAPI, It can also be accessed atJSP built-in targets。

2.1 Use the ActionContext class to get

approach

functionalities

void put(String key,Object value)

Put the key-value pair into the ActionContext object, corresponding to the setAttribute() method of the HttpServletRequest in the Servlet

Object get(String key)

Get the value in the ActionContext object by the parameter key

Map<String,Object> getApplication()

Return aApplication hit the targetMap targets

static ActionContext getContext()

Get the current thread'sActionContext targets, That is, the creation of targets, here targets notnew coming out

Map<String,Object> getParameters()

Returns a list of allHttpServletRequest parameter information of theMap targets

Map<String,Object> getSession()

Return aMap typeHttpSession targets

void setApplication(Map<String,Object> application)

Set the context of the Application

void setSesstion(Map<String,Object> session)

Set a Session value of type Map

This way is struts2 recommended way to get the jsp page object, coupling (jsp page and action relationship) is very low, action does not need to know the jsp page in the form specific name property value can finally get the input value.

Example code.

jsp page

  <form action="${pageContext.request.contextPath}/action1.action" method="post">
     name and surname:<input type="text" name="name"><br>
     classes or grades in school:<input type="text" name="class"><br>
     age:<input type="text" name="age"><br>
    <input type="submit" value=" submit">
  </form>

action class

package cc.wenshixin.action;

import java.util.Arrays;
import java.util.Map;
import java.util.Set;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class ActionContextDemo extends ActionSupport{
    @Override
    public String execute() throws Exception {
        //1. gainActionContext targets
        ActionContext context = ActionContext.getContext();
        //2. invoke approach Get the data of the form,key is the form input item of thename property value,value is the value of the input
        Map<String, Object> map = context.getParameters();
        
        Set<String> keys = map.keySet();
        
        for (String key : keys) {
There may be more than one value for //value, as there may be checkboxes for the input items
            Object[] obj = (Object[])map.get(key);
            System.out.println(Arrays.toString(obj));
        }
        return NONE;
    }
}

struts configuration

  <package name="demo1" extends="struts-default" namespace="/">
    <action name="action1" class="cc.wenshixin.action.ActionContextDemo">
        <!--  Because there is no return value, So there's no needresult label -->
    </action>
  </package>

2.2 Use the ServletActionContext class to get the

This approach is achieved byServletActionContext Static of the class approach Get the HttpServletRequest object of the web application,HttpServletResponse targets,ServletContext targets,PageContext targets realized。 This approach is like writingservlet the same as, Use this often。

approach

functionalities

static HttpServletRequest getRequest()

Get the HttpServletRequest object of the web application

static HttpServletResponse getResponse()

Get the HttpServletResponse object of the web application

static ServletContext getServletContext()

gainweb applicableServletContext targets

static PageContext getPageContext()

gainweb applicablePageContext targets

The sample code is as follows.

The jsp page is the same as above, note that the path to the form submission is changed.

action class

package cc.wenshixin.action;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class ServletActionContextDemo extends ActionSupport{
    @Override
    public String execute() throws Exception {
        HttpServletRequest request = ServletActionContext.getRequest();
        
        String name = request.getParameter("name");
        String banji = request.getParameter("class");
        String age = request.getParameter("age");
        
        System.out.println(" name and surname:"+name+", classes or grades in school:"+banji+", age:"+age);
        return NONE;
    }
}

struts configuration

    <action name="action2" class="cc.wenshixin.action.ServletActionContextDemo">
    <!--  Because there is no return value, So there's no needresult label -->
    </action>

2.3 Use interface injection to obtain

struts A series of interfaces are provided in, Just letaction Implementing interfaces, You can getservle hit the target targets。

interface name

functionalities

ServletRequestAware

Action classes that implement this interface can access the web application's HttpservletRequest object

ServletResponseAware

implements the interface'sAction class-accessibleWeb applicableHttpServletResponse targets

SessionAware

implements the interface'sAction class-accessibleWeb applicableHttpSession targets

ServletContextAware

implements the interface'sAction class-accessibleWeb applicableServletContext targets

The sample code is as follows.

The jsp page is the same as above, note that the path to the form submission is changed.

action class

package cc.wenshixin.action;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ServletRequestAware;

import com.opensymphony.xwork2.ActionSupport;

public class ActionWithAware extends ActionSupport implements ServletRequestAware{
    
    private HttpServletRequest request;
    
    @Override
    public void setServletRequest(HttpServletRequest request) {
        this.request = request;
    }
    
    @Override
    public String execute() throws Exception {
        String name = request.getParameter("name");
        String banji = request.getParameter("class");
        String age = request.getParameter("age");
        
        System.out.println(" name and surname:"+name+", classes or grades in school:"+banji+", age:"+age);
        return NONE;
    }
}

struts configuration

<action name="action3" class="cc.wenshixin.action.ActionWithAware">
    <!--  Because there is no return value, So there's no needresult label -->
    </action>

3.Encapsulating form data


In servlet, if you want to encapsulate the data in the form into an object, the usual practice is to first get the value of the page form, in new an object, set the properties of this object. Struts2 provides a simpler way to wrap form data into objects than this primitive wrapper.

3.1 Attribute encapsulation

Directly put the form submit The data encapsulated in the Action Class in the properties of。

Requirements for the Action class.

    1. Define data members in the Action class that have the same value as the form name property
    1. Generate data members corresponding to the set approach( It is recommended that the set approach harmonyget approach Write it all out.)

The sample code is as follows.

jsp page

  <form action="${pageContext.request.contextPath}/action1.action" method="post">
     name and surname:<input type="text" name="name"><br>
     classes or grades in school:<input type="text" name="banji"><br>
     age:<input type="text" name="age"><br>
  <input type="submit" value=" submit">
  </form>

Action Class

package cc.wenshixin.action;

import com.opensymphony.xwork2.ActionSupport;

public class ActionDemo1 extends ActionSupport{
    private String name; // in the form name and surname
    private String banji; // in the form classes or grades in school
    private int age; // in the form age

    public void setName(String name) {
        this.name = name;
    }

    public void setBanji(String banji) {
        this.banji = banji;
    }

    public void setAge(int age) {
        this.age = age;
    }
    
    @Override
    public String execute() throws Exception {
        System.out.println(" name and surname:"+name+", classes or grades in school:"+banji+", age:"+age);
        return NONE;
    }
}

struts configuration

  <package name="demo1" extends="struts-default" namespace="/">
    <action name="action1" class="cc.wenshixin.action.ActionDemo1">
    <!--  Because there is no return value, So there's no needresult label -->
    </action>
  </package>

From the above code, we will find that if the form has many data items, then there will be many properties in the Action, plus the set method, the Action class will become very bloated, the following expression wrapping way can effectively solve this problem.

3.2 Model-driven packaging

Using model-driven encapsulation, It is also possible to wrap form data in physical category targets in, This implementation is done by implementing a model-driven interface ModelDriven acquired by。

Implementation steps.

    1. prepare physical category code, and generates the attributes of the set harmony get approach。
    1. (located) at Action Class use in physical categorynew an physical category of targets, and implement the interface ModelDriven of getModel() approach。
    1. of the input item of the form in the pagenam The attribute value should be the same as the physical category The properties of the one-to-one correspondence。

The sample code is as follows.

jsp page

<form action="${pageContext.request.contextPath}/action2.action" method="post">
     name and surname:<input type="text" name="name"><br>
     classes or grades in school:<input type="text" name="banji"><br>
     age:<input type="text" name="age"><br>
  <input type="submit" value=" submit">

physical category

package cc.wenshixin.entity;

public class Student {
private String name;  // Name of student
     private String banji;  // Student's class
     private int age;  // Age of students

     // The get and set methods are omitted here
    
     // The toString() method of the entity class has been overridden to make it easier to print the values of the properties in the class
    @Override
    public String toString() {
        return "Student [name=" + name + ", banji=" + banji + ", age=" + age + "]";
    }
}

Action Class

package cc.wenshixin.action;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cc.wenshixin.entity.Student;

public class ActionDemo2 extends ActionSupport implements ModelDriven<Student>{
    private Student student = new Student();

    @Override
    public Student getModel() {
        // Returns the createdstudent targets
        return student;
    }
    
    @Override
    public String execute() throws Exception {
        System.out.println(student);
        return NONE;
    }
}

struts configuration

    <action name="action2" class="cc.wenshixin.action.ActionDemo2">
    <!--  Because there is no return value, So there's no needresult label -->
    </action>

3.3 Expression wrapping

Using expression wrapping allows you to wrap form data into physical category targets interior, Expression wrapping is actually a form of property wrapping, Here is a separate list of。

Implementation steps.

    1. prepare physical category code, and generates the attributes of the set harmony get approach。
    1. (located) at Action Class use in physical category statement physical category variables of the。
    1. In the form input item's name The attribute value is written as physical category variable name. properties in the form of an expression.

The sample code is as follows.

jsp page

  <form action="${pageContext.request.contextPath}/action3.action" method="post">
     name and surname:<input type="text" name="student.name"><br>
     classes or grades in school:<input type="text" name="student.banji"><br>
     age:<input type="text" name="student.age"><br>
  <input type="submit" value=" submit">
  </form>

physical category Same as the model-driven wrapper approach

Action Class

package cc.wenshixin.action;

import com.opensymphony.xwork2.ActionSupport;

import cc.wenshixin.entity.Student;

public class ActionDemo3 extends ActionSupport {
    private Student student; //  Student information in the form

    public Student getStudent() {
        return student;
    }

    public void setStudent(Student student) {
        this.student = student;
    }

    @Override
    public String execute() throws Exception {
        System.out.println(student);
        return NONE;
    }
}

struts configuration

    <action name="action3" class="cc.wenshixin.action.ActionDemo3">
    <!--  Because there is no return value, So there's no needresult label -->
    </action>

3.3 Comparison of Model-Driven and Expression Wrapping

Similarities. Both can encapsulate data into physical category targets in

Differences. Using a model driver only encapsulates the data into a physical category targets in, That is, in a Action Class It is not possible to use a model driver to encapsulate data into a different physical category targets in, This is because in Action Class A generic type that implements an interface can only be a physical category of, And using expression wrapping allows you to wrap the data in the form into a different physical category of targets in。

4.Encapsulating data into collections

In development, Sometimes you need to add inserts in bulk targets, This is where the data needs to be encapsulated into a collection, The general set used is List Collective and Map muster。

4.1 Encapsulating data into a List collection

Implementation steps:

    1. Write the entity class and generate the set and get methods for the properties.
    1. (located) at Action Class state in physical category of List muster, and generate list variable set harmony get approach
    1. In the page, use the List set expression

The sample code is as follows.

jsp page

  <form action="${pageContext.request.contextPath}/action4.action" method="post">
     name and surname:<input type="text" name="list[0].name"><br>
     classes or grades in school:<input type="text" name="list[0].banji"><br>
     age:<input type="text" name="list[0].age"><br>
    <br>
     name and surname:<input type="text" name="list[1].name"><br>
     classes or grades in school:<input type="text" name="list[1].banji"><br>
     age:<input type="text" name="list[1].age"><br>
  <input type="submit" value=" submit">
  </form>

physical category Same as above.

Action Class

package cc.wenshixin.action;

import java.util.List;

import com.opensymphony.xwork2.ActionSupport;

import cc.wenshixin.entity.Student;

public class ActionDemo4 extends ActionSupport {
    List<Student> list;

    public List<Student> getList() {
        return list;
    }

    public void setList(List<Student> list) {
        this.list = list;
    }
    
    @Override
    public String execute() throws Exception {
        for (Student student : list) {
            System.out.println(student);
        }
        return NONE;
    }
}

struts configuration

    <action name="action4" class="cc.wenshixin.action.ActionDemo4">
    <!--  Because there is no return value, So there's no needresult label -->
    </action>

4.2 Wrapping data into a Map collection

Implementation steps.

    1. Write the entity class and generate the set and get methods for the properties.
    1. Declare the Map collection of the entity class in the Action class and generate the set and get methods of the map variables
    1. In the page, use the map set expression

The sample code is as follows.

jsp page

  <form action="${pageContext.request.contextPath}/action5.action" method="post">
     name and surname:<input type="text" name="map['one'].name"><br>
     classes or grades in school:<input type="text" name="map['one'].banji"><br>
     age:<input type="text" name="map['one'].age"><br>
    <br>
     name and surname:<input type="text" name="map['two'].name"><br>
     classes or grades in school:<input type="text" name="map['two'].banji"><br>
     age:<input type="text" name="map['two'].age"><br>
  <input type="submit" value=" submit">
  </form>

physical category Same as above.

Action Class

package cc.wenshixin.action;

import java.util.Map;

import com.opensymphony.xwork2.ActionSupport;

import cc.wenshixin.entity.Student;

public class ActionDemo5 extends ActionSupport {
    Map<String, Student> map;

    public Map<String, Student> getMap() {
        return map;
    }

    public void setMap(Map<String, Student> map) {
        this.map = map;
    }
    
    @Override
    public String execute() throws Exception {
        for(String key : map.keySet())
        {
            Student student = map.get(key);
            System.out.println(student);
        }
        return NONE;
    }
}

struts configuration

    <action name="action5" class="cc.wenshixin.action.ActionDemo5">
    <!--  Because there is no return value, So there's no needresult label -->
    </action>

Recommended>>
1、DNF server has run down millions of players angry at Tencent
2、10 tips for writing efficient shell scripts under Linux
3、This Japanese hotel is so good everything moves on its own
4、The first large stadium intelligent system in Zhejiang Province is officially online
5、6 types of artificial neural networks often used in machine learning

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    Contact US

    Welcome to Intefrankly.

    Intefrankly is a platform that you can show your opnions related to IT technology, and communicates to the people who interested in IT and Artificial Intelligence area.