idea struts插件_使用Struts 2的查询网格(无插件)
idea struts插件
當(dāng)將jQuery與struts 2結(jié)合使用時(shí),開發(fā)人員被說服使用struts2-jQuery插件 。 因?yàn)榇蠖鄶?shù)論壇和其他Internet資源都支持jQuery struts2 jQuery插件。我有這種經(jīng)驗(yàn)。 我想使用帶有struts 2的jQuery網(wǎng)格插件,但不使用struts2 jQuery插件。 對于我而言,很難找到無需使用struts2 jQuery插件即可實(shí)現(xiàn)struts 2動(dòng)作類以創(chuàng)建jQuery網(wǎng)格的教程或任何好的資源。 最后,我自己解決了這個(gè)問題,并打算為您提供方便。 本教程介紹了如何在不使用插件的情況下使用struts2創(chuàng)建jQuery網(wǎng)格。 我從現(xiàn)有項(xiàng)目中過濾掉了這段代碼。 該項(xiàng)目的體系結(jié)構(gòu)基于strts2,spring和hibernate集成環(huán)境。 我敢肯定,您可以自定義這些代碼,使其適合您的環(huán)境。
步驟01: 為“ 省 ”主屏幕創(chuàng)建實(shí)體類。
我將JPA用作持久性技術(shù),并使用spring( HibernateDaoSupport )提供的Hibernate數(shù)據(jù)訪問支持。 我不會(huì)詳細(xì)解釋這些東西。 我主要關(guān)心的是如何創(chuàng)建支持jQuery網(wǎng)格的struts 2動(dòng)作類。 這是我的實(shí)體類。
Province.java
/*** */ package com.shims.model.maintenance;import java.io.Serializable; import java.util.ArrayList; import java.util.List;import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.SequenceGenerator; import javax.persistence.Table;import org.hibernate.annotations.Cascade;import com.shims.model.Audited;/*** @author Semika Siriwardana**/@Entity@Table(name='PROVINCE') public class Province extends Audited implements Serializable {private static final long serialVersionUID = -6842726343310595087L;@Id@SequenceGenerator(name='province_seq', sequenceName='province_seq')@GeneratedValue(strategy = GenerationType.AUTO, generator = 'province_seq')private Long id;@Column(name='description', nullable = false)private String name;@Column(name='status', nullable = false)private char status;/*** */public Province() {super();}/*** @param id*/public Province(Long id) {super();this.id = id;}/*** @return the id*/public Long getId() {return id;}/*** @param id the id to set*/public void setId(Long id) {this.id = id;}/*** @return the name*/public String getName() {return name;}/*** @param name the name to set*/public void setName(String name) {this.name = name;}/*** @return the status*/public char getStatus() {return status;}/*** @param status the status to set*/public void setStatus(char status) {this.status = status;} }步驟02: 為“省”主屏幕網(wǎng)格創(chuàng)建JSP文件 。
請記住,jQuery網(wǎng)格是jQuery的插件。 因此,您需要下載jQuery網(wǎng)格插件的相關(guān)CSS文件和JS文件。 您可能需要在JSP文件的開頭部分包含以下資源。
<link type='text/css' rel='stylesheet' media='screen' href='<%=request.getContextPath()%>/css/jquery/themes/redmond/jquery-ui-1.8.16.custom.css'> <link type='text/css' rel='stylesheet' media='screen' href='<%=request.getContextPath()%>/css/ui.jqgrid.css'> <script src='<%=request.getContextPath()%>/js/jquery-1.6.2.min.js' type='text/javascript'></script> <script src='<%=request.getContextPath()%>/js/grid.locale-en.js' type='text/javascript'></script> <script src='<%=request.getContextPath()%>/js/jquery.jqGrid.src.js' type='text/javascript'></script> <script src='<%=request.getContextPath()%>/js/jquery-ui-1.8.16.custom.min.js' type='text/javascript'></script>然后,我們將在JSP文件中創(chuàng)建所需的DOM內(nèi)容以呈現(xiàn)網(wǎng)格。 為此,您只需要在JSP文件中放置一個(gè)簡單的TABLE和DIV元素,并具有給定的ID,如下所示。
<table id='list'></table> <div id='pager'></div>需要在“ 尋呼機(jī) ” DIV標(biāo)簽來顯示jQuery的網(wǎng)格的分頁欄。
步驟03: 為“省”主屏幕網(wǎng)格創(chuàng)建JS文件。
jQuery網(wǎng)格需要使用javascript啟動(dòng)。 我將在加載頁面時(shí)啟動(dòng)網(wǎng)格。 有很多功能,如添加新記錄,更新記錄,刪除記錄,jQuery網(wǎng)格支持的搜索。 我想,如果您可以創(chuàng)建初始網(wǎng)格,則可以熟悉這些內(nèi)容。 此javascript僅包含啟動(dòng)網(wǎng)格的代碼。
var SHIMS = {} var SHIMS.Province = {onRowSelect: function(id) {//Handle event},onLoadComplete: function() {//Handle grid load complete event.},onLoadError: function() {//Handle when data loading into grid failed. },/*** Initialize grid*/initGrid: function(){jQuery('#list').jqGrid({ url:CONTEXT_ROOT + '/secure/maintenance/province!search.action', id:'gridtable', caption:'SHIMS:Province Maintenance',datatype: 'json', pager: '#pager', colNames:['Id','Name','Status'], pagerButtons:true,navigator:true,jsonReader : {root: 'gridModel', page: 'page',total: 'total',records: 'records',repeatitems: false, id: '0' }, colModel:[ {name:'id',index:'id', width:200, sortable:true, editable:false, search:true},{name:'name',index:'name', width:280, sortable:true, editable:true, search:true, formoptions:{elmprefix:'(*)'},editrules :{required:true}},{name:'provinceStatus',index:'provinceStatus', width:200, sortable:false, editable:true, search:false, editrules:{required:true}, edittype:'select', editoptions:{value:'A:A;D:D'}}], rowNum:30, rowList:[10,20,30], width:680,rownumbers:true,viewrecords:true, sortname: 'id', viewrecords: true, sortorder: 'desc', onSelectRow:SHIMS.Province.onRowSelect, loadComplete:SHIMS.Province.onLoadComplete,loadError:SHIMS.Province.onLoadError,editurl:CONTEXT_ROOT + '/secure/maintenance/province!edit.action' });},/*** Invoke this method with page on load.*/onLoad: function() {this.initGrid();} }; 我想重點(diǎn)介紹上述代碼中的一些代碼片段。 網(wǎng)格初始化對象的' jsonReader '屬性是很難找到的關(guān)鍵點(diǎn),并且花費(fèi)了大量時(shí)間使網(wǎng)格能夠正常工作。
根 –這應(yīng)該是對象列表。
page –當(dāng)前頁碼。 總數(shù) –這是總頁數(shù)。 例如,如果您有1000條記錄且頁面大小為10,則“總計(jì)”值為100。
記錄 – 記錄總數(shù)或記錄數(shù)。
如果要使用JSON數(shù)據(jù)創(chuàng)建網(wǎng)格,則指定的“ url ”的響應(yīng)應(yīng)為這種格式的JSON響應(yīng)。 下面顯示了示例JSON響應(yīng)。
{'gridModel':[{'id':15001,'name':'Western','provinceStatus':'A'},{'id':14001,'name':'North','provinceStatus':'A'},{'id':13001,'name':'North Central','provinceStatus':'A'},{'id':12002,'name':'East','provinceStatus':'A'},{'id':12001,'name':'Southern','provinceStatus':'A'}], 'page':1, 'records':11, 'rows':30, 'sidx':'id', 'sord':'desc', 'total':2}以上字段應(yīng)在操作類中聲明并適當(dāng)更新。 我稍后再說。 如果您打算使用添加記錄,刪除記錄,更新記錄,搜索等操作,則必須指定“ editurl ”。
在JSP文件中,在close body標(biāo)記的上方,我放置了以下腳本來調(diào)用網(wǎng)格初始化代碼。
var CONTEXT_ROOT = '<%=request.getContextPath()%>';jQuery(document).ready(function(){SHIMS.Province.onLoad();});步驟04: 為“省”主屏幕網(wǎng)格創(chuàng)建Struts2動(dòng)作類。
這是本教程最重要的部分。
ProvinceAction.java
/*** */ package com.shims.web.actions.maintenance.province;import java.util.List;import org.apache.log4j.Logger; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.ParentPackage; import org.apache.struts2.convention.annotation.Result; import org.apache.struts2.convention.annotation.Results; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller;import com.opensymphony.xwork2.ModelDriven; import com.shims.dto.Page; import com.shims.dto.ProvinceDto; import com.shims.model.maintenance.Province; import com.shims.service.maintenance.api.ProvinceService; import com.shims.support.SHIMSSoringSupport; import com.shims.web.actions.common.BaseAction; import com.shims.web.common.WebConstants;/*** @author Semika Siriwardana**/@Controller@Namespace(WebConstants.MAINTENANCE_NAMESPACE) @ParentPackage(WebConstants.MAINTENANCE_PACKAGE)@Results({@Result(name=ProvinceAction.SUCCESS, location='/jsp/maintenance/province.jsp'), @Result(name = 'json', type = 'json')}) public class ProvinceAction extends BaseAction<Province> implements ModelDriven<Province> {private static final long serialVersionUID = -3007855590220260696L;private static Logger logger = Logger.getLogger(ProvinceAction.class);@Autowiredprivate ProvinceService provinceService;private List<Province> gridModel = null;private Province model = new Province();private Integer rows = 0;private Integer page = 0;private String sord;private String sidx;private Integer total = 0;private Integer records = 0;@Overridepublic String execute() {return SUCCESS;}/*** Search provinces* @return*/public String search() throws Exception {Page<Province> resultPage = provinceService.findByCriteria(model, getRequestedPage(page));List<Province> provinceList = resultPage.getResultList(); setGridModel(provinceList); setRecords(resultPage.getRecords());setTotal(resultPage.getTotals());return JSON;}/*** @return the gridModel*/public List<Province> getGridModel() {return gridModel;}/*** @param gridModel the gridModel to set*/public void setGridModel(List<Province> gridModel) {this.gridModel = gridModel;}/*** @return the page*/public Integer getPage() {return page;}/*** @param page the page to set*/public void setPage(Integer page) {this.page = page;}/*** @return the rows*/public Integer getRows() {return rows;}/*** @param rows the rows to set*/public void setRows(Integer rows) {this.rows = rows;}/*** @return the sidx*/public String getSidx() {return sidx;}/*** @param sidx the sidx to set*/public void setSidx(String sidx) {this.sidx = sidx;}/*** @return the sord*/public String getSord() {return sord;}/*** @param sord the sord to set*/public void setSord(String sord) {this.sord = sord;}/*** @return the total*/public Integer getTotal() {return total;}/*** @param total the total to set*/public void setTotal(Integer total) {this.total = total;}/*** @return the records*/public Integer getRecords() {return records;}/*** @param records the records to set*/public void setRecords(Integer records) {this.records = records;}@Overridepublic Province getModel() {return model;}}getRequestedPage()方法是在'BaseAction'類中實(shí)現(xiàn)的通用方法,該類返回給定類型的'Page'實(shí)例。
BaseAction.java
/*** */ package com.shims.web.actions.common;import java.util.Map;import javax.servlet.http.HttpServletRequest;import org.apache.struts2.interceptor.ServletRequestAware; import org.apache.struts2.interceptor.SessionAware;import com.opensymphony.xwork2.ActionSupport; import com.shims.dto.Page; import com.shims.dto.security.UserDto; import com.shims.web.common.WebConstants;import flexjson.JSONSerializer;/*** @author Semika Siriwardana**/public abstract class BaseAction<T> extends ActionSupport implements ServletRequestAware, SessionAware {private static final long serialVersionUID = -8209196735097293008L;protected static final Integer PAGE_SIZE = 10;protected HttpServletRequest request;protected Map<String, Object> session; protected String JSON = 'json';public abstract String execute(); public HttpServletRequest getRequest() {return request;}@Overridepublic void setServletRequest(HttpServletRequest request) {this.request = request;}protected void setRequestAttribute(String key, Object obj) {request.setAttribute(key, obj);}/*** Returns generic Page instance.* @param domain* @param employeeDto* @return*/protected Page<T> getRequestedPage(Integer page){Page<T> requestedPage = new Page<T>(); requestedPage.setPage(page);requestedPage.setRows(PAGE_SIZE);return requestedPage;}/*** @return the session*/public Map<String, Object> getSession() { return session;}/*** @param session the session to set*/public void setSession(Map<String, Object> session) { this.session = session;}}我已經(jīng)解釋了“ gridModel ”,“ 頁面 ”,“ 總計(jì) ”和“記錄 ”。 當(dāng)我們使用某些列對網(wǎng)格中的數(shù)據(jù)進(jìn)行排序時(shí),jQuery網(wǎng)格會(huì)傳遞被稱為“排序順序”和“排序索引”的“ sord ”和“ sidx ”。 要獲取這些拖曳字段,我們應(yīng)該在action類中使用聲明它,并提供setter和getter方法。 稍后,我們可以基于兩個(gè)參數(shù)對數(shù)據(jù)列表進(jìn)行排序。
步驟05: 實(shí)施服務(wù)方法。
從這里開始,大多數(shù)技術(shù)都特定于我當(dāng)前的項(xiàng)目框架。 我將解釋這些內(nèi)容,以便您理解我如何開發(fā)相關(guān)服務(wù)和DAO方法。 由于jQuery網(wǎng)格支持分頁,因此需要一種適當(dāng)?shù)姆绞絹韽那岸说胶蠖嗽購暮蠖说角岸私粨Q網(wǎng)格信息。 為此,我實(shí)現(xiàn)了通用的“ Page”類。
/*** */ package com.shims.dto;import java.util.ArrayList; import java.util.List;/*** @author semikas**/public class Page<T> {/*** Query result list.*/private List<T> resultList = new ArrayList<T>(); /*** Requested page number.*/private Integer page = 1;/*** Number of rows displayed in a single page.*/private Integer rows = 10;/*** Total number of records return from the query.*/private Integer records;/*** Total number of pages.*/private Integer totals;/*** @return the resultDtoList*/public List<T> getResultList() {return resultList;}/*** @param resultDtoList the resultDtoList to set*/public void setResultList(List<T> resultList) {this.resultList = resultList;}/*** @return the page*/public Integer getPage() {return page;}/*** @param page the page to set*/public void setPage(Integer page) {this.page = page;}/*** @return the rows*/public Integer getRows() {return rows;}/*** @param rows the rows to set*/public void setRows(Integer rows) {this.rows = rows;}/*** @return the records*/public Integer getRecords() {return records;}/*** @param records the records to set*/public void setRecords(Integer records) {this.records = records;}/*** @return the totals*/public Integer getTotals() {return totals;}/*** @param totals the totals to set*/public void setTotals(Integer totals) {this.totals = totals;}} 同樣,通過一些搜索條件,我們可以獲取數(shù)據(jù)并相應(yīng)地更新網(wǎng)格。
我的服務(wù)接口和實(shí)現(xiàn)類如下。
ProvinceService.java
/*** */ package com.shims.service.maintenance.api;import java.util.List;import com.shims.dto.Page; import com.shims.exceptions.ServiceException; import com.shims.model.maintenance.Province;/*** @author Semika Siriwardana**/ public interface ProvinceService {/*** Returns list of provinces for a given search criteria.* @return* @throws ServiceException*/public Page<Province> findByCriteria(Province searchCriteria, Page<Province> page) throws ServiceException;}ProvinceServiceImpl.java
/*** */ package com.shims.service.maintenance.impl;import java.util.ArrayList; import java.util.List;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;import com.shims.dto.Page; import com.shims.exceptions.ServiceException; import com.shims.model.maintenance.Province; import com.shims.persist.maintenance.api.ProvinceDao; import com.shims.service.maintenance.api.ProvinceService;/*** @author Semika Siriwardana**/@Servicepublic class ProvinceServiceImpl implements ProvinceService {@Autowiredprivate ProvinceDao provinceDao; /*** {@inheritDoc} */@Overridepublic Page<Province> findByCriteria(Province searchCriteria, Page<Province> page) throws ServiceException {Page<Province> resultPage = provinceDao.findByCriteria(searchCriteria, page); return resultPage;}}我正在使用' page '實(shí)例在前端和后端之間交換網(wǎng)格信息。
接下來,我將解釋本教程的其他重要部分。
步驟06: 實(shí)現(xiàn)數(shù)據(jù)訪問方法。
在DAO方法中,我們應(yīng)該僅過濾用戶所請求頁面的記錄,還應(yīng)該更新“ page ”實(shí)例屬性,以便應(yīng)將這些記錄反映到網(wǎng)格中。 由于我正在使用Hibernate模式,因此我使用了“條件”從數(shù)據(jù)庫中檢索所需的數(shù)據(jù)。 您可以通過自己的方式來實(shí)現(xiàn),但是它應(yīng)該正確地更新網(wǎng)格信息。
省Dao.java
/*** */ package com.shims.persist.maintenance.api;import com.shims.dto.Page; import com.shims.exceptions.DataAccessException; import com.shims.model.maintenance.Province; import com.shims.persist.common.GenericDAO;/*** @author Semika Siriwardana**/ public interface ProvinceDao extends GenericDAO<Province, Long> { /*** Returns search results for a given search criteria.* @param searchCriteria* @param page* @return* @throws DataAccessException*/public Page<Province> findByCriteria(Province searchCriteria, Page<Province> page) throws DataAccessException;}ProvinceDaoImpl.java
/*** */ package com.shims.persist.maintenance.impl;import java.util.List;import org.hibernate.Criteria; import org.hibernate.SessionFactory; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository;import com.shims.dto.Page; import com.shims.exceptions.DataAccessException; import com.shims.model.maintenance.Province; import com.shims.persist.maintenance.api.ProvinceDao;/*** @author Semika Siriwardana**/@Repositorypublic class ProvinceDaoImpl extends AbstractMaintenanceDaoSupport<Province, Long> implements ProvinceDao {@Autowiredpublic ProvinceDaoImpl(SessionFactory sessionFactory) {setSessionFactory(sessionFactory);}/*** {@inheritDoc} */@SuppressWarnings('unchecked')@Overridepublic Page<Province> findByCriteria(ProvinceDto searchCriteria, Page<Province> page) throws SHIMSDataAccessException {Criteria criteria = getSession().createCriteria(Province.class);if (searchCriteria.getName() != null && searchCriteria.getName().trim().length() != 0) {criteria.add(Restrictions.ilike('name', searchCriteria.getName(), MatchMode.ANYWHERE)); }//get total number of records firstcriteria.setProjection(Projections.rowCount());Integer rowCount = ((Integer)criteria.list().get(0)).intValue();//reset projection to nullcriteria.setProjection(null);Integer to = page.getPage() * page.getRows();Integer from = to - page.getRows();criteria.setFirstResult(from);criteria.setMaxResults(to); //calculate the total pages for the queryInteger totNumOfPages =(int) Math.ceil((double)rowCount / (double)page.getRows());List<Province> privinces = (List<Province>)criteria.list(); //Update 'page' instance.page.setRecords(rowCount); //Total number of recordspage.setTotals(totNumOfPages); //Total number of pagespage.setResultList(privinces);return page; } }我認(rèn)為,這對于希望將純jQuery與struts2結(jié)合使用的開發(fā)人員將是一個(gè)很好的幫助。 如果您發(fā)現(xiàn)與該主題更多相關(guān)的信息,請?jiān)谙旅姘l(fā)布。
參考: 如何在沒有插件的Struts 2中使用jQuery網(wǎng)格? 從我們的JCG合作伙伴 Semika loku kaluge在Code Box博客上獲得。
翻譯自: https://www.javacodegeeks.com/2012/06/query-grid-with-struts-2-without-plugin.html
idea struts插件
總結(jié)
以上是生活随笔為你收集整理的idea struts插件_使用Struts 2的查询网格(无插件)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 法国用英语怎么说 法国的英语是什么
- 下一篇: 盯着的拼音 大家可以学习一下