In the last article, we completed the dataGrid display of json data, but it was not associated with the background. We simply displayed the json data we made ourselves. In this section, we integrated json and Struts2 to connect the interaction between EasyUI and Struts2.
1. Construction of json environment
The json environment is very simple, just import the json jar package, as follows:
(Note: json-lib-2.4's jar package download address: http://xiazai.VeVB.COM/201605/yuanma/json-lib-2.4(VeVB.COM).rar)
2. Improve Action
There is a property in the DataGrid control that is url, which can specify the URL address of the requested data. In the previous section, we directly set this address to a specific json file. Here we set this url to an action, such as url:'category_queryJoinAccount.action', which means that the queryJoinAccount method of the categoryAction will be requested (the code of query.jsp will be given at the end of the article). So we need to complete the queryJoinAccount method in categoryAction.
Before integrating Struts2 and json, let's take a look at what requests were sent for the json data displayed before:
Because type is a property of the Category class, we have implemented the ModelDriven<Category> interface in BaseAction, so this type will be encapsulated into the model. We don’t need to worry about it, we can obtain it through the model. However, we need to obtain the page and rows parameters automatically sent by EasyUI, so we can add two member variables page and rows to BaseModel and implement the get and set methods. Finally, we need to consider one thing. After all these parameters are obtained, we query the data in the database based on these parameters. So where do we put the data we found? It also needs to be packaged into json format and sent to the front desk before it can be displayed by DataGrid. We don’t consider how to package the query data into json format. We first consider putting this data in one place. It is natural to think of using Map, because the data in json format is in the form of key-value. Thinking of this, we continue to improve BaseAction:
@Controller("baseAction") @Scope("prototype") public class BaseAction<T> extends ActionSupport implements RequestAware,SessionAware,ApplicationAware,ModelDriven<T> { //page and rows are related to paging. PageMap stores the query data, and then packages it into json format. //page and rows to implement the get and set methods. PageMap only needs to implement the get method, because pageMap does not receive front-end parameters, but is protected Integer page; protected Integer rows; protected Map<String, Object> pageMap = null;//Let different Actions implement them by themselves//Omit get and set methods... /*************************** The following is still the original BaseAction part****************************/ //service object @Resource protected CategoryService categoryService; @Resource protected AccountService accountService; //Domain object protected Map<String, Object> request; protected Map<String, Object> session; protected Map<String, Object> application; @Override public void setApplication(Map<String, Object> application) { this.application = application; } @Override public void setSession(Map<String, Object> session) { this.session = session; } @Override public void setRequest(Map<String, Object> request) { this.request = request; } //ModelDriven protected T model; @Override public T getModel() { ParameterizedType type = (ParameterizedType)this.getClass().getGenericSuperclass(); Class clazz = (Class)type.getActualTypeArguments()[0]; try { model = (T)clazz.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } return model; } } OK, after improving BaseCategory, we can write the queryJoinAccount method in categoryAction. We delete all the original methods in categoryAction, because those were used for testing when building the environment before, and they were no longer needed. Now we have really started the project code:
@Controller("categoryAction") @Scope("prototype") public class CategoryAction extends BaseAction<Category> { public String queryJoinAccount() { // Used to store the data of paging pageMap = new HashMap<String, Object>(); //Query the corresponding data based on keywords and paging parameters. We have written this method in Service. At that time, we completed the cascading query List<Category> categoryList = categoryService.queryJoinAccount(model.getType(), page, rows); pageMap.put("rows", categoryList); //Stored in JSON format. From the json file in the previous section, it can be seen that a key is total and a key is rows. Here we store the rows first. //Query the total number of records based on the keywords Long total = categoryService.getCount(model.getType()); //This method has not been written, let's go to the Service layer to improve it later// System.out.println(total); pageMap.put("total", total); //Storage it in JSON format, and then store total return "jsonMap"; } } In this way, we have written the Action. Now the Action gets the parameters sent from the front desk, and then querys the total number of records of the specified type and all products of the specified type according to the parameters. It is stored according to the keys specified in json (i.e. total and rows) and placed in the HashMap. After that, as long as the data in this HashMap is packaged into json format and sent to the front desk, it can be displayed by DataGrid. We first put this HashMap, first improve the service layer code, and then package the data in this HashMap.
3. Improve categoryService
From the above categoryAction, we can see that a getCount method needs to be added to the categoryService, and it must be implemented in the specific implementation class, as follows:
//CategoryService interface public interface CategoryService extends BaseService<Category> { //Query category information, cascading administrator public List<Category> queryJoinAccount(String type, int page, int size); //Query using the name of the category//Query the total number of records based on keywords public Long getCount(String type); } //CategoryServiceImpl implement class @SuppressWarnings("unchecked") @Service("categoryService") public class CategoryServiceImpl extends BaseServiceImpl<Category> implements CategoryService { @Override public List<Category> queryJoinAccount(String type, int page, int size) { String hql = "from Category c left join fetch c.account where c.type like :type"; return getSession().createQuery(hql) .setString("type", "%" + type + "%") .setFirstResult((page-1) * size) //Show from the first one.setMaxResults(size) //Show several .list(); } @Override public Long getCount(String type) { String hql = "select count(c) from Category c where c.type like :type"; return (Long) getSession().createQuery(hql) .setString("type", "%" + type + "%") .uniqueResult(); //Return a record: total number of records} } So far, the path to obtaining data in this database has been opened. The first two steps have been completed to retrieve data from the front desk->database-->, and then we start to package the data stored in the HashMap and then send it to the front desk.
4. Configure struts.xml
Packaging the specified data can be completed through configuration in struts.xml. Let’s first look at the 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}"> <!-- You must add the json package first, and then inherit the json-default above --> <result name="jsonMap" type="json"> <!-- To convert data to json object --> <param name="root">pageMap</param> <!-- Configure blacklists, filter unnecessary options, and support regular expression json format: {total:3,rows:[{account:{id:2,login:"user",name:"customer service A",pass:"user"},hot:true,id:3,…}]} --> <param name="excludeProperties"> <!-- rows[0].account.pass--> <!-- Regular expressions cannot be displayed here. A bug in CSDN, I will follow the image and put it below--> </param> </result> </action> <action name="account_*" method="{1}"> <result name="index">/index.jsp</result> </action> <!-- The action used to complete the system request forwarding, all requests are handed over to execute--> <action name="send_*_*"> <result name="send">/WEB-INF/{1}/{2}.jsp</result> </action> </package> </struts>From the above configuration, we can see that first of all, package must inherit json-default, because json-default inherits struts-default, because there is a struts2-json-plugin-2.3.24.1.jar in the json jar package. You can open it and see that there is a struts-plugin.xml inside. You can open it and see that json-default inherits struts-default:
Next I configure <result>, name is the string returned just by action, and type must be matched into json. Then there is the parameters in result. First of all, the parameter that must be matched with name as root. This parameter must be matched into the HashMap object that needs to be converted just now, that is, the pageMap we defined. With the configuration of this parameter, struts will package the data in the pageMap into json format. Then configure the blacklist. The blacklist means telling struts which fields do not need to be packaged when packaging, such as information about administrator passwords. From the jason format in the comment above, you can see that rows[0].account.pass represents the password field, but there must be more than one data, so we have to use regular expressions to represent it, so that all passwords will not be packaged into json.
5. Modify query.jsp content
At this point, we have packaged the data into json format. Next, we will improve the content of the front-end query.jsp to make DataGrid display correctly:
<%@ 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" %> <script type="text/javascript"> $(function(){ $('#dg').datagrid({ //url address is changed to request categoryAction url:'category_queryJoinAccount.action', loadMsg:'Loading......', queryParams:{type:''}, //type parameters, there is no need to pass specific types here, because we want to display all //width:300, fitColumns:true, striped:true, nowrap:true, singleSelect:true, pagination:true, rowStyler: function(index,row){ console.info("index" + index + "," + row) if(index % 2 == 0) { return 'background-color:#fff;'; } else { return 'background-color:#ff0;'; } }, frozenColumns:[[ {field:'checkbox',checkbox:true}, {field:'id',title:'number',width:200} //The field fields here should be the same as those in the database, that is, they should be the same as those in the json data]], columns:[[ {field:'type',title:'Category name',width:100, //field type formatter: function(value,row,index){ return "<span>" + value + "</span>"; } }, {field:'hot',title:'hot',width:100, //field hot formatter: function(value,row,index){ if(value) { //If it is hot, the value is true, and the value is a boolean variable return "<input type='checkbox' checked='checked' disabled='true'"; //Tick} else { return "<input type='checkbox' disable='true'"; //Don't check} } }, {field:'account.login',title:'Administrator',width:200, //account.loginAdministrator login name formatter: function(value,row,index){ if(row.account != null && row.account.login != null) { return row.account.login; //If the login name is not empty, display the login name} else { return "There is no administrator in this category"; } } } ] ] }); }); </script> </head> <body> <table id="dg"></table> </body> </html> 6. Test shows results
Finally, let's test the display results of DataGrid, as follows:
At this point, we have successfully integrated Struts2 and json, and now we can transmit data in json format to the foreground.
(Note: In the end, I will provide the source code download of the entire project! Everyone is welcome to collect or share)
Original address: http://blog.csdn.net/eson_15/article/details/51332758
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.