-->

Struts2, best practice for using method={1}

2019-04-01 04:35发布

问题:

I'm new to Struts 2 and I've come across this syntax (recommended in the tutorial).

<action name="Register_*" method="{1}" class="Register">
    <result name="input">/member/Register.jsp</result>
    <result type="redirectAction">Menu</result>
</action>

I understand that it calls Register.{1} method. The problem is a user could put in another (random) value and cause a 500 error (which would correctly be logged as an error).

How can this be prevented?

回答1:

First of all it won't call the Register.{1} method. It would call Register_{1} where {1} might be an action type (usually edit, show e.t.c)

Meaning that the URL is actually

Register_View
Register_Edit
e.t.c.

So if a user manually changes the URL to something that is not there such as

Register_methodThatDoesNotExist

then struts 2 will return an error.

But why is this a problem? In any web application that uses any technology if the user tampers manually with the URL an error will be returned (also the 404)

What are you trying to prevent exactly?

Update:

To prevent 500 errors you can catch all actions (that do not match any rule) and redirect them in an error page. See the "Wildcard Default" default paragraph at the struts 2 wiki

http://cwiki.apache.org/WW/action-configuration.html

This must be at the end of the struts configuration



回答2:

In my applications we use it like this:

  <action name="*/*" class="{1}Action" method="{2}">
       <interceptor-ref name="CustomAuthStack" />       
            <result>/pages/{1}/{2}.jsp</result>
            <result name="input">/pages/error/denied.jsp</result>
            <result name="logout">/pages/error/denied.jsp</result>

            <!-- methods that come back to listing after processing -->
            <result name="remove" type="redirectAction">{1}/list</result>
            <result name="save"   type="redirectAction">{1}/list</result>
            <result name="enable"   type="redirectAction">{1}/list</result>

   ....

   </action>

for slashes in action like myapp/users/list you must enable slashes in action with the

<constant name="struts.enable.SlashesInActionNames" value="true" />

in the strus.xml.

so now you have a standard:

action --> UserAction jsp -----> users/list.jsp

etc.