Search code examples
javaformsstruts2struts-action

How to handle Action's form data that is not coming from JSP in Struts 2?


I have a form in search.jsp

<s:form name="employeeSearchForm" action="searchAction" method="post">
    <s:textfield name="id" label="Employee ID"/>
    <s:textfield name="name" label="Employee Name"/>
    <s:submit/>
</s:form>

In struts.xml

<package name="example" namespace="/" extends="default">

    <action name="searchAction" class="example.SearchAction">
        <result>/example/search.jsp</result>
    </action>

</package>

Then the SearchAction class

public class SearchAction extends ActionSupport {

    private String id;
    private String name;

    @Override
    public String execute() throws Exception {

        if ("".equals(id.trim())) {    //#1

        ...

    }

    ...
}

See the #1 line code, if I clicked submit button from the Form in search.jsp, the id field will not be null, but if I open http://127.0.0.1:8080/myapps/searchAction.action directly, id field will be null.

In this case, I can use field check in SearchAction.exeucte(), e.g. if (id != null) , but I doubt if it's the most elegant way.

Anyone can suggest better way?


Solution

  • private String id=""; \quick fix.

    But app shouldn't allow the user hitting the action directly user should be authenticated and/or authorized before.