Shikha Dhawan
Shikha Dhawan

Reputation: 1424

Struts2-Jquery Grid : Data not getting displayed

I'm using struts2-jquery grid.

gridmodel in my action class is getting updated correctly. But, nothing is getting displayed on the grid.

struts.xml

<struts>

    <package name="default" namespace="/searchAndUpdate" extends="struts-default,json-default">

        <action name="listUsers" class="com.pilot.web.action.ListUsers" method="getJSON">
            <result name="success">/jsp/userList.jsp</result>
            <result name="input">/jsp/userList.jsp</result>
        </action>
</package> 

userList.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib prefix="sj" uri="/struts-jquery-tags"%>
<%@ taglib prefix="sjg" uri="/struts-jquery-grid-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<sj:head jqueryui="true" jquerytheme="redmond"/>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="Content-Style-Type" content="text/css" />
</head>
<body>
<h3>Application Users</h3>
<s:actionerror/>
<s:actionmessage/>
<s:url id="remoteurl" action="/searchAndUpdate/listUsers"/>
    <sjg:grid
        id="gridtable" 
        caption="Application Users" 
        dataType="json" 
        href="%{remoteurl}" 
        pager="true" 
        gridModel="gridModel" 
        rowList="10,15,20" 
        rowNum="15" 
        rownumbers="true" 
        resizable="true" 
        viewrecords="true" 
    >
        <sjg:gridColumn name="id" index="id" title="Id" formatter="integer" sortable="false"/>
        <sjg:gridColumn name="userName" index="userName" title="User Name" sortable="true"/>
        <sjg:gridColumn name="fullName" index="fullName" title="Full Name" sortable="false"/>
        <sjg:gridColumn name="email" index="email" title="EMail" sortable="false"/>
    </sjg:grid>
</body>
</html>

ListUsers.java

package com.pilot.web.action;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import com.opensymphony.xwork2.ActionSupport;
import com.oxxo.pilot.backend.jdbc.dao.impl.User;


public class ListUsers extends ActionSupport {
        private static final long serialVersionUID = 1L;
        private List<User> gridModel;
        //get how many rows we want to have into the grid - rowNum attribute in the grid
        private Integer rows = 0;
        //Get the requested page. By default grid sets this to 1.
        private Integer page = 0;
        // Your Total Pages
        private Integer total = 0;
        // All Records
        private Integer records = 0;
        // sorting order - asc or desc
        private String sord;
        // get index row - i.e. user click to sort.
        private String sidx;
        public String getAllApplicationData() {
                List<User> users = userListFromDb();
                if (users != null && getSord() != null
                                && getSord().equalsIgnoreCase("asc")) {
                        Collections.sort(users, null);
                }
                if (getSord() != null && "desc".equalsIgnoreCase(getSord())) {
                        Collections.sort(users, null);
                        Collections.reverse(users);
                }
                setRecord(users.size());
                int to = (getRows() * getPage());
                if (to > getRecord())
                        to = getRecord();

                setGridModel(users);
                setTotal((int) Math.ceil((double) getRecord() / (double) getRows()));
                System.out.println("Total is : " + getTotal());
                System.out.println("Record is : " + getRecord());
                for(User user: users){
                        System.out.println(user.getUserName() + ", " + user.getFullName() + ", " + user.getEmail());
                }
                if (hasActionMessages() || hasActionErrors()) {
                        return INPUT;
                }
                return SUCCESS;
        }

        private List<User> userListFromDb() {
           // MOCKED List for now
                List<User> users = new ArrayList<User>();
                User user1 = new User();
                user1.setId(1);
                user1.setUserName("user1");
                user1.setFullName("User ABC");
                user1.setEmail("[email protected]");

                User user2 = new User();
                user2.setId(1);
                user2.setUserName("user2");
                user2.setFullName("User DEF");
                user2.setEmail("[email protected]");

                users.add(user1);
                users.add(user2);
                return users; // TODO FETCH LIST OF USERS FROM DB
        }

        public String getJSON() {
                System.out.println("here in getJSON");
                return getAllApplicationData();
        }

        public Integer getRows() {
                return rows;
        }

        public void setRows(Integer rows) {
                this.rows = rows;
        }

        public Integer getPage() {
                return page;
        }

        public void setPage(Integer page) {
                this.page = page;
        }

        public Integer getTotal() {
                return total;
        }

        public void setTotal(Integer total) {
                this.total = total;
        }

        public Integer getRecord() {
                return records;
        }

        public void setRecord(Integer records) {
                this.records = records;
                if (this.records > 0 && this.rows > 0) {
                        this.total = (int) Math.ceil((double) this.records
                                        / (double) this.rows);
                } else {
                        this.total = 0;
                }
        }
        public List<User> getGridModel() {
                return gridModel;
        }
        public void setGridModel(List<User> gridModel) {
                this.gridModel = gridModel;
        }
        public String getSord() {
                return sord;
        }
        public void setSord(String sord) {
                this.sord = sord;
        }
        public String getSidx() {
                return sidx;
        }
        public void setSidx(String sidx) {
                this.sidx = sidx;
        }
        public void setSearchField(String searchField) {
        }

