Struts2.0+Hibernate3.0+Spring3.2整合实例

说明:本文章是对Struts2.0+Hibernate3.0+Spring3.2的整合,主要的功能为基本CRUD操作,及分页、登陆等操作。非常适合java新手学习与研究,采用最简单的配置及文档注释,学者可以一边看一边练习并思考,项目案例结构与内容具体如下:

案例配置要求:

  1. 采用eclipse进行编写及测试;
  2. 数据库采用Oracle数据库;
  3. 整体采用Struts2.0+Hibernate3.0+Spring3.2框架设计

首先我们来看一下项目结构及所需jar包(这是正确测试与编译的前提)

项目结构:


所需jar包:

         

项目文件及内容:

1.web.xml

<span style="font-size:14px;"><?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">
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <context-param>
        <param-name>contextConfigLocation</param-name>
    	<param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app></span>


2.applicationContext.xml(spring配置文件)

<span style="font-size:14px;"><?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:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-2.5.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

	<!-- 读取jdbc.properties里的配置信息 -->
	<bean
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<value>classpath:jdbc.properties</value>
		</property>
	</bean>

	<bean id="dataSource" destroy-method="close"
		class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
	</bean>

	<!-- xml方式配置sessionFactory -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<!-- 映射文件的包路径 -->
		<property name="mappingResources">
			<list>
				<value>com/anllin/usermgr/model/Us.hbm.xml</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<!-- 数据库方言 -->
				<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
				<!-- 打印sql语句 -->  
				<prop key="hibernate.show_sql">true</prop>
				<!-- 格式化sql语句 -->  
                <!-- <prop key="hibernate.format_sql">true</prop>   -->
				<prop key="hibernate.current_session_context_class">thread</prop>
			</props>
		</property>
	</bean>

	<!-- 开启事务管理 -->
	<bean id="txManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

	<!-- spring事务的xml配置 ,建议使用 -->
	<aop:config>
		<aop:pointcut id="bussinessService"
			expression="execution(* com.anllin.usermgr.service..*.*(..))" />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="bussinessService" />
	</aop:config>

	<!-- 对不同的方法进行不同的事务管理 -->
	<tx:advice id="txAdvice" transaction-manager="txManager">
		<tx:attributes>
			<tx:method name="get*" read-only="true" />
			<tx:method name="isExists*" read-only="true" />
			<tx:method name="*" propagation="REQUIRED" read-only="false" />
		</tx:attributes>
	</tx:advice>

	<!-- UsDaoImpl继承 HibernateDaoSupport,即可使用hibernateTemplate -->
	<bean id="usDao" class="com.anllin.usermgr.dao.impl.UsDaoImpl" scope="singleton">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	<bean id="usService" class="com.anllin.usermgr.service.impl.UsServiceImpl">
		<property name="usDao" ref="usDao" />
	</bean>
	<!-- 创建ListUsAction的对象 依赖注入其业务逻辑层对象属性 -->
	<bean id="listUsAction" class="com.anllin.usermgr.action.ListUsAction" 	scope="prototype">
		<property name="usService" ref="usService" />
	</bean>
	<!-- 创建控制层SaveUsAction的对象 依赖注入其业务层对象属性 -->
	<bean id="saveUsAction" class="com.anllin.usermgr.action.SaveUsAction" 	scope="prototype">
		<property name="usService" ref="usService" />
	</bean>
	<!-- 创建deleteUsAction的对象  依赖注入其业务逻辑层对象属性-->
	<bean id="deleteUsAction" class="com.anllin.usermgr.action.DeleteUsAction" 	scope="prototype">
		<property name="usService" ref="usService"></property>
	</bean>
	<!-- 创建findUsByIdAction的对象  依赖注入其业务逻辑层对象属性-->
	<bean id="findUsByIdAction" class="com.anllin.usermgr.action.FindUsByIdAction" 	scope="prototype">
		<property name="usService" ref="usService"></property>
	</bean>
	<!-- 创建updateUsAction的对象  依赖注入其业务逻辑层对象属性-->
	<bean id="updateUsAction" class="com.anllin.usermgr.action.UpdateUsAction" 	scope="prototype">
		<property name="usService" ref="usService"></property>
	</bean>
	<!-- 创建ListPageUsAction的对象 依赖注入其业务逻辑层对象属性 -->
	<bean id="listPageUsAction" class="com.anllin.usermgr.action.ListPageUsAction" 	scope="prototype">
		<property name="usService" ref="usService" />
	</bean>
	<!-- 创建LoginUsAction的对象 依赖注入其业务逻辑层对象属性 -->
	<bean id="loginUsAction" class="com.anllin.usermgr.action.LoginUsAction" 	scope="prototype">
		<property name="usService" ref="usService" />
	</bean>
	<!-- 创建queryAllUsAction的对象 依赖注入其业务逻辑层对象属性 -->
	<bean id="queryAllUsAction" class="com.anllin.usermgr.action.QueryAllUsAction" 	scope="prototype">
		<property name="usService" ref="usService" />
	</bean>
