`
x125521853
  • 浏览: 71269 次
  • 性别: 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
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics