null
null

Reputation: 9114

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?

Upvotes: 0

Views: 1242

Answers (2)

Aleksandr M
Aleksandr M

Reputation: 24396

In web environment it is usually hard to tell whether user provided input or not (empty vs null). In your case you can validate values using Struts2 validation http://struts.apache.org/2.x/docs/validation.html.

Upvotes: 0

MohanaRao SV
MohanaRao SV

Reputation: 1125

private String id=""; \quick fix.

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

Upvotes: 1

Related Questions