Search code examples
springspring-mvctiles2

How to Update a JSP in Spring MVC and Apache Tiles


I am using Apache Tiles 2 in my Spring 3 MVC application,the layout is : a menu on the left and body on the right.

layout.jsp

<table>
  <tr>
    <td height="250"><tiles:insertAttribute name="menu" /></td>
    <td width="350"><tiles:insertAttribute name="body" /></td>
  </tr>
</table>

menu.jsp

<div><ul>
<li><a href="account.html">account</a></li>
<li><a href="history.html">history</a></li></ul></div>

body of history.jsp

<c:forEach var="history" items="${histories}"><p><c:out value="${history}"></c:out></p></c:forEach>

I also have a controller for history

@Controller 
public class HistoryController {

@RequestMapping("/history")
public ModelAndView showHistory() {

    ArrayList <String> histories = read from DB.
    return new ModelAndView("history","histories",histories);

   }
}

So, everytime when I click the history link at the menu, the showHistory() is called.

But there is a more complicate case. The history DB has hundreds entries, so we decide to display the first 10 only when history.jsp displays first time, then add a "show more histories" button to the history.jsp to display the next 10 by we adding another controller.

The problem is, when a user does the following:

  1. clicks history link, it shows 0-9 histories,
  2. clicks "show more histories" to display 10 to 19,
  3. clicks account link to go back to the account page,
  4. clicks history link again, instead of the history.jsp display 10 to 19, it displays 0-9.

How can I make the history.jsp to display the last visited histories instead of display from the beginning.

I am very new to Spring, all suggestions are welcome. Thanks.


Solution

  • What you would do is store in the session the last requested range. If the user does not specify a range (in the request) you use the session stored on.

    Something like this

    @RequestMapping("/history")
    public ModelAndView showHistory(@RequestParam(value="startIndex", defaultValue="-1") Integer startIndex, HttpSession session) {
        Integer start = Integer.valueOf(0);
        if (startIndex == null || startIndex.intValue() < 0) {
            // get from session
            Integer sessionStartIndex = (Integer) session.getAttribute("startIndex");
            if (sessionStartIndex != null) {
                start = sessionStartIndex;
            }
        } else {
            start = startIndex;
        }
        session.setAttribute("startIndex", start);
        ArrayList <String> histories = read from DB, starting with start.
        return new ModelAndView("history","histories",histories);
    
       }