</beans></span>

3.struts.xml(Struts2.0配置文件)


<?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>
	<package name="registration" namespace="/" extends="struts-default">
		<!-- 保存用户的Action -->
		<action name="saveUs" class="saveUsAction">
			<result name="success" type="redirect">listUs.action</result>
			<!-- <result name="input">/save.jsp</result> -->
		</action>
		<!-- 显示所有用户的Action -->
		<action name="listUs" class="listUsAction">
			<result name="success">/listUs.jsp</result>
		</action>
		<!-- 删除用户的Action -->
		<action name="deleteUs" class="deleteUsAction">
			<result name="success" type="redirect">listUs.action</result>
		</action>
		<!-- 查询用户的Action -->
		<action name="findUsById" class="findUsByIdAction">
			<result name="success">/updateUs.jsp</result>
		</action>
		<!-- 更新用户的Action -->
		<action name="updateUs" class="updateUsAction">
			<result name="success" type="redirect">listUs.action</result>
		</action>
		<!-- 分页显示所有用户的Action -->
		<action name="listPageUs" class="listPageUsAction">
			<result name="success">/listPageUs.jsp</result>
		</action>
		<!-- 登陆用户的Action -->
		<action name="loginUs" class="loginUsAction">
			<!-- <result name="success">/listPageUs.jsp</result> -->
			<result name="success">/index.jsp</result>
		</action>
		<!-- 条件查询用户的Action -->
		<action name="queryAllUs" class="queryAllUsAction">
			<result name="success">/queryAllUs.jsp</result>
		</action>
	</package>
</struts>

4.jdbc.properties

#jdbc.driverClassName=com.mysql.jdbc.Driver
#jdbc.url=jdbc\:mysql\://localhost\:3306/usermgr
#jdbc.username=root
#jdbc.password=123
jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:orcl
jdbc.username=username
jdbc.password=password

5.log4j.properties(日志记录,也可去掉)

#log4j.rootLogger=info, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.rootLogger=warn, stdout


#log4j.logger.org.hibernate=debug
#log4j.logger.org.hibernate.test=info
### log schema export/update ###
log4j.logger.org.hibernate.tool.hbm2ddl=debug
#log4j.logger.org.hibernate.sql.ordering.antlr.OrderByFragmentTranslator=trace
#log4j.logger.org.hibernate.ejb=debug
#log4j.logger.org.hibernate.ejb.packaging=debug
#log4j.logger.org.hibernate.reflection=debug

6.UsDao.java

package com.anllin.usermgr.dao;

import java.util.List;

import com.anllin.usermgr.model.Us;

public interface UsDao {
	/**
	 * 保存用户
	 * 
	 * @param us
	 */
	public void saveUs(Us us);

	/**
	 * 登陆用户
	 * 
	 * @param us
	 */
	public Us loginUs(Us us);

	/**
	 * 删除用户
	 * 
	 * @param id
	 */
	public void deleteUs(int id);

	/**
	 * 根据id找到某个用户
	 * 
	 * @param id
	 */
	public Us findUsById(int id);

	/**
	 * 查询所有的用户
	 * 
	 * @param us
	 *            return List<Us>
	 */
	public List<Us> findAllUs();

	/**
	 * 更新用户
	 * 
	 * @param us
	 */
	public void updateUs(Us us);

	/**
	 * 分页查询
	 * 
	 * @param hql
	 *            查询条件
	 * @param offset
	 *            开始记录
	 * @param length
	 *            一次查询几条记录
	 * @return 查询的记录集合
	 */
	public List<Us> queryForPage(final String hql, final int offset,
			final int length);

	/**
	 * 查询所有的记录数
	 * 
	 * @param hql
	 *            查询条件
	 * @return 总记录数
	 */
	public int getAllRowCount(String hql);

