SSH如何實(shí)現(xiàn)條件查詢和分頁查詢

這篇文章將為大家詳細(xì)講解有關(guān)SSH如何實(shí)現(xiàn)條件查詢和分頁查詢,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

創(chuàng)新互聯(lián)是專業(yè)的代縣網(wǎng)站建設(shè)公司,代縣接單;提供成都網(wǎng)站建設(shè)、成都網(wǎng)站設(shè)計(jì),網(wǎng)頁設(shè)計(jì),網(wǎng)站設(shè)計(jì),建網(wǎng)站,PHP網(wǎng)站建設(shè)等專業(yè)做網(wǎng)站服務(wù);采用PHP框架,可快速的進(jìn)行代縣網(wǎng)站開發(fā)網(wǎng)頁制作和功能擴(kuò)展;專業(yè)做搜索引擎喜愛的網(wǎng)站,專業(yè)的做網(wǎng)站團(tuán)隊(duì),希望更多企業(yè)前來合作!

1、QueryHelper和PageResult

QueryHelper是進(jìn)行HQL查詢的輔助類,而PageResult則是進(jìn)行分頁查詢的結(jié)果類。

QueryHelper.java

package com.rk.core.utils;

import java.util.ArrayList;
import java.util.List;

public class QueryHelper {
	//from子句
	private String fromClause = "";
	//where子句
	private String whereClause = "";
	//order by子句
	private String orderByClause = "";
	
	private List<Object> parameters;
	//排序順序
	public static String ORDER_BY_DESC = "DESC";//降序
	public static String ORDER_BY_ASC = "ASC";//升序
	
	/**
	 * 構(gòu)造from子句
	 * @param clazz 實(shí)體類
	 * @param alias 實(shí)體類對應(yīng)的別名
	 */
	public QueryHelper(Class clazz,String alias){
		fromClause = "FROM " + clazz.getSimpleName() + " " + alias;
	}
	
	/**
	 * 構(gòu)造where子句
	 * @param condition 查詢條件語句;例如:i.title like ?
	 * @param params 查詢條件語句中對應(yīng)的查詢條件值;例如:%標(biāo)題%
	 */
	public void addCondition(String condition, Object... params){
		if(whereClause.length() > 1){ //非第一個(gè)查詢條件
			whereClause += " AND " + condition;
		}
		else{//第一個(gè)查詢條件
			whereClause += " WHERE " + condition;
		}
		
		//設(shè)置 查詢條件值 到 查詢條件值集合 中
		if(parameters == null){
			parameters = new ArrayList<Object>();
		}
		if(params != null){
			for(Object param : params){
				parameters.add(param);
			}
		}
	}
	
	/**
	 * 構(gòu)造order by子句
	 * @param property 排序?qū)傩?;例如:i.createTime
	 * @param order 排序順序;例如:DESC 或者 ASC
	 */
	public void addOrderByProperty(String property, String order){
		if(orderByClause.length()>1){ //非第一個(gè)排序?qū)傩?
			orderByClause += ", " + property + " " + order;
		}
		else{ //第一個(gè)排序?qū)傩?
			orderByClause = " ORDER BY " + property + " " + order;
		}
	}
	
	//查詢hql語句
	public String getQueryListHql(){
		return fromClause + whereClause + orderByClause;
	}
	
	//查詢統(tǒng)計(jì)數(shù)的hql語句
	public String getQueryCountHql(){
		return "SELECT COUNT(*) " + fromClause + whereClause;
	}
	
	//查詢hql語句中對應(yīng)的查詢條件值集合
	public List<Object> getParameters(){
		return parameters;
	}
}

QueryHelper分析:由3部分組成 

(1)from子句

(2)where子句

(3)order by子句

PageResult.java

package com.rk.core.entity;

import java.util.ArrayList;
import java.util.List;

public class PageResult {
	//總記錄數(shù)
	private long totalCount;
	//當(dāng)前頁號
	private int pageNo;
	//總頁數(shù)
	private int totalPageCount;
	//頁大小
	private int pageSize;
	//列表記錄
	private List items;
	
