We completed the DataGrid display JSON data, but did not link with the background, but simply show our own JSON data, in this section we integrate JSON and Struts2 to get through the interaction between Easyui and Struts2.
1. JSON Environment setup
The JSON environment is simple enough to import the JSON jar bundle as follows:
(Note: json-lib-2.4 's jar package download address: http://xiazai.jb51.net/201605/yuanma/json-lib-2.4 (jb51.net). rar)
2. Perfect action
a property in the DataGrid control is a URL that specifies the URL of the requested data, and in the previous section we set this address directly into a specific JSON file, where we set the URL to an action, such as URL: ' Category _queryjoinaccount.action ', representing the Queryjoinaccount method that will request categoryaction (the end of the article will give the query.jsp code). So we need to complete the Queryjoinaccount method in Categoryaction.
Before Struts2 and JSON are consolidated, let's take a look at what requests were made before the JSON data was displayed:
Because type is an attribute of the Category class, we have implemented the Modeldriven<category> interface in baseaction, so this type is encapsulated into model, we don't need to control it, can be obtained by model, but the page and rows parameters that are automatically sent by Easyui we need to get it ourselves, so we can add two member variables page and rows in the Basemodel and implement get and set methods, and finally, consider After all these parameters are obtained, we go to the database to query the data based on these parameters, so where do we put the data? It is also packaged into a JSON format to be sent to the foreground to be displayed by the DataGrid. Let's not think about how to package the queried data into JSON format, we first consider putting this data in one place, it is natural to think of using map, because the JSON format data is key-value form. Thinking here, we continue to refine Baseaction:
@Controller ("Baseaction") @Scope ("prototype") public class Baseaction<t> extends Actionsupport implements Reques taware,sessionaware,applicationaware,modeldriven<t> {//page is related to rows and pagination, Pagemap store the query's data, and then package it into JSON-formatted//page and
Rows to implement get and set methods, Pagemap only need to implement the Get method, because Pagemap is not to receive the foreground parameters, is to let struts obtain protected Integer page;
protected Integer rows; Protected Map<string, object> Pagemap = null;//let different action themselves to implement//omit get and Set methods .../******************* below or
Originally 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> sessions) {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; }
}
Well, after perfecting the basecategory, we can write the Queryjoinaccount method in the categoryaction, we will delete the original method in Categoryaction, because those are used before the setting up of the environment. , now really start the project code:
@Controller ("Categoryaction")
@Scope ("prototype") Public
class Categoryaction extends baseaction< category> {public
String Queryjoinaccount () {
//data used to store pagination
Pagemap = new hashmap<string, object> ( );
Query the corresponding data based on the keywords and pagination parameters. This method we have written in the service, when the completion of cascading query
list<category> categorylist = Categoryservice.queryjoinaccount ( Model.gettype (), page, rows);
Pagemap.put ("Rows", categorylist); stored in JSON format, as can be seen from the JSON file in the previous section, a key is total, and a key is rows, where rows are stored
///Based on the keyword query totals of records
Long = Categoryservice.getcount (Model.gettype ()); This method does not write, we later go to the service layer to improve
// System.out.println (total);
Pagemap.put ("Total", total); Store in JSON format, then store total for return
"Jsonmap";
}
So we're done with the action, and now the action gets the parameters from the front desk, then queries the total number of records for the specified type based on the parameters, and all the items of the specified type, and stores the key (that is, total and rows) as specified in JSON. Put it in the HashMap, and then just package the data in this hashmap into a JSON format and send it to the foreground to be displayed by the DataGrid. We first put this hashmap, first to improve the service layer code, and then to pack the data in this hashmap.
3. Perfect Categoryservice
from the above categoryaction, it is necessary to add a GetCount method to the Categoryservice and implement it in the concrete implementation class as follows:
Categoryservice interface public interface Categoryservice extends baseservice<category> {//query category information, Cascade Administrator public L Ist<category> queryjoinaccount (String type, int page, int size);
Use the name of the category query//query total record number by keyword public Long getcount (String type); //categoryserviceimpl Implementation Class @SuppressWarnings ("Unchecked") @Service ("Categoryservice") public class Categoryserviceim PL extends baseserviceimpl<category> implements Categoryservice {@Override public list<category> Quer Yjoinaccount (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) * siz
e)//starting from the first few shows. Setmaxresults (size)//display several. List (); @Override Public Long GetCount (String type) {string hql = ' Select count ' (c) from Category C where C.type Li
Ke:type "; Return (Long) GetsessioN (). CreateQuery (HQL). SetString ("type", "%" + type + "%"). Uniqueresult ();
Returns a record: Total Records}}
So far, the data in this database to get through the road, the first two steps to complete the previous--> database--> data, and then began to pack the data stored in the HashMap, and then sent to the front desk.
4. Configure Struts.xml
by configuring in Struts.xml, you can package the specified data, and we'll 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 "& The gt;/web-inf/main/aindex.jsp</result> </global-results> <!--class corresponds to the ID value of the action that is configured in spring because you want to give Spring Management--> <action name= "category_*" class= "categoryaction" method= "{1}" > <!--you must add a JSON package before the Cheng Json-default--> <result name= "Jsonmap" type= "JSON" > <!--data to be converted to a JSON object--> Aram Name= "Root" >pageMap</param> <!--config blacklist, filter unwanted options, 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-->
<!--there is no regular expression here, a bug in Csdn, I'm going to take a picture of the drop face--> </param> </result> </action> <action name= "account_*" class= "accountaction" method= "{1}" > <result name= "index" >/index.jsp</result> </action> <!--to complete the system request forwarding action, all requests are Give execute--> <action name= "send_*_*" class= "SendAction" > <result name= "Send" >/WEB-INF/{1}/{2}.J
sp</result> </action> </package> </struts>
From the above configuration can be seen, first package to inherit Json-default, because Json-default inherited Struts-default, Because there is a struts2-json-plugin-2.3.24.1.jar in the JSON jar bag, open to see a struts-plugin.xml inside, open to see Json-default is inherited Struts-default:
Next I configure <result>,name to be the string returned by the action, and type must be JSON. Then there is the argument in result, which must first be matched with the parameter named Root, which is to be matched to the HashMap object that just needs to be converted, that is, the pagemap we defined, with the configuration of this parameter, Struts does not package the data in the PAGEMAP into JSON format. Then is the configuration blacklist, the meaning of the blacklist is to tell struts in the packaging, which fields do not need to pack, such as the administrator password information, such as the above note in the Jason format can be seen Rows[0]. Account.pass represents the Password field, but the data must be more than one, so we have to use regular expressions so that all passwords are not packaged into JSON.
5. Modify QUERY.JSP Content
so we've packaged the data in JSON format, and then we'll refine the front desk query.jsp to let the DataGrid display correctly:
<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
6. Test Display Results
Finally, we test the DataGrid display as follows:
Here, we successfully integrated STRUTS2 and JSON, and now we can transfer JSON-formatted data to the foreground.
(Note: In the end I will provide the entire project source download!) Welcome everyone to collect or share
Original address: http://blog.csdn.net/eson_15/article/details/51332758
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.