formsjspstruts2action-mappingdmi

Why method prefix not working in Struts 2.3.32


I use Struts 2.3.32 and this is the code.

methodPrefix.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!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>
    <s:form action="methodPrefix" theme="simple">
        name: <br/>
        <s:textfield name="name"/>
        <br><br>
        <s:submit value="Create Person"/>
        <s:submit name="method:cancel" value="Cancel"/>
    </s:form>
</body>
</html>

MethodPrefixAction.java

   public class MethodPrefixAction 
    {
        private String name;
        private String message;
        
        public String execute() throws Exception
        {
            message = name + " create";
            return "success";
        }
        public String cancel() throws Exception
        {
            message = "cancel";
            return "success";
        }
        
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getMessage() {
            return message;
        }
        public void setMessage(String message) {
            this.message = message;
        }
    }

struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
    <constant name="struts.mapper.action.prefix.enabled" value="true" />
     
    <package name="default" extends="struts-default" namespace="">
        <action name="goMethodPrefixPage">
            <result>/chapter4/methodPrefix.jsp</result>
        </action>
        <action name="methodPrefix" class="example.chapter4.MethodPrefixAction">
            <result>/chapter4/methodPrefixResult.jsp</result>
        </action>
    </package>
</struts>

when I push Cancel button, It do not call cancel() method, just call execute() method.

I don't know why method: prefix not work.

I searched a lot, and I know method: prefix configuration is false by default in Struts 2.3.32, so I used a constant..... but it did not work


Solution

  • This constant

    <constant name="struts.mapper.action.prefix.enabled" value="true" />
    

    works only for action: prefix, not a method: prefix. So you should use the action attribute to submit tag.

    <s:submit action="cancel" value="Cancel"/>
    

    Note: If you have DMI turned off the action: prefix is still available.