	//避免分頁過大或過小
	public static final int MAX_PAGE_SIZE = 100;
	public static final int MIN_PAGE_SIZE = 3;
	
	
	public PageResult(long totalCount, int totalPageCount,int pageSize, int pageNo, List items) {
		this.totalCount = totalCount;
		this.totalPageCount = totalPageCount;
		this.pageSize = pageSize;
		this.pageNo = pageNo;
		this.items = items; 
	}

	public long getTotalCount() {
		return totalCount;
	}

	public void setTotalCount(long totalCount) {
		this.totalCount = totalCount;
	}

	public int getPageNo() {
		return pageNo;
	}

	public void setPageNo(int pageNo) {
		this.pageNo = pageNo;
	}

	public int getTotalPageCount() {
		return totalPageCount;
	}

	public void setTotalPageCount(int totalPageCount) {
		this.totalPageCount = totalPageCount;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public List getItems() {
		return items;
	}

	public void setItems(List items) {
		this.items = items;
	}
}

對于PageResult的分析:

(1)總記錄數(shù)totalCount (根據(jù)sql語句從數(shù)據(jù)庫獲得)

(2)每一頁的大小pageSize (一般由前臺(tái)指定)

(3)由(1)和(2)得出總的頁數(shù)totalPageCount (計(jì)算得出)

(4)判斷當(dāng)前頁pageNo是否合理(是否小于1,是否大于totalPageCount);如果不合理,則進(jìn)行校正

(5)取出當(dāng)前頁的數(shù)據(jù)items

2、使用QueryHelper

使用QueryHelper主要集中在dao層面上進(jìn)行實(shí)現(xiàn),而service層只是調(diào)用下一層(dao層)的功能。

2.1、Dao層

BaseDao.java

package com.rk.core.dao;

import java.io.Serializable;
import java.util.List;

import com.rk.core.entity.PageResult;
import com.rk.core.utils.QueryHelper;


public interface BaseDao<T> {
	//新增
	void save(T entity);
	//更新
	void update(T entity);
	//根據(jù)id刪除
	void delete(Serializable id);
	//根據(jù)id查找
	T findById(Serializable id);
	//查找列表
	List<T> findAll();
	//條件查詢實(shí)體列表
	List<T> findList(String hql, List<Object> parameters);
	//條件查詢實(shí)體列表--查詢助手queryHelper
	List<T> findList(QueryHelper queryHelper);
	//分頁條件查詢實(shí)體列表--查詢助手queryHelper
	PageResult getPageResult(QueryHelper queryHelper, int pageNo, int pageSize);
}

其中添加的方法有