        public void setSearchString(String searchString) {
        }

        public void setSearchOper(String searchOper) {
        }

        public void setLoadonce(boolean loadonce) {
        }
        public void setSession(Map<String, Object> session) {
        }
}

I did refer to the solution on struts2 jquery grid data not load?

But that solution did not work. Instead of data getting displayed on the grid, it prompted to save the file & that file contained the following info:

{"JSON":"success","gridModel":[{"email":"[email protected]","fullName":"User ABC","id":1,"userName":"user1"},{"email":"[email protected]","fullName":"User DEF","id":1,"userName":"user2"}],"page":0,"record":2,"rows":0,"sidx":null,"sord":null,"total":2147483647}*

As per my understanding row & page are automatically handled by the plugin. But as per the json data above they are not getting incremented. Hard-coded them to the size of the gridmodel and the json data I got is:

{"JSON":"success","allApplicationData":"success","gridModel":[{"email":"[email protected]","fullName":"User ABC","id":1,"userName":"user1"},{"email":"[email protected]","fullName":"User DEF","id":1,"userName":"user2"}],"page":1,"record":2,"rows":2,"sidx":null,"sord":null,"total":1}

On updating struts.xml as

 <result-types>
        <result-type name="json" class="org.apache.struts2.json.JSONResult" />
        </result-types>
        <action name="listUsers" class="com.oxxo.pilot.web.action.ListUsers">
            <result name="success" type="json">/jsp/userList.jsp</result>
            <result name="input" type="json">/jsp/userList.jsp</result>
        </action>

the json data is displayed on the browser.

Thanks, Shikha

Upvotes: 0

Views: 9425

Answers (3)

Shikha Dhawan
Shikha Dhawan

Reputation: 1424

The correct solution is :

Struts.xml:

<result-types>
            <result-type name="json" class="org.apache.struts2.json.JSONResult" />
        </result-types>

<action name="listUsers" method="getAllApplicationData"   class="com.pilot.web.action.ListUsers">
            <result name="success">/jsp/userList.jsp</result>
            <result name="input">/jsp/fail.jsp</result>
        </action>
        <action name="getData" method="getAllApplicationData"   class="com.pilot.web.action.ListUsers">
            <result name="success" type="json"></result>
        </action>

Index.jsp

<s:form action="/searchAndUpdate/listUsers" method="post">
        <s:submit name="ListUsers" value="List All Users" align="right" />
    </s:form>

userList.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib prefix="sj" uri="/struts-jquery-tags"%>
<%@ taglib prefix="sjg" uri="/struts-jquery-grid-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<sj:head jqueryui="true" jquerytheme="redmond"/>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="Content-Style-Type" content="text/css" />
</head>
<body>
<h3>Application Users</h3>
<s:actionerror/>
<s:actionmessage/>
<s:url id="remoteurl" action="/searchAndUpdate/getData"/>
    <sjg:grid
        id="gridtable" 
        caption="Application Users" 
        href="%{remoteurl}" 
        pager="true" 
        gridModel="gridModel" 
        rowList="10,15,20" 
        rowNum="15" 
        rownumbers="true" 
        resizable="true" 
        viewrecords="true" 
        name="gridModel" 
    >
        <sjg:gridColumn name="id" index="id" title="Id" formatter="integer" sortable="false"/>
        <sjg:gridColumn name="userName" index="userName" title="User Name" sortable="true"/>
        <sjg:gridColumn name="fullName" index="fullName" title="Full Name" sortable="false"/>
        <sjg:gridColumn name="email" index="email" title="EMail" sortable="false"/>
    </sjg:grid>
</body>
</html>

This is a working code. Working perfectly fine :)

The issue was : The jsp accepts data type json as an input & the action ListUsers has to render a jsp. So, I made two different actions. One that returns "json" which serves as an input to the jsp & one which renders the jsp on success.

Upvotes: 3

batbaatar
batbaatar

Reputation: 5468

Try to have 2 methods that return parameters in your action class. If the result name is INPUT you should return normal parameters. And when you query your grid values you should return JSON. What am I saying is change your action results to this:

<action name="listUsers_*" method={1} class="com.oxxo.pilot.web.action.ListUsers">
    <result name="success" type="json">/jsp/userList.jsp</result>
    <result name="input">/jsp/userList.jsp</result>
</action>

And in your action class

public String execute() throws Exception { return INPUT;}
public String getJSON() { return getAllApplicationData();}

I don't know if execute() method normally returns INPUT when it is not implemented

In your page, add getJSON to call getJSON method on your action class.

<s:url id="remoteurl" action="listUsers_getJSON"/>

Hope this helps, and let me know if you worked it out

Upvotes: 0

coding_idiot
coding_idiot

Reputation: 13734

action should return JSON.

 <action name="listUsers" class="com.pilot.web.action.ListUsers" method="getJSON">
            <result name="success" type="json"/>
        </action>

You can find a few grid examples here.

Upvotes: 0

Related Questions