Spring SSH模糊分頁查詢(可模糊子表)

在Web.xml文件配置中添加配置

 <!-- 配置struts過濾器 -->
  <filter>
  	<filter-name>struts</filter-name>
  	<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>struts</filter-name>
	<url-pattern>/*</url-pattern>
  </filter-mapping>
  <!-- 配置Spring監聽器 -->
  <listener>
  	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- 加載在classpath目錄下的application文件 -->
  <context-param>
  	<param-name>contextConfigLocation</param-name>
  	<param-value>classpath*:application*.xml</param-value>
  </context-param>

實體類(用註解方式完成Hibernate的映射配置)

Category.java

package com.mingde.po;


import java.util.HashSet;
import java.util.Set;


import javax.persistence.CascadeType;
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.Table;


@Entity
@Table(name="co_dbinf_category")
public class Category {
	private int cate_id;
	private String cdcname;
	private String intro;
	
	private Set<Info> infos=new HashSet<>();
	
	public Category() {
		super();
	}
	public Category(int cate_id, String cdcname, String intro) {
		super();
		this.cate_id = cate_id;
		this.cdcname = cdcname;
		this.intro = intro;
	}
	@OneToMany(fetch=FetchType.EAGER,cascade=CascadeType.ALL,orphanRemoval=true,mappedBy="category")
	public Set<Info> getInfos() {
		return infos;
	}
	public void setInfos(Set<Info> infos) {
		this.infos = infos;
	}
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	public int getCate_id() {
		return cate_id;
	}
	public void setCate_id(int cate_id) {
		this.cate_id = cate_id;
	}
	public String getCdcname() {
		return cdcname;
	}
	public void setCdcname(String cdcname) {
		this.cdcname = cdcname;
	}
	public String getIntro() {
		return intro;
	}
	public void setIntro(String intro) {
		this.intro = intro;
	}
	@Override
	public String toString() {
		return "Category [cate_id=" + cate_id + ", cdcname=" + cdcname + ", intro=" + intro + ", infos=" + infos + "]";
	}
	
}

Info.java

package com.mingde.po;

import java.sql.Date;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="co_dbinf_info")
public class Info {
	private int info_id;
	private String createor_id;
	private String state;
	private String title;
	private String keyword;
	private String cdicontent;
	private Date create_date;
	
	private Category category;
	
	public Info() {
		super();
	}
	public Info(int info_id, String createor_id, String state, String title, String keyword, String cdicontent,
			Date create_date) {
		super();
		this.info_id = info_id;
		this.createor_id = createor_id;
		this.state = state;
		this.title = title;
		this.keyword = keyword;
		this.cdicontent = cdicontent;
		this.create_date = create_date;
	}
	@ManyToOne(fetch=FetchType.EAGER)
	@JoinColumn(name="co_id")
	public Category getCategory() {
		return category;
	}
	public void setCategory(Category category) {
		this.category = category;
	}
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	public int getInfo_id() {
		return info_id;
	}
	public void setInfo_id(int info_id) {
		this.info_id = info_id;
	}
	public String getCreateor_id() {
		return createor_id;
	}
	public void setCreateor_id(String createor_id) {
		this.createor_id = createor_id;
	}
	public String getState() {
		return state;
	}
	public void setState(String state) {
		this.state = state;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getKeyword() {
		return keyword;
	}
	public void setKeyword(String keyword) {
		this.keyword = keyword;
	}
	public String getCdicontent() {
		return cdicontent;
	}
	public void setCdicontent(String cdicontent) {
		this.cdicontent = cdicontent;
	}
	public Date getCreate_date() {
		return create_date;
	}
	public void setCreate_date(Date create_date) {
		this.create_date = create_date;
	}
	@Override
	public String toString() {
		return "Info [info_id=" + info_id + ", createor_id=" + createor_id + ", state=" + state + ", title=" + title
				+ ", keyword=" + keyword + ", cdicontent=" + cdicontent + ", create_date=" + create_date + "]";
	}
	
}


PageBean.java

package com.mingde.po;

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

public class PageBean {
	
	private int page;
	private int pageSize;
	private int totalRecored;
	private int totalPage;
	private List<Category> categorys=new ArrayList<>();
	public PageBean() {
		super();
	}
	public PageBean(int page, int pageSize, int totalRecored, int totalPage, List<Category> categorys) {
		super();
		this.page = page;
		this.pageSize = pageSize;
		this.totalRecored = totalRecored;
		this.totalPage = totalPage;
		this.categorys = categorys;
	}
	public int getPage() {
		return page;
	}
	public void setPage(int page) {
		this.page = page;
	}
	public int getPageSize() {
		return pageSize;
	}
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	public int getTotalRecored() {
		return totalRecored;
	}
	public void setTotalRecored(int totalRecored) {
		this.totalRecored = totalRecored;
	}
	public int getTotalPage() {
		return totalPage;
	}
	public void setTotalPage(int totalPage) {
		this.totalPage = totalPage;
	}
	public List<Category> getCategorys() {
		return categorys;
	}
	public void setCategorys(List<Category> categorys) {
		this.categorys = categorys;
	}
	@Override
	public String toString() {
		return "PageBean [page=" + page + ", pageSize=" + pageSize + ", totalRecored=" + totalRecored + ", totalPage="
				+ totalPage + ", categorys=" + categorys + "]";
	}

}

在classpath目錄下配置Spring容器:applicationContext.xml

右擊classpath目錄→New→Other...


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
	
	<!-- 註解必須配置此項,代表spring容器會主動掃描com.mingde包及其子包下的所有註解 -->
	<context:component-scan base-package="com.mingde"/>
	<!-- 用c3p0配置數據源 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"></property>
		<property name="jdbcUrl" value="jdbc:sqlserver://localhost:1433;databaseName=CMIP3" ></property>
		<property name="user" value="sa"></property>
		<property name="password" value="123"></property>
	</bean>
	<!-- 配置sessionFactory -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<!-- 獲取數據源 -->
		<property name="dataSource" ref="dataSource" />
		<!-- 配置Hibernate常用屬性 -->
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.dialect">org.hibernate.dialect.SQLServer2008Dialect</prop>
			</props>
		</property>
		<!-- 配置註解映射 -->
		<property name="packagesToScan">
			<value>com.mingde.po</value>
		</property>
	</bean>
	
	<!-- 配置事務 -->
	<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"
	 p:sessionFactory-ref="sessionFactory" />
	<tx:annotation-driven/>
</beans>

dao層

IBaseDao.java

package com.mingde.dao;

import java.util.List;

public interface IBaseDao {

	List findAll(String hql);
	
}

BaseDaoImpl.java

package com.mingde.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.mingde.dao.IBaseDao;

@Transactional
@Repository("baseDao")//在spring容器中存放定義的名稱爲baseDao的bean,將該類放入到bean中,方便在action中獲取
//因爲若在action直接new一個BaseDaoImpl的話,是獲取不到sessionFactory的
public class BaseDaoImpl implements IBaseDao{

	@Resource	//在spring容器中引入名稱爲sessionFactory的bean
	private SessionFactory sessionFactory;
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	@Transactional(readOnly=true)
	public List findAll(String hql) {
		Session session =sessionFactory.getCurrentSession();
		return session.createQuery(hql).list();
	}
	
	
}

Struts.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
	<constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>
	<constant name="struts.devMode" value="true"></constant>
	<package name="struts" extends="struts-default">
		<action name="*_*" class="com.mingde.action.ZAction" method="{2}" >
			<result name="{2}">/WEB-INF/{1}/{2}.jsp</result>
			<result name="to_list" type="redirect">{1}_list</result>
		</action>
	</package>
</struts>

Action類

package com.mingde.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.mingde.dao.IBaseDao;
import com.mingde.po.Category;
import com.mingde.po.Info;
import com.mingde.po.PageBean;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class ZAction extends ActionSupport{
	
	@Resource(name="baseDao")	//引入spring容器中名稱爲baseDao的beanDao
	private IBaseDao bd;
	private List<Category> clist=new ArrayList<>();
	private PageBean pb=new PageBean();
	private Map<Integer,Category> map=new HashMap<>();
	private List<Info> ilist=new ArrayList<>();
	private int cate_id;
	private String createor_id;
	private String title;
	
	
	public String list()throws Exception{
		String hql="from Info where 1=1 ";
		if(cate_id!=0)hql+=" and category.cate_id="+cate_id;
		if(null!=createor_id && !"".equals(createor_id))hql+=" and createor_id like '%"+createor_id+"%'";
		if(null!=title && !"".equals(title))hql+=" and title like '%"+title+"%'";
		clist=bd.findAll("from Category where 1=1 ");
		ilist=bd.findAll(hql);
		
		for(Info i:ilist){
			if(!map.containsKey(i.getCategory().getCate_id())){
				map.put(i.getCategory().getCate_id(),i.getCategory());
				i.getCategory().setInfos(new HashSet<>());
				i.getCategory().getInfos().add(i);
			}else{
				map.get(i.getCategory().getCate_id()).getInfos().add(i);
			}
		}
		
		//將數組轉化爲集合
		/*Integer[] i=new Integer[10];
		List<Integer> asList = Arrays.asList(i);*/
		
		if(pb.getPage()==0)pb.setPage(1);
		if(pb.getPageSize()==0)pb.setPageSize(2);
		pb.setTotalRecored(map.size());
		pb.setTotalPage((int)Math.ceil((double)map.size()/pb.getPageSize()));
		//將map的值轉換爲list集合
		List<Category> c=new ArrayList<>(map.values());
		//用來判斷截取第二位置的位置
		int flag=c.size();
		if(flag>pb.getPage()*pb.getPageSize()){
			flag=pb.getPage()*pb.getPageSize();
		}
		//截取某個下標到某個下標之間的值
		List<Category> subList = c.subList((pb.getPage()-1)*pb.getPageSize(), flag);
		pb.setCategorys(subList);
		return "list";
	}

	/** 所有的屬性都需要get和set方法,這裏省略…… **/
	
}