	//條件查詢實(shí)體列表
	List<T> findList(String hql, List<Object> parameters);
	//條件查詢實(shí)體列表--查詢助手queryHelper
	List<T> findList(QueryHelper queryHelper);
	//分頁條件查詢實(shí)體列表--查詢助手queryHelper
	PageResult getPageResult(QueryHelper queryHelper, int pageNo, int pageSize);

BaseDaoImpl.java

package com.rk.core.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.rk.core.dao.BaseDao;
import com.rk.core.entity.PageResult;
import com.rk.core.utils.HibernateConfigurationUtils;
import com.rk.core.utils.QueryHelper;

public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T> {

	private Class<T> clazz;
	
	@SuppressWarnings("unchecked")
	public BaseDaoImpl() {
		ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
		Type[] args = pt.getActualTypeArguments();
		this.clazz = (Class<T>) args[0];
	}
	
	public void save(T entity) {
		getHibernateTemplate().save(entity);
	}

	public void update(T entity) {
		getHibernateTemplate().update(entity);
	}

	public void delete(Serializable id) {
		String identifierPropertyName = HibernateConfigurationUtils.getIdentifierPropertyName(clazz);
		Session session = getSession();
		session.createQuery("delete from " + clazz.getSimpleName() + " where " + identifierPropertyName + "=?")
			   .setParameter(0, id).executeUpdate();
	}

	public T findById(Serializable id) {
		return getHibernateTemplate().get(clazz, id);
	}

	@SuppressWarnings("unchecked")
	public List<T> findAll() {
		Session session = getSession();
		Query query = session.createQuery("from " + clazz.getSimpleName());
		return query.list();
	}

	public List<T> findList(String hql, List<Object> parameters) {
		Query query = getSession().createQuery(hql);
		if(parameters != null){
			for(int i=0;i<parameters.size();i++){
				query.setParameter(i, parameters.get(i));
			}
		}
		return query.list();
	}

	public List<T> findList(QueryHelper queryHelper) {
		Query query = getSession().createQuery(queryHelper.getQueryListHql());
		List<Object> parameters = queryHelper.getParameters();
		if(parameters != null){
			for(int i=0;i<parameters.size();i++){
				query.setParameter(i, parameters.get(i));
			}
		}
		return query.list();
	}

	public PageResult getPageResult(QueryHelper queryHelper, int pageNo,int pageSize) {
		//1、準(zhǔn)備hql語句和參數(shù)
		String hql = queryHelper.getQueryListHql();
		String countHql = queryHelper.getQueryCountHql();
		List<Object> parameters = queryHelper.getParameters();
		//2、獲取總的數(shù)據(jù)記錄數(shù)
		Query queryCount = getSession().createQuery(countHql);
		if(parameters != null){
			for(int i=0;i<parameters.size();i++){
				queryCount.setParameter(i, parameters.get(i));
			}
		}
		long totalCount = (Long) queryCount.uniqueResult();
		//3、對頁的大小進(jìn)行約束
		if(pageSize < PageResult.MIN_PAGE_SIZE) pageSize = PageResult.MIN_PAGE_SIZE;
		if(pageSize > PageResult.MAX_PAGE_SIZE) pageSize = PageResult.MAX_PAGE_SIZE;
		//4、求解總頁數(shù)
		int quotient = (int) (totalCount / pageSize);
		int remainder = (int) (totalCount % pageSize);
		int totalPageCount = remainder==0?quotient:(quotient+1);
		//5、對當(dāng)前頁進(jìn)行約束
		if(pageNo < 1) pageNo = 1;
		if(pageNo > totalPageCount) pageNo = totalPageCount;
		//6、查詢當(dāng)前頁的數(shù)據(jù)
		Query query = getSession().createQuery(hql);
		if(parameters != null){
			for(int i=0;i<parameters.size();i++){
				query.setParameter(i, parameters.get(i));
			}
		}
		query.setFirstResult((pageNo-1)*pageSize);//設(shè)置數(shù)據(jù)起始索引號
		query.setMaxResults(pageSize);
		List list= query.list();
		//7、返回分頁數(shù)據(jù)
		return new PageResult(totalCount,totalPageCount,pageSize,pageNo,list);
	}

}

其中添加的方法有:

	public List<T> findList(String hql, List<Object> parameters) {
		Query query = getSession().createQuery(hql);
		if(parameters != null){
			for(int i=0;i<parameters.size();i++){
				query.setParameter(i, parameters.get(i));
			}
		}
		return query.list();
	}

	public List<T> findList(QueryHelper queryHelper) {
		Query query = getSession().createQuery(queryHelper.getQueryListHql());
		List<Object> parameters = queryHelper.getParameters();
		if(parameters != null){
			for(int i=0;i<parameters.size();i++){
				query.setParameter(i, parameters.get(i));
			}
		}
		return query.list();
	}

	public PageResult getPageResult(QueryHelper queryHelper, int pageNo,int pageSize) {
		//1、準(zhǔn)備hql語句和參數(shù)
		String hql = queryHelper.getQueryListHql();
		String countHql = queryHelper.getQueryCountHql();
		List<Object> parameters = queryHelper.getParameters();
		//2、獲取總的數(shù)據(jù)記錄數(shù)
		Query queryCount = getSession().createQuery(countHql);
		if(parameters != null){
			for(int i=0;i<parameters.size();i++){
				queryCount.setParameter(i, parameters.get(i));
			}
		}
		long totalCount = (Long) queryCount.uniqueResult();
		//3、對頁的大小進(jìn)行約束
		if(pageSize < PageResult.MIN_PAGE_SIZE) pageSize = PageResult.MIN_PAGE_SIZE;
		if(pageSize > PageResult.MAX_PAGE_SIZE) pageSize = PageResult.MAX_PAGE_SIZE;
		//4、求解總頁數(shù)
		int quotient = (int) (totalCount / pageSize);
		int remainder = (int) (totalCount % pageSize);
		int totalPageCount = remainder==0?quotient:(quotient+1);
		//5、對當(dāng)前頁進(jìn)行約束
		if(pageNo < 1) pageNo = 1;
		if(pageNo > totalPageCount) pageNo = totalPageCount;
		//6、查詢當(dāng)前頁的數(shù)據(jù)
		Query query = getSession().createQuery(hql);
		if(parameters != null){
			for(int i=0;i<parameters.size();i++){
				query.setParameter(i, parameters.get(i));
			}
		}
		query.setFirstResult((pageNo-1)*pageSize);//設(shè)置數(shù)據(jù)起始索引號
		query.setMaxResults(pageSize);
		List list= query.list();
		//7、返回分頁數(shù)據(jù)
		return new PageResult(totalCount,totalPageCount,pageSize,pageNo,list);
	}

2.2、Action層

BaseAction.java

package com.rk.core.action;

import com.opensymphony.xwork2.ActionSupport;
import com.rk.core.entity.PageResult;

public abstract class BaseAction extends ActionSupport {
	protected String[] selectedRow;	
	protected PageResult pageResult;
	protected int pageNo;
	protected int pageSize;
	protected String searchContent;
	
