Search code examples
javaweb-applicationsstruts2actionognl

Could you explain what happens with Struts2 web application?


An action class

public class IndexAction extends ActionSupport implements SessionAware {
private int submitPage;
//getter-setter

a method

public String execute() {

        // this means that session is NEW
        if(!session.containsKey("progres")) {

            System.out.println("NEW session");
            System.out.println("level " + 1);
            session.put("level", 1);
            return SUCCESS;
        }

jsp page

<% Integer level = (Integer)session.getAttribute("level"); %>
<c:set var="level" scope="request" value='<%=session.getAttribute("level")%>' />
<!--<c:out value="Level: ${level}"/>-->

<h2>Task <c:out value="${level}"/></h2>
<s:form action="index">
<s:hidden name="submitPage" value="%{level}" />
...

When I first time visit this page it renders to this

<!--Level: 1-->

<h2>Task 1.</h2>


<form id="index" name="index" action="/Struts2HiberQuize_2/index.action" method="post">
<table class="wwFormTable">
    <input type="hidden" name="submitPage" value="0" id="index_submitPage"/>
    ...

Why hidden fild contains value="0", it must be value="1" ? This happens if page accesed first time. Next times that hidden value corresponds to var="level" as should.


Solution

  • Because the value is populated from the hidden field name attribute bound to action's int attribute that contains 0 value. You don't have a value in the value attribute because your expression returns nothing i.e. don't have level in the value stack.

    That is how it works: the tag reads the value from the value attribute and if it's null then it uses a value from the name attribute as OGNL expression. After the expression is evaluated the returned value rendered to the value attribute of the input tag.