	/**
	 * 条件查询所有的用户
	 * 
	 * @param us
	 *            return List<Us>
	 */
	public List<Us> queryAllUs(Us us);
}

7.UsDaoImpl.java

package com.anllin.usermgr.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.anllin.usermgr.dao.UsDao;
import com.anllin.usermgr.model.Us;

public class UsDaoImpl extends HibernateDaoSupport implements UsDao {
	public void deleteUs(int id) {
		Us us = findUsById(id);
		if (us != null) {
			this.getHibernateTemplate().delete(us);
		}
	}

	@SuppressWarnings("unchecked")
	public List<Us> findAllUs() {
		String hql = "from Us";
		return (List<Us>) this.getHibernateTemplate().find(hql);
	}

	public Us findUsById(int id) {
		return (Us) this.getHibernateTemplate().get(Us.class, id);
	}

	public void saveUs(Us us) {
		this.getHibernateTemplate().save(us);
	}

	public void updateUs(Us us) {
		this.getHibernateTemplate().update(us);
	}

	/**
	 * 查询所有的记录数
	 * 
	 * @param hql
	 *            查询条件
	 * @return 总记录数
	 */
	public int getAllRowCount(String hql) {
		return this.getHibernateTemplate().find(hql).size();
	}

	/**
	 * 分页查询
	 * 
	 * @param hql
	 *            查询条件
	 * @param offset
	 *            开始记录
	 * @param length
	 *            一次查询几条记录
	 * @return 查询的记录集合
	 */
	@SuppressWarnings("unchecked")
	public List<Us> queryForPage(final String hql, final int offset,
			final int length) {
		List<Us> list = getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(hql);
				query.setFirstResult(offset);
				query.setMaxResults(length);
				List<Us> list = query.list();
				return list;
			}
		});
		return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Us loginUs(final Us us) {
		return (Us) this.getHibernateTemplate().execute(
				new HibernateCallback() {
					public Object doInHibernate(Session session)
							throws HibernateException, SQLException {
						String hql = "from Us u where u.username=? and u.password=?";
						Query query = session.createQuery(hql);
						query.setString(0, us.getUsername());
						query.setString(1, us.getPassword());
						return query.uniqueResult();
					}
				});
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Us> queryAllUs(final Us us) {
		List<Us> list = getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Criteria criteria = session.createCriteria(Us.class);
				String username = us.getUsername();
				String password = us.getPassword();
				if (username == null || username.length() <= 0) {
					criteria.add(Restrictions.eq("password", us.getPassword()));
				}
				if (password == null || password.length() <= 0) {
					criteria.add(Restrictions.eq("username", us.getUsername()));
				}
				List<Us> list = criteria.list();
				return list;
			}
		});
		return list;
	}
}

8.UsService.java

package com.anllin.usermgr.service;

import java.util.List;

import com.anllin.usermgr.model.PageBean;
import com.anllin.usermgr.model.Us;

public interface UsService {
	/**
	 * 保存用户
	 * 
	 * @param us
	 */
	public void saveUs(Us us);

	/**
	 * 登陆用户
	 * 
	 * @param us
	 */
	public Us loginUs(Us us);

	/**
	 * 删除用户
	 * 
	 * @param id
	 */
	public void deleteUs(int id);

	/**
	 * 根据id找到某个用户
	 * 
	 * @param id
	 */
	public Us findUsById(int id);

	/**
	 * 查询所有的用户
	 * 
	 * @param us
	 *            return List<Us>
	 */
	public List<Us> findAllUs();

	/**
	 * 更新用户
	 * 
	 * @param us
	 */
	public void updateUs(Us us);

	/**
	 * 分页查询
	 * 
	 * @param pageSize
	 *            每页显示多少记录
	 * @param currentPage
	 *            当前页
	 * @return 封装了分页信息的bean
	 */
	public PageBean queryForPage(int pageSize, int page);

	/**
	 * 条件查询所有的用户
	 * 
	 * @param us
	 *            return List<Us>
	 */
	public List<Us> queryAllUs(Us us);
}

9.UsServiceImpl.java

package com.anllin.usermgr.service.impl;

import java.util.List;

import com.anllin.usermgr.dao.UsDao;
import com.anllin.usermgr.model.PageBean;
import com.anllin.usermgr.model.Us;
import com.anllin.usermgr.service.UsService;

public class UsServiceImpl implements UsService {
	private UsDao usDao;

	public UsDao getUsDao() {
		return usDao;
	}