	public String[] getSelectedRow() {
		return selectedRow;
	}
	public void setSelectedRow(String[] selectedRow) {
		this.selectedRow = selectedRow;
	}
	public PageResult getPageResult() {
		return pageResult;
	}
	public void setPageResult(PageResult pageResult) {
		this.pageResult = pageResult;
	}
	public int getPageNo() {
		return pageNo;
	}
	public void setPageNo(int pageNo) {
		this.pageNo = pageNo;
	}
	public int getPageSize() {
		return pageSize;
	}
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	public String getSearchContent() {
		return searchContent;
	}
	public void setSearchContent(String searchContent) {
		this.searchContent = searchContent;
	}
	
}

其中對查詢條件支持的字段有:

	protected String searchContent;

其中對分頁查詢支持的字段有:

	protected PageResult pageResult;
	protected int pageNo;
	protected int pageSize;

InfoAction.java 主要關(guān)注listUI()方法,其它方法只是為了參考和理解

	//列表頁面
	public String listUI(){
		//加載分類集合
		ActionContext.getContext().getContextMap().put("infoTypeMap", Info.INFO_TYPE_MAP);
		//分頁數(shù)據(jù)查詢
		QueryHelper queryHelper = new QueryHelper(Info.class, "i");
		try {
			if(StringUtils.isNotBlank(searchContent)){
				searchContent = URLDecoder.decode(searchContent, "UTF-8");
				queryHelper.addCondition("i.title like ?", "%"+searchContent+"%");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		queryHelper.addOrderByProperty("i.createTime", QueryHelper.ORDER_BY_DESC);
		String hql = queryHelper.getQueryListHql();
		pageResult = infoService.getPageResult(queryHelper, pageNo, pageSize);
		
		return "listUI";
	}
	//跳轉(zhuǎn)到新增頁面
	public String addUI(){
		//加載分類集合
		ActionContext.getContext().getContextMap().put("infoTypeMap", Info.INFO_TYPE_MAP);
		info = new Info();
		info.setCreateTime(new Timestamp(new Date().getTime())); // 是為了在頁面中顯示出當(dāng)前時(shí)間
		return "addUI";
	}
	
	//保存新增
	public String add(){
		if(info != null){
			infoService.save(info);
		}
		return "list";
	}
	
	//跳轉(zhuǎn)到編輯頁面
	public String editUI(){
		//加載分類集合
		ActionContext.getContext().getContextMap().put("infoTypeMap", Info.INFO_TYPE_MAP);
		if(info != null && info.getInfoId() != null){
			info = infoService.findById(info.getInfoId());
		}
		return "editUI";
	}
	
	//保存編輯
	public String edit(){
		if(info != null){
			infoService.update(info);
		}
		return "list";
	}
	
	//刪除
	public String delete(){
		if(info != null && info.getInfoId() != null){
			infoService.delete(info.getInfoId());
		}
		return "list";
	}
	
	//批量刪除
	public String deleteSelected(){
		if(selectedRow != null){
			for(String id : selectedRow){
				infoService.delete(id);
			}
		}
		return "list";
	}

其中,searchContent/pageNo/pageSize/pageResult變量繼承自父類(BaseAction)。

除了實(shí)現(xiàn)條件查詢(分頁查詢)之外,還要在進(jìn)行“刪除和編輯”操作時(shí),需要記錄“查詢關(guān)鍵字”、“頁碼”。而新增操作,則不需要記住原來的“查詢關(guān)鍵字”和“頁碼”,因?yàn)槲覀冞M(jìn)行添加操作后,想看到的就是自己新添加的對象,而不是原來查詢條件下記錄。

在struts-tax.xml中,action是進(jìn)行如下映射的:

        <!-- InfoAction -->
        <action name="info_*" class="infoAction" method="{1}">
        	<result name="{1}">/WEB-INF/jsp/tax/info/{1}.jsp</result>
        	<result name="list" type="redirectAction">
        		<param name="actionName">info_listUI</param>
        		<param name="searchContent">${searchContent}</param>
        		<param name="pageNo">${pageNo}</param>
        		<param name="encode">true</param>
        	</result>
        </action>

此處對searchContent內(nèi)容進(jìn)行Url encode的轉(zhuǎn)換,因?yàn)樵趌istUI()方法代碼中,

searchContent = URLDecoder.decode(searchContent, "UTF-8");

對于URLEncoder和URLDecoder的一個(gè)小測試

