海口制作网站企业,深圳网站建设seo推广优化,996工作制是什么意思,共享ip服务器做网站当将jQuery与struts 2一起使用时#xff0c;开发人员被说服使用struts2-jQuery插件 。 因为大多数论坛和其他Internet资源都支持struts2 jQuery插件。我有这种经验。 我想将Struts 2使用jQuery Grid插件#xff0c;但不使用struts2 jQuery插件。 对于我而言#xff0c;很难找… 当将jQuery与struts 2一起使用时开发人员被说服使用struts2-jQuery插件 。 因为大多数论坛和其他Internet资源都支持struts2 jQuery插件。我有这种经验。 我想将Struts 2使用jQuery Grid插件但不使用struts2 jQuery插件。 对于我而言很难找到无需使用struts2 jQuery插件即可实现struts 2动作类以创建jQuery网格的教程或任何好的资源。 最后我自己解决了这个问题并打算为您提供方便。 本教程介绍了如何在不使用插件的情况下使用struts2创建jQuery网格。 我从现有项目中过滤掉了这段代码。 该项目的架构基于strts2spring和hibernate集成环境。 我敢肯定您可以自定义这些代码使其适合您的环境。 步骤01 为“ 省 ”主屏幕创建实体类。 我将JPA用作一种持久性技术并使用spring HibernateDaoSupport 提供的休眠数据访问支持。 我不会详细解释这些东西。 我主要关心的是如何创建支持jQuery网格的struts 2动作类。 这是我的实体类。 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**/EntityTable(namePROVINCE) public class Province extends Audited implements Serializable {private static final long serialVersionUID -6842726343310595087L;IdSequenceGenerator(nameprovince_seq, sequenceNameprovince_seq)GeneratedValue(strategy GenerationType.AUTO, generator province_seq)private Long id;Column(namedescription, nullable false)private String name;Column(namestatus, 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 为“省”主屏幕网格创建JSP文件 。 请记住jQuery网格是jQuery的插件。 因此您需要下载jQuery网格插件的相关CSS文件和JS文件。 您可能需要在JSP文件的开头部分包含以下资源。 link typetext/css relstylesheet mediascreen href%request.getContextPath()%/css/jquery/themes/redmond/jquery-ui-1.8.16.custom.css
link typetext/css relstylesheet mediascreen href%request.getContextPath()%/css/ui.jqgrid.css
script src%request.getContextPath()%/js/jquery-1.6.2.min.js typetext/javascript/script
script src%request.getContextPath()%/js/grid.locale-en.js typetext/javascript/script
script src%request.getContextPath()%/js/jquery.jqGrid.src.js typetext/javascript/script
script src%request.getContextPath()%/js/jquery-ui-1.8.16.custom.min.js typetext/javascript/script 然后我们将在JSP文件中创建所需的DOM内容以呈现网格。 为此您只需要在JSP文件中放置带有给定ID的简单TABLE和DIV元素如下所示。 table idlist/table
div idpager/div 需要在“ 寻呼机 ” DIV标签来显示jQuery的网格的分页栏。 步骤03 为“省”主屏幕网格创建JS文件。 jQuery网格需要使用javascript启动。 我将在加载页面时启动网格。 有很多功能例如添加新记录更新记录删除记录jQuery网格支持的搜索。 我想如果您可以创建初始网格则可以熟悉这些内容。 此javascript仅包含启动网格的代码。 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();}
}; 我希望突出显示以上代码中的一些代码片段。 网格初始化对象的 jsonReader 属性是很难找到的关键点并且花费了大量时间使网格正常工作。 根 –这应该是对象列表。 page –当前页码。 总数 –这是总页数。 例如如果您有1000条记录并且页面大小为10则“总计”值为100。 记录 – 记录总数或记录数。 如果要使用JSON数据创建网格则指定的“ url ”的响应应为这种格式的JSON响应。 下面显示了示例JSON响应。 {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} 以上字段应在操作类中声明并适当更新。 我稍后再说。 如果您打算使用诸如添加记录删除记录更新记录搜索等操作则必须指定“ editurl ”。 在JSP文件中在close body标记的上方我放置了以下脚本来调用网格初始化代码。 var CONTEXT_ROOT %request.getContextPath()%;jQuery(document).ready(function(){SHIMS.Province.onLoad();}); 步骤04 为“省”主屏幕网格创建Struts2动作类。 这是本教程最重要的部分。 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**/ControllerNamespace(WebConstants.MAINTENANCE_NAMESPACE) ParentPackage(WebConstants.MAINTENANCE_PACKAGE)Results({Result(nameProvinceAction.SUCCESS, location/jsp/maintenance/province.jsp), Result(name json, type json)}) public class ProvinceAction extends BaseActionProvince implements ModelDrivenProvince {private static final long serialVersionUID -3007855590220260696L;private static Logger logger Logger.getLogger(ProvinceAction.class);Autowiredprivate ProvinceService provinceService;private ListProvince 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 {PageProvince resultPage provinceService.findByCriteria(model, getRequestedPage(page));ListProvince provinceList resultPage.getResultList(); setGridModel(provinceList); setRecords(resultPage.getRecords());setTotal(resultPage.getTotals());return JSON;}/*** return the gridModel*/public ListProvince getGridModel() {return gridModel;}/*** param gridModel the gridModel to set*/public void setGridModel(ListProvince 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类中实现的通用方法该类返回给定类型的Page实例。 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 BaseActionT extends ActionSupport implements ServletRequestAware, SessionAware {private static final long serialVersionUID -8209196735097293008L;protected static final Integer PAGE_SIZE 10;protected HttpServletRequest request;protected MapString, 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 PageT getRequestedPage(Integer page){PageT requestedPage new PageT(); requestedPage.setPage(page);requestedPage.setRows(PAGE_SIZE);return requestedPage;}/*** return the session*/public MapString, Object getSession() { return session;}/*** param session the session to set*/public void setSession(MapString, Object session) { this.session session;}} 我已经解释了“ gridModel ”“ 页面 ”“ 总计 ”和“记录 ”。 当我们使用某些列对网格中的数据进行排序时jQuery网格会传递被称为“排序顺序”和“排序索引”的“ sord ”和“ sidx ”。 要获取这些拖曳字段我们应该在action类中使用声明它并提供setter和getter方法。 稍后我们可以根据两个参数对数据列表进行排序。 步骤05 实施服务方法。 从这里开始大多数技术都特定于我当前的项目框架。 我将解释这些内容以便您理解我如何开发相关服务和DAO方法。 由于jQuery网格支持分页因此需要一种正确的方式来从前端到后端再从后端到前端交换网格信息。 为此我实现了通用的“ Page”类。 /*** */
package com.shims.dto;import java.util.ArrayList;
import java.util.List;/*** author semikas**/public class PageT {/*** Query result list.*/private ListT resultList new ArrayListT(); /*** 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 ListT getResultList() {return resultList;}/*** param resultDtoList the resultDtoList to set*/public void setResultList(ListT 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;}} 同样通过一些搜索条件我们可以获取数据并相应地更新网格。 我的服务接口和实现类如下。 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 PageProvince findByCriteria(Province searchCriteria, PageProvince 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 PageProvince findByCriteria(Province searchCriteria, PageProvince page) throws ServiceException {PageProvince resultPage provinceDao.findByCriteria(searchCriteria, page); return resultPage;}} 我正在使用 page 实例在前端和后端之间交换网格信息。 接下来我将解释本教程的其他重要部分。 步骤06 实现数据访问方法。 在DAO方法中我们应该仅过滤用户所请求页面的记录还应该更新“ page ”实例属性以便应将其反映到网格中。 由于我正在使用休眠模式因此我使用了“条件”从数据库中检索所需的数据。 您可以通过自己的方式来实现但是它应该正确地更新网格信息。 省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 GenericDAOProvince, Long { /*** Returns search results for a given search criteria.* param searchCriteria* param page* return* throws DataAccessException*/public PageProvince findByCriteria(Province searchCriteria, PageProvince 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 AbstractMaintenanceDaoSupportProvince, Long implements ProvinceDao {Autowiredpublic ProvinceDaoImpl(SessionFactory sessionFactory) {setSessionFactory(sessionFactory);}/*** {inheritDoc} */SuppressWarnings(unchecked)Overridepublic PageProvince findByCriteria(ProvinceDto searchCriteria, PageProvince 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());ListProvince privinces (ListProvince)criteria.list(); //Update page instance.page.setRecords(rowCount); //Total number of recordspage.setTotals(totNumOfPages); //Total number of pagespage.setResultList(privinces);return page; }
} 我认为这对于希望将纯jQuery与struts2结合使用的开发人员将是一个很好的帮助。 如果您发现与该主题更多相关的信息请在下面发布。 参考 如何在没有插件的Struts 2中使用jQuery网格 从我们的JCG合作伙伴 Semika loku kaluge在Code Box博客上获得。 翻译自: https://www.javacodegeeks.com/2012/06/query-grid-with-struts-2-without-plugin.html