	public void setUsDao(UsDao usDao) {
		this.usDao = usDao;
	}

	@Override
	public void saveUs(Us us) {
		this.usDao.saveUs(us);
	}

	@Override
	public void deleteUs(int id) {
		this.usDao.deleteUs(id);
	}

	@Override
	public void updateUs(Us us) {
		this.usDao.updateUs(us);
	}

	@Override
	public Us findUsById(int id) {
		return this.usDao.findUsById(id);
	}

	@Override
	public List<Us> findAllUs() {
		return this.usDao.findAllUs();
	}

	/**
	 * 分页查询
	 * 
	 * @param pageSize
	 *            每页显示多少记录
	 * @param currentPage
	 *            当前页
	 * @return 封装了分页信息的bean
	 */
	public PageBean queryForPage(int pageSize, int page) {
		final String hql = "from Us us order by us.id"; // 查询语句
		int allRow = usDao.getAllRowCount(hql); // 总记录数
		int totalPage = PageBean.countTatalPage(pageSize, allRow); // 总页数
		final int offset = PageBean.countOffset(pageSize, page); // 当前页开始记录
		final int length = pageSize; // 每页记录数
		final int currentPage = PageBean.countCurrentPage(page); // 当前页
		List list = usDao.queryForPage(hql, offset, length); //
		// 把分页信息保存到Bean当中
		PageBean pageBean = new PageBean();
		pageBean.setPageSize(pageSize);
		pageBean.setCurrentPage(currentPage);
		pageBean.setAllRow(allRow);
		pageBean.setTotalPage(totalPage);
		pageBean.setList(list);
		pageBean.init();
		return pageBean;
	}

	@Override
	public Us loginUs(Us us) {
		return this.usDao.loginUs(us);
	}

	@Override
	public List<Us> queryAllUs(Us us) {
		return this.usDao.queryAllUs(us);
	}
}

10.Us.java

package com.anllin.usermgr.model;

import java.io.Serializable;

public class Us implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private int id;
	private String username;
	private String password;
	private int age;
	private String birthday;

	public int getId() {
		return id;
	}

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

	public String getUsername() {
		return username;
	}

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

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public int getAge() {
		return age;
	}

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

	public String getBirthday() {
		return birthday;
	}

	public void setBirthday(String birthday) {
		this.birthday = birthday;
	}

}

11.PageBean.java(分页类封装)

package com.anllin.usermgr.model;

import java.util.List;

public class PageBean {
	private List<Us> list; // 要返回的某一页的记录列表
	private int allRow; // 总记录数
	private int totalPage; // 总页数
	private int currentPage; // 当前页
	private int pageSize; // 每页的记录数
	private boolean isFirstPage; // 是否为当前第一页
	private boolean isLastPage; // 是否为最后一页
	private boolean hasPreviousPage; // 是否有前一页
	private boolean hasNextPage; // 是否有下一页

	
	public List<Us> getList() {
		return list;
	}

	public void setList(List<Us> list) {
		this.list = list;
	}

	public int getAllRow() {
		return allRow;
	}

	public void setAllRow(int allRow) {
		this.allRow = allRow;
	}

	public int getTotalPage() {
		return totalPage;
	}

	public void setTotalPage(int totalPage) {
		this.totalPage = totalPage;
	}

	public int getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	public int getPageSize() {
		return pageSize;
	}

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

	public boolean isFirstPage() {
		return isFirstPage;
	}

	public void setFirstPage(boolean isFirstPage) {
		this.isFirstPage = isFirstPage;
	}

	public boolean isLastPage() {
		return isLastPage;
	}

	public void setLastPage(boolean isLastPage) {
		this.isLastPage = isLastPage;
	}

	public boolean isHasPreviousPage() {
		return hasPreviousPage;
	}

	public void setHasPreviousPage(boolean hasPreviousPage) {
		this.hasPreviousPage = hasPreviousPage;
	}

	public boolean isHasNextPage() {
		return hasNextPage;
	}

	public void setHasNextPage(boolean hasNextPage) {
		this.hasNextPage = hasNextPage;
	}

	/**
	 * 初始化分页信息
	 */
	public void init() {
		this.isFirstPage = isFirstPage;
		this.isLastPage = isLastPage;
		this.hasPreviousPage = hasPreviousPage;
		this.hasNextPage = hasNextPage;
	}