	@Test
	public void test() throws Exception{
		String str = "中國";
		String strEncode = URLEncoder.encode(str,"utf-8");
		String strDecode = URLDecoder.decode(strEncode, "utf-8");
		String strDecode2 = URLDecoder.decode(str, "utf-8");
		
		System.out.println(str);
		System.out.println(strEncode);
		System.out.println(strDecode);
		System.out.println(strDecode2);
	}

輸出

中國
%E4%B8%AD%E5%9B%BD
中國
中國

UrlEncoder的源碼

public class URLDecoder {

    // The platform default encoding
    static String dfltEncName = URLEncoder.dfltEncName;


    /**
     * Decodes a <code>application/x-www-form-urlencoded</code> string using a specific
     * encoding scheme.
     *
     * The supplied encoding is used to determine what characters 
     * are represented by any consecutive sequences of the form "%xy".
     * 
     * 
     * Note: The World Wide Web Consortium Recommendation states that
     * UTF-8 should be used. Not doing so may introduce incompatibilites.
     * 
     *
     * @param s the <code>String</code> to decode
     * @param enc   The name of a supported character encoding
     * @return the newly decoded <code>String</code>
     */
    public static String decode(String s, String enc)
        throws UnsupportedEncodingException{

        boolean needToChange = false;
        int numChars = s.length();
        StringBuffer sb = new StringBuffer(numChars > 500 ? numChars / 2 : numChars);
        int i = 0;

        if (enc.length() == 0) {
            throw new UnsupportedEncodingException ("URLDecoder: empty string enc parameter");
        }

        char c;
        byte[] bytes = null;
        while (i < numChars) {
            c = s.charAt(i);
            switch (c) {
            case '+':
                sb.append(' ');
                i++;
                needToChange = true;
                break;
            case '%':
                /*
                 * Starting with this instance of %, process all
                 * consecutive substrings of the form %xy. Each
                 * substring %xy will yield a byte. Convert all
                 * consecutive  bytes obtained this way to whatever
                 * character(s) they represent in the provided
                 * encoding.
                 */

                try {

                    // (numChars-i)/3 is an upper bound for the number
                    // of remaining bytes
                    if (bytes == null)
                        bytes = new byte[(numChars-i)/3];
                    int pos = 0;

                    while ( ((i+2) < numChars) &&
                            (c=='%')) {
                        int v = Integer.parseInt(s.substring(i+1,i+3),16);
                        if (v < 0)
                            throw new IllegalArgumentException("URLDecoder: Illegal hex characters in escape (%) pattern - negative value");
                        bytes[pos++] = (byte) v;
                        i+= 3;
                        if (i < numChars)
                            c = s.charAt(i);
                    }

                    // A trailing, incomplete byte encoding such as
                    // "%x" will cause an exception to be thrown

                    if ((i < numChars) && (c=='%'))
                        throw new IllegalArgumentException(
                         "URLDecoder: Incomplete trailing escape (%) pattern");

                    sb.append(new String(bytes, 0, pos, enc));
                } catch (NumberFormatException e) {
                    throw new IllegalArgumentException(
                    "URLDecoder: Illegal hex characters in escape (%) pattern - "
                    + e.getMessage());
                }
                needToChange = true;
                break;
            default:
                sb.append(c);
                i++;
                break;
            }
        }

        return (needToChange? sb.toString() : s);
    }
}

3、JSP頁面

3.1、pageNavigator.jsp

在WebRoot/common目錄下

<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<div class="c_pate" >
	<s:if test="pageResult.totalCount > 0">
		<table width="100%" class="pageDown" border="0" cellspacing="0" cellpadding="0">
			<tr>
				<td align="right">
                	總共<s:property value="pageResult.totalCount"/>條記錄,
                	當(dāng)前第 <s:property value="pageResult.pageNo"/> 頁,
                 	共<s:property value="pageResult.totalPageCount"/> 頁 &nbsp;&nbsp;
                    <s:if test="pageResult.pageNo > 1">
                            <a href="javascript:doGoPage(<s:property value="pageResult.pageNo-1"/>)">上一頁</a>&nbsp;&nbsp;
                    </s:if>
                    <s:else>
                    	<a href="javascript:;">上一頁</a>&nbsp;&nbsp;
                    </s:else>        
                    <s:if test="pageResult.pageNo < pageResult.totalPageCount">
                            <a href="javascript:doGoPage(<s:property value="pageResult.pageNo+1"/>)">下一頁</a>
                    </s:if>
                    <s:else>
                    	<a href="javascript:;">下一頁</a>
                    </s:else>        
					到&nbsp;<input id="pageNo" name="pageNo" type="text"  onkeypress="if(event.keyCode == 13){doGoPage(this.value);}" min="1"
					max="<s:property value="pageResult.totalPageCount"/>" value="<s:property value="pageResult.pageNo"/>" /> &nbsp;&nbsp;
			    </td>
			</tr>
		</table>
	</s:if>
	<s:else>
		暫無數(shù)據(jù)!
	</s:else>
</div>
<script type="text/javascript">
	//翻頁
	function doGoPage(pageNum){
		document.getElementById("pageNo").value = pageNum;
		document.forms[0].action = list_url;
		document.forms[0].submit();
	}
	//搜索
   function doSearch(){
		//重置頁號
		$('#pageNo').val(1);
		document.forms[0].action = list_url;
		document.forms[0].submit();
	}
</script>

注意:在這最后一段Javascript中引用了一個(gè)list_url變量,它需要在主頁面(listUI.jsp)內(nèi)提供它的值。

3.2、listUI.jsp

<%@page import="org.apache.struts2.components.Include"%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <%@include file="/common/header.jsp"%>
    <title>信息發(fā)布管理</title>
    <script type="text/javascript">
      	//全選、全反選
		function doSelectAll(){
			// jquery 1.6 前
			//$("input[name=selectedRow]").attr("checked", $("#selAll").is(":checked"));
			//prop jquery 1.6+建議使用
			$("input[name=selectedRow]").prop("checked", $("#selAll").is(":checked"));		
		}
        //新增
        function doAdd(){
        	document.forms[0].action = "${basePath}/tax/info_addUI.action";
        	document.forms[0].submit();
        }
        //編輯
        function doEdit(id){
            document.forms[0].action = "${basePath}/tax/info_editUI.action?info.infoId="+id;
        	document.forms[0].submit();
        }
        //刪除
        function doDelete(id){
        	document.forms[0].action = "${basePath}/tax/info_delete.action?info.infoId="+id;
        	document.forms[0].submit();
        }
        //批量刪除
        function doDeleteAll(){
        	document.forms[0].action = "${basePath}/tax/info_deleteSelected.action";
        	document.forms[0].submit();
        }
        //異步發(fā)布信息,信息的id及將要改成的信息狀態(tài)
  		function doPublic(infoId, state){
  			//1、更新信息狀態(tài)
  			$.ajax({
  				url:"${basePath}/tax/info_publicInfo.action",
  				data:{"info.infoId":infoId,"info.state":state},
  				type:"post",
  				success:function(msg){
  					//2、更新狀態(tài)欄、操作攔的顯示值
  					if("更新狀態(tài)成功" == msg){
  						if(state == 1){//說明信息狀態(tài)已經(jīng)被改成 發(fā)布,狀態(tài)欄顯示 發(fā)布,操作欄顯示 停用
  							$('#show_'+infoId).html("發(fā)布");
  							$('#oper_'+infoId).html('<a href="javascript:doPublic(\''+infoId+'\',0)">停用</a>');
  						}
  						else{
  							$('#show_'+infoId).html("停用");
  							$('#oper_'+infoId).html('<a href="javascript:doPublic(\''+infoId+'\',1)">發(fā)布</a>');
  						}
  					}
  					else{
  						alert("更新信息狀態(tài)失??!");
  					}
  				},
  				error:function(){
  					alert("更新信息狀態(tài)失??!");
  				}
  			});
  		}
        var list_url = "${basePath}/tax/info_listUI.action";

    </script>
</head>
<body class="rightBody">
<form name="form1" action="" method="post">
    <div class="p_d_1">
        <div class="p_d_1_1">
            <div class="content_info">
                <div class="c_crumbs"><div><b></b><strong>信息發(fā)布管理</strong></div> </div>
                <div class="search_art">
                    <li>
                        信息標(biāo)題:<s:textfield name="searchContent" cssClass="s_text" id="searchContent"  cssStyle="width:160px;"/>
                    </li>
                    <li><input type="button" class="s_button" value="搜 索" onclick="doSearch()"/></li>
                    <li >
                        <input type="button" value="新增" class="s_button" onclick="doAdd()"/>&nbsp;
                        <input type="button" value="刪除" class="s_button" onclick="doDeleteAll()"/>&nbsp;
                    </li>
                </div>

                <div class="t_list" >
                    <table width="100%" border="0">
                        <tr class="t_tit">
                            <td width="30" align="center"><input type="checkbox" id="selAll" onclick="doSelectAll()" /></td>
                            <td align="center">信息標(biāo)題</td>
                            <td width="120" align="center">信息分類</td>
                            <td width="120" align="center">創(chuàng)建人</td>
                            <td width="140" align="center">創(chuàng)建時(shí)間</td>
                            <td width="80" align="center">狀態(tài)</td>
                            <td width="120" align="center">操作</td>
                        </tr>
                        <s:iterator value="pageResult.items" status="st">
                            <tr <s:if test="#st.odd"> bgcolor="f8f8f8" </s:if> >
                                <td align="center"><input type="checkbox" name="selectedRow" value="<s:property value='infoId'/>"/></td>
                                <td align="center"><s:property value="title"/></td>
                                <td align="center">
                                	<s:property value="#infoTypeMap[type]"/>	
                                </td>
                                <td align="center"><s:property value="creator"/></td>
                                <td align="center"><s:date name="createTime" format="yyyy-MM-dd HH:mm"/></td>
                                <td id="show_<s:property value='infoId'/>" align="center"><s:property value="state==1?'發(fā)布':'停用'"/></td>
                                <td align="center">
                                	<span id="oper_<s:property value="infoId"/>">
                                		<s:if test="state==1">
                                			<a href="javascript:doPublic('<s:property value="infoId" />',0)">停用</a>
                                		</s:if>
                                		<s:else>
                                			<a href="javascript:doPublic('<s:property value="infoId"/>',1)">發(fā)布</a>
                                		</s:else>
                                	</span>
                                    <a href="javascript:doEdit('<s:property value='infoId'/>')">編輯</a>
                                    <a href="javascript:doDelete('<s:property value='infoId'/>')">刪除</a>
                                </td>
                            </tr>
                        </s:iterator>
                    </table>
                </div>
            </div>
			<%@include file="/common/pageNavigator.jsp" %>
        </div>
    </div>
</form>

</body>
</html>

知識點(diǎn)(1):在點(diǎn)擊搜索的時(shí)候,要將頁碼設(shè)置為1

        function doSearch(){
        	//重置頁號
        	$('#pageNo').val(1);
        	document.forms[0].action = list_url;
        	document.forms[0].submit();
        }

知識點(diǎn)(2):現(xiàn)在獲取的顯示數(shù)據(jù)不再是List對象,而是PageResult對象

<s:iterator value="pageResult.items" status="st">

知識點(diǎn)(3):為了引入通用的pageNavigator.jsp,需要定義一個(gè)list_url變量

var list_url = "${basePath}/tax/info_listUI.action";

引入頁面

<%@include file="/common/pageNavigator.jsp" %>

3.3、editUI.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <%@include file="/common/header.jsp"%>
    <title>信息發(fā)布管理</title>
	<script type="text/javascript" src="${basePath}/js/ueditor/ueditor.config.js"></script>
	<script type="text/javascript" src="${basePath}/js/ueditor/ueditor.all.js"></script>
	<script type="text/javascript" src="${basePath}/js/ueditor/lang/zh-cn/zh-cn.js"></script>
    <script>
    	window.UEDITOR_HOME_URL = "${basePath}/js/ueditor";
    	window.onload = function(){
    		var ue = UE.getEditor("editor");
    	}
    </script>
</head>
<body class="rightBody">
<form id="form" name="form" action="${basePath}/tax/info_edit.action" method="post" enctype="multipart/form-data">
    <div class="p_d_1">
        <div class="p_d_1_1">
            <div class="content_info">
    <div class="c_crumbs"><div><b></b><strong>信息發(fā)布管理</strong>&nbsp;-&nbsp;修改信息</div></div>
    <div class="tableH2">修改信息</div>
    <table id="baseInfo" width="100%" align="center" class="list" border="0" cellpadding="0" cellspacing="0"  >
        <tr>
            <td class="tdBg" width="200px">信息分類:</td>
            <td><s:select name="info.type" list="#infoTypeMap"/></td>
            <td class="tdBg" width="200px">來源:</td>
            <td><s:textfield name="info.source"/></td>
        </tr>
        <tr>
            <td class="tdBg" width="200px">信息標(biāo)題:</td>
            <td colspan="3"><s:textfield name="info.title" cssStyle="width:90%"/></td>
        </tr>
        <tr>
            <td class="tdBg" width="200px">信息內(nèi)容:</td>
            <td colspan="3"><s:textarea id="editor" name="info.content" cssStyle="width:90%;height:160px;" /></td>
        </tr>
        <tr>
            <td class="tdBg" width="200px">備注:</td>
            <td colspan="3"><s:textarea name="info.memo" cols="90" rows="3"/></td>
        </tr>
        <tr>
            <td class="tdBg" width="200px">創(chuàng)建人:</td>
            <td>
            	<s:property value="info.creator"/>
            	<s:hidden name="info.creator"/>            
            </td>
            <td class="tdBg" width="200px">創(chuàng)建時(shí)間:</td>
            <td>
              	<s:date name="info.createTime" format="yyyy-MM-dd HH:ss"/>
             	<s:hidden name="info.createTime"/>
            </td>
        </tr>
    </table>
    <!-- 當(dāng)前信息的id和狀態(tài) -->
    <s:hidden name="info.infoId"/>
    <s:hidden name="info.state"/>
    <!-- 暫存查詢條件值 -->
    <s:hidden name="searchContent"/>
    <s:hidden name="pageNo"/>
    <div class="tc mt20">
        <input type="submit" class="btnB2" value="保存" />
        &nbsp;&nbsp;&nbsp;&nbsp;
        <input type="button"  onclick="javascript:history.go(-1)" class="btnB2" value="返回" />
    </div>
    </div></div></div>
</form>
</body>
</html>

知識點(diǎn)(1):為了保存查詢的關(guān)鍵字和分頁,將相應(yīng)信息隱藏在編輯頁面

    <!-- 暫存查詢條件值 -->
    <s:hidden name="searchContent"/>
    <s:hidden name="pageNo"/>

關(guān)于“SSH如何實(shí)現(xiàn)條件查詢和分頁查詢”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯(cuò),請把它分享出去讓更多的人看到。

文章名稱:SSH如何實(shí)現(xiàn)條件查詢和分頁查詢
鏈接分享:http://bm7419.com/article28/gihijp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設(shè)計(jì)公司、網(wǎng)站建設(shè)標(biāo)簽優(yōu)化、服務(wù)器托管、網(wǎng)站改版

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都app開發(fā)公司