Struts2 using the OGNL expression language to access static and static properties and the problems and workarounds I encounter

Source: Internet
Author: User
Tags modifiers tomcat server

1. In the previous article, I introduced the OGNL expression language, which I wanted to add to the article with an example of using OGNL to access static and static properties, but last night when I wrote the code, I reported a warning to get the value of the static property, but not the return value of the static method. So write a special article today to introduce.



2. Here I enclose this example to learn how to use OGNL expressions to access static methods and properties.

(1). Where the syntax for accessing static or static properties is: The path of the @ class @ Method name, the @ class path @ property name, the path to the class in the syntax, the package name + class name.


(2). For OGNL, Java.lang.Math is its default class, and if you call Java.lang.Math's static method, you do not need to specify the name of the class, for example: @ @min (4,10), compare the two who are smaller and output the smaller number.


Note: The 1th of these is also understood to call a static and static property of a class, where 2nd can also be understood as invoking a static method in the JDK class.


(3). The project structure is as follows:



(4). First create a new STRUTS2 project, the project name is Statictest, create a new class, placed under the COM.GK package, the class name is Statictest, the complete code is as follows:

Package Com.gk;public class Statictest{public static string str= ' static property ';p ublic static string s () {return ' static Method ";}}

Open the Index.jsp page, change the encoding format to Utf-8, add <%@ taglib uri= "/struts-tags" prefix= "s"%>, you can use struts tags, the code is as follows:

<%@ page language= "java" import= "java.util.*" pageencoding= "Utf-8"%><%@ taglib uri= "/struts-tags" prefix= "s" %><%string path = Request.getcontextpath (); String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >


Be sure to configure the Struts.xml configuration file to allow access to static methods using OGNL, otherwise you cannot use OGNL to access static methods, you must include this line of code in the Struts.xml file:

<constant name= "Struts.ognl.allowStaticMethodAccess" value= "true" ></constant>

The complete Struts.xml file is as follows:

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE struts public    "-//apache software foundation//dtd struts Configuration 2.0//en"    "/http Struts.apache.org/dtds/struts-2.0.dtd "><struts><constant name=" Struts.enable.DynamicMethodInvocation "value=" true "></constant><constant name=" Struts.devmode "value= "True" ></constant><constant name= "struts.ognl.allowStaticMethodAccess" value= "true" ></constant ></struts>


(5). Then deploy the project to the Tomcat server, open the Tomcat server, and run as follows:

Why is the return value of a static method not being taken? Very strange!


3. Find the Access static method, not get its return value, and then look at the console, with a warning message, but not an error, as shown in the warning message:



This warning message made me do it. The console output information is com.opensymphony.xwork2.ognl.SecurityMemberAccess warn class warning, which is the target class [class Com.gk.StaticTest] or declaring class of member type [public static java.lang.String Com.gk.statictest.s ()] is excluded! , which means that the target class Staictest class or the member type of the declaring class [public static Java.lang.String Com.gk.statictest.s ()] is excluded, was driven out, indicating that this means, I have Baidu a bit, Found a small part of the students will report this error, but did not solve, so I went to check the underlying code, see can see why?


(1). This warning is com.opensymphony.xwork2.ognl.SecurityMemberAccess warn, so I found this securitymemberaccess class, It is placed under the COM.OPENSYMPHONY.XWORK2.OGNL package, and this package is placed under the Xwork-core-2.3.20.jar package, so we have to import this package source code to view, this import I said in the previous article, It is shown here again in the form of graphs:

First find this JAR package:

Select the jar package, then right-click, select Properties, find the package you need to download the build environment, and find the Xwork-core related file, e:/struts-2.3.20/struts-2.3.20/src/ Xwork-core/src/main/java, copy the red box to the place, click the arrow pointing to the two buttons, first apply the Apply button, then click OK OK button:

So we can open the. class file under this jar package, all of which are familiar Java code.


(2). Open the Securitymemberaccess class under the COM.OPENSYMPHONY.XWORK2.OGNL package, as shown:

When you double-click Open, the code is as follows:

/* Copyright 2002-2006,2009 the Apache software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * You are not a use this file except in compliance with the License. * Obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * unless required by app Licable law or agreed into writing, software * Distributed under the License is distributed on a "as is" BASIS, * Withou T warranties or CONDITIONS of any KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package Com.opensymphony.xwork2.ognl;import Com.opensymphony.xwork2.util.logging.logger;import Com.opensymphony.xwork2.util.logging.loggerfactory;import OGNL. Defaultmemberaccess;import Java.lang.reflect.member;import Java.lang.reflect.method;import Java.lang.reflect.modifier;import Java.util.collections;import Java.util.map;import Java.util.Set;import Java.util.regex.matcher;import Java.util.regex.pattern;/** * Allows access decisions to being made on the basis of whether a member are static or not. * Also blocks or allows access to properties. */public class Securitymemberaccess extends Defaultmemberaccess {private static final Logger LOG = Loggerfactory.getlo    Gger (Securitymemberaccess.class);    Private Final Boolean allowstaticmethodaccess;    Private set<pattern> excludeproperties = Collections.emptyset ();    Private set<pattern> acceptproperties = Collections.emptyset ();    Private set<class<?>> excludedclasses = Collections.emptyset ();    Private set<pattern> Excludedpackagenamepatterns = Collections.emptyset ();        Public Securitymemberaccess (Boolean method) {super (FALSE);    Allowstaticmethodaccess = method;    } public boolean getallowstaticmethodaccess () {return allowstaticmethodaccess;     } @Override public Boolean isaccessible (Map context, Object target, Member Member, String PropertyName) {   if (checkenumaccess (target, member)) {if (log.istraceenabled ()) {Log.trace ("allowing access            to enum #0 ", target);        } return true; } if (Ispackageexcluded (Target.getclass (). Getpackage (), Member.getdeclaringclass (). Getpackage ())) {if ( Log.iswarnenabled ()) {Log.warn ("package of Target [#0] or package of member [#1] is excluded!", Target, M            Ember);        } return false;                } if (Isclassexcluded (Target.getclass (), Member.getdeclaringclass ())) {if (log.iswarnenabled ()) {            Log.warn ("Target class [#0] or declaring class of member type [#1] is excluded!", Target, member);        } return false;        } Boolean allow = true; if (!checkstaticmethodaccess (member)) {if (log.istraceenabled ()) {Log.warn ("Access to Static [            #0] is blocked! ", member);        } allow = false;   }     Failed static test if (!allow) return false;                Now check for standard scope rules return Super.isaccessible (context, Target, member, PropertyName)    && Isacceptableproperty (PropertyName);        } protected Boolean checkstaticmethodaccess (Member Member) {int modifiers = member.getmodifiers ();        if (modifier.isstatic (modifiers)) {return allowstaticmethodaccess;        } else {return true;            }} protected Boolean checkenumaccess (Object target, Member Member) {if (target instanceof Class) {            Class Clazz = (Class) target;        if (Enum.class.isAssignableFrom (clazz) && member.getname (). Equals ("values") return true;    } return false; } protected Boolean ispackageexcluded (Package Targetpackage, package memberpackage) {for (Pattern Pattern:exc Ludedpackagenamepatterns) {if (Pattern.matcher (targetpackagE.getname ()). Matches () | |            Pattern.matcher (Memberpackage.getname ()). Matches ()) {return true;    }} return false;  } protected Boolean isclassexcluded (class<?> targetclass, class<?> declaringclass) {if (Targetclass = = Object.class | |        Declaringclass = = Object.class) {return true;  } for (class<?> excludedclass:excludedclasses) {if (Targetclass.isassignablefrom (Excludedclass) ||            Declaringclass.isassignablefrom (Excludedclass)) {return true;    }} return false; } protected Boolean Isacceptableproperty (String name) {return name = = NULL | |    (!isexcluded (name)) && isaccepted (name)); } protected Boolean isaccepted (String paramname) {if (!this.acceptproperties.isempty ()) {for (patte                RN pattern:acceptproperties) {Matcher Matcher = Pattern.matcher (paramname); if (Matcher.matChes ()) {return true;        }}//no match, but Acceptedparams was not empty return false;    }//empty Acceptedparams return true; } protected Boolean isexcluded (String paramname) {if (!this.excludeproperties.isempty ()) {for (Patt                Ern pattern:excludeproperties) {Matcher Matcher = Pattern.matcher (paramname);                if (Matcher.matches ()) {return true;    }}} return false; } public void Setexcludeproperties (set<pattern> excludeproperties) {this.excludeproperties = ExcludePrope    Rties; } public void Setacceptproperties (set<pattern> acceptedproperties) {this.acceptproperties = AcceptedPrope    Rties; } public void Setexcludedclasses (set<class<?>> excludedclasses) {this.excludedclasses = ExcludedCla    sses; } public void SetexcludedpackagenamEpatterns (set<pattern> excludedpackagenamepatterns) {this.excludedpackagenamepatterns = ExcludedPackageNameP    Atterns; }}


The code is not much, we only see the important, you can look at the code through the outline:


Outline of variables, constants, and methods, one click to see, which I found the error of the line, but did not know how to solve the problem, depressed! As shown in the following:


It is to report this line of warning, this line of warning is determined by judging isclassexcluded this method:

This method determines whether the target class and the superclass are equal or declares whether the class and superclass are the same. The same words return true, this is not much to explain, and then we error the line of the image of the two classes, one is the target class, a declaration class, and this declaration class is obtained through the members, which do not know why, So look at the underlying code and do not understand, so can only ask for my enthusiastic group of friends.

Note: Why do I want to introduce the underlying code here, because it helps us understand and learn why the code is written and why this warning is reported. Because the level is limited, so I also depressed!


(3). I went to consult my group of friends, my group is Andro, made a complaint, the group of friends asked you have encountered any problem, say, see I understand no, I told them this question, after a while a group of friends said I went to Struts's official website to check the next, Said the latest version of STRUTS2 does not support the OGNL access static method, it is estimated that because of security issues, access to static methods afraid of unsafe, think I use is really the latest version, I said no wonder the teacher asked us to use a more stable version, do not use the latest, sure enough, I copy the core code of the above project to the lower version of the project, it is possible, really twists ah!



4. The code of the above example is correct, because of the version problem, only can use OGNL access to static properties, and not access static methods, so I use the lower version of the jar package, I put some code above this project copy, adjust, change some names, etc., I use the version of:

After everything is done, the effect is as follows:

This allows you to use OGNL to access the static method and get the value to get it.



5. Summary: for using the OGNL expression language to access the static method, this is less used, if you use OGNL to access the static method, but get not the value, and the console output as I described above some of the warning information, it is possible that your version is the latest reason, the code is not wrong, Therefore, it is recommended to use a more stable version, using the more stable version, through the above example, you can use OGNL to access the static method and get the return value of its static method.



6. The above content is only for you to learn the reference, write bad, please forgive me, if there is a problem, please point out, such as the article has errors, please point out, thank you!

.

Struts2 using the OGNL expression language to access static and static properties and the problems and workarounds I encounter

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.