How we can pass dojo EnhancedGrid Store items to spring MVC Controller and save in DB?

寵の児 提交于 2019-12-23 12:47:33

问题


My requirement is to do read, update, delete & insert operations of datas from DB using front end as DOJO & Spring MVC.

I am able to fetch the records from db and display in DOJO Enhanced Grid(Editable Grid). On editing the grid data, I don't know how to send the Grid Store Items to my Spring Controller and Update/Insert/Delete in my DB.

Here is the code I have tried to fetch the data from java controller to front end.

Controller Class

@RequestMapping(value="eiaProjectSummary", produces = "application/json")
public @ResponseBody Map<String, Object> getEIAProjectSummary(
    @RequestParam(required = true) String prodGroupId,
    @RequestParam(required = true) List<Integer> eiaValues
    ) {         
    Map<String, Object> returnList = new HashMap<String, Object>();         
    List<PCPTAnalysisBean> pcptList = //getting the list of records from DB.        
    returnList.put("eiaProjSummaryList", pcptList);         
    return returnList;
}  

Javascript

dojo.xhrGet({       
    url: "pcptAnalysis/eiaProjectSummary.json?prodGroupId="+ prodGrpId +"&eiaValues="+eiaValues,
    handleAs: "json",
    preventCache: true,
    load: function(response) {
        var resultsGrid = new dojo.data.ItemFileReadStore({
            data: {
                items:response.eiaProjSummaryList
            }
        });
        grid = new dojox.grid.EnhancedGrid({store: resultsGrid,
            structure: layout,
            selectionMode: "multiple",
            rowSelector: '0px'
        });
    }
});

Similarly, I need to send the edited Grid Store Items from Javascript to My Controller Class. I don't know how to send my Grid Store data from javascript ajax post and how to receive it in my Controller class method. Kindly help me.


回答1:


Have a look at this working demo, it does a save from a browser Dojo client to a spring MVC backend.

3 JSON Customers are passed in a POST request, simulating the contents of a grid: two elements where in the grid, and one was added.

The 3 elements get sent in the POST request as JSON, and get all saved into a database using JPA. The server returns back a JSON response containing the 3 saved customers or an error - see demo code here

See the demo working:

Installation and running instructions:

git clone https://mydevutils@bitbucket.org/mydevutils/dojo-spring-mvc-hello-world.git
mvn clean install tomcat7:run-war 

Then open a browser and go to:

http://localhost:8080

The demo needs a Postgres local database to work, which is well worth having locally for development purposes.

@Controller
public class DojoSpringMvcController {


    @Autowired(required =true)
    private CustomerService customerService;

    @RequestMapping(method = RequestMethod.POST  , value = "/hello", produces = {MediaType.APPLICATION_JSON_VALUE})
    @ResponseBody
    public List<Customer> sampleController(@RequestBody List<Customer> customers) {

        for (Customer current : customers) {
            customerService.saveCustomer(current);
        }

        return customers;
    }
}

The client code:

When the 'Send To Server' button is pushed, this code get's executed to send the data:

    var gridData = [{ssn:'0050', lastName: 'Customer1'}, {ssn: '0051', lastName:'Customer2'} ];

    function send() {

      var ssn = document.getElementsByName('ssn')[0].value;
      var lastName = document.getElementsByName('lastName')[0].value;

      var newCustomer = {'ssn': ssn, 'lastName': lastName };

      // add to list of existing customers and do a POST with everything
     gridData.push(newCustomer);

      dojo.xhrPost({
          url: 'http://localhost:8080/dojo-hello-world/hello',
          postData: dojo.toJson(gridData),
          handleAs: "text",
          headers: {
             'Content-Type': 'application/json',
          },
          load: function(response) {
             console.log('Response: ' + response);
             alert('JSON received from server:' + response);
          },
          error: function(error) {
                console.log(error);
                alert('error occurred, check the console!');
          }
      });

    }



回答2:


Well, first you would need event listeners in your JavaScript (Dojo) that are invoked when a user desires to update, delete, or insert a new row. You would then grab the necessary data from the object in the row that is to be modified. For inserting and updating, you could use dojo.xhrPut and/or dojo.xhrPost. See this discussion for a good definition of the differences between HTTP PUT and POST. For deleting a record, you would naturally use the dojo.xhrDelete.

On the Spring side, utilize the @ModelAttribute to parse request parameters into Java Object. Below is an example in which ProjectSummary is a pre-defined POJO with getters and setters matching the request parameters expected for the update.

@RequestMapping(value = "/projectsummary/{id}", method = RequestMethod.PUT)
public void updateProjectSummary(@ModelAttribute("projectSummary") ProjectSummary projectSummary, @PathVariable long summmaryId, Model model) {
  projectSummary.setId(summaryId);

  // a pre-defined service object
  service.updateProjectSummary(projectSummary);

  model.addAttribute("success", true);
}

To use POST or DELETE instead of PUT, you would change RequestMethod.PUT to RequestMethod.POST or RequestMethod.DELETE. For the delete, you probably would not need the model attribute but just an identifier passed in the URL for the resource to be deleted. For the POST, it should be very similar to the PUT.

I hope this is helpful enough to get you started.



来源:https://stackoverflow.com/questions/21065047/how-we-can-pass-dojo-enhancedgrid-store-items-to-spring-mvc-controller-and-save

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!