S2SH+DWR实现的增删改查实例

本文介绍了一个使用Struts2、Spring、Hibernate(S2SH)整合的学生信息管理系统项目。主要内容包括技术选型、数据库设计及实现,并展示了部分表现层页面代码。

一、介绍

 

主要技术:

    (1)s2sh之间的整合

    (2)dwr和s2sh整合(验证姓名是否相同)

    (3)强大的jquery validator验证框架验证表单

    (4)分页bean的编写

    (5)过滤器,拦截器的编写

    (6)泛型dao的编写

二、实例
1、数据库脚本
本例是采用mysql数据库,脚本如下:
  1. CREATE DATABASE /*!32312 IF NOT EXISTS*/`practice` /*!40100 DEFAULT CHARACTER SET gbk */;  
  2. USE `practice`;  
  3. DROP TABLE IF EXISTS `student`;  
  4. CREATE TABLE `student` (  
  5.   `id` int(11) NOT NULL AUTO_INCREMENT,  
  6.   `name` varchar(50) DEFAULT NULL,  
  7.   `age` int(11) DEFAULT NULL,  
  8.   `sex` varchar(1) DEFAULT NULL,  
  9.   `address` varchar(100) DEFAULT NULL,  
  10.   PRIMARY KEY (`id`)  
  11. ) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=gbk;  
  12. insert  into `student`(`id`,`name`,`age`,`sex`,`address`) values (2,'张民生',24,'男','江苏淮安市'),(26,'李军',41,'男','江苏南京'),(27,'李丽丽',25,'女','浙江杭州'),(28,'周塔利',36,'男','黑龙江'),(29,'李丽',24,'女','湖北'),(30,'凯萨',21,'女','新疆乌鲁木齐');  
  13. DROP TABLE IF EXISTS `users`;  
  14. CREATE TABLE `users` (  
  15.   `id` int(11) NOT NULL AUTO_INCREMENT,  
  16.   `username` varchar(50) DEFAULT NULL,  
  17.   `password` varchar(50) DEFAULT NULL,  
  18.   PRIMARY KEY (`id`)  
  19. ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=gbk;  
  20. insert  into `users`(`id`,`username`,`password`) values (1,'admin','123456');  
 
2、表现层
(1)login.jsp(登录页面)
  1. <%@ page language="java" import="java.util.*" pageEncoding="gbk"%>  
  2. <%@taglib prefix="s" uri="/struts-tags"%>  
  3. <%  
  4.     String path = request.getContextPath();  
  5.     String basePath = request.getScheme() + "://"  
  6.             + request.getServerName() + ":" + request.getServerPort()  
  7.             + path + "/";  
  8. %>  
  9. <html>  
  10.     <head>  
  11.         <base href="<%=basePath%>">  
  12.         <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/style.css" mce_href="${pageContext.request.contextPath}/css/style.css">  
  13.         <mce:script type="text/javascript" src="<%=path%><!--  
  14. /js/jquery-1.4.2.min.js">  
  15. // --></mce:script>  
  16.         <mce:script type="text/javascript" src="<%=path%><!--  
  17. /js/jquery.validate_pack.js">  
  18. // --></mce:script>  
  19.         <mce:script type="text/javascript" src="<%=path%><!--  
  20. /js/login.js">  
  21. // --></mce:script>  
  22.         </head>  
  23.     <body style="text-align: center" mce_style="text-align: center">  
  24.         <form action="user_login.action" method="post" id="loginForm">  
  25.             <s:actionmessage/>  
  26.             <p>  
  27.             <label for="username">用户名:</label>  
  28.             <input type="text" name="user.username" id="username"/>  
  29.             <span id="usernamespan"></span>  
  30.             </p>  
  31.             <p>  
  32.             <label for="password">密      码:</label>  
  33.             <input type="password" name="user.password" id="password"/>  
  34.             <span id="passwordspan"></span>  
  35.             </p>  
  36.             <input type="submit" value="提交" /><input type="reset" value="重置" />  
  37.         </form>  
  38.     </body>  
  39. </html>  
 
(2)logout.jsp(退出页面)
  1. <%@ page language="java" pageEncoding="ISO-8859-1"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  7. <html>  
  8.   <head>  
  9.     <base href="<%=basePath%>">  
  10.      <meta http-equiv="pragma" content="no-cache">  
  11.         <meta http-equiv="cache-control" content="no-cache">  
  12.         <meta http-equiv="expires" content="0">  
  13.         <meta http-equiv="refresh" content="0; url=<%=path%>/login.jsp" />  
  14.           
  15.     <title>My JSP 'logout.jsp' starting page</title>  
  16.   </head>  
  17.     
  18.   <body>  
  19.     <%  
  20.     response.setHeader("Pragma","No-cache");            
  21.     response.setHeader("Cache-Control","no-cache");     
  22.     response.setHeader("Cache-Control""no-store");     
  23.     response.setDateHeader("Expires",0);  
  24.     if(session!=null)  
  25.         session.invalidate();  
  26.     %>  
  27.   </body>  
  28. </html>  
 
(3)exception(错误异常显示页面)
  1. <%@ page contentType="text/html; charset=gbk"%>  
  2. <%@taglib prefix="s" uri="/struts-tags"%>  
  3. <html>  
  4. <head>  
  5.     <title><s:text name="exception_title"/></title>  
  6. </head>  
  7. <body style="padding:10px;background-color:#D6D3CE;" mce_style="padding:10px;background-color:#D6D3CE;">  
  8. <center><h2><s:text name="exception_title"/></h2></center>  
  9. <font color="#FF0000"><b><s:text name="exception_prompt"/></b></font><br/>  
  10. <textarea rows="22" cols="106">  
  11.     <!-- 输出异常信息内容 -->  
  12.     <s:property value="exception.message"/>  
 
(4)studentList.jsp(学生列表页面)
  1. <%@ page language="java" import="java.util.*" pageEncoding="gbk"  
  2.     isELIgnored="false"%>  
  3. <%@ taglib prefix="s" uri="/struts-tags"%>  
  4. <%  
  5.     String path = request.getContextPath();  
  6.     String basePath = request.getScheme() + "://"  
  7.             + request.getServerName() + ":" + request.getServerPort()  
  8.             + path + "/";  
  9. %>  
  10. <html>  
  11.     <head>  
  12.         <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />  
  13.         <title>学生信息管理列表</title>  
  14.         <mce:script type="text/javascript" src="<%=path%><!--  
  15. /js/jquery-1.4.2.min.js">  
  16. // --></mce:script>  
  17.         <mce:script type="text/javascript" src="<%=path%><!--  
  18. /js/main.js">  
  19. // --></mce:script>  
  20.         <mce:style type="text/css"><!--  
  21. body {  
  22.     margin-left: 0px;  
  23.     margin-top: 0px;  
  24.     margin-right: 0px;  
  25.     margin-bottom: 0px;  
  26. }  
  27. .tabfont01 {  
  28.     font-family: "宋体";  
  29.     font-size: 9px;  
  30.     color: #555555;  
  31.     text-decoration: none;  
  32.     text-align: center;  
  33. }  
  34. .font051 {  
  35.     font-family: "宋体";  
  36.     font-size: 12px;  
  37.     color: #333333;  
  38.     text-decoration: none;  
  39.     line-height: 20px;  
  40. }  
  41. .font201 {  
  42.     font-family: "宋体";  
  43.     font-size: 12px;  
  44.     color: #FF0000;  
  45.     text-decoration: none;  
  46. }  
  47. .button {  
  48.     font-family: "宋体";  
  49.     font-size: 14px;  
  50.     height: 37px;  
  51. }  
  52. html {  
  53.     overflow-x: auto;  
  54.     overflow-y: auto;  
  55.     border: 0;  
  56. }  
  57. -->  
  58. a:link {color:green;text-decoration:none  
  59.       
  60. }  
  61. a:visited {color:red;text-decoration:none  
  62.       
  63. }  
  64. a:hover {color:blue;text-decoration:overline;font-size:20pt  
  65.       
  66. }  
  67. --></mce:style><style type="text/css" mce_bogus="1">body {  
  68.     margin-left: 0px;  
  69.     margin-top: 0px;  
  70.     margin-right: 0px;  
  71.     margin-bottom: 0px;  
  72. }  
  73. .tabfont01 {  
  74.     font-family: "宋体";  
  75.     font-size: 9px;  
  76.     color: #555555;  
  77.     text-decoration: none;  
  78.     text-align: center;  
  79. }  
  80. .font051 {  
  81.     font-family: "宋体";  
  82.     font-size: 12px;  
  83.     color: #333333;  
  84.     text-decoration: none;  
  85.     line-height: 20px;  
  86. }  
  87. .font201 {  
  88.     font-family: "宋体";  
  89.     font-size: 12px;  
  90.     color: #FF0000;  
  91.     text-decoration: none;  
  92. }  
  93. .button {  
  94.     font-family: "宋体";  
  95.     font-size: 14px;  
  96.     height: 37px;  
  97. }  
  98. html {  
  99.     overflow-x: auto;  
  100.     overflow-y: auto;  
  101.     border: 0;  
  102. }  
  103. -->  
  104. a:link {color:green;text-decoration:none  
  105.       
  106. }  
  107. a:visited {color:red;text-decoration:none  
  108.       
  109. }  
  110. a:hover {color:blue;text-decoration:overline;font-size:20pt  
  111.       
  112. }</style>  
  113.     </head>  
  114.     <body style="text-align: center" mce_style="text-align: center">  
  115.         <form name="fom" id="fom" method="post" action="student_query.action">  
  116.             <table width="98%" border="0" align="center" cellpadding="0"  
  117.                 cellspacing="0">  
  118.                 <tr>  
  119.                     <td colspan="2">  
  120.                     <span style="text-align: center" mce_style="text-align: center">  
  121.                         当前用户:  
  122.                         <s:property value="#session.user.username" />  
  123.                             登录时间:  
  124.                         <mce:script type="text/javascript"><!--  
  125. document.write(new Date().toLocaleString())  
  126. // --></mce:script>  
  127. </span>  
  128.                         <span style="margin-right: 100px; float: right;" mce_style="margin-right: 100px; float: right;"><a  
  129.                             class=style2 style="text-decoration: none;"  
  130.                             href="<%=path%>/logout.jsp"><font  
  131.                                 color="red" size="3">退出</font> </a>  
  132.                         </span>  
  133.                     </td>  
  134.                 </tr>  
  135.                 <tr>  
  136.                     <td width="880">  
  137.                         查询方式:  
  138.                         <select name="querytype">  
  139.                             <option <s:if test='querytype==1'>selected="selected"</s:if>  
  140.                                 value="1">  
  141.                                 学生姓名  
  142.                             </option>  
  143.                             <option <s:if test='querytype==2'>selected="selected"</s:if>  
  144.                                 value="2">  
  145.                                 性别  
  146.                             </option>  
  147.                         </select>  
  148.                         <input name="condition" value="<s:property value='condition'/>"  
  149.                             type="text" size="12" />  
  150.                         <input type="submit" class="right-button02" value="查 询" />  
  151.                     </td>  
  152.                     <td width="20">  
  153.                         <input type="button"  
  154.                             onclick="javascript:window.location.href='<%=path%>/student_toAdd.action'"  
  155.                             class="right-button02" value="添加">  
  156.                     </td>  
  157.                 </tr>  
  158.             </table>  
  159.             <table width="100%" border="0" cellpadding="4" cellspacing="1"  
  160.                 bgcolor="#464646" class="newfont03">  
  161.                 <thead>  
  162.                     <tr class="CTitle">  
  163.                         <td height="22" colspan="10" align="center"  
  164.                             style="font-size: 16px">  
  165.                             学生信息管理列表  
  166.                         </td>  
  167.                     </tr>  
  168.                 </thead>  
  169.                 <tbody>  
  170.                     <tr bgcolor="#EEEEEE" align="center">  
  171.                         <td width="4%">  
  172.                             编号  
  173.                         </td>  
  174.                         <td width="15%" align="center" height="30">  
  175.                             姓名  
  176.                         </td>  
  177.                         <td width="10%" align="center" height="30">  
  178.                             性别  
  179.                         </td>  
  180.                         <td width="10%">  
  181.                             年龄  
  182.                         </td>  
  183.                         <td width="13%">  
  184.                             地址  
  185.                         </td>  
  186.                         <td>  
  187.                             操作  
  188.                         </td>  
  189.                     </tr>  
  190.                     <s:if  
  191.                         test="(pageListData.dataList!=null)&&(!pageListData.dataList.isEmpty())">  
  192.                         <s:iterator value="#request.pageListData.dataList" id="u"  
  193.                             status="st">  
  194.                             <tr id="changecolor" bgcolor="#FFFFFF" align="center">  
  195.                                 <td>  
  196.                                     <s:property value="#st.index+1+(currentPage-1)*pageSize" />  
  197.                                 </td>  
  198.                                 <td>  
  199.                                     <s:property value="#u.name" />  
  200.                                 </td>  
  201.                                 <td>  
  202.                                     <s:property value="#u.sex" />  
  203.                                 </td>  
  204.                                 <td>  
  205.                                     <s:property value="#u.age" />  
  206.                                 </td>  
  207.                                 <td>  
  208.                                     <s:property value="#u.address" />  
  209.                                 </td>  
  210.                                 <td>  
  211.                                     <a  
  212.                                         href="${pageContext.request.contextPath}/student_toUpdate.action?stu.id=${u.id}&¤tPage=${currentPage}">修改</a>  
  213.                                     <a  
  214.                                         href="${pageContext.request.contextPath}/student_delete.action?stu.id=${u.id}"  
  215.                                         onclick="return confirm('删除后无法恢复,确定要删除吗')">删除</a>  
  216.                                 </td>  
  217.                             </tr>  
  218.                         </s:iterator>  
  219.                     </s:if>  
  220.                 </tbody>  
  221.             </table>  
  222.             <s:property value="#request.pageListData.footer" escape="false" />  
  223.         </form>  
  224.     </body>  
  225. </html>  
 
(5)studentEdit.jsp(学生信息修改页面)
  1. <%@ page language="java" import="java.util.*" pageEncoding="gbk"%>  
  2. <%@ taglib prefix="s" uri="/struts-tags"%>  
  3. <%  
  4. String path = request.getContextPath();  
  5. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  6. %>  
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.     <title>学生信息修改</title>  
  12.     <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/style.css" mce_href="${pageContext.request.contextPath}/css/style.css">  
  13.     <mce:script type="text/javascript" src="<%=path%><!--  
  14. /js/jquery-1.4.2.min.js">  
  15. // --></mce:script>  
  16.     <mce:script type="text/javascript" src="<%=path%><!--  
  17. /js/jquery.validate_pack.js">  
  18. // --></mce:script>  
  19.     <mce:script type="text/javascript" src="<%=path%><!--  
  20. /js/student.js">  
  21. // --></mce:script>  
  22.     <mce:script type='text/javascript' src="<%=request.getContextPath()%><!--  
  23. /dwr/interface/studentService.js">  
  24. // --></mce:script>  
  25.     <mce:script type='text/javascript' src="<%=request.getContextPath()%><!--  
  26. /dwr/engine.js">  
  27. // --></mce:script>  
  28.     <mce:script type='text/javascript' src="<%=request.getContextPath()%><!--  
  29. /dwr/util.js">  
  30. // --></mce:script>  
  31.   </head>  
  32.     
  33.   <body style="text-align:center" mce_style="text-align:center">  
  34.    <form action="<%=request.getContextPath()%>/student_update.action" id="studentUpdateForm"  
  35.             method="post">  
  36.             <input type="hidden" name="stu.id" value="<s:property value='stu.id'/>"/>  
  37.              <input type="hidden" name="currentPage" value="<s:property value='currentPage'/>"/>  
  38.                                 学生信息修改  
  39.             <p>  
  40.                 <label class="required">  
  41.                     姓名:  
  42.                 </label>  
  43.                 <input type="text" id="name"   
  44.                 value="<s:property value='stu.name'/>"  
  45.                     name="stu.name" />  
  46.                     <input type="hidden"  
  47.                 value="<s:property value='stu.name'/>"  
  48.                     id="stuname" />  
  49.                 <span id="namespan"></span>  
  50.             </p>  
  51.             <p>  
  52.                 <label class="required">  
  53.                     年龄:  
  54.                 </label>  
  55.                 <input type="text" id="chooseone"   
  56.                 value="<s:property value='stu.age'/>"  
  57.                     name="stu.age" />  
  58.                 <span id="agespan"></span>  
  59.             </p>  
  60.             <p>  
  61.                 <label class="required">  
  62.                     性别:  
  63.                 </label>  
  64.                 <input type="text" id="choosetwo"  name="stu.sex" value="<s:property value='stu.sex'/>" />  
  65.                 <span id="sexspan"></span>  
  66.             </p>  
  67.             <p>  
  68.                 <label class="required">  
  69.                     地址:  
  70.                 </label>  
  71.                 <input type="text" id="choosethree"   value="<s:property value='stu.address'/>"  
  72.                     name="stu.address" />  
  73.                 <span id="addressspan"></span>  
  74.             </p>  
  75.             <center>  
  76.                 <input type="submit"   
  77.                     id="send" value="提交" />  
  78.                     <input type="button" value="返回" onclick="javascript:window.location.href='<%=path%>/student_query.action?currentPage=<s:property value='currentPage'/>'"/>  
  79.             </center>  
  80.         </form>  
  81.   </body>  
  82. </html>  
 
(6)studentAdd.jsp(学生信息添加页面)
  1. <%@ page language="java" import="java.util.*" pageEncoding="gbk"%>  
  2. <%@ taglib prefix="s" uri="/struts-tags"%>  
  3. <%  
  4.     String path = request.getContextPath();  
  5.     String basePath = request.getScheme() + "://"  
  6.             + request.getServerName() + ":" + request.getServerPort()  
  7.             + path + "/";  
  8. %>  
  9. <html>  
  10.     <head>  
  11.         <base href="<%=basePath%>">  
  12.         <title>学生信息添加</title>  
  13.         <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/style.css" mce_href="${pageContext.request.contextPath}/css/style.css">  
  14.         <mce:script type="text/javascript" src="<%=path%><!--  
  15. /js/jquery-1.4.2.min.js">  
  16. // --></mce:script>  
  17.         <mce:script type="text/javascript" src="<%=path%><!--  
  18. /js/jquery.validate_pack.js">  
  19. // --></mce:script>  
  20.         <mce:script type="text/javascript" src="<%=path%><!--  
  21. /js/student.js">  
  22. // --></mce:script>  
  23.         <mce:script type='text/javascript' src="<%=request.getContextPath()%><!--  
  24. /dwr/interface/studentService.js">  
  25. // --></mce:script>  
  26.         <mce:script type='text/javascript' src="<%=request.getContextPath()%><!--  
  27. /dwr/engine.js">  
  28. // --></mce:script>  
  29.         <mce:script type='text/javascript' src="<%=request.getContextPath()%><!--  
  30. /dwr/util.js">  
  31. // --></mce:script>  
  32.     </head>  
  33.     <body style="text-align: center" mce_style="text-align: center">  
  34.         <form action="<%=request.getContextPath()%>/student_add.action"  
  35.             method="post" id="studentForm">  
  36.             学生信息添加  
  37.             <p>  
  38.                 <label for="name" class="required">  
  39.                     姓名:  
  40.                 </label>  
  41.                 <input type="text" id="name" name="stu.name"/>  
  42.                 <span id="namespan"></span>  
  43.             </p>  
  44.             <p>  
  45.                 <label for="age" class="required">  
  46.                     年龄:  
  47.                 </label>  
  48.                 <input type="text" id="age" name="stu.age" />  
  49.                 <span id="agespan"></span>  
  50.             </p>  
  51.             <p>  
  52.                 <label for="sex" class="required">  
  53.                     性别:  
  54.                 </label>  
  55.                 <input type="text" id="sex" name="stu.sex" />  
  56.                 <span id="sexspan"></span>  
  57.             </p>  
  58.             <p>  
  59.                 <label for="address" class="required">  
  60.                     地址:  
  61.                 </label>  
  62.                 <input type="text" id="address" name="stu.address" />  
  63.                 <span id="addressspan"></span>  
  64.             </p>  
  65.             <input type="submit" value="提 交" />  
  66.             <input type="button" value="返回"  
  67.                 onclick="javascript:window.location.href='<%=path%>/student_query.action?currentPage=<s:property value='currentPage'/>'" />  
  68.         </form>  
  69.     </body>  
  70. </html>  
 
(7)js脚本
student.js(采用jquery validator验证框架验证表单以及采用dwr框架验证姓名是否存在)
  1. $(document).ready(function() {  
  2.     // 字符验证           
  3.         jQuery.validator.addMethod("stringCheck",  
  4.                 function(value, element) {  
  5.                     return this.optional(element)  
  6.                             || /^[/u0391-/uFFE5/w]+$/.test(value);  
  7.                 }, "只能包括中文字、英文字母、数字和下划线");  
  8.         // 中文字两个字节           
  9.         jQuery.validator.addMethod("byteRangeLength", function(value, element,  
  10.                 param) {  
  11.             var length = value.length;  
  12.             for ( var i = 0; i < value.length; i++) {  
  13.                 if (value.charCodeAt(i) > 127) {  
  14.                     length++;  
  15.                 }  
  16.             }  
  17.             return this.optional(element)  
  18.                     || (length >= param[0] && length <= param[1]);  
  19.         }, "请确保输入的值在3-15个字节之间(一个中文字算2个字节)");  
  20.         //结合dwr框架验证姓名是否存在  
  21.         jQuery.validator.addMethod("checkName", function(value, element) {  
  22.             var flag = false;  
  23.             dwr.engine.setAsync(false);  
  24.             studentService.isExistName(value,"add",function(data) {  
  25.                 flag = !data;  
  26.             });  
  27.             dwr.engine.setAsync(true);  
  28.             return flag;  
  29.         }, "用户名已经存在,请重新输入!");  
  30.         jQuery.validator.addMethod("checkNameForUpdate", function(value, element) {  
  31.             var flag = false;  
  32.             dwr.engine.setAsync(false);  
  33.             var temp=document.getElementById("stuname").value==value;  
  34.             studentService.isExistName(value+":"+temp,"update",function(data) {  
  35.                 flag = !data;  
  36.             });  
  37.             dwr.engine.setAsync(true);  
  38.             return flag;  
  39.         }, "用户名已经存在,请重新输入!");  
  40.         // 验证年龄 1-149之间     
  41.         jQuery.validator.addMethod("ageCheck", function(value, element) {  
  42.             return this.optional(element)  
  43.                     || /^([1-9]{1}|[1-9]{1}[0-9]{1}|1[1-4]{1}[0-9]{1})$/  
  44.                             .test(value);  
  45.         }, "只能1-149之间的数字!");  
  46.         // 验证性别   
  47.         jQuery.validator.addMethod("sexCheck",  
  48.                 function(value, element) {  
  49.                     return this.optional(element)  
  50.                             || /^[/u4E00-/u9FFF]{1}$/.test(value);  
  51.                 }, "只能是一个汉字");  
  52.         //// 身份证号码验证           
  53.         //jQuery.validator.addMethod("isIdCardNo", function(value, element) {           
  54.         //    return this.optional(element) || isIdCardNo(value);           
  55.         //}, "请正确输入您的身份证号码");        
  56.         //         
  57.         //// 手机号码验证           
  58.         //jQuery.validator.addMethod("isMobile", function(value, element) {           
  59.         //    var length = value.length;       
  60.         //    var mobile = /^(((13[0-9]{1})|(15[0-9]{1}))+/d{8})$/;       
  61.         //    return this.optional(element) || (length == 11 && mobile.test(value));           
  62.         //}, "请正确填写您的手机号码");           
  63.         //         
  64.         //// 电话号码验证           
  65.         //jQuery.validator.addMethod("isTel", function(value, element) {           
  66.         //    var tel = /^/d{3,4}-?/d{7,9}$/;    //电话号码格式010-12345678       
  67.         //    return this.optional(element) || (tel.test(value));           
  68.         //}, "请正确填写您的电话号码");       
  69.         //      
  70.         //// 联系电话(手机/电话皆可)验证       
  71.         //jQuery.validator.addMethod("isPhone", function(value,element) {       
  72.         //    var length = value.length;       
  73.         //    var mobile = /^(((13[0-9]{1})|(15[0-9]{1}))+/d{8})$/;       
  74.         //    var tel = /^/d{3,4}-?/d{7,9}$/;       
  75.         //    return this.optional(element) || (tel.test(value) || mobile.test(value));       
  76.         //      
  77.         //}, "请正确填写您的联系电话");       
  78.         //         
  79.         //// 邮政编码验证           
  80.         //jQuery.validator.addMethod("isZipCode", function(value, element) {           
  81.         //    var tel = /^[0-9]{6}$/;           
  82.         //    return this.optional(element) || (tel.test(value));           
  83.         //}, "请正确填写您的邮政编码");        
  84.         //开始验证     studentUpdateForm  
  85.         $("#studentForm").validate( {  
  86.             /**//* 设置验证规则 */  
  87.             rules : {  
  88.                 "stu.name" : {  
  89.                     required : true,  
  90.                     stringCheck : true,  
  91.                     checkName : true,  
  92.                     byteRangeLength : [ 3, 15 ]  
  93.                 },  
  94.                 "stu.age" : {  
  95.                     required : true,  
  96.                     ageCheck : true  
  97.                 },  
  98.                 "stu.sex" : {  
  99.                     required : true,  
  100.                     sexCheck : true  
  101.                 },  
  102.                 "stu.address" : {  
  103.                     required : true,  
  104.                     stringCheck : true,  
  105.                     byteRangeLength : [ 3, 100 ]  
  106.                 }  
  107.             },  
  108.             //设置错误信息  
  109.             messages : {  
  110.                 "stu.name" : {  
  111.                     required : "请填写用户名",  
  112.                     stringCheck : "用户名只能包括中文字、英文字母、数字和下划线",  
  113.                     checkName : "该姓名已经存在",  
  114.                     byteRangeLength : "用户名必须在3-15个字符之间(一个中文字算2个字符)"  
  115.                 },  
  116.                 "stu.age" : {  
  117.                     required : "请输入年龄",  
  118.                     email : "请输入1-149之间的数字"  
  119.                 },  
  120.                 "stu.sex" : {  
  121.                     required : "请输入您的性别",  
  122.                     isPhone : "请输入一个汉字"  
  123.                 },  
  124.                 "stu.address" : {  
  125.                     required : "请输入您的联系地址",  
  126.                     stringCheck : "请正确输入您的联系地址",  
  127.                     byteRangeLength : "请详实您的联系地址以便于我们联系您"  
  128.                 }  
  129.             },  
  130.             errorPlacement : function(error, element) {  
  131.                 element.parent().find("span").html(error)  
  132.             },  
  133.             success : function(label) {  
  134.                 label.html(" ").addClass("ok");  
  135.             }  
  136.         });  
  137.         //开始验证 修改页面    
  138.         $("#studentUpdateForm").validate( {  
  139.             /**//* 设置验证规则 */  
  140.             rules : {  
  141.                 "stu.name" : {  
  142.                     required : true,  
  143.                     stringCheck : true,  
  144.                     checkNameForUpdate : true,  
  145.                     byteRangeLength : [ 3, 15 ]  
  146.                 },  
  147.                 "stu.age" : {  
  148.                     required : true,  
  149.                     ageCheck : true  
  150.                 },  
  151.                 "stu.sex" : {  
  152.                     required : true,  
  153.                     sexCheck : true  
  154.                 },  
  155.                 "stu.address" : {  
  156.                     required : true,  
  157.                     stringCheck : true,  
  158.                     byteRangeLength : [ 3, 100 ]  
  159.                 }  
  160.             },  
  161.             //设置错误信息  
  162.             messages : {  
  163.                 "stu.name" : {  
  164.                     required : "请填写用户名",  
  165.                     stringCheck : "用户名只能包括中文字、英文字母、数字和下划线",  
  166.                     checkNameForUpdate : "该姓名已经存在",  
  167.                     byteRangeLength : "用户名必须在3-15个字符之间(一个中文字算2个字符)"  
  168.                 },  
  169.                 "stu.age" : {  
  170.                     required : "请输入年龄",  
  171.                     email : "请输入1-149之间的数字"  
  172.                 },  
  173.                 "stu.sex" : {  
  174.                     required : "请输入您的性别",  
  175.                     isPhone : "请输入一个汉字"  
  176.                 },  
  177.                 "stu.address" : {  
  178.                     required : "请输入您的联系地址",  
  179.                     stringCheck : "请正确输入您的联系地址",  
  180.                     byteRangeLength : "请详实您的联系地址以便于我们联系您"  
  181.                 }  
  182.             },  
  183.             errorPlacement : function(error, element) {  
  184.                 element.parent().find("span").html(error)  
  185.             },  
  186.             success : function(label) {  
  187.                 label.html(" ").addClass("ok");  
  188.             }  
  189.         });  
  190.     });  
 
main.js
  1. //检查分页列表页面页码输入框  
  2. function checkCurrentPage(input, totalPages) {  
  3.     if (!input.match(/^/d*$/)) {  
  4.         alert("只能输入数字");  
  5.         document.getElementById("jumpPageBox").value = document  
  6.                 .getElementById("pages").value;  
  7.         document.getElementById("jumpPageBox").focus();  
  8.     } else if (input > totalPages || parseInt(input) <= 0) {  
  9.         alert("对不起,你输入的页码有误!");  
  10.         document.getElementById("jumpPageBox").value = document  
  11.                 .getElementById("pages").value;  
  12.         document.getElementById("jumpPageBox").focus();  
  13.     }  
  14. }  
  15. //去掉前后空格  
  16. function trim(s) {  
  17.     try {  
  18.         return s.replace(/(^/s*)|(/s*$)/g, "");  
  19.     } catch (e) {  
  20.         return s;  
  21.     }  
  22. }  
  23. //给列表中id为changecolor的那些行变色  
  24. $(document).ready(function() {  
  25.     $("table tbody tr[id*='changecolor']").mouseover(function() {  
  26.         $(this).css("background""orange");  
  27.     }).mouseout(function() {  
  28.         $(this).css("background""white");  
  29.     })  
  30. });  
 
login.js(采用jquery validator验证框架验证登录表单)
  1. $(document).ready(function() {      
  2.         $("#loginForm").validate( {  
  3.             /**//* 设置验证规则 */  
  4.             rules : {  
  5.                 "user.username" : {  
  6.                     required : true  
  7.                 },  
  8.                 "user.password" : {  
  9.                     required : true  
  10.                 }  
  11.             },  
  12.             //设置错误信息  
  13.             messages : {  
  14.                 "user.username" : {  
  15.                     required : "请填写用户名"  
  16.                 },  
  17.                 "user.password" : {  
  18.                     required : "请填写密码"  
  19.                 }  
  20.             },  
  21.             errorPlacement : function(error, element) {  
  22.                 element.parent().find("span").html(error)  
  23.             },  
  24.             success : function(label) {  
  25.                 label.html(" ").addClass("ok");  
  26.             }  
  27.         });  
  28.     });  
 
除此之外,还用到jquery及其验证框架的js库,请自行下载
(8)CSS
style.css
  1. label.required:after {  
  2.     content:"(*)";  
  3.     color:red;  
  4.     font-family:"Lucida Grande",Verdana,Arial,Helvetica,sans-serif;  
  5. }  
  6. label.ok {  
  7.     background:url("../images/valid.gif") no-repeat;  
  8.     padding-left:16px;  
  9. }  
  10. label.error {  
  11.     color:#d00;  
  12.     text-transform:none;  
  13.     margin-left:6px;  
  14. }  
  15. label.choice {  
  16.     vertical-align:middle;  
  17.     font-weight:normal;  
  18.     text-transform:none;  
  19. }  
 
3、数据访问层及其业务层
(1)DAO层
 BaseDAO.java
  1. package com.anxin.dao;  
  2. import java.util.List;  
  3. import com.anxin.util.PageListData;  
  4. public interface BaseDAO<T,PK> {  
  5.     public void save(T entity);  
  6.     public void delete(T entity);  
  7.     public void deleteById(Class<T> entityClass, PK id);  
  8.     public void saveOrUpdate(T entity);  
  9.     public List<T> findAll(Class<T> entityClass);  
  10.     public PageListData findList(Class<T> entityClass, String hql, Object[] paramsint currentPage, int pageSize);  
  11.     public List<T> findByProperty(Class<T> entityClass, String propertyName, Object value,int type);  
  12.     public T findById(Class<T> entityClass, PK id);  
  13. }  
 
BaseDAOImpl.java
  1. package com.anxin.dao.impl;  
  2. import java.io.Serializable;  
  3. import java.util.List;  
  4. import org.hibernate.Query;  
  5. import org.slf4j.Logger;  
  6. import org.slf4j.LoggerFactory;  
  7. import org.springframework.orm.hibernate3.support.HibernateDaoSupport;  
  8. import com.anxin.dao.BaseDAO;  
  9. import com.anxin.util.PageListData;  
  10. public class BaseDAOImpl<T, PK extends Serializable> extends  
  11.         HibernateDaoSupport implements BaseDAO<T, PK> {  
  12.     static Logger logger = LoggerFactory.getLogger(BaseDAOImpl.class);  
  13.     // 保存  
  14.     public void save(T entity) {  
  15.         try {  
  16.             getHibernateTemplate().save(entity);  
  17.         } catch (RuntimeException re) {  
  18.             throw re;  
  19.         }  
  20.     }  
  21.     // 保存或者更新  
  22.     public void saveOrUpdate(T entity) {  
  23.         try {  
  24.             getHibernateTemplate().merge(entity);  
  25.         } catch (RuntimeException re) {  
  26.             throw re;  
  27.         }  
  28.     }  
  29.     // 删除  
  30.     public void delete(T entity) {  
  31.         try {  
  32.             getHibernateTemplate().delete(entity);  
  33.         } catch (RuntimeException re) {  
  34.             throw re;  
  35.         }  
  36.     }  
  37.     // 根据id删除某个对象  
  38.     public void deleteById(Class<T> entityClass, PK id) {  
  39.         try {  
  40.             getHibernateTemplate().delete(findById(entityClass, id));  
  41.         } catch (RuntimeException re) {  
  42.             throw re;  
  43.         }  
  44.     }  
  45.     // 根据id加载某个对象  
  46.     public T findById(Class<T> entityClass, PK id) {  
  47.         try {  
  48.             return (T) getHibernateTemplate().get(entityClass, id);  
  49.         } catch (RuntimeException re) {  
  50.             logger.error("findById " + entityClass.getName() + " failed :{}",  
  51.                     re);  
  52.             throw re;  
  53.         }  
  54.     }  
  55.     // 查找所有的对象  
  56.     public List<T> findAll(Class<T> entityClass) {  
  57.         try {  
  58.             return getHibernateTemplate().loadAll(entityClass);  
  59.         } catch (RuntimeException re) {  
  60.             throw re;  
  61.         }  
  62.     }  
  63.     // 根据某个属性及其值精确或模糊查找对象  
  64.     public List<T> findByProperty(Class<T> entityClass, String propertyName,  
  65.             Object value, int type) {  
  66.         String queryString = "";  
  67.         try {  
  68.             if (type == 1) {// type=1是精确查找  
  69.                 queryString = "from " + entityClass.getName()  
  70.                         + " as model where model." + propertyName + "= ?";  
  71.             } else if (type == 2) {// type=2是模糊查找  
  72.                 queryString = "from " + entityClass.getName()  
  73.                         + " as model where model." + propertyName + "like ?";  
  74.             }  
  75.             return getHibernateTemplate().find(queryString, value);  
  76.         } catch (RuntimeException re) {  
  77.             throw re;  
  78.         }  
  79.     }  
  80.     // 根据hql语句及其查询参数,当前页数,每页显示的数目得到分页列表  
  81.     public PageListData findList(Class<T> entityClass, String hql,  
  82.             Object[] paramsint currentPage, int pageSize) {  
  83.         PageListData listdata=null;  
  84.         try {  
  85.             Query query = getSession().createQuery(getCountsHql(hql));  
  86.             if (null != params && 0 != params.length) {  
  87.                 for (int i = 0; i < params.length; i++) {  
  88.                     query.setParameter(i, params[i]);  
  89.                 }  
  90.             } else {  
  91.                 logger.warn("参数为空");  
  92.             }  
  93.             int total = ((Long) query.uniqueResult()).intValue();  
  94.             logger.debug("总记录数:", total);  
  95.             query = getSession().createQuery(hql);  
  96.             if (null != params && 0 != params.length) {  
  97.                 for (int i = 0; i < params.length; i++) {  
  98.                     query.setParameter(i, params[i]);  
  99.                 }  
  100.             }  
  101.             if (0 != pageSize) {  
  102.                 query.setFirstResult(  
  103.                         (currentPage == 0 ? 0 : currentPage - 1) * pageSize)  
  104.                         .setMaxResults(pageSize);  
  105.             }  
  106.             List data = query.list();  
  107.             listdata=new PageListData(total,pageSize,currentPage,  
  108.                     data);  
  109.         } catch (RuntimeException re) {  
  110.             throw re;  
  111.         }  
  112.         return listdata;  
  113.     }  
  114.     private String getCountsHql(String hql) {  
  115.         int index = hql.indexOf("from");  
  116.         if (index != -1) {  
  117.             return "select count(*) " + hql.substring(index);  
  118.         }  
  119.         throw new RuntimeException("sql语句异常" + hql);  
  120.     }  
  121. }  
 
UserDAO.java
  1. package com.anxin.dao;  
  2. import com.anxin.bean.User;  
  3. public interface UserDAO extends BaseDAO<User,Integer>{  
  4.     public User checkLogin(User user);  
  5. }  
 
UserDAOImpl.java
  1. package com.anxin.dao.impl;  
  2. import org.hibernate.Query;  
  3. import com.anxin.bean.User;  
  4. import com.anxin.dao.UserDAO;  
  5. public class UserDAOImpl extends BaseDAOImpl<User,Integer> implements UserDAO{  
  6.     public User checkLogin(User user){  
  7.         String hql="from User u where u.username=? and u.password=?";  
  8.         Query q=getSession().createQuery(hql);  
  9.         q.setString(0, user.getUsername()).setString(1, user.getPassword());  
  10.         return q.list()!=null&&q.list().size()>0?(User)q.list().get(0):null;  
  11.     }  
  12. }  
 
StudentDAO.java
  1. package com.anxin.dao;  
  2. import com.anxin.bean.Student;  
  3. public interface StudentDAO extends BaseDAO<Student,Integer>{  
  4. }  
 
StudentDAOImpl.java
  1. package com.anxin.dao.impl;  
  2. import com.anxin.bean.Student;  
  3. import com.anxin.dao.StudentDAO;  
  4. public class StudentDAOImpl extends BaseDAOImpl<Student,Integer> implements StudentDAO{  
  5.       
  6. }  
 
(2)service层
StudentService.java
  1. package com.anxin.service;  
  2. import java.util.List;  
  3. import java.util.Map;  
  4. import com.anxin.bean.Student;  
  5. import com.anxin.bean.User;  
  6. import com.anxin.util.PageListData;  
  7. public interface StudentService{  
  8.     public void save(Student stu);  
  9.     public void delete(Student stu);  
  10.     public void deleteById(Integer id);  
  11.     public void update(Student stu);  
  12.     public PageListData findList(Map param, int currentPage, int pageSize);  
  13.     public boolean isExistSameProperty(Map param);  
  14.     public Student findById(Integer id);  
  15.     public List<Student> findAll();  
  16.     public List<Student> findByCondition(Map param,int type);  
  17. }  
 
StudentServiceImpl.java
  1. package com.anxin.service.impl;  
  2. import java.util.List;  
  3. import java.util.Map;  
  4. import com.anxin.bean.Student;  
  5. import com.anxin.bean.User;  
  6. import com.anxin.dao.StudentDAO;  
  7. import com.anxin.dao.UserDAO;  
  8. import com.anxin.service.StudentService;  
  9. import com.anxin.service.UserService;  
  10. import com.anxin.util.PageListData;  
  11. public class StudentServiceImpl implements StudentService {  
  12.     private StudentDAO dao;  
  13.     public void save(Student stu) {  
  14.         dao.save(stu);  
  15.     }  
  16.     public void delete(Student stu) {  
  17.         dao.delete(stu);  
  18.     }  
  19.     public void deleteById(Integer id) {  
  20.         dao.deleteById(Student.class, id);  
  21.     }  
  22.     public void update(Student stu) {  
  23.         dao.saveOrUpdate(stu);  
  24.     }  
  25.     public PageListData findList(Map param, int pageNum, int pageSize) {  
  26.         String hql = "from Student where 1=1 ";  
  27.         for (Object o : param.keySet()) {  
  28.             hql += " and " + o.toString() + " ? ";  
  29.         }  
  30.         Object params[] = param.values().toArray();  
  31.         return dao.findList(Student.class, hql, params, pageNum, pageSize);  
  32.     }  
  33.     public boolean isExistSameProperty(Map param) {  
  34.         return true;  
  35.     }  
  36.     public Student findById(Integer id) {  
  37.         return dao.findById(Student.class, id);  
  38.     }  
  39.     public List<Student> findAll() {  
  40.         return dao.findAll(Student.class);  
  41.     }  
  42.     public boolean isExistName(String name, String type) {  
  43.         boolean flag=false;  
  44.         if ("add".equals(type)) {  
  45.             List list = dao.findByProperty(Student.class"name", name, 1);  
  46.             flag=(list != null && list.size() > 0 ? true : false);  
  47.         } else if ("update".equals(type)) {  
  48.             String temp[]=name.split(":");  
  49.             List list = dao.findByProperty(Student.class"name", temp[0], 1);  
  50.             if(Boolean.parseBoolean(temp[1]))  
  51.                 flag=(list!=null&&list.size()>1?true:false);  
  52.             else  
  53.                 flag=(list!=null&&list.size()>0?true:false);  
  54.         }  
  55.         return flag;  
  56.     }  
  57.     public List<Student> findByCondition(Map param, int type) {  
  58.         return dao.findByProperty(Student.classnullnull, type);  
  59.     }  
  60.     public StudentDAO getDao() {  
  61.         return dao;  
  62.     }  
  63.     public void setDao(StudentDAO dao) {  
  64.         this.dao = dao;  
  65.     }  
  66. }  
 
UserService.java
  1. package com.anxin.service;  
  2. import java.util.List;  
  3. import java.util.Map;  
  4. import com.anxin.bean.User;  
  5. import com.anxin.util.PageListData;  
  6. public interface UserService{  
  7.     public void save(User user);  
  8.     public void delete(User user);  
  9.     public void deleteById(Integer id);  
  10.     public void update(User user);  
  11.     public PageListData findList(Map param, int currentPage, int pageSize);  
  12.     public boolean isExistSameProperty(Map param);  
  13.     public User findById(Integer id);  
  14.     public List<User> findAll();  
  15.     public List<User> findByCondition(Map param,int type);  
  16.     public User checkLogin(User user);  
  17. }  
 
UserServiceImpl.java
  1. package com.anxin.service.impl;  
  2. import java.util.List;  
  3. import java.util.Map;  
  4. import com.anxin.bean.User;  
  5. import com.anxin.dao.UserDAO;  
  6. import com.anxin.service.UserService;  
  7. import com.anxin.util.PageListData;  
  8. public class UserServiceImpl implements UserService {  
  9.     private UserDAO dao;  
  10.     public void save(User user) {  
  11.         dao.save(user);  
  12.     }  
  13.     public void delete(User user) {  
  14.         dao.delete(user);  
  15.     }  
  16.     public void deleteById(Integer id) {  
  17.         dao.deleteById(User.class, id);  
  18.     }  
  19.     public void update(User user) {  
  20.         dao.saveOrUpdate(user);  
  21.     }  
  22.     public PageListData findList(Map param, int pageNum, int pageSize) {  
  23.         String hql = "from User";  
  24.         Object params[] = param.values().toArray();  
  25.         return dao.findList(User.class, hql, params, pageNum, pageSize);  
  26.     }  
  27.     public boolean isExistSameProperty(Map param) {  
  28.         return true;  
  29.     }  
  30.     public User findById(Integer id) {  
  31.         return dao.findById(User.class, id);  
  32.     }  
  33.     public List<User> findAll() {  
  34.         return dao.findAll(User.class);  
  35.     }  
  36.     public List<User> findByCondition(Map param, int type) {  
  37.         return dao.findByProperty(User.classnullnull, type);  
  38.     }  
  39.     public User checkLogin(User user) {  
  40.         return dao.checkLogin(user);  
  41.     }  
  42.     public UserDAO getDao() {  
  43.         return dao;  
  44.     }  
  45.     public void setDao(UserDAO dao) {  
  46.         this.dao = dao;  
  47.     }  
  48. }  
 
(3)bean及其Hibernate实体映射文件
Student.java
  1. package com.anxin.bean;  
  2. public class Student {  
  3.     private int id;  
  4.     private String name;  
  5.     private int age;  
  6.     private String sex;  
  7.     private String address;  
  8.     public int getId() {  
  9.         return id;  
  10.     }  
  11.     public void setId(int id) {  
  12.         this.id = id;  
  13.     }  
  14.     public String getName() {  
  15.         return name;  
  16.     }  
  17.     public void setName(String name) {  
  18.         this.name = name;  
  19.     }  
  20.     public int getAge() {  
  21.         return age;  
  22.     }  
  23.     public void setAge(int age) {  
  24.         this.age = age;  
  25.     }  
  26.     public String getSex() {  
  27.         return sex;  
  28.     }  
  29.     public void setSex(String sex) {  
  30.         this.sex = sex;  
  31.     }  
  32.     public String getAddress() {  
  33.         return address;  
  34.     }  
  35.     public void setAddress(String address) {  
  36.         this.address = address;  
  37.     }  
  38.       
  39. }  
 
User.java
  1. package com.anxin.bean;  
  2. public class User implements java.io.Serializable {  
  3.     private int id;  
  4.     private String username;  
  5.     private String password;  
  6.     public User(){}  
  7.     public User(String username,String password){  
  8.         this.username=username;  
  9.         this.password=password;  
  10.     }  
  11.     public int getId() {  
  12.         return id;  
  13.     }  
  14.     public void setId(int id) {  
  15.         this.id = id;  
  16.     }  
  17.     public String getUsername() {  
  18.         return username;  
  19.     }  
  20.     public void setUsername(String username) {  
  21.         this.username = username;  
  22.     }  
  23.     public String getPassword() {  
  24.         return password;  
  25.     }  
  26.     public void setPassword(String password) {  
  27.         this.password = password;  
  28.     }  
  29. }  
 
Student.hbm.xml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  4. <!--   
  5.     Mapping file autogenerated by MyEclipse Persistence Tools  
  6. -->  
  7. <hibernate-mapping>  
  8.     <class name="com.anxin.bean.Student" table="student" catalog="practice">  
  9.         <id name="id" type="java.lang.Integer">  
  10.             <column name="id" />  
  11.             <generator class="native" />  
  12.         </id>  
  13.         <property name="name" type="java.lang.String">  
  14.             <column name="name" length="50"/>  
  15.         </property>  
  16.         <property name="age" type="java.lang.Integer">  
  17.             <column name="age"/>  
  18.         </property>  
  19.         <property name="sex" type="java.lang.String">  
  20.             <column name="sex" length="1"/>  
  21.         </property>  
  22.         <property name="address" type="java.lang.String">  
  23.             <column name="address" length="100"/>  
  24.         </property>  
  25.     </class>  
  26. </hibernate-mapping>  
 
User.hbm.xml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  4. <!--   
  5.     Mapping file autogenerated by MyEclipse Persistence Tools  
  6. -->  
  7. <hibernate-mapping>  
  8.     <class name="com.anxin.bean.User" table="users" catalog="practice">  
  9.         <id name="id" type="java.lang.Integer">  
  10.             <column name="id" />  
  11.             <generator class="native" />  
  12.         </id>  
  13.         <property name="username" type="java.lang.String">  
  14.             <column name="username" length="50"/>  
  15.         </property>  
  16.         <property name="password" type="java.lang.String">  
  17.             <column name="password" length="50"/>  
  18.         </property>  
  19.     </class>  
  20. </hibernate-mapping>  
 
4、逻辑处理Action层
BaseAction.java
  1. package com.anxin.struts.action;  
  2. import com.anxin.util.OVLoadProperties;  
  3. import com.anxin.util.PageListData;  
  4. import com.opensymphony.xwork2.ActionSupport;  
  5. public class BaseAction extends ActionSupport{  
  6.     protected PageListData pageListData;//分页组件  
  7.     protected int currentPage=1;//当前页  
  8.     protected int pageSize=Integer.parseInt(OVLoadProperties.getInstance().getProperties("pageSize"));//每页显示的数目  
  9.     protected int querytype;//查询类型  
  10.     protected String condition;//查询条件  
  11.     public PageListData getPageListData() {  
  12.         return pageListData;  
  13.     }  
  14.     public void setPageListData(PageListData pageListData) {  
  15.         this.pageListData = pageListData;  
  16.     }  
  17.     public int getCurrentPage() {  
  18.         return currentPage;  
  19.     }  
  20.     public void setCurrentPage(int currentPage) {  
  21.         this.currentPage = currentPage;  
  22.     }  
  23.     public int getPageSize() {  
  24.         return pageSize;  
  25.     }  
  26.     public void setPageSize(int pageSize) {  
  27.         this.pageSize = pageSize;  
  28.     }  
  29.     public int getQuerytype() {  
  30.         return querytype;  
  31.     }  
  32.     public void setQuerytype(int querytype) {  
  33.         this.querytype = querytype;  
  34.     }  
  35.     public String getCondition() {  
  36.         return condition==null?"":condition.trim();  
  37.     }  
  38.     public void setCondition(String condition) {  
  39.         this.condition=(condition==null?"":condition.trim());  
  40.     }  
  41.       
  42. }  
 
UserAction.java
  1. package com.anxin.struts.action;  
  2. import com.anxin.bean.User;  
  3. import com.anxin.service.UserService;  
  4. import com.opensymphony.xwork2.ActionContext;  
  5. public class UserAction extends BaseAction{  
  6.     private UserService service;  
  7.     private User user;  
  8.     public String login(){  
  9.         user=service.checkLogin(user);  
  10.         if(user!=null){  
  11.             ActionContext.getContext().getSession().put("user", user);  
  12.             return "success";  
  13.         }  
  14.         else{  
  15.             this.addActionMessage("用户名或密码错误!");  
  16.             return "input";  
  17.         }  
  18.     }  
  19.     public UserService getService() {  
  20.         return service;  
  21.     }  
  22.     public void setService(UserService service) {  
  23.         this.service = service;  
  24.     }  
  25.     public User getUser() {  
  26.         return user;  
  27.     }  
  28.     public void setUser(User user) {  
  29.         this.user = user;  
  30.     }  
  31. }  
 
StudentAction.java
  1. package com.anxin.struts.action;  
  2. import java.util.HashMap;  
  3. import java.util.Map;  
  4. import com.anxin.bean.Student;  
  5. import com.anxin.service.StudentService;  
  6. public class StudentAction extends BaseAction {  
  7.     private StudentService service;  
  8.     private Student stu;  
  9.     // 转到增加页面  
  10.     public String toAdd() {  
  11.         return "add";  
  12.     }  
  13.     // 添加学生  
  14.     public String add() {  
  15.         service.save(stu);  
  16.         return "success";  
  17.     }  
  18.     // 转到修页面  
  19.     public String toUpdate() {  
  20.         stu = service.findById(stu.getId());  
  21.         return "update";  
  22.     }  
  23.     // 更新信息  
  24.     public String update() {  
  25.         Student temp = service.findById(stu.getId());  
  26.         temp.setId(stu.getId());  
  27.         temp.setAddress(stu.getAddress());  
  28.         temp.setAge(stu.getAge());  
  29.         temp.setName(stu.getName());  
  30.         temp.setSex(stu.getSex());  
  31.         service.update(temp);  
  32.         return "success";  
  33.     }  
  34.     // 查询列表  
  35.     public String query() {  
  36.         Map<String, String> param = new HashMap<String, String>();  
  37.         if (!"".equals(condition)) {  
  38.             if (querytype == 1) {  
  39.                 param.put("name like""%" + condition + "%");  
  40.             } else if (querytype == 2) {  
  41.                 param.put("sex =", condition);  
  42.             }  
  43.         }  
  44.         pageListData = service.findList(param, currentPage, pageSize);  
  45.         return "query";  
  46.     }  
  47.     // 删除学生  
  48.     public String delete() {  
  49.         service.deleteById(stu.getId());  
  50.         return "success";  
  51.     }  
  52.     public StudentService getService() {  
  53.         return service;  
  54.     }  
  55.     public void setService(StudentService service) {  
  56.         this.service = service;  
  57.     }  
  58.     public Student getStu() {  
  59.         return stu;  
  60.     }  
  61.     public void setStu(Student stu) {  
  62.         this.stu = stu;  
  63.     }  
  64. }  
 
5、公用的一些类
OpenSessionInViewFilter.java(重写spring包中的OpenSessionInViewFilter类,目的是解决事务提交出现的bug)
  1. package com.anxin.util;  
  2. import org.hibernate.FlushMode;  
  3. import org.hibernate.Session;  
  4. import org.hibernate.SessionFactory;  
  5. import org.springframework.dao.DataAccessResourceFailureException;  
  6. import org.springframework.orm.hibernate3.SessionFactoryUtils;  
  7. public class OpenSessionInViewFilter extends org.springframework.orm.hibernate3.support.OpenSessionInViewFilter {  
  8.       
  9.     /** 
  10.      * we do a different flushmode than in the codebase 
  11.      * here 
  12.      */  
  13.     protected Session getSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {  
  14.             Session session = SessionFactoryUtils.getSession(sessionFactory, true);  
  15.             session.setFlushMode(FlushMode.COMMIT);  
  16.             return session;  
  17.     }  
  18.     /** 
  19.      * we do an explicit flush here just in case 
  20.      * we do not have an automated flush 
  21.      */  
  22.     protected void closeSession(Session session, SessionFactory factory) {  
  23.             session.flush();  
  24.             super.closeSession(session, factory);  
  25.     }  
  26. }  
 
PageListData.java(分页组件)
  1. package com.anxin.util;  
  2. import java.util.ArrayList;  
  3. import java.util.List;  
  4. import java.util.Locale;  
  5. import javax.servlet.http.HttpServletRequest;  
  6. public class PageListData {  
  7.     // 分页结果集  
  8.     private List dataList = null;  
  9.     // 记录总数  
  10.     private int totalcount = 0;  
  11.     // 每页显示记录数  
  12.     private int pageSize = 0;  
  13.     // 当前页数  
  14.     private int currentPage = 1;  
  15.     // 总页数  
  16.     private int totalPageCount = 1;  
  17.     //分页页脚  
  18.     private String footer;  
  19.     /*初始化分页组件*/  
  20.     public PageListData(int totalcount, int pageSize, int currentPage,  
  21.             List dataList) {  
  22.         setTotalcount(totalcount);  
  23.         setPageSize(pageSize);  
  24.         setCurrentPage(currentPage);  
  25.         setDataList(dataList);  
  26.         setFooter(getFooter());  
  27.     }  
  28.     /** 
  29.      * 封装分页栏函数 必需被包含在某个Form之中 
  30.      *  
  31.      * @return String pages 当前页号 pageSize 每页显示行数 
  32.      */  
  33.     public String getFooter() {  
  34.         StringBuffer pageStr = new StringBuffer("");  
  35.         pageStr.append("<center><p class='pages'>");  
  36.         int totalPages = getTotalPageCount(); // 总页数  
  37.         int prevPage = currentPage - 1; // 上一页  
  38.         int nextPage = currentPage + 1; // 下一页  
  39.         pageStr.append("<span style="color:#6795B4;" mce_style="color:#6795B4;">共有" + totalcount  
  40.                 + "条记录</span>  ");  
  41.         pageStr.append("<span style="color:#6795B4;" mce_style="color:#6795B4;">第" + currentPage + "页/共"  
  42.                 + totalPages + "页</span>  ");  
  43.         if (currentPage > 1)  
  44.             pageStr  
  45.                     .append("<span><a style="cursor: pointer;text-decoration:underline;color:#6795B4" mce_style="cursor: pointer;text-decoration:underline;color:#6795B4"onclick='document.getElementById(/"pages/").value=1;document.getElementById(/"pages/").form.submit();'>首页</a></span>  ");  
  46.         if (currentPage == 1)  
  47.             pageStr  
  48.                     .append("<span style="color:#6795B4" mce_style="color:#6795B4">首页</span>    ");  
  49.         if (currentPage > 1)  
  50.             pageStr  
  51.                     .append("<span><a style="cursor: pointer;text-decoration:underline;color:#6795B4" mce_style="cursor: pointer;text-decoration:underline;color:#6795B4" onclick='document.getElementById(/"pages/").value="  
  52.                             + prevPage  
  53.                             + ";document.getElementById(/"pages/").form.submit();'>上一页</a></span>  ");  
  54.         if (currentPage <= 1)  
  55.             pageStr  
  56.                     .append("<span style="color:#6795B4" mce_style="color:#6795B4">上一页</span>  ");  
  57.         if (currentPage < totalPages)  
  58.             pageStr  
  59.                     .append("<span><a style="cursor: pointer;text-decoration:underline;color:#6795B4;" mce_style="cursor: pointer;text-decoration:underline;color:#6795B4;" onclick='document.getElementById(/"pages/").value="  
  60.                             + nextPage  
  61.                             + ";document.getElementById(/"pages/").form.submit();'>下一页</a></span>  ");  
  62.         if (currentPage >= totalPages)  
  63.             pageStr  
  64.                     .append("<span style="color:#6795B4;" mce_style="color:#6795B4;">下一页</span>  ");  
  65.         if (currentPage < totalPages)  
  66.             pageStr  
  67.                     .append("<span><a style="cursor: pointer;text-decoration:underline;color:#6795B4;" mce_style="cursor: pointer;text-decoration:underline;color:#6795B4;" onclick='document.getElementById(/"pages/").value="  
  68.                             + totalPages  
  69.                             + ";document.getElementById(/"pages/").form.submit();'>末页</a></span>  ");  
  70.         if (currentPage == totalPages)  
  71.             pageStr  
  72.                     .append("<span style="color:#6795B4;" mce_style="color:#6795B4;">末页</span>  ");  
  73.         pageStr  
  74.                 .append("<span style="color:#6795B4;" mce_style="color:#6795B4;">跳转至第:<input type='text' value='"  
  75.                         + currentPage  
  76.                         + "'id='jumpPageBox' size='2' onblur='checkCurrentPage(document.getElementById(/"jumpPageBox/").value,"  
  77.                         + totalPages  
  78.                         + ")'/>页<input class='right-button02' type='button' value='跳转' onclick='document.getElementById(/"pages/").value=document.getElementById(/"jumpPageBox/").value;document.getElementById(/"pages/").form.submit();'/></span>");  
  79.         pageStr.append("</p></center>");  
  80.         pageStr.append("<input type='hidden' value='" + currentPage  
  81.                 + "' name='currentPage' id='pages' />");  
  82.         pageStr.append("<input type='hidden' value='" + pageSize  
  83.                 + "' name='pageSize' id='pageSize' />");  
  84.         return pageStr.toString();  
  85.     }  
  86.     public List getDataList() {  
  87.         return dataList;  
  88.     }  
  89.     public void setDataList(List dataList) {  
  90.         this.dataList = dataList;  
  91.     }  
  92.     public int getTotalcount() {  
  93.         return totalcount;  
  94.     }  
  95.     public void setTotalcount(int totalcount) {  
  96.         this.totalcount = totalcount;  
  97.     }  
  98.     public int getPageSize() {  
  99.         return pageSize;  
  100.     }  
  101.     public void setPageSize(int pageSize) {  
  102.         this.pageSize = pageSize;  
  103.     }  
  104.     public int getCurrentPage() {  
  105.         return currentPage;  
  106.     }  
  107.     public void setCurrentPage(int currentPage) {  
  108.         this.currentPage = currentPage;  
  109.     }  
  110.     //计算总页数,如果为0则置为1  
  111.     public int getTotalPageCount() {  
  112.         int p;  
  113.         if (totalcount % pageSize == 0) {  
  114.             p=totalcount / pageSize;  
  115.         } else {  
  116.             p=totalcount / pageSize + 1;  
  117.         }  
  118.         return p==0?1:p;  
  119.     }  
  120.     public void setTotalPageCount(int totalPageCount) {  
  121.         this.totalPageCount = totalPageCount;  
  122.     }  
  123.     public void setFooter(String footer) {  
  124.         this.footer = footer;  
  125.     }  
  126. }  
 
OVLoadProperties.java(读取properties文件的内容)
  1. package com.anxin.util;  
  2. import java.io.FileInputStream;  
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.util.Properties;  
  6. //单例模式实现读取zxc.properties文件的内容  
  7. public class OVLoadProperties {  
  8.     // 声明一个自己的实例  
  9.     private static OVLoadProperties instance = new OVLoadProperties();  
  10.     final static String fileName = "/config.properties";  
  11.     // 返回该实例  
  12.     public static synchronized OVLoadProperties getInstance() {  
  13.         return instance;  
  14.     }  
  15.     // 获取key所对应的值  
  16.     public String getProperties(String key) {  
  17.         Properties p = new Properties();  
  18.         InputStream is = null;  
  19.         try {  
  20.             // zxc.properties文件放在src目录的下边  
  21.             is = OVLoadProperties.class.getResourceAsStream(fileName);  
  22.             if (is == null)  
  23.                 is = new FileInputStream(fileName);  
  24.             p.load(is);  
  25.         } catch (Exception e) {  
  26.             System.out.println("加载文件出错啦!" + e.getMessage());  
  27.         } finally {  
  28.             if (is != null) {  
  29.                 try {  
  30.                     is.close();  
  31.                 } catch (IOException e) {  
  32.                     // TODO Auto-generated catch block  
  33.                     System.out.println(e.getMessage());  
  34.                 }  
  35.             }  
  36.         }  
  37.         return p.getProperty(key);  
  38.     }  
  39. }  
 
confic.properties
  1. pageSize=5  
 
log4j.properties
  1. log4j.debug=true  
  2. log4j.rootLogger=DEBUG,A1  
  3. log4j.appender.A1=org.apache.log4j.ConsoleAppender  
  4. log4j.appender.A1.Threshold=info  
  5. log4j.appender.A1.layout=org.apache.log4j.PatternLayout  
  6. log4j.appender.A1.layout.ConversionPattern=%-4r %-5p [%t] %37c %3x - %m%n  
 
6、过滤器和拦截器
LoginFilter.java(jsp页面过滤器)
  1. package com.anxin.filter;  
  2. import java.io.IOException;  
  3. import javax.servlet.Filter;  
  4. import javax.servlet.FilterChain;  
  5. import javax.servlet.FilterConfig;  
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.ServletRequest;  
  8. import javax.servlet.ServletResponse;  
  9. import javax.servlet.http.HttpServletRequest;  
  10. import javax.servlet.http.HttpServletResponse;  
  11. import javax.servlet.http.HttpSession;  
  12. import com.anxin.bean.User;  
  13. public class LoginFilter implements Filter{  
  14.     public void destroy(){  
  15.     }  
  16.     public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException,ServletException{  
  17.         HttpSession session=((HttpServletRequest)request).getSession();  
  18.         ((HttpServletResponse)response).setHeader("Pragma","No-cache");            
  19.         ((HttpServletResponse)response).setHeader("Cache-Control","no-cache");     
  20.         ((HttpServletResponse)response).setHeader("Cache-Control""no-store");     
  21.         ((HttpServletResponse)response).setDateHeader("Expires",0);  
  22.         User user=(User)session.getAttribute("user");  
  23.         String url=(((HttpServletRequest)request).getRequestURI());  
  24.         if(url.endsWith("/login.jsp")||url.endsWith("/BaseProject/")){  
  25.             chain.doFilter(request, response);  
  26.         }else{  
  27.             if(session.getAttribute("user")==null){  
  28.                 ((HttpServletResponse)response).sendRedirect(((HttpServletRequest)request).getContextPath()+"/login.jsp");  
  29.             }else{  
  30.                 chain.doFilter(request, response);  
  31.             }  
  32.         }  
  33.     }  
  34.     public void init(FilterConfig filterConfig)throws ServletException{  
  35.           
  36.     }  
  37. }  
 
LoginedCheckInterceptor(action拦截器)
  1. package com.anxin.struts.interceptor;  
  2. import javax.servlet.http.HttpServletResponse;  
  3. import org.apache.struts2.ServletActionContext;  
  4. import com.anxin.bean.User;  
  5. import com.opensymphony.xwork2.ActionInvocation;  
  6. import com.opensymphony.xwork2.interceptor.AbstractInterceptor;  
  7. /** session过期、登录有效性及操作的权限验证拦截器 */  
  8. public class LoginedCheckInterceptor extends AbstractInterceptor {  
  9.     /** 拦截请求并进行登录有效性验证 */  
  10.     public String intercept(ActionInvocation ai) throws Exception {  
  11.         //取得请求的URL  
  12.         String url = ServletActionContext.getRequest().getRequestURL().toString();  
  13.         HttpServletResponse response=ServletActionContext.getResponse();  
  14.         response.setHeader("Pragma","No-cache");            
  15.         response.setHeader("Cache-Control","no-cache");     
  16.         response.setHeader("Cache-Control""no-store");     
  17.         response.setDateHeader("Expires",0);  
  18.         User user = null;  
  19.         //对登录与注销请求直接放行,不予拦截  
  20.         if (url.indexOf("user_login.action")!=-1 || url.indexOf("logout.action")!=-1){  
  21.             return ai.invoke();  
  22.         }  
  23.         else{  
  24.             //验证Session是否过期  
  25.             if(!ServletActionContext.getRequest().isRequestedSessionIdValid()){  
  26.                 //session过期,转向session过期提示页,最终跳转至登录页面  
  27.                 return "tologin";  
  28.             }  
  29.             else{  
  30.                 user = (User)ServletActionContext.getRequest().getSession().getAttribute("user");  
  31.                 //验证是否已经登录  
  32.                 if (user==null){  
  33.                     //尚未登录,跳转至登录页面  
  34.                     return "tologin";  
  35.                 }else{                    
  36.                     return ai.invoke();  
  37.                                   
  38.                 }                 
  39.             }             
  40.         }  
  41.     }  
  42. }  
 
7、S2SH整合核心配置文件
struts.properties
  1. struts.i18n.encoding = gbk  
  2. struts.custom.i18n.resources=messageResource  
  3. struts.locale=zh_CN  
  4. struts.objectFactory=spring  
  5. struts.devMode=true  
  6. struts.ui.theme=simple  
  7. struts.ui.templateDir=template  
  8. struts.ui.templateSuffix=ftl  
 
struts.xml
  1. <?xml version="1.0" encoding="gbk"?>  
  2. <!DOCTYPE struts PUBLIC  
  3.         "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
  4.         "http://struts.apache.org/dtds/struts-2.0.dtd"><struts>  
  5.     <package name="anxin" extends="struts-default">  
  6.         <!-- 配置自定义拦截器LoginedCheckInterceptor -->  
  7.         <interceptors>  
  8.             <interceptor name="loginedCheck" class="com.anxin.struts.interceptor.LoginedCheckInterceptor"/>  
  9.             <interceptor-stack name="mystack">  
  10.                 <interceptor-ref name="loginedCheck" />  
  11.                 <interceptor-ref name="defaultStack" />  
  12.             </interceptor-stack>  
  13.         </interceptors>         
  14.       
  15.         <!-- 定义全局result -->  
  16.         <global-results>  
  17.             <!-- 定义名为exception的全局result -->  
  18.             <result name="exception">exception.jsp</result>  
  19.             <result name="tologin">login.jsp</result>  
  20.         </global-results>  
  21.         <!-- 定义全局异常映射 -->  
  22.         <global-exception-mappings>  
  23.             <!-- 捕捉到Exception异常(所有异常)时跳转到exception所命名的视图上 -->  
  24.             <exception-mapping exception="java.lang.Exception" result="exception"/>  
  25.         </global-exception-mappings>    
  26.         <action name="user_*" class="userAction" method="{1}">  
  27.             <result name="input">login.jsp</result>  
  28.             <result name="success" type="redirect">student_query.action</result>  
  29.             <interceptor-ref name="mystack" />  
  30.         </action>  
  31.         <action name="student_*" class="studentAction" method="{1}">  
  32.             <result name="add">jsp/studentAdd.jsp</result>  
  33.             <result name="update">jsp/studentEdit.jsp</result>  
  34.             <result name="query">jsp/studentList.jsp</result>  
  35.             <result name="success" type="redirect">student_query.action</result>  
  36.             <interceptor-ref name="mystack" />  
  37.         </action>  
  38.     </package>      
  39. </struts>  
 
applicationContext.xml
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans  
  3.     xmlns="http://www.springframework.org/schema/beans"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">  
  6.     <!-- 定义使用C3P0连接池的数据源 -->  
  7.     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">  
  8.         <!-- 指定连接数据库的JDBC驱动 -->  
  9.         <property name="driverClass">  
  10.             <value>com.mysql.jdbc.Driver</value>  
  11.          </property>  
  12.         <!-- 连接数据库所用的URL -->  
  13.         <property name="jdbcUrl">  
  14.             <value>jdbc:mysql://localhost:3306/practice?useUnicode=true&characterEncoding=gbk</value>  
  15.         </property>  
  16.         <!-- 连接数据库的用户名 -->  
  17.         <property name="user">  
  18.             <value>root</value>  
  19.         </property>  
  20.         <!-- 连接数据库的密码 -->  
  21.         <property name="password">  
  22.             <value>123</value>  
  23.         </property>  
  24.         <!-- 设置数据库连接池的最大连接数 -->  
  25.         <property name="maxPoolSize">  
  26.             <value>20</value>  
  27.         </property>  
  28.         <!-- 设置数据库连接池的最小连接数 -->  
  29.         <property name="minPoolSize">  
  30.             <value>2</value>  
  31.         </property>  
  32.         <!-- 设置数据库连接池的初始化连接数 -->  
  33.         <property name="initialPoolSize">  
  34.             <value>2</value>  
  35.         </property>  
  36.         <!-- 设置数据库连接池的连接的最大空闲时间,单位为秒 -->  
  37.         <property name="maxIdleTime">  
  38.             <value>20</value>  
  39.         </property>  
  40.     </bean>  
  41.     <!-- 定义Hibernate的SessionFactory -->  
  42.     <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
  43.         <!-- 依赖注入上面定义的数据源dataSource -->  
  44.         <property name="dataSource" ref="dataSource"/>  
  45.         <!-- 注册Hibernate的ORM映射文件 -->  
  46.         <property name="mappingResources">  
  47.             <list>  
  48.                 <value>com/anxin/orm/mapping/User.hbm.xml</value>  
  49.                  <value>com/anxin/orm/mapping/Student.hbm.xml</value>                
  50.             </list>  
  51.         </property>  
  52.         <!-- 设置Hibernate的相关属性 -->  
  53.         <property name="hibernateProperties">  
  54.             <props>  
  55.                 <!-- 设置Hibernate的数据库方言 -->  
  56.                 <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>  
  57.                 <!-- 设置Hibernate是否在控制台输出SQL语句,开发调试阶段通常设为true -->  
  58.                 <prop key="show_sql">true</prop>  
  59.                 <!-- 设置Hibernate一个提交批次中的最大SQL语句数 -->  
  60.                 <prop key="hibernate.jdbc.batch_size">50</prop>  
  61.             </props>  
  62.         </property>  
  63.     </bean>  
  64.     <!--定义Hibernate的事务管理器HibernateTransactionManager -->  
  65.     <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">  
  66.         <!-- 依赖注入上面定义的sessionFactory -->  
  67.         <property name="sessionFactory" ref="sessionFactory"/>  
  68.     </bean>  
  69.     <!--定义Spring的事务拦截器TransactionInterceptor -->  
  70.     <bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">  
  71.         <!--  依赖注入上面定义的事务管理器transactionManager -->  
  72.         <property name="transactionManager" ref="transactionManager"/>  
  73.         <!-- 定义需要进行事务拦截的方法及所采用的事务控制类型 -->       
  74.         <property name="transactionAttributes">             
  75.             <props>  
  76.                 <!-- 以browse、list、load、getis开头的所有方法采用只读型事务控制类型 -->  
  77.                 <prop key="browse*">PROPAGATION_REQUIRED,readOnly</prop>  
  78.                 <prop key="list*">PROPAGATION_REQUIRED,readOnly</prop>  
  79.                 <prop key="load*">PROPAGATION_REQUIRED,readOnly</prop>  
  80.                 <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>  
  81.                 <prop key="is*">PROPAGATION_REQUIRED,readOnly</prop>  
  82.                 <!-- 所有方法均进行事务控制,如果当前没有事务,则新建一个事务 -->  
  83.                 <prop key="*">PROPAGATION_REQUIRED</prop>  
  84.             </props>  
  85.         </property>  
  86.     </bean>  
  87.       
  88.     <!-- 定义BeanNameAutoProxyCreatorf进行Spring的事务处理-->  
  89.     <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">  
  90.         <!--  针对指定的bean自动生成业务代理 -->  
  91.         <property name="beanNames">   
  92.             <list>  
  93.                 <value>userService</value>  
  94.                  <value>studentService</value>  
  95.             </list>  
  96.         </property>  
  97.         <!--  这个属性为true时,表示被代理的是目标类本身而不是目标类的接口 -->  
  98.         <property name="proxyTargetClass">  
  99.             <value>true</value>  
  100.         </property>  
  101.        <!--  依赖注入上面定义的事务拦截器transactionInterceptor -->  
  102.         <property name="interceptorNames">  
  103.             <list>  
  104.                 <value>transactionInterceptor</value>   
  105.             </list>  
  106.         </property>  
  107.     </bean>     
  108.       
  109.     <!-- ************************************service和dao配置开始**************************** -->        
  110.     <!-- 装配通用数据库访问类BaseDAOImpl -->      
  111.     <bean id="userdao" class="com.anxin.dao.impl.UserDAOImpl">  
  112.         <property name="sessionFactory" ref="sessionFactory"/>  
  113.     </bean>  
  114.     <bean id="studentdao" class="com.anxin.dao.impl.StudentDAOImpl">  
  115.         <property name="sessionFactory" ref="sessionFactory"/>  
  116.     </bean>  
  117.     <bean id="userService" class="com.anxin.service.impl.UserServiceImpl">  
  118.         <property name="dao" ref="userdao"/>  
  119.     </bean>  
  120.     <bean id="studentService" class="com.anxin.service.impl.StudentServiceImpl">  
  121.         <property name="dao" ref="studentdao"/>  
  122.     </bean>  
  123.     <!-- ************************************service和dao配置结束**************************** -->  
  124.       
  125.     <!-- ************************************Action配置开始**************************** -->     
  126.     <!-- 部署Struts2负责系统用户管理的控制器AdminAction -->   
  127.     <bean id="userAction" class="com.anxin.struts.action.UserAction" scope="prototype">  
  128.         <property name="service" ref="userService"/>  
  129.     </bean>  
  130.     <bean id="studentAction" class="com.anxin.struts.action.StudentAction" scope="prototype">  
  131.         <property name="service" ref="studentService"/>  
  132.     </bean>         
  133.     <!-- ************************************Action配置结束**************************** -->                                     
  134. </beans>  
 
web.xml
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  5.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  6.     <!-- 指定Spring的配置文件 -->  
  7.     <context-param>  
  8.         <param-name>contextConfigLocation</param-name>  
  9.         <param-value>/WEB-INF/classes/applicationContext.xml</param-value>  
  10.     </context-param>  
  11.     <!-- 指定以Listener方式启动Spring容器 -->  
  12.     <listener>  
  13.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  14.     </listener>  
  15.     <!-- 定义Struts2的核心控制器FilterDispathcer -->  
  16.     <filter>  
  17.         <filter-name>struts2</filter-name>  
  18.         <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>  
  19.     </filter>  
  20.     <!-- 定义编码过滤器 -->  
  21.     <filter>  
  22.         <filter-name>encodingFilter</filter-name>  
  23.         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  24.         <init-param>  
  25.             <param-name>encoding</param-name>  
  26.             <param-value>gbk</param-value>  
  27.         </init-param>  
  28.     </filter>  
  29.     <filter>  
  30.         <filter-name>hibernateFilter</filter-name>  
  31.         <filter-class>com.anxin.util.OpenSessionInViewFilter</filter-class>  
  32.     </filter>  
  33.     <filter-mapping>  
  34.         <filter-name>hibernateFilter</filter-name>  
  35.         <url-pattern>*.action</url-pattern>  
  36.     </filter-mapping>  
  37.     <filter-mapping>  
  38.         <filter-name>struts2</filter-name>  
  39.         <url-pattern>/*</url-pattern>  
  40.     </filter-mapping>  
  41.     <filter-mapping>  
  42.         <filter-name>encodingFilter</filter-name>  
  43.         <url-pattern>*.action</url-pattern>  
  44.     </filter-mapping>  
  45.     <filter-mapping>  
  46.         <filter-name>encodingFilter</filter-name>  
  47.         <url-pattern>*.jsp</url-pattern>  
  48.     </filter-mapping>  
  49.     <filter>  
  50.         <filter-name>struts-cleanup</filter-name>  
  51.         <filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class>  
  52.     </filter>  
  53.     <filter-mapping>  
  54.         <filter-name>struts-cleanup</filter-name>  
  55.         <url-pattern>/*</url-pattern>  
  56.     </filter-mapping>  
  57.         <filter>  
  58.         <!-- 定义核心Filter的名字 -->  
  59.         <filter-name>LoginFilter</filter-name>  
  60.         <!-- 定义核心Filter的实现类 -->  
  61.         <filter-class>  
  62.             com.anxin.filter.LoginFilter  
  63.         </filter-class>  
  64.     </filter>  
  65.     <filter-mapping>  
  66.         <filter-name>LoginFilter</filter-name>  
  67.         <url-pattern>*.jsp</url-pattern>  
  68.     </filter-mapping>  
  69.     <servlet>  
  70.         <servlet-name>dwr</servlet-name>  
  71.         <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>  
  72.         <!--此处指定项目处于开发之中,故可通过http://localhost:8000/dwrdemo1/dwr/,而不会出现403 -->  
  73.         <init-param>  
  74.             <param-name>debug</param-name>  
  75.             <param-value>true</param-value>  
  76.         </init-param>  
  77.         <init-param>  
  78.             <param-name>crossDomainSessionSecurity</param-name>  
  79.             <param-value>false</param-value>  
  80.         </init-param>  
  81.     </servlet>  
  82.     <servlet-mapping>  
  83.         <servlet-name>dwr</servlet-name>  
  84.         <url-pattern>/dwr/*</url-pattern>  
  85.     </servlet-mapping>  
  86.     <welcome-file-list>  
  87.         <welcome-file>login.jsp</welcome-file>  
  88.     </welcome-file-list>  
  89.     <!-- 配置404与500错误处理 -->  
  90.     <error-page>  
  91.         <error-code>404</error-code>  
  92.         <location>/404.htm</location>  
  93.     </error-page>  
  94.     <error-page>  
  95.         <error-code>500</error-code>  
  96.         <location>/500.htm</location>  
  97.     </error-page>  
  98. </web-app>  
 
dwr.xml
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 1.0//EN" "http://www.getahead.ltd.uk/dwr/dwr10.dtd">  
  3. <dwr>  
  4.     <!-- without allow, DWR isn't allowed to do anything -->  
  5.     <allow>  
  6.         <!-- <create creator="new" javascript="CountyDWR"> -->  
  7.         <!-- <param name="class">com.anxin.utils.CountyDWR</param> -->  
  8.         <!-- </create> -->  
  9.         <!-- <convert match="com.anxin.utils.DWRCity" converter="bean"> -->  
  10.         <!-- <param name="include" value="cityid,cityname"/> -->  
  11.         <!-- </convert> -->  
  12.         <create javascript="studentService" creator="spring">  
  13.             <param name="beanName" value="studentService"/>  
  14.         </create>  
  15.     </allow>  
  16. </dwr>  
 
三、运行效果
页面没怎么修饰,比较土哈
(1)登陆页面
(2)学生信息列表页面
(3)学生信息添加页面
(4)学生信息修改页面


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值