`
x125521853
  • 浏览: 72671 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

struts2+hibernate(文件批量上传至数据库+Ajax分页显示)

    博客分类:
  • Item
阅读更多

一:创建web项目导入struts2和hibernate的jar包,jar包放入WEB-INF下lib目录里

     struts2的jar包六个:struts2-core-2.1.8.1.jar,commons-fileupload-1.2.1.jar

                          commons-io-1.3.2.jar,freemarker-2.3.15.jar

                          ognl-2.7.3.jar,xwork-core-2.1.6.jar   

     hibernate的jar包十八个:antlr-2.7.6.jar,asm.jar ,asm-attrs.jar,

                      c3p0-0.9.1.jar,cglib-2.1.3.jar ,hibernate3.jar

                      commons-collections-2.1.1.jar  ,jaas.jar

                      commons-logging-1.0.4.jar,dom4j-1.6.1.jar 

                      ehcache-1.2.3.jar,javassist.jar,jaxen-1.1-beta-7.jar

                      jdbc2_0-stdext.jar,jta.jar ,log4j-1.2.11.jar,

                       xerces-2.6.2.jar ,xml-apis.jar

二:model层

    Student.java   

package com.wdpc.hibernate.model;

import java.util.Date;

public class Student {
	private String id;
	private String username;//姓名
	private Integer age;//年龄
	private Date bithday;//生日
	private String address;//地址
	private MyClass myclass;

	//无参构造
	public Student() {
		super();
	}
	
	//有参构造
	public Student(String username, Integer age, Date bithday, String address) {
		super();
		this.username = username;
		this.age = age;
		this.bithday = bithday;
		this.address = address;
	}

	public Student(String id, String username, Integer age, Date bithday,
			String address, MyClass myclass) {
		super();
		this.id = id;
		this.username = username;
		this.age = age;
		this.bithday = bithday;
		this.address = address;
		this.myclass = myclass;
	}	

	public Student(String username, Integer age, Date bithday, String address,
			MyClass myclass) {
		super();
		this.username = username;
		this.age = age;
		this.bithday = bithday;
		this.address = address;
		this.myclass = myclass;
	}

	//get,set方法
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public Date getBithday() {
		return bithday;
	}

	public void setBithday(Date bithday) {
		this.bithday = bithday;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public MyClass getMyclass() {
		return myclass;
	}

	public void setMyclass(MyClass myclass) {
		this.myclass = myclass;
	}
}

 

   //Student.hbm.xml  

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.wdpc.hibernate.model">
	<class name="Student" table="student">
		<id name="id" type="java.lang.String" column="id" length="32">
			<generator class="uuid.hex"/>
		</id>
		<property name="username" type="java.lang.String" column="username"/>
		<property name="age" type="java.lang.Integer" column="age"/>
		<property name="bithday" type="java.util.Date" column="bithday"/>
		<property name="address" type="java.lang.String" column="address"/>
		<many-to-one name="myclass" class="MyClass" cascade="save-update">
			<column name="class_id" length="32" />
		</many-to-one>
	</class>
</hibernate-mapping>

   此映射文件要与Student.java类放在一起,放在model层下

 

   //MyClass.java  

package com.wdpc.hibernate.model;

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

public class MyClass {
	private String id;
	private String name;//班级名
	private Set<Student> students = new HashSet<Student>();

	public MyClass(String id, String name, Set<Student> students) {
		super();
		this.id = id;
		this.name = name;
		this.students = students;
	}

	public MyClass(String name) {
		super();
		this.name = name;
	}

	public MyClass(String name, Set<Student> students) {
		super();
		this.name = name;
		this.students = students;
	}

	public MyClass() {
		super();
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Set<Student> getStudents() {
		return students;
	}

	public void setStudents(Set<Student> students) {
		this.students = students;
	}
}

 

   //MyClass.hbm.xml  

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.wdpc.hibernate.model">
	<class name="MyClass" table="myclass">
		<id name="id" type="java.lang.String" column="id" length="32">
			<generator class="uuid.hex"/>
		</id>
		<property name="name" type="java.lang.String" column="name"/>
		<set name="students">
			<key column="class_id"/>
			<one-to-many class="Student"/>
		</set>
	</class>
</hibernate-mapping>

    此xml配置同上

  

    以下类放置组件包内

   //BaseAction.java  

package com.wdpc.hibernate.comms;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;

public class BaseAction extends ActionSupport implements ServletResponseAware, ServletRequestAware,
		SessionAware {

	protected HttpServletResponse response;
	protected HttpServletRequest request;
	protected Map<String, Object> session;

	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public Map<String, Object> getSession() {
		return session;
	}
}

  

  //HibernateUtil.java 

package com.wdpc.hibernate.comms;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
	private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
	private static Configuration configuration = new Configuration();
	private static org.hibernate.SessionFactory sessionFactory;
	private static String configFile = CONFIG_FILE_LOCATION;
	
	static {
		try {
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}
	private HibernateUtil() {
	}
	
	public static Session getSession() throws HibernateException {
		Session session = (Session) threadLocal.get();

		if (session == null || !session.isOpen()) {
			if (sessionFactory == null) {
				rebuildSessionFactory();
			}
			session = (sessionFactory != null) ? sessionFactory
					.getCurrentSession() : null;
			threadLocal.set(session);
		}
		return session;
	}
	
	public static void rebuildSessionFactory() {
		try {
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}
	
	public static void closeSession() throws HibernateException {
		Session session = (Session) threadLocal.get();
		threadLocal.set(null);

		if (session != null) {
			session.close();
		}
	}
	
	public static org.hibernate.SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	
	public static void setConfigFile(String configFile) {
		HibernateUtil.configFile = configFile;
		sessionFactory = null;
	}
	
	public static Configuration getConfiguration() {
		return configuration;
	}
}

 

   //LazyFilter.java(过滤器)  

package com.wdpc.hibernate.comms;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class LazyFilter implements Filter {

	public void destroy() {

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		Session session = null;
		Transaction transaction = null;
		try {
			session = HibernateUtil.getSession();
			transaction = session.getTransaction();
			transaction.begin();
			chain.doFilter(request, response);
			transaction.commit();
		} catch (Exception e) {
			transaction.rollback();
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	public void init(FilterConfig arg0) throws ServletException {

	}
}

 

   //Page.java  

package com.wdpc.hibernate.comms;

import java.util.List;
import com.wdpc.hibernate.model.Student;

public class Page {
	private int pageSize; 
	private List<Student> data; 
	private long totalCount; 
	private int currentPageNo; 
	
	public Page() {
		pageSize = 5;
		currentPageNo = 1;
	}
	
	public Page(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getPageSize() {
		return pageSize;
	}

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

	public List<Student> getData() {
		return data;
	}

	public void setData(List<Student> data) {
		this.data = data;
	}

	public long getTotalCount() {
		return totalCount;
	}

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

	public int getCurrentPageNo() {
		if (totalCount == 0)
			currentPageNo = 0;
		return currentPageNo;
	}

	public void setCurrentPageNo(int currentPageNo) {
		this.currentPageNo = currentPageNo;
	}

	public long getTotalPageCount() {
		return totalCount % pageSize == 0 ? totalCount / pageSize : totalCount
				/ pageSize + 1;
	}	
}

 

  // dao层:StudentDao.java  

package com.wdpc.hibernate.dao;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.text.DateFormat;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import com.wdpc.hibernate.comms.HibernateUtil;
import com.wdpc.hibernate.model.MyClass;
import com.wdpc.hibernate.model.Student;

public class StudentDao {
	//批量上传文件
	public void create(File attach) throws Exception {
		Session session = null;
		try {
			session = HibernateUtil.getSession();
			BufferedReader br = new BufferedReader(new FileReader(attach));
			String line = null;
			int i = 0;
			MyClass myclass = new MyClass("Java0801");
			while ((line = br.readLine()) != null) {
				i++;
				String[] str = line.split(",");
				Student student = new Student(str[0], Integer.parseInt(str[1]),
						DateFormat.getDateInstance().parse(str[2]), str[3],
						myclass);
				session.save(student);
				if (i % 20 == 0) {
					session.flush();//刷新缓存,将缓存中的内容同步到数据库中
					session.clear();//强制清除缓存
				}
			}
			br.close();
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	//分页查询
	public List<Student> findAll(int pageSize, int currentPageNo)
			throws Exception {
		Session session = null;
		List<Student> list = null;
		try {
			session = HibernateUtil.getSession();
			Query query = session.createQuery("from Student");
			query.setFirstResult((currentPageNo - 1) * pageSize); // 设置开始行数
			query.setMaxResults(pageSize); // 设置每页大小
			list = query.list();//这里每一行都是一个1维数组
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		return list;
	}

	//获取总数
	public long getStudentAllCount() throws Exception {		
		Session session = null;
		Long count = null;
		try {
			session = HibernateUtil.getSession();			
			Query query = session.createQuery("select count(*) from Student");
			count = (Long)query.iterate().next();
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		return count;
	}

	//查询
	public Long getStudentByNameCount(String nameVal) throws Exception {
		Session session = null;
		Long count = null;
		try {
			session = HibernateUtil.getSession();
			Query query = session.createQuery("select count(*) from Student where username like :a");
			query.setParameter("a", "%" + nameVal + "%");
			count = (Long)query.iterate().next();
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		return count;
	}

	//查询
	public List<Student> findByName(int pageSize, int currentPageNo,
			String nameVal) throws Exception {
		Session session = null;
		List<Student> list = null;
		try {
			session = HibernateUtil.getSession();
			Query query = session
					.createQuery("from Student where username like :a");	
			query.setParameter("a", "%" + nameVal + "%");
			query.setFirstResult((currentPageNo - 1) * pageSize); 
			query.setMaxResults(pageSize); 
			list = query.list();
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		return list;
	}
}

 

  //service层:StudentService.java 

package com.wdpc.hibernate.service;

import java.io.File;
import java.util.List;
import com.wdpc.hibernate.model.Student;

public interface StudentService {
	public void create(File attach) throws Exception;
	public List<Student> findAll(int pageSize, int currentPageNo) throws Exception;
	public long getStudentAllCount() throws Exception;
	public Long getStudentByNameCount(String nameVal) throws Exception;
	public List<Student> findByName(int pageSize, int currentPageNo,
			String nameVal) throws Exception;
}

 

   //实现service层:StudentServiceImpl.java  

package com.wdpc.hibernate.service.impl;

import java.io.File;
import java.util.List;
import com.wdpc.hibernate.dao.StudentDao;
import com.wdpc.hibernate.model.Student;
import com.wdpc.hibernate.service.StudentService;

public class StudentServiceImpl implements StudentService {
	private StudentDao studentDao;
	
	public StudentServiceImpl() {
		studentDao = new StudentDao();
	}
	public void create(File attach) throws Exception {
		studentDao.create(attach);
	}
	public List<Student> findAll(int pageSize, int currentPageNo)
			throws Exception {
		return studentDao.findAll(pageSize, currentPageNo);
	}
	public Long getStudentByNameCount(String nameVal) throws Exception {
		return studentDao.getStudentByNameCount(nameVal);
	}
	
	public List<Student> findByName(int pageSize, int currentPageNo,
			String nameVal) throws Exception {
		return studentDao.findByName(pageSize, currentPageNo, nameVal);
	}
	public long getStudentAllCount() throws Exception {
		return studentDao.getStudentAllCount();
	}
}

 

  // action层:StudentAction.java 

package com.wdpc.hibernate.action;

import java.io.File;
import com.opensymphony.xwork2.ModelDriven;
import com.wdpc.hibernate.comms.BaseAction;
import com.wdpc.hibernate.comms.Page;
import com.wdpc.hibernate.model.Student;
import com.wdpc.hibernate.service.StudentService;
import com.wdpc.hibernate.service.impl.StudentServiceImpl;


public class StudentAction extends BaseAction implements ModelDriven<Student> {
	private File attach;
	private String attachFileName; // 隐藏属性,用来获取文件名
	private String attachContentType;// 隐藏属性,用来获取文件类型
	private StudentService studentService;
	private Student student;
	private Page page;
	private String username;
	
	public StudentAction() {
		studentService = new StudentServiceImpl();
		student = new Student();
		page = new Page();
	}

	public String index() {
		list();
		return "success";
	}

	//上传文件
	public String doUpload() throws Exception {
		studentService.create(attach);
		list();		
		return "doUpload";
	}

	public String list(){			
		try {
			if ( student.getUsername()!= null && student.getUsername().trim().length() > 0) {					
				page.setTotalCount(studentService.getStudentByNameCount(student
						.getUsername().trim()));
				page.setData(studentService.findByName(page.getPageSize(), page
						.getCurrentPageNo(), student.getUsername().trim()));
			}else{				
				page.setTotalCount(studentService.getStudentAllCount());
				page.setData(studentService.findAll(page.getPageSize(), page
						.getCurrentPageNo()));
				
			}
			return "list";
		} catch (Exception e) {
			return "list_error";
		}
		
	}

	public File getAttach() {
		return attach;
	}

	public void setAttach(File attach) {
		this.attach = attach;
	}

	public String getAttachFileName() {
		return attachFileName;
	}

	public void setAttachFileName(String attachFileName) {
		this.attachFileName = attachFileName;
	}

	public String getAttachContentType() {
		return attachContentType;
	}

	public void setAttachContentType(String attachContentType) {
		this.attachContentType = attachContentType;
	}

	public Student getModel() {
		return student;
	}
	
	public void setStudent(Student student) {
		this.student = student;
	}	

	public Student getStudent() {
		return student;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public Page getPage() {
		return page;
	}

	public void setPage(Page page) {
		this.page = page;
	}
}

 

   //struts.xml配置   

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
	<!-- 设置一些全局的常量开关 -->
	<constant name="struts.i18n.encoding" value="UTF-8" />
	<constant name="struts.action.extension" value="do,action" />
	<constant name="struts.serve.static.browserCache " value="false" />
	<constant name="struts.configuration.xml.reload" value="true" />
	<constant name="struts.devMode" value="true" />
	<constant name="struts.enable.DynamicMethodInvocation" value="false" />
	<package name="hibernate" extends="struts-default">
		<action name="index" class="com.wdpc.hibernate.action.StudentAction" method="index">
			<result name="success">/WEB-INF/page/show.jsp</result>
		</action>
		<action name="doUpload" class="com.wdpc.hibernate.action.StudentAction" method="doUpload">
			<result name="doUpload">/WEB-INF/page/success.jsp</result>
		</action>
		<action name="list" class="com.wdpc.hibernate.action.StudentAction" method="list">
			<result name="list">/WEB-INF/page/success.jsp</result>
			<result name="list_error">/WEB-INF/page/error.jsp</result>
		</action>
	</package>
</struts>

   此xml文件放到web项目src跟目录下

 

   //hibernate.cfg.xml  

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<!-- 设置使用数据库的语言 -->
		<property name="dialect">org.hibernate.dialect.SQLServerDialect</property>	
		<!-- 确定以何种方式产生Session-->
		<property name="current_session_context_class">thread</property>
		<!-- 关闭缓存-->
		<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
		<!-- 是否自动创建对应的数据库表-->
		<!-- property name="hbm2ddl.auto">create</property-->
		<!-- 设置是否显示执行的语言 -->
		<property name="show_sql">true</property>
		<!--设置开关的大小
		<property name="jdbc.batch_size">20</property> -->
		<!-- 数据库连接属性设置 -->
		<property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
		<property name="connection.url">jdbc:sqlserver://localhost:1433;DatabaseName=test</property>
		<property name="connection.username">sa</property>
		<property name="connection.password">admin</property>
		<!-- 设置 c3p0连接池的属性-->
		<property name="connection.useUnicode">true</property>
		<property name="hibernate.c3p0.max_statements">100</property>
		<property name="hibernate.c3p0.idle_test_period">3000</property>
		<property name="hibernate.c3p0.acquire_increment">2</property>
		<property name="hibernate.c3p0.timeout">5000</property>
		<property name="hibernate.connection.provider_class">
			org.hibernate.connection.C3P0ConnectionProvider
		</property>
		<property name="hibernate.c3p0.validate">true</property>
		<property name="hibernate.c3p0.max_size">3</property>
		<property name="hibernate.c3p0.min_size">1</property>

		<!-- 加载映射文件-->
		<mapping resource="com/wdpc/hibernate/model/MyClass.hbm.xml" />
		<mapping resource="com/wdpc/hibernate/model/Student.hbm.xml" />
	</session-factory>	
</hibernate-configuration>

   此xml文件放到web项目src跟目录下

 

    //上传的文件Book1.csv

      用excel文档制作,保存的扩展名为.csv文件     

 

   //web.xml 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	<filter>
		<filter-name>lazyFilter</filter-name>
		<filter-class>com.wdpc.hibernate.comms.LazyFilter</filter-class>
	</filter>
	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
	</filter>
	
	<filter-mapping>
		<filter-name>lazyFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

   

   //index.jsp  

<%@ page language="java" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:redirect url="index.do"/>

 

   //show.jsp上传页面  

<%@ page language="java" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:set var="basePath" value="${pageContext.request.contextPath}" />
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>文件上传</title>
    <style type="text/css">
    	form{
    		margin-left:300px;
    		margin-top: 100px;
    	}
    </style>
  </head>
  <body>
  	<form method="post" action="${basePath}/doUpload.do" enctype="multipart/form-data">
		<input type="file" name="attach" />
		<br /><br />
		<input type="submit" value="提交"/ style="margin-left: 50px;">
	</form>  	
  </body>
</html>

  

   //success.jsp上传成功后用分页显示  

<%@ page language="java" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<c:set var="basePath" value="${pageContext.request.contextPath}" />
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<title></title>
		<script type="text/javascript">
			function navigation(navigateValue) {
		var currentPageNoObj = document.getElementById("currentPageNo");
		var totalPageCount = Number(document.getElementById("totalPageCount").value);
		var val = Number(currentPageNoObj.value);
		switch (navigateValue) {
		case "first":
			if (val == 1) {
				return false;
			} else {
				currentPageNoObj.value = 1;
			}
			break;
		case "previous":
			if (val == 1) {
				return false;
			} else {
				currentPageNoObj.value = --val;
			}
			break;
		case "next":
			if (val == totalPageCount) {
				return false;
			} else {
				currentPageNoObj.value = ++val;
			}
			break;
		case "last":
			if (val == totalPageCount) {
				return false;
			} else {
				currentPageNoObj.value = totalPageCount;
			}
			break;
		}
		document.getElementById("navigationForm").submit();
	}
 		</script>
	</head>
	<body>
		<form action="${basePath}/list.do" method="post" enctype="multipart/form-data">
			按学生姓名查找:
			<input type="text" name="username" value="${student.username}" />
			<input type="submit" value="查找" />
		</form>
		<br />
		<table border="1" width="900px">
			<tr>
				<td>ID</td>
				<td>姓名</td>
				<td>年龄</td>
				<td>生日</td>
				<td>地址</td>
			</tr>
			<c:choose>
				<c:when test="${empty page.data}">
					<tr>
						<td colspan="3" align="center">
							暂时没有记录
						</td>
					</tr>
				</c:when>
				<c:otherwise>
					<c:forEach var="student" items="${page.data}">
						<tr>
							<td>${student.id}</td>
							<td>${student.username}</td>
							<td>${student.age}</td>
							<td>${student.bithday}</td>
							<td>${student.address}</td>
						</tr>
					</c:forEach>
				</c:otherwise>
			</c:choose>
		</table>
		<br />
		<br />
		<form method="post" id="navigationForm" action="${basePath}/list.do">
			<!-- 当前页 -->
			<input type="hidden" name="page.currentPageNo" id="currentPageNo" value="${page.currentPageNo}" />
			<!-- 总页数 -->
			<input type="hidden" id="totalPageCount" value="${page.totalPageCount}" />
			<!-- 查询条件 -->
			<input type="hidden" name="username" value="${student.username}" />
		</form>
		共 ${page.totalCount}条记录, 每页${page.pageSize}条,共${page.totalPageCount}页, 当前页${page.currentPageNo} /
					${page.totalPageCount}
		<a href="#" onclick="navigation('first')">首页</a>&nbsp;&nbsp;
		<a href="#" onclick="navigation('previous')">上一页</a>&nbsp;&nbsp;
		<a href="#" onclick="navigation('next')">下一页</a>&nbsp;&nbsp;
		<a href="#" onclick="navigation('last')">未尾</a>
	</body>
</html>

 

   //error.jsp上传失败显示页面  

<%@ page language="java" pageEncoding="utf-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  </head>
  <body>
   	 失败
  </body>
</html>

    以上三个JSP页面放到WEB-INF/page页面下

 

   数据库test,表名student,myclass

  

use test
create table student(
	id nvarchar(32) primary key,
	username nvarchar(10),
	age int,
	bithday datetime,
	address nvarchar(20)
)   
create table myclass(
	id nvarchar(32) primary key,
	name nvarchar(10)
)

 

三:大致的项目图   

 

 

  • 大小: 70.9 KB
  • 大小: 55.6 KB
分享到:
评论

相关推荐

    Struts2+Spring+Hibernate+Ehcache+AJAX+JQuery+Oracle 框架集成用户登录注册Demo工程

    2.Action里通过struts2-spring-plugin.jar插件自动根据名字注入。 3.Ajax无刷新异步调用Struts2,返回Json数据,以用户注册为例。 4.在服务端分页查询功能,优点:实时性:跳页才查询。数据量小:只加载当前页的记录...

    基于JSP+Struts2+hibernate的个人博客系统

    **基于JSP+Struts2+Hibernate的个人博客系统** 在Web开发领域,构建一个功能完善的个人博客系统是一项常见的任务,而使用JSP、Struts2和Hibernate这三种技术的组合,可以创建出高效且易于维护的解决方案。下面将...

    struts2+hibernate的网上购物管理系统的课程设计

    为了提高用户体验,我们还需要考虑页面的动态加载、分页显示、Ajax异步请求等功能。Struts2提供了一些插件,如Tiles和Struts2 jQuery Plugin,可以帮助我们实现这些功能。 安全方面,Struts2提供了安全相关的拦截器...

    (3.0版本)自己写的struts2+hibernate+spring实例

    jar包:项目中除了使用了struts2,hibernate3.0和spring1.8以外(用spring2.0的包也可以.不能低于1.8的包.)还是用了junit,ajax,第三方的table组件.等等.所以需要下载相对应的包. 为了上传jar.我专门申请了一个网盘.所有...

    用struts1+hibernate+jsp做的简单的登录系统

    我自己做的简单登录系统,用的是struts1+hibernate+jsp,里面实现了增删改查,还有分页,用了点ajax,局域网之内可以访问,实现了同一用户不能同时在多台机器上同时登陆,呵呵,做的比较累,跟大伙分享分享。

    struts2+hibernate 简单网上书店

    《基于Struts2和Hibernate的简单网上书店系统详解》 在信息技术日新月异的今天,Web应用开发已经成为IT行业的重要组成部分。其中,Struts2和Hibernate作为两个强大的开源框架,被广泛应用于Java Web开发中。本篇...

    struts2+spring+hibernate分页显示

    在这个“Struts2+Spring+Hibernate分页显示”的解决方案中,我们将深入探讨如何利用这三大框架实现数据的分页展示。 Struts2作为MVC(模型-视图-控制器)架构的一部分,主要负责处理HTTP请求,控制应用程序的流程。...

    struts2+hibernate+Spring后台表格分页

    在后台表格分页的场景下,Struts2接收前端页面发送的分页参数,如当前页码和每页显示条数,然后调用相应的Action方法处理这些请求。 2. **Hibernate框架**:Hibernate是一个对象关系映射(ORM)工具,用于简化...

    Struts2+Spring3+Hibernate3 用户管理系统实例源码

    本例主要是实现了struts2+spring3+hibernate3的 基本框架搭建的注册登录,以及用户增删改查,适于初学者学习。 包括:注册 登录功能 分页的实现 前端校验 验证码的实现 注册时有ajax 校验,登录时 后台从数据库...

    基于struts2+hibernate框架的简单的新闻管理系统

    【基于Struts2+Hibernate框架的简单新闻管理系统】 在JavaEE开发中,Struts2和Hibernate是两个常用的核心框架,它们分别负责控制层和持久层的处理。这个新闻管理系统是利用这两个框架构建的一个典型示例,旨在实现...

    网络硬盘(Struts 2+Hibernate+Spring实现)

    2. 文件上传:用户可以选择本地文件上传到网络硬盘,文件的元信息(如名称、大小、创建时间等)会被保存到数据库。 3. 文件下载:用户可以查看并下载已上传的文件。 4. 文件管理:包括文件的移动、复制、重命名、...

    Ajax+hibernate+struts实现无刷新的分页

    本篇将详细介绍如何利用Ajax、Hibernate和Struts框架,构建一个在用户界面上实现无刷新的分页系统,同时数据库采用Oracle。 ### 一、Hibernate分页 **1. Hibernate的Criteria查询** Hibernate 提供了 Criteria API...

    struts+spring+hibernate+dwr+分页例子

    在实际的项目中,这些框架的整合需要配置文件(如Struts的struts-config.xml,Spring的applicationContext.xml,Hibernate的hibernate.cfg.xml),以及相应的Java类。例如,Struts Action类会调用Spring管理的...

    Struts2 + Spring 2.5 + Hibernate 3.3 整合(实际使用项目,version1)

    包含有完整的jar包和源代码,这是专门为我们实验室定制开发的,包含了架构基于s2sh技术网站的参考实现(包括了全部基础部分:如分页,缓存,文件上传,连接池等等)希望对初学JavaEE WEB开的人有所帮助。...

    Struts+Hibernate+Spring+JS 分页程序(一)

    Struts、Hibernate、Spring 和 JavaScript 是Java开发中常用的四大框架,它们在Web应用程序开发中各自承担着不同的职责。Struts提供了MVC(Model-View-Controller)架构模式,用于处理用户请求并展示结果;Hibernate...

    struts2+hibernate+datagrid index.jsp+book.css+book.js

    在Java Web开发中,DataGrid常与Struts2和Hibernate结合使用,例如通过Ajax技术动态加载由Hibernate查询的数据到DataGrid中,为用户提供流畅的体验。 在这个项目中,"index.jsp"是主页面文件,可能包含了DataGrid的...

    Extjs+struts2+hibernate 做的一个简单的图书管理系统(源代码)

    1. **图书查询**:用户可以通过关键词、作者、出版社等条件进行图书搜索,这需要ExtJS向Struts2发送查询请求,Struts2调用Hibernate查询数据库并返回结果。 2. **图书添加/编辑**:当用户要新增或修改图书信息时,...

    开发基于Struts Spring Hibernate Ajax的网上信息发布平台(Struts Hibernate Spring Ajax)--Chapter1

    在本章中,我们将深入探讨如何开发一个基于Struts、Spring、Hibernate和Ajax的网上信息发布平台。这四个技术是Java Web开发中的核心组件,它们各自承担着不同的职责,共同构建了一个强大而灵活的后端架构。 **...

Global site tag (gtag.js) - Google Analytics