In the previous section, we completed using DataGrid to display all product information. In this section, we started to add several functions: add, update, delete and query. First, we implement the display in the front desk, and then do the background to obtain data.
1. Foreground implementation of adding, updating, deleting and querying functions
There is a toolbar property in the DataGrid control, which adds the toolbar. We can add these buttons to the toolbar property to achieve corresponding functions. Let’s first look at the official documentation’s definition of toolbar:
We use arrays to define the toolbar and add the following code to the query.jsp page:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <%@ include file="/public/head.jspf" %> <style type="text/css"> body { margin: 1px; } .searchbox { margin: -3; } </style> <script type="text/javascript"> $(function(){ $('#dg').datagrid({ // Change the url address to request categoryAction url:'category_queryJoinAccount.action', singleSelect:false, //If true, only single line display is allowed, the selection all function is invalid //Set pagination pagination:true, //Set the number of records displayed per page, the default is 10 pageSize:5, //Set the optional number of records per page for user selection, the default is 10,20,30,40... pageList:[5,10,15,20], idField:'id',//Specify id as the identification field, which is useful when deleting and updating. If you configure this field, page change will not affect the selected item when turning the page/***************************************/ toolbar: [{ iconCls: 'icon-add', text:'Add category', handler: function(){ alert('--add category--'); } },'-',{ iconCls: 'icon-edit', text:'Update category', handler: function(){ alert('--update category--'); } },'-',{ iconCls: 'icon-remove', text:'Delete category', handler: function(){ //Judge whether there are selected row records, use getSelections to get all selected rows var rows = $("#dg").datagrid("getSelections"); //Return the selected row, if no rows are selected, return an empty array if(rows.length == 0) { //Pop up the prompt message $.messager.show({ //The syntax is similar to static methods in java. Direct object calls title:'Error prompt', msg:'at least one record must be selected', timeout:2000, showType:'slide', }); } else { // Prompt whether to confirm the deletion. If confirmed, execute the logic of deletion $.messager.confirm('Delete Confirm dialog', 'Are you sure you want to delete this item? ', function(r){ if (r){ // Exit operation; alert("--Delete operation--") } }); } } } },'-',{ //The query button is not a LinkButton, it has syntax, but it also supports parsing HTML tag text:"<input id='ss' name='ss' name='ss' />" }], //Convert the ordinary text box into a query search text box $('#ss').searchbox({ //Trigger the query event searcher:function(value,name){ //Value represents the entered value//Query operation}, prompt:'Please enter the search keyword' //Default display}); /******************************************************************/ }); </script> </head> <body> <table id="dg"></table> </body> </html>In this way, we have set up a foreground framework for adding, updating, deleting and querying. Now it can be displayed in the foreground. There is no data coming in the background, just a prompt box pops up, but the display function has been completed. Let’s take a look at the effect:
Next, we will complete the corresponding functions one by one.
2. Implementation of DataGrid category query
The query implementation is the simplest. Enter the keyword in the search box, then pass the keyword as a parameter to the action, and then the Service takes out the data from the database, packages it into json format and passes it to the front desk for display. This process is the same as the product information displayed before. We only need to add the code for the search part in the above jsp, and there is no need to change the other codes. The added code is as follows:
//Convert the ordinary text box into a query search text box $('#ss').searchbox({ //Trigger the query event searcher:function(value,name){ //value represents the input value//alert(value + "," + name) //Get the keyword of the current query, load the corresponding information through DataGrid, and use load to load and display all lines on the first page. //If a parameter is specified, it will replace the 'queryParams' attribute. Usually, you can execute a query by passing some parameters. By calling this method, you will send a request to the action specified by the url above and load new data from the server. $('#dg').datagrid('load',{ type: value }); }, prompt:'Please enter the search keyword' });The load method can load all rows on the first page. It has a parameter. If specified, it will bring queryParams with it. Otherwise, the parameters specified by queryParams above are passed by default. Here we set the type to the value of value, that is, the query keyword entered by the user, and then pass it to the action. The background searches in the database based on the value entered by the user and returns it to the foreground. The execution results are as follows:
In this way, I completed the search function, which is relatively simple.
3. Implementation of DataGrid category deletion
Now let’s implement the delete function. From the above jsp, we can see that before deletion, we determine whether the user has selected a record. If not, we will give the user a prompt. If it is selected, a pop-up window will allow the user to confirm. If it is true, the delete function will be executed. There is a detail to note. If you want to delete multiple records at once, the singleSelect property above should be set to false.
First, we have supplemented the code deleted in query.jsp above, see below:
{ iconCls: 'icon-remove', text:'Delete category', handler: function(){ //Judge whether there are selected row records, use getSelections to get all selected rows var rows = $("#dg").datagrid("getSelections"); //Return the selected row, if no rows are selected, return an empty array if(rows.length == 0) { //Pop up the prompt message $.messager.show({ //The syntax is similar to static methods in java. Direct object calls title:'Error prompt', msg:'at least one record must be selected', timeout:2000, showType:'slide', }); } else { // Prompt whether to confirm the deletion. If confirmed, the logic of deletion is executed $.messager.confirm('Delete Confirm dialog', 'Are you sure you want to delete this item?', function(r){ if (r){ //1. Get the corresponding id from the obtained record, splice the value of the id, and then send the background 1,2,3,4 var ids = ""; for(var i = 0; i < rows.length; i ++) { ids += rows[i].id + ","; } ids = ids.substr(0, ids.lastIndexOf(",")); //2. Send ajax request $.post("category_deleteByIds.action",{ids:ids},function(result){ if(result == "true") { //Delete the just selected record, otherwise it will affect the subsequent update operation $("#dg").datagrid("uncheckAll"); //Refresh the current page, when querying, we use load, refresh the first page, and reload is refreshing the current page $("#dg").datagrid("reload"); //Default is the queryParams above without parameters } else { $.messager.show({ title:'Delete exception', msg:'Delete failed, please check the operation', timeout:2000, showType:'slide', }); } },"text"); } }); } } } } } } } If the user chooses to delete, a dialog box will first pop up. When the user determines that he wants to delete, we first need to obtain the id of the product selected by the user, splice these ids into a string, and then send an ajax request to the background. The first parameter in $.post is sent to that action, the second parameter is the sent parameter, and the third parameter is the callback function, that is, after the deletion is successful, the method in the function is executed. The parameter result of the function is transmitted from the background, and the fourth parameter is optional, which is the type of return data. Let's focus on the content in $.post. When the background returns a "true" to indicate that the deletion is successful, then we call the reload method in DataGrid to refresh the page. The reload is the same as the load used in the previous query. The difference is that the reload stays on the current page after refreshing, while the load displays the first page.
Okay, the front-end page part is written. Next, complete the corresponding method in the background. First, add the deleteByIds method in the categoryService and implement the method in its implementation class categoryServceImpl:
//categoryService interface public interface CategoryService extends BaseService<Category> { //Query category information, cascading administrator public List<Category> queryJoinAccount(String type, int page, int size); //Query the name of the category//Query the total number of records based on keywords public Long getCount(String type); //Delete multiple records based on ids public void deleteByIds(String ids); } //categoryServiceImpl implementation class @SuppressWarnings("unchecked") @Service("categoryService") public class CategoryServiceImpl extends BaseServiceImpl<Category> implements CategoryService { //Other methods are omitted and written... You can refer to the corresponding chapter content in the previous chapter @Override public void deleteByIds(String ids) { String hql = "delete from Category c where c.id in (" + ids + ")"; getSession().createQuery(hql).executeUpdate(); } } After writing the Service part, we will start writing the Action part. Because we want to get the ids data transmitted from the front desk, there must be a variable in the action that implements the get and set methods to receive this data. In addition, we need to pass the result to the front desk. When we do cascading queries in the previous chapter, the method used is to struts to package the query result data into json format and pass it to the front desk, so a map is needed, and then the map is converted into json format through the configuration file. Here, the data we pass to the front desk is relatively simple. If we successfully delete the shares, we can just pass a "true" so we don't need to package it into json format. We transmit it through streaming. The principle is the same as before. Prime Minister, we have to have a stream object to save the "true" bytes, and then through configuration, the object is streamed to the front desk. We still write these two objects in BaseAction, as follows:
@Controller("baseAction") @Scope("prototype") public class BaseAction<T> extends ActionSupport implements RequestAware,SessionAware,ApplicationAware,ModelDriven<T> { //Get the ids to be deleted, there must be a get and set method//The stream is used to return data to the foreground. This data is obtained by struts and then transmitted to the foreground through the form of a stream, so implement the get method to protected String ids; protected InputStream inputStream; //Omitted below... } The corresponding methods in CategoryAction are as follows:
@Controller("categoryAction") @Scope("prototype") public class CategoryAction extends BaseAction<Category> { public String queryJoinAccount() { //Omitted... } public String deleteByIds() { System.out.println(ids); categoryService.deleteByIds(ids); //If the deletion is successful, it will be executed downwards. We pass "true" to the foreground in the form of a stream inputStream = new ByteArrayInputStream("true".getBytes()); //Save the bytes of "true" into the stream inputStream return "stream"; } } Next, let’s look at the corresponding configuration in struts.xml:
<struts> <constant name="struts.devMode" value="true" /> <package name="shop" extends="json-default"><!-- jason-default inherits struts-default --> <global-results> <result name="aindex">/WEB-INF/main/aindex.jsp</result> </global-results> <!-- class corresponds to the id value of the Action configured in Spring, because it is to be handed over to Spring management--> <action name="category_*" method="{1}"> <result name="jsonMap" type="json"> <!-- omitted--> </result> <result name="stream" type="stream"> <!-- In the form of stream, type is stream --> <param name="inputName">inputStream</param> <!-- There is data to be transmitted in the imputStream--> </result> </action> <action name="account_*" method="{1}"> <result name="index">/index.jsp</result> </action> <!-- Used to complete the action forwarding of the system request, all requests are handed to execute--> <action name="send_*_*"> <result name="send">/WEB-INF/{1}/{2}.jsp</result> </action> </package> </struts>In this way, we have done the deletion operation and see the effect:
After the test is successful, we can also select multiple items to delete at one time. At this point, the deletion function is completed.
Original address: http://blog.csdn.net/eson_15/article/details/51338991
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.