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

SSH framework tour - struts2 (3)


struts.jpg

1.OGNL


1.1 OGNL Overview

OGNL, full name is Object-Graph Navigation Language (Object Navigation Language), is a powerful open source expression language, through a simple expression syntax you can access any property of the object, call the object's methods, traverse the entire object structure graph, to achieve field type conversion and other functions. OGNL is integrated into struts2 and is not part of the struts2 project. struts2 uses OGNL to replace the EL expressions in the original java web project.

1.2 OGNL structure

  • Expression (Expression)

Expressions are the heart of the entire OGNL, and OGNL parses expressions to know what to do, e.g., operations that take values from objects.

  • Root Object (Root Object)

The root object can be understood as the object on which OGNL operates, and the expression simply describes the operations done on this object. OGNL is called the Object Navigation Language, which means that objects are placed in a diagram, and other objects associated with this object can be found by using any one object as the root.

  • Context (Context)

OGNL also needs a contextual environment during the fetch operation. With the root object and expression, OGNL knows what operation to do to whom instead, but it also needs to know where this operation is executed, i.e. the contextual environment. The context environment Context is an object of type Map, and accessing an object in Context in an expression requires the use of the # sign plus the name of the object.

1.3 Simple use of OGNL

OGNL (located) at struts2 in, To combine struts2 together with the labels of the use, first of all introduce into OGNL of jar packet,(located) at jsp page in which we can then directly use OGNL The expression needs to be completed before use EL expression combination java What only code can do。

Bullseye.

Remember to configure the struts2 interceptor in the web.xml file.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
   <!--   introducestruts2 of the tag library -->
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 <!--  (located) atstruts2  Tagged in. use ognl  expression (math.) -->
  <s:property value="'ognl'.length()"/>
 <!--  The output of the page is ognl  The length of this string 4 -->
</body>
</html>

2.The value stack in Struts2


2.1 What is the value stack

In the original java web project, after the operation in the servlet, put the data into the domain object, and then use EL expressions in the jsp page to get the data value, the domain object can store and take the value in a certain range. A storage mechanism is also provided in struts2, similar to a domain object, which is a value stack that can also store and fetch values. This puts the data in the value stack in the Action class, so that you can get the data in the value stack in the page.

The value stack in English is ValueStack, It's actually struts2 An interface to the, but (not) OgnlValueStack be ValueStack implementation class of the, Browser access an action when requesting,struts2 The architecture will create a action instance will also create an instance of OgnlValueStack Example of the value stack of,OgnlValueStack Throughout Action Life cycle of an instance,struts2 use OGNL to put the request action The parameters in the encapsulated object are stored in the value stack, and through OGNL expression to read the values of the properties of objects in the value stack。

2.2 Value stack objects

The previously mentioned ActionContext and ServletActionContext have methods to get the ValueStack, you can go to the source code of these two classes, so through these two classes you can get a reference to the ValueStack object.

Difference between servlet and action.

    1. Servlets are created by default on the first access, only once, as a single instance of the object.
    1. Action is created on each access, and each time an action is accessed, an action object is created, corresponding to the creation of a value stack object.

The sample code is as follows.

proves that there is only one valueStack object in each action object.

package cc.wenshixin.action;

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

public class ActionDemo1 extends ActionSupport {
    @Override
    public String execute() throws Exception {
         //1. Get the object of ActionContext class
        ActionContext context = ActionContext.getContext();
         //2. Call the method to get a reference to the value stack object
        ValueStack stack1 = context.getValueStack();
        ValueStack stack2 = context.getValueStack();
         //3. Compare two value stack references to see if they are references to the same value stack object
         System.out.println(stack1==stack2);  // results in true
        return NONE;
    }
}

2.3 The internal structure of the value stack

The name suggests that the value stack has the structural properties of a stack in a data structure, first in, last out (last in, first out). You can look at the source code of the OgnlValueStack class or Debug the structure of the value stack and see that the value stack has two properties, root and context, which are the two main parts of the value stack. The root part is based on a List collection. The root property inherits from ArrayList and implements stacking and stacking functions to store actions and instances and requested parameters, and we generally manipulate the data in the root. The context is based on a Map collection, which is the OnglContext (context) that stores references to objects such as parameters, requests, responses, sessions, applications, etc.

Storage structure table for the context section

key (fixed)

value

request

Reference to request object

session

References to httpSesion objects

application

Reference to servletContext object

parameter

Passing the relevant parameters

att

The values of the three domain objects

A tag for debugging the value stack, s:debug, is provided in struts2, using which you can view the value stack structure and the stored values.

The relevant codes are as follows.

jsp page

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
   <!--   introducestruts2 of the tag library -->
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!--  usedebug Tab to see the values in the value stack -->
  <s:debug></s:debug>
</body>
</html>

Action Class

package cc.wenshixin.action;

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

public class ActionDemo2 extends ActionSupport {
    @Override
    public String execute() throws Exception {
        return "success";
    }
}

struts configuration

    <package name="demo1" extends="struts-default" namespace="/">
        <action name="action2" class="cc.wenshixin.action.ActionDemo2">
          <result name="success">/debug.jsp</result>
        </action>
    </package>

Debug's result 1

3.Related operations of the value stack


3.1 Value stack holds data

There are many ways to put data into the value stack, and a few common ways are described below.

3.1.1 Using the value stack object, call the set() method in the object

will be above Action Class Replace the part of the code in, Refresh the page, look overdebug Structure in the label, The value stack was found to have an extra map targets, use set() approach, will store the object into amap Assembling。

public String execute() throws Exception {
         //1. Get the object of ActionContext class
        ActionContext context = ActionContext.getContext();
         //2. Call the method to get a reference to the value stack object
        ValueStack stack = context.getValueStack();
        
         // call the set method   
        stack.set("name", " Simon");
        
        return "success";
    }

set method

3.1.2 Using the value stack object, call the push() method in the object

Change some of the code in the Action class above to the following, refresh the page, and look at the structure in the debug tab to see that there is an extra String object in the value stack, and that using the push() method will store the object in a String string.

public String execute() throws Exception {
         //1. Get the object of ActionContext class
        ActionContext context = ActionContext.getContext();
         //2. Call the method to get a reference to the value stack object
        ValueStack stack = context.getValueStack();
        
        // invoke push method
        stack.push(" Simon");
        
        return "success";
    }

push method

3.1.3 Defining variables in the Action, generating the get method of the variable

will be above Action Class Replace the code in, Refresh the page, look overdebug Structure in the label, The name of one more defined variable was found in the properties of the value stack, and the value of that property is Action The value assigned to this variable in。

package cc.wenshixin.action;

import com.opensymphony.xwork2.ActionSupport;

public class ActionDemo5 extends ActionSupport {
    
     private String name;  // Define variables
    
     //get method for generating variables
    public String getName() {
        return name;
    }

    @Override
    public String execute() throws Exception {
        name = " Simon"; // Assigning a value to a variable
        
        return "success";
    }
}

get method

3.1.4 Putting objects into the value stack

Implementation steps.

    1. Creating Entity Class Objects
    1. Defining variables for entity class objects
    1. Generating variables for get method

will be above Action Class Replace the code in, The object of the entity class creates itself, Refresh the page, look overdebug Structure in the label, The name of one more defined variable was found in the properties of the value stack, and the value of that property is Action The value assigned to this variable in。

package cc.wenshixin.action;

import com.opensymphony.xwork2.ActionSupport;

import cc.wenshixin.entity.Student;

public class ActionDemo6 extends ActionSupport {
//1. Define object variables, here you can also not create the object content, in the following new
    private Student student = new Student();
     //2. get method of the generated object
    public Student getStudent() {
        return student;
    }

    @Override
    public String execute() throws Exception {
         // Assigning values to objects
        student.setName(" Simon");
        student.setSex(" women");
        
        return "success";
    }
}

Storage object

3.1.5 Putting list sets into the value stack

Implementation steps.

    1. Creating Entity Class Objects
    1. Defines the list set variable of the entity class object
    1. Generating variables for get method

Change the code in the Action class above to the following, where the object of the entity class creates itself, refresh the page, and look at the structure in the debug tab to find that the value stack has an additional defined list collection name in its properties, and that the value of the property is the object added to the list collection in Action.

package cc.wenshixin.action;

import java.util.ArrayList;
import java.util.List;

import com.opensymphony.xwork2.ActionSupport;

import cc.wenshixin.entity.Student;

public class ActionDemo7 extends ActionSupport {

    private List<Student> list = new ArrayList<Student>();

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

    @Override
    public String execute() throws Exception {
        Student student1 = new Student();
        student1.setName(" Simon");
        student1.setSex(" male");
        
        Student student2 = new Student();
        student2.setName(" small red");
        student2.setSex(" women");
        
        list.add(student1);
        list.add(student2);
        
        return "success";
    }
}

list collection

3.2 Get the value stack data

The above is really Action Putting data in the value stack, The following is in the jsp pages use Struts2 label + OGNL Expressions bring this data to light。

3.2.1 Getting the value of a string

Use the code of the Action class in 3.1.3 above to display the value inside the string in the Action.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
   <!--   introducestruts2 of the tag library -->
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
  <!--  Get the value of a string -->
  <s:property value="name"/>
</body>
</html>

3.2.2 Getting the value of an object

Use the code from the Action class in 3.1.4 above to display the values of the objects in the Action, accessed by appending the following code to the jsp code above.

    <!--  Get the value of the object -->
  <s:property value="student.name"/>
  <s:property value="student.sex"/>

3.2.3 Getting the value of a list collection

There are three ways to get the values in a list collection.

Using the code of the Action class from 3.1.5 above, display the values of the list collection in the Action and append the following code to the jsp code above to access it.

  • The first way requires knowing the number of elements in the list collection.
 <!--  The first way to get list collection value in -->
  <s:property value="list[0].name"/>
  <s:property value="list[0].sex"/>
  <s:property value="list[1].name"/>
  <s:property value="list[1].sex"/>
  • The second way is through <s:iterator> Tag traversal <s:property> The value in the tag
<!--  The second way to get list collection value in -->
  <s:iterator value="list">
    <s:property value="name"/>
    <s:property value="sex"/>
  </s:iterator>
  • The third way uses # to fetch the elements of the list species

Mechanism: put the element objects from each traversal into context, use OGNL expressions to get the data in context requires special notation #

<!--  The third way to get list collection value in -->
  <s:iterator value="list" var="student">
    <s:property value="#student.name"/>
    <s:property value="#student.sex"/>
  </s:iterator>

3.2.4 Other means of access

Use the code of the Action class in 3.1.1 above to get the value stored on the value stack with the set() method, using the name of the value set in the set() method.

  <!--  Other means of access -->
  <s:property value="name"/>

use on top of 3.1.2 hit the target Action Class code, Access to push() The value that the method stores on the value stack, owing to use push() Method set value has no name, Only the set value, use Data name of the value stack top, Get the value based on the data name, But the way it's written is a bit odd, The array name follows。

  <!--  Other means of access -->
  <s:property value="[0].top"/>

1.4 Summary of the use of # and % in OGNL

1.4.1 Use of #

Get in front list The third way in the set, use finish # come and get context Data for species。

1.4.2 Use of %

struts2 The form input tag is also defined in the, If the struts2 in the form tag of the use OGNL Expressions are not recognized, need %{OGNL expressions} Only then can it be identified.

use on top of 3.1.3 hit the target Action Class code, Placing the value in a string in a form input item。

    <!-- struts2 of the form input items -->
  <s:textfield name="name" value="%{name}"></s:textfield>

Recommended>>
1、McGrawHill CEO AI in the classroom is here
2、How the Cloud Convergence UK works
3、Image recognition technology is advanced AI division chief reveals Apples selfdriving progress
4、Cryptocurrency trading dynamics the ethereum blockchain reigns supreme
5、Running ride with python3 under mac

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

    已发送

    朋友将在看一看看到

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

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号