	/**
	 * 计算总页数 静态方法
	 * 
	 * @param pageSize
	 *            每页的记录数
	 * @param allRow
	 *            总记录数
	 * @return 总页数
	 */
	public static int countTatalPage(final int pageSize, final int allRow) {
		int toalPage = allRow % pageSize == 0 ? allRow / pageSize : allRow
				/ pageSize + 1;
		return toalPage;
	}

	/**
	 * 计算当前页开始的记录
	 * 
	 * @param pageSize
	 *            每页记录数
	 * @param currentPage
	 *            当前第几页
	 * @return 当前页开始记录号
	 */
	public static int countOffset(final int pageSize, final int currentPage) {
		final int offset = pageSize * (currentPage - 1);
		return offset;
	}

	/**
	 * 计算当前页,若为0或者请求的URL中没有“?page = ”则用1代替
	 * 
	 * @param page
	 *            传入的参数(可能为空,即0 则返回1)
	 * @return
	 */
	public static int countCurrentPage(int page) {
		final int curpage = (page == 0 ? 1 : page);
		return curpage;
	}
}

12.Us.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>
    <class name="com.anllin.usermgr.model.Us" dynamic-update="true" dynamic-insert="true">
        <id name="id" column="id" type="int">
            <!-- <generator class="native"/> -->
            <generator class="sequence">
            	<param name="sequence">id</param>
            </generator>
        </id>
        <property name="username" type="string">
            <column name="username" length="20"/>
        </property>
        <property name="password" type="string">
            <column name="password" length="20"/>
        </property>
        <property name="age" type="int">
            <column name="age"/>
        </property>
        <property name="birthday" type="string">
            <column name="birthday" length="100"/>
        </property>
    </class>
</hibernate-mapping>

13.index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>User Manager</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    
  </head>
  <body>
      <div>
        <h1>User Manager</h1><br/><br/><br/>
        <s:a href="listPageUs.action">Show All Users Page</s:a><br/>
        <s:a href="listUs.action">Show All Users</s:a><br/>
        <s:a href="saveUs.jsp">Add a New User</s:a><br/>
        <s:a href="loginUs.jsp">login User</s:a><br/>
        <s:a href="queryUs.jsp">query User</s:a><br/>
    </div>
  </body>
</html>

14.saveUs.java

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>Save User</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
</head>
  
  <body>
      <h1>Save User</h1>
	    <s:form action="saveUs" theme="simple">
	    	<%-- id: <s:textfield name="us.id"/><br/> --%>
	        username: <s:textfield name="us.username"/><br/>
	        password: <s:password name="us.password"/><br/>
	        age: <s:textfield name="us.age"/><br/>
	        birthday: <s:textfield name="us.birthday"/><br/>
	        <s:submit value="submit"/>
	    </s:form>
  </body>
</html>

15.updateUs.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>Update User</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">

    <STYLE type="text/css">
    h1
    {
        color: blue;
    }
    </STYLE>
  </head>
  
  <body>
      <h1>Update User</h1>
	      <s:form action="updateUs" theme="simple">
	          <s:hidden name="us.id" value="%{#request.us.id}"></s:hidden>
	          username: <s:textfield name="us.username" value="%{#request.us.username}"/><br/>
	          password: <s:textfield name="us.password" value="%{#request.us.password}"/><br/>
	          age: <s:textfield name="us.age" value="%{#request.us.age}"/><br/>
	          birthday: <s:textfield name="us.birthday" value="%{#request.us.birthday}"/><br/>
	          <s:submit value="sumbit changed"></s:submit>
	      </s:form>
      <s:debug></s:debug>
  </body>
</html>

16.listUs.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>List All Users</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
  </head>
  <SCRIPT type="text/javascript">
      function del()
      {
        var result = confirm("你确定删除吗?");
        if(result)
        {
          return true;
        }
        else
        {
          return false;
        }
      }
</SCRIPT>
  <body>
       <h1><font color="red">用户列表</font></h1>
      <table align="center" width="80%" border="1">
          <tr>
          	  <th>id</th>
              <th>username</th>
              <th>password</th>
              <th>age</th>
              <th>birthday</th>
              <th>update</th>
              <th>delete</th>
          </tr>
          <s:iterator value="us">
              <tr>
				 <td>
					<s:property value="id" />
				 </td>
				 <td>
                      <s:property value="username"/>
                  </td>
                  <td>
                      <s:property value="password"/>
                  </td>
                  <td>
                      <s:property value="age"/>
                  </td>
                  <td>
                      <s:property value="birthday"/>
                  </td>
                  <td>
                      <s:a href="findUsById.action?id=%{#this.id}">update</s:a>
                  </td>
                  <td>
                      <s:a href="deleteUs.action?id=%{#this.id}" οnclick="return del()">delete</s:a>
                  </td>
              </tr>
          </s:iterator>  
      </table>
  </body>
</html>

17.listPageUs.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>List All Users</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
</head>
<SCRIPT type="text/javascript">
	function del() {
		var result = confirm("你确定删除吗?");
		if (result) {
			return true;
		} else {
			return false;
		}
	}
</SCRIPT>
<body>
	<h1>
		<font color="red">用户列表</font>
	</h1>
	<table align="center" width="80%" border="1">
		<tr>
			<th>id</th>
			<th>username</th>
			<th>password</th>
			<th>age</th>
			<th>birthday</th>
			<th>update</th>
			<th>delete</th>
		</tr>
		<s:iterator value="us">
			<tr>
				<td><s:property value="id" /></td>
				<td><s:property value="username" /></td>
				<td><s:property value="password" /></td>
				<td><s:property value="age" /></td>
				<td><s:property value="birthday" /></td>
				<td><s:a href="findUsById.action?id=%{#this.id}">update</s:a></td>
				<td><s:a href="deleteUs.action?id=%{#this.id}"
						οnclick="return del()">delete</s:a></td>
			</tr>
		</s:iterator>
		<s:iterator value="pageBean">
			<tr>
				<td colspan="6" align="center">共<s:property value="allRow" />条记录
					共<s:property value="totalPage" />页 当前第<s:property
						value="currentPage" />页<br> <s:if test="%{currentPage == 1}">
           第一页  上一页
         </s:if> <!-- currentPage为当前页 --> <s:else>
						<a href="listPageUs.action?page=1">第一页</a>
						<a
							href="listPageUs.action?page=<s:property value="%{currentPage-1}"/>">上一页</a>
					</s:else> <s:if test="%{currentPage != totalPage}">
						<a
							href="listPageUs.action?page=<s:property value="%{currentPage+1}"/>">下一页</a>
						<a href="listPageUs.action?page=<s:property value="totalPage"/>">最后一页</a>
					</s:if> <s:else>
         下一页  最后一页
         </s:else>
				</td>
			</tr>
		</s:iterator>
	</table>
</body>
</html>

18.loginUs.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>Add User</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
</head>
  
  <body>
      <h1>login User</h1>
	    <s:form action="loginUs" theme="simple">
	        username: <s:textfield name="us.username"/><br/>
	        password: <s:password name="us.password"/><br/>
	        <s:submit value="submit"/>
	    </s:form>
  </body>
</html>

19.queryUs.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>Add User</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
</head>
  
  <body>
      <h1>query User</h1>
	    <s:form action="queryAllUs" theme="simple">
	        username: <s:textfield name="us.username"/><br/>
	        password: <s:password name="us.password"/><br/>
	        <s:submit value="submit"/>
	    </s:form>
  </body>
</html>

20.queryAllUs.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>List All Users</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
</head>
<SCRIPT type="text/javascript">
	function del() {
		var result = confirm("你确定删除吗?");
		if (result) {
			return true;
		} else {
			return false;
		}
	}
</SCRIPT>
<body>
	<h1>
		<font color="red">用户列表</font>
	</h1>
	<table align="center" width="80%" border="1">
		<tr>
			<th>id</th>
			<th>username</th>
			<th>password</th>
			<th>age</th>
			<th>birthday</th>
			<th>update</th>
			<th>delete</th>
		</tr>
		<s:iterator value="usList">
			<tr>
				<td><s:property value="id" /></td>
				<td><s:property value="username" /></td>
				<td><s:property value="password" /></td>
				<td><s:property value="age" /></td>
				<td><s:property value="birthday" /></td>
				<td><s:a href="findUsById.action?id=%{#this.id}">update</s:a></td>
				<td><s:a href="deleteUs.action?id=%{#this.id}"
						οnclick="return del()">delete</s:a></td>
			</tr>
		</s:iterator>
	</table>
</body>
</html>

至此,案例相关文件已全部编写,如需运行测试请将数据库部分自行编写,表名对应实体类名,列名对应类名变量即可,再将所需jar包(如图)导入便可直接运行,本例其实也花费了数日完成,力求简洁,方便改动等,希望学者能再此基础上尽心使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值