JSP頁面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<script>
	function $(v){
		return document.getElementById(v);
	}
	function fun(v){
		$(v).style.display=$(v).style.display=="none"?"":"none";
	}
	function funp(v){
		$('page').value=v;
		$("frm").submit();
	}
	function funp2(v){
		$('page').value=1;
		$('pageSize').value=v;
		$("frm").submit();
	}
</script>
<body>
	<h2>列表</h2>
	<table align="center" width=1200 border=1 rules="all">
		<tr><td colspan=4>
			<s:form id="frm" action="z_list" theme="simple">
 				<s:hidden name="pb.page" id="page"></s:hidden>
 				<s:hidden name="pb.pageSize" id="pageSize"></s:hidden>
 				欄目:<s:select name="cate_id" list="clist" listKey="cate_id" listValue="cdcname"
 				headerKey="0" headerValue="全部"></s:select>
 				發佈人:<s:textfield name="createor_id" ></s:textfield>
 				信息標題:<s:textfield name="title" ></s:textfield>
 				<s:submit value="查詢"></s:submit>
 			</s:form>
 		</td></tr>
		<tr>
			<th>ID</th><th>欄目</th><th>內容</th><th>操作</th>
		</tr>
		<s:iterator value="pb.categorys">
			<tr align="center" οnclick="fun('z_${cate_id }')">
				<td><s:property value="cate_id" /></td>
				<td><s:property value="cdcname" /></td>
				<td><s:property value="intro" /></td>
				<td>
					修改
					刪除
				</td>
			</tr>
			<tr id="z_${cate_id }" style="display:none" >
				<td colspan=4>
					<table border=1 rules="all" align="center" width="1000">
						<tr>
							<th>ID</th><th>發佈人</th><th>分類ID</th><th>信息標題</th><th>關鍵字</th><th>正文</th><th>創建日期</th>
						</tr>
						<s:iterator value="infos">
							<tr align="center">
								<td><s:property value="info_id" /></td>
								<td><s:property value="createor_id" /></td>
								<td><s:property value="state" /></td>
								<td><s:property value="title" /></td>
								<td><s:property value="keyword" /></td>
								<td><s:property value="cdicontent" /></td>
								<td><s:property value="create_date" /></td>
							</tr>
						</s:iterator>
					</table>
				</td>
			</tr>
		</s:iterator>
				<tr>
			<td colspan=4>
				<s:if test="pb.page==1 && pb.page<pb.totalPage">
					<a  href="javascript:void(0)" οnclick="funp(${pb.page+1})">下一頁</a>
					<a  href="javascript:void(0)" οnclick="funp(${pb.totalPage})">尾頁</a>
				</s:if>
				<s:if test="pb.page!=1 && pb.page==pb.totalPage">
					<a  href="javascript:void(0)" οnclick="funp(1)">首頁</a>
					<a  href="javascript:void(0)" οnclick="funp(${pb.page-1})">上一頁</a>
				</s:if>
				<s:if test="pb.page>1 && pb.page<pb.totalPage">
					<a  href="javascript:void(0)" οnclick="funp(1)">首頁</a>
					<a  href="javascript:void(0)" οnclick="funp(${pb.page-1})">上一頁</a>
					<a  href="javascript:void(0)" οnclick="funp(${pb.page+1})">下一頁</a>
					<a  href="javascript:void(0)" οnclick="funp(${pb.totalPage})">尾頁</a>
				</s:if>
				         
				<s:if test="pb.totalPage!=0">
					第${pb.page }頁 / 共${pb.totalPage }頁
				</s:if>
				         
				每頁顯示<input size="1" οnblur="funp2(this.value)" value="${pb.pageSize }" >條信息
			</td>
		</tr>
	</table>
</body>
</html>







發佈了62 篇原創文章 · 獲贊 9 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章