注:图片在最后
01 OA的概念
OA:办公自动化
在企业中,有些特别复杂的流程,这些流程有三个作用:
<1>对流程进行控制
<2>在走流程的过程中会产生一些数据,把这些数据整理出来,做查询、分析、统计。
* BI 智能分析 * 数据挖掘
产生这两个领域的原因
* 大量数据
<3>协同工作 完成一项工作需要好几个部门进行参与,这几个部门的数据之间是相互共享的,来完成一个任务。
02 书写每个模块的流程
1、需求分析
2、根据持久化类和映射文件建表
3、写dao和service
4、测试dao和service
5、写action
6、写配置文件
7、写页面
8、运行
03 表的设计
设计表的时候一定不能设计成饼状图或者网状图,而应该找到一个核心,形成星形关系表。
04 持久化类与映射文件
cn.itheima.oa.domain.User.java
public class User implements Serializable {
private Long uid ;
private String username ;
private String password ;
private String sex ;
private String phone ;
private String email ;
private Department department ;
private Set posts ;
public Long getUid() {
return uid ;
}
public void setUid(Long uid) {
this.uid = uid;
}
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 String getSex() {
return sex ;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getPhone() {
return phone ;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email ;
}
public void setEmail(String email) {
this.email = email;
}
public Department getDepartment() {
return department ;
}
public void setDepartment(Department department) {
this.department = department;
}
public Set<Post> getPosts() {
return posts ;
}
public void setPosts(Set<Post> posts) {
this.posts = posts;
}
}
cn.itheima.oa.domain.Department.java
public class Department implements Serializable {
private Long did ;
private String dname ;
private String description ;
private Set users ;
public Set<User> getUsers() {
return users ;
}
public void setUsers(Set<User> users) {
this.users = users;
}
public Long getDid() {
return did ;
}
public void setDid(Long did) {
this.did = did;
}
public String getDname() {
return dname ;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getDescription() {
return description ;
}
public void setDescription(String description) {
this.description = description;
}
}
cn.itheima.oa.domain.Post.java
public class Post implements Serializable {
private Long pid ;
private String pname ;
private String description ;
private Set users ;
public Set<User> getUsers() {
return users ;
}
public void setUsers(Set<User> users) {
this.users = users;
}
public Long getPid() {
return pid ;
}
public void setPid(Long pid) {
this.pid = pid;
}
public String getPname() {
return pname ;
}
public void setPname(String pname) {
this.pname = pname;
}
public String getDescription() {
return description ;
}
public void setDescription(String description) {
this.description = description;
}
}
cn.itheima.oa.domain.User.hbm.xml
<?xml version ="1.0" encoding="UTF-8" ?> <many-to-one name="department" class="cn.itheima.oa.domain.Department" column="did" ></many-to-one>
<set name ="posts" table="user_post" >
<key>
<column name ="uid" ></column>
</key>
<many-to-many class ="Post" column="pid" ></many-to-many>
</set>
</class>
Version2:
<?xml version ="1.0" encoding="UTF-8" ?> <many-to-one name="department" class="Department" column="did" ></many-to-one>
<set name ="posts" table="user_post" >
<key>
<column name ="uid" ></column>
</key>
<many-to-many class ="Post" column="pid" ></many-to-many>
</set>
</class>
cn.itheima.oa.domain.Post.hbm.xml
<?xml version ="1.0" encoding="UTF-8" ?>cn.itheima.oa.domain.Department.hbm.xml
<?xml version ="1.0" encoding="UTF-8" ?>hibernate.cfg.xml
<?xml version ="1.0" encoding="UTF-8" ?> org.hibernate.dialect.MySQLDialect <property name ="hibernate.connection.driver_class" >com.mysql.jdbc.Driver</property>
<property name ="hibernate.connection.username" >root</ property>
<property name ="hibernate.connection.password" >sorry</ property>
<property name ="hibernate.connection.url" >jdbc:mysql://localhost:3306/oa</property>
<property name ="hbm2ddl.auto" >update</ property>
<mapping resource ="cn/itheima/oa/domain/Department.hbm.xml" />
<mapping resource ="cn/itheima/oa/domain/Post.hbm.xml" />
<mapping resource ="cn/itheima/oa/domain/User.hbm.xml" />
执行结果:
05 DepartmentDao与DepartmentService
cn.itheima.oa.dao.DepartmentDao.java
public interface DepartmentDao {
public Collection getAllDepartments() throws Exception;
public void saveDepartment(Department department) throws Exception;
//这里之所以用Serializable,是想要让这个参数能够传入任何类型的数值
public void deleteDepartment(Serializable departmentId) throws Exception;
public void updateDepartment(Department department) throws Exception;
public Department getDepartmentById(Serializable departmentId) throws Exception;
}
cn.itheima.oa.dao.impl.DepartmentDaoImpl.java
public class DepartmentDaoImpl extends HibernateDaoSupport implements DepartmentDao {
public void saveDepartment (Department department) throws Exception {
this.getHibernateTemplate().save(department);
}
public void deleteDepartment(Serializable departmentId) throws Exception {
Department department = this.getDepartmentById(departmentId);
this.getHibernateTemplate().delete(department);
}
public Collection<Department> getAllDepartments() throws Exception {
return this .getHibernateTemplate().find("from Department");
}
public Department getDepartmentById(Serializable departmentId) throws Exception {
return (Department) this.getHibernateTemplate().get(Department.class, departmentId);
}
public void updateDepartment(Department department) throws Exception {
this.getHibernateTemplate().update(department);
}
}
cn.itheima.oa.service.DepartmentService.java
public interface DepartmentService {
public Collection getAllDepartments() throws Exception;
public void saveDepartment(Department department) throws Exception;
public void deleteDepartment(Serializable departmentId) throws Exception;
public void updateDepartment(Department department) throws Exception;
public Department getDepartmentById(Serializable departmentId) throws Exception;
}
cn.itheima.oa.service.impl.DepartmentServiceImpl.java
public class DepartmentServiceImpl implements DepartmentService {
private DepartmentDao departmentDao ;
public DepartmentDao getDepartmentDao() {
return departmentDao ;
}
public void setDepartmentDao(DepartmentDao departmentDao) {
this.departmentDao = departmentDao;
}
public void deleteDepartment(Serializable departmentId) throws Exception {
departmentDao.deleteDepartment(departmentId);
}
public Collection<Department> getAllDepartments() throws Exception {
return departmentDao .getAllDepartments();
}
public Department getDepartmentById(Serializable departmentId)
throws Exception {
return departmentDao .getDepartmentById(departmentId);
}
public void saveDepartment(Department department) throws Exception {
departmentDao.saveDepartment(department);
}
public void updateDepartment(Department department) throws Exception {
departmentDao.updateDepartment(department);
}
}
applicationContext-db.xml
<?xml version ="1.0" encoding="UTF-8" ?> <bean name ="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" >
<property name ="configLocation" >
<value> classpath:hibernate/hibernate.cfg.xml</ value >
</property>
</bean>
<bean id ="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" >
<property name ="sessionFactory" >
<ref bean ="sessionFactory" />
</property>
</bean>
<tx:advice transaction-manager ="transactionManager" id= "tx">
<tx:attributes>
<tx:method name ="save*" read-only="false" />
<tx:method name ="update*" read-only="false" />
<tx:method name ="delete*" read-only="false" />
<!-- 表示出了上面情况以外所有的情况 -->
<tx:method name ="*" read-only="true" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut expression ="execution(* cn.itheima.oa.service..*(..))" id ="perform" />
<aop:advisor advice-ref ="tx" pointcut-ref="perform" />
</aop:config>
applicationContext-department.xml
<?xml version ="1.0" encoding="UTF-8" ?> <bean id ="departmentDao" class="cn.itheima.oa.dao.impl.DepartmentDaoImpl" >
<property name ="sessionFactory" >
<ref bean ="sessionFactory" />
</property>
</bean>
<bean id ="departmentService" class="cn.itheima.oa.service.impl.DepartmentServiceImpl" >
<property name ="departmentDao" >
<ref bean ="departmentDao" />
</property>
</bean>
applicationContext.xml
<?xml version ="1.0" encoding="UTF-8" ?> <import resource ="applicationContext-db.xml" />
<import resource ="applicationContext-department.xml" />
cn.itheima.oa.test.DepartmentTest.java
public class DepartmentTest extends BaseSpring {
DepartmentService departmentService = (DepartmentService)context .getBean(“departmentService”);
@Test
public void testDepartmentService(){
System. out.println(departmentService );
}
@Test
public void testSaveDepartment() throws Exception {
Department department = new Department();
department.setDname( "软件研发部" );
department.setDescription( "程序员");
departmentService.saveDepartment(department);
}
@Test
public void testDeleteDepartment() throws Exception {
departmentService.deleteDepartment(1L);
}
@Test
public void testGetAllDepartments () throws Exception{
Collection<Department> departments = departmentService.getAllDepartments();
System. out.println(departments.size());
}
@Test
public void testUpdateDepartment() throws Exception{
Department department = departmentService.getDepartmentById(1L);
department.setDescription( "很多程序员" );
departmentService.updateDepartment(department);
}
}
06 DepartmentAction
cn.itheima.oa.action.BaseAction.java
public class BaseAction extends ActionSupport {
public static final String LISTACTION = “listAction”;
public static final String ADD_UI = “addUI”;
public static final String UPDATE_UI = “updateUI”;
public static final String ACTION2ACTION = “action2action”;
public static String listAction = LISTACTION;
public static String add_ui = ADD_UI;
public static String update_ui = UPDATE_UI;
public static String action2action = ACTION2ACTION;
}
cn.itheima.oa.action.DepartmentAction.java
public class DepartmentAction extends BaseAction {
private DepartmentService departmentService ;
public DepartmentService getDepartmentService() {
return departmentService ;
}
public void setDepartmentService(DepartmentService departmentService) {
this.departmentService = departmentService;
}
public String showDepartments() throws Exception {
Collection<Department> departments = departmentService.getAllDepartments();
ActionContext. getContext().put("dList", departments);
return listAction ;
}
}
struts/struts-department.xml
<?xml version ="1.0" encoding="UTF-8" ?> /WEB-INF/jsp/department/list.jspstruts.xml
<?xml version ="1.0" encoding="UTF-8" ?>applicationContext-department.xml
<?xml version ="1.0" encoding="UTF-8" ?> <bean id ="departmentDao" class="cn.itheima.oa.dao.impl.DepartmentDaoImpl" >
<property name ="sessionFactory" >
<ref bean ="sessionFactory" />
</property>
</bean>
<bean id ="departmentService" class="cn.itheima.oa.service.impl.DepartmentServiceImpl" >
<property name ="departmentDao" >
<ref bean ="departmentDao" />
</property>
</bean>
<bean id ="departmentAction" class="cn.itheima.oa.action.DepartmentAction" scope="prototype" >
<property name ="departmentService" >
<ref bean ="departmentService" />
</property>
</bean>
07 Jsp文件
<1>新建一个JSP文件,并且只保留<%@ page language= “java” import=“java.util." pageEncoding=“UTF-8” %>,将其他代码全部删除掉。然后将静态页面拷贝进来,这样就可以防止乱码问题。
<2>将css和js文件拷贝到webroot下。
<3>由于此时文件中会有很多的重复性代码,这时候可以新建一个common.jsp,将所有的重复代码放在这个jsp,然后使其他的jsp页面通过<%@ include file= “/WEB-INF/jsp/common/common.jsp” %>将common.jsp包含进本jsp中,提高代码的复用性。
<4>将jsp文件中所有的相对路径替换成相对于本应用的路径,也就是将类似“…/”替换成“${pageContext.request.contextPath}”。
<5>修改显示数据的静态文本为动态的(<s:property value="”/>)。
WEB-INF/jsp/common/common.jsp
<%@ taglib uri =“/struts-tags” prefix=“s” %>
WEB-INF/jsp/department/list.jsp
<%@ page language =“java” import=“java.util.*” pageEncoding=“UTF-8” %>
<%@ include file =“/WEB-INF/jsp/common/common.jsp” %>

<!-- 表头-->
<thead>
<tr align =center valign=middle id= TableTitle>
<td width ="150px" >部门名称</ td>
<td width ="200px" >职能说明</ td>
<td> 相关操作</td >
</tr>
</thead>
<!--显示数据列表-->
<tbody id ="TableData" class="dataContainer" datakey="departmentList" >
<!-- 用标签将静态文本替换成动态的 -->
<s:iterator value ="#dList" >
<tr class ="TableDetail1 template" >
<td>< s:property value="dname"/> </td >
<td>< s:property value="description" /> </ td>
<td>< a onClick="return window.confirm('这将删除所有的下级部门,您确定要删除吗?')" href="#" >删除</ a>
<a href ="saveUI.html" >修改</ a>
</td>
</tr>
</s:iterator>
</tbody>
</table >
<!-- 其他功能超链接 -->
<div id= "TableTail">
<div id ="TableTail_inside" >
<a href ="saveUI.html" ><img src=" ${pageContext.request.contextPath}/css/images/createNew.png" /></ a>
</div>
</div >
1,列表页面只显示一层的(同级的)部门数据,默认显示最顶级的部门列表。
2,点击部门名称,可以查看此部门相应的下级部门列表。
3,删除部门时,同时删除此部门的所有下级部门。
执行结果:
08 JS文件
/WEB-INF/jsp/common/common.jsp
<%@ taglib uri =“/struts-tags” prefix =“s” %>
< script language =“javascript” src =" ${pageContext.request.contextPath} /js/jquery-1.4.2.js" ></ script>
< link type =“text/css” rel =“stylesheet” href ="
p
a
g
e
C
o
n
t
e
x
t
.
r
e
q
u
e
s
t
.
c
o
n
t
e
x
t
P
a
t
h
/
c
s
s
/
b
l
u
e
/
p
a
g
e
C
o
m
m
o
n
.
c
s
s
"
/
>
<
s
c
r
i
p
t
l
a
n
g
u
a
g
e
=
"
j
a
v
a
s
c
r
i
p
t
"
s
r
c
=
"
{pageContext.request.contextPath} /css/blue/pageCommon.css" /> < script language= "javascript" src ="
pageContext.request.contextPath/css/blue/pageCommon.css"/><scriptlanguage="javascript"src="{pageContext.request.contextPath} /js/jquery-confirm-plugin.js ">
js/jquery-confirm-plugin.js
(function($){
$.oaconfirm = function(){
$(“a”).each(function(){
var text = $(this).text()
if(text==“删除”){
$(this).unbind(“click”);
KaTeX parse error: Expected 'EOF', got '}' at position 132: … }̲ }); …);
js/department.js
$().ready(function(){
$.oaconfirm();
});
09 删除操作
/WEB-INF/jsp/department/list.jsp
<%@ page language =“java” import=“java.util.*” pageEncoding=“UTF-8” %>
<%@ include file =“/WEB-INF/jsp/common/common.jsp” %>

<!-- 表头-->
<thead>
<tr align =center valign=middle id= TableTitle>
<td width ="150px" >部门名称</ td>
<td width ="200px" >职能说明</ td>
<td> 相关操作</td >
</tr>
</thead>
<!--显示数据列表-->
<tbody id ="TableData" class="dataContainer" datakey="departmentList" >>
<s:iterator value ="#dList" >
<tr class ="TableDetail1 template" >
<td>< s:property value="dname"/> </td >
<td>< s:property value="description" /> </ td>
<td>
<s:a action ="departmentAction_delete?did=%{did}" >删除</ s:a>
<a href ="saveUI.html" >修改</ a>
</td>
</tr>
</s:iterator>
</tbody>
</table >
<!-- 其他功能超链接 -->
<div id= "TableTail">
<div id ="TableTail_inside" >
<a href ="saveUI.html" ><img src=" ${pageContext.request.contextPath}/css/images/createNew.png" /></ a>
</div>
</div >
1,列表页面只显示一层的(同级的)部门数据,默认显示最顶级的部门列表。
2,点击部门名称,可以查看此部门相应的下级部门列表。
3,删除部门时,同时删除此部门的所有下级部门。
cn.itheima.oa.action.DepartmentAction.java
public class DepartmentAction extends BaseAction implements ModelDriven{
private Department department = new Department();
public Department getModel() {
return department ;
}
private DepartmentService departmentService ;
public DepartmentService getDepartmentService() {
return departmentService ;
}
public void setDepartmentService(DepartmentService departmentService) {
this.departmentService = departmentService;
}
public String showDepartments() throws Exception {
Collection<Department> departments = departmentService.getAllDepartments();
ActionContext. getContext().put("dList", departments);
return listAction ;
}
public String delete() throws Exception {
Department department2 = departmentService.getDepartmentById(this.getModel().getDid());
departmentService.deleteDepartment(department2.getDid());
return action2action ;
}
}
struts/struts-department.xml
<?xml version ="1.0" encoding="UTF-8" ?> /WEB-INF/jsp/department/list.jsp departmentAction_showDepartments.action10 添加操作
1、/WEB-INF/jsp/department/list.jsp
<%@ page language =“java” import=“java.util.*” pageEncoding=“UTF-8” %>
<%@ include file =“/WEB-INF/jsp/common/common.jsp” %>

<!-- 表头-->
<thead>
<tr align =center valign=middle id= TableTitle>
<td width ="150px" >部门名称</ td>
<td width ="200px" >职能说明</ td>
<td> 相关操作</td >
</tr>
</thead>
<!--显示数据列表-->
<tbody id ="TableData" class="dataContainer" datakey="departmentList" >
<!-- 用标签将静态文本替换成动态的 -->
<s:iterator value ="#dList" >
<tr class ="TableDetail1 template" >
<td>< s:property value="dname"/> </td >
<td>< s:property value="description" /> </ td>
<td>
<s:a action="departmentAction_delete?did=%{did}" >删除</ s:a>
<a href ="saveUI.html" >修改</ a>
</td>
</tr>
</s:iterator>
</tbody>
</table >
<!-- 其他功能超链接 -->
<div id= "TableTail">
<div id ="TableTail_inside" >
<a href ="departmentAction_addUI.action" ><img src=" ${pageContext.request.contextPath}/css/images/createNew.png" /></ a>
</div>
</div >
1,列表页面只显示一层的(同级的)部门数据,默认显示最顶级的部门列表。
2,点击部门名称,可以查看此部门相应的下级部门列表。
3,删除部门时,同时删除此部门的所有下级部门。
2、/WEB-INF/jsp/department/addUI.jsp
<%@ page language =“java” import=“java.util.*” pageEncoding=“UTF-8” %>
<%@ include file =“/WEB-INF/jsp/common/common.jsp” %>

<!-- 表单内容显示 -->
<div class ="ItemBlockBorder" >
<div class ="ItemBlock" >
<table cellpadding ="0" cellspacing="0" class="mainForm" >
<tr>< td>部门名称 </td>
<!-- 通过设置value=""来确保不用回显 -->
<td>< s:textfield name="dname" value ="" cssClass="InputStyle" /></td>
</tr>
<tr>< td>职能说明 </td>
<td>< s:textarea name="description" value ="" cssClass="TextareaStyle" /></td>
</tr>
</table>
</div>
</div>
<!-- 表单操作 -->
<div id ="InputDetailBar" >
<input type ="image" src=" ${pageContext.request.contextPath}/css/images/save.png" />
<a href ="javascript:history.go(-1);" ><img src=" ${pageContext.request.contextPath}/css/images/goBack.png" /></a>
</div>
</s:form >
1,上级部门的列表是有层次结构的(树形)。
2,如果是修改:上级部门列表中不能显示当前修改的部门及其子孙部门。因为不能选择自已或自已的子部门作为上级部门。
3、cn.itheima.oa.action.DepartmentAction.java
public class DepartmentAction extends BaseAction implements ModelDriven{
private Department department = new Department();
public Department getModel() {
return department ;
}
private DepartmentService departmentService ;
public DepartmentService getDepartmentService() {
return departmentService ;
}
public void setDepartmentService(DepartmentService departmentService) {
this.departmentService = departmentService;
}
public String showDepartments() throws Exception {
Collection<Department> departments = departmentService.getAllDepartments();
ActionContext. getContext().put("dList", departments);
return listAction ;
}
public String delete() throws Exception {
Department department2 = departmentService.getDepartmentById(this.getModel().getDid());
departmentService.deleteDepartment(department2.getDid());
return action2action ;
}
public String addUI() throws Exception {
return add_ui ;
}
public String add() throws Exception {
Department department = new Department();
BeanUtils. copyProperties(this.getModel(), department);
departmentService.saveDepartment(department);
return action2action ;
}
}
4、struts-department.xml
<?xml version ="1.0" encoding="UTF-8" ?> /WEB-INF/jsp/department/list.jsp departmentAction_showDepartments.action /WEB-INF/jsp/department/addUI.jsp departmentAction_add.action 11 更新操作 1、/WEB-INF/jsp/department/updateUI.jsp <%@ page language ="java" import="java.util.*" pageEncoding="UTF-8" %> <%@ include file ="/WEB-INF/jsp/common/common.jsp" %>
<!-- 表单内容显示 -->
<div class ="ItemBlockBorder" >
<div class ="ItemBlock" >
<table cellpadding ="0" cellspacing="0" class="mainForm" >
<tr>< td>部门名称 </td>
<!-- 通过设置value=""来确保不用回显 -->
<td>< s:textfield name="dname" cssClass="InputStyle" /></td>
</tr>
<tr>< td>职能说明 </td>
<td>< s:textarea name="description" cssClass="TextareaStyle" /></td>
</tr>
</table>
</div>
</div>
<!-- 表单操作 -->
<div id ="InputDetailBar" >
<input type ="image" src=" ${pageContext.request.contextPath}/css/images/save.png" />
<a href ="javascript:history.go(-1);" ><img src=" ${pageContext.request.contextPath}/css/images/goBack.png" /></a>
</div>
</s:form >
1,上级部门的列表是有层次结构的(树形)。
2,如果是修改:上级部门列表中不能显示当前修改的部门及其子孙部门。因为不能选择自已或自已的子部门作为上级部门。
2、/WEB-INF/jsp/department/list.jsp
<%@ page language =“java” import=“java.util.*” pageEncoding=“UTF-8” %>
<%@ include file =“/WEB-INF/jsp/common/common.jsp” %>

<!-- 表头-->
<thead>
<tr align =center valign=middle id= TableTitle>
<td width ="150px" >部门名称</ td>
<td width ="200px" >职能说明</ td>
<td> 相关操作</td >
</tr>
</thead>
<!--显示数据列表-->
<tbody id ="TableData" class="dataContainer" datakey="departmentList" >
<!-- 用标签将静态文本替换成动态的 -->
<s:iterator value ="#dList" >
<tr class ="TableDetail1 template" >
<td>< s:property value="dname"/> </td >
<td>< s:property value="description" /> </ td>
<td>
<s:a action="departmentAction_delete?did=%{did}" >删除</ s:a>
<s:a action="departmentAction_updateUI?did=%{did}" >修改</ s:a>
</td>
</tr>
</s:iterator>
</tbody>
</table >
<!-- 其他功能超链接 -->
<div id= "TableTail">
<div id ="TableTail_inside" >
<a href ="departmentAction_addUI.action" ><img src=" ${pageContext.request.contextPath}/css/images/createNew.png" /></ a>
</div>
</div >
1,列表页面只显示一层的(同级的)部门数据,默认显示最顶级的部门列表。
2,点击部门名称,可以查看此部门相应的下级部门列表。
3,删除部门时,同时删除此部门的所有下级部门。
3、cn.itheima.oa.action.DepartmentAction.java
public class DepartmentAction extends BaseAction implements ModelDriven{
private Department department = new Department();
public Department getModel() {
return department ;
}
private DepartmentService departmentService ;
public DepartmentService getDepartmentService() {
return departmentService ;
}
public void setDepartmentService(DepartmentService departmentService) {
this.departmentService = departmentService;
}
public String showDepartments() throws Exception {
Collection<Department> departments = departmentService.getAllDepartments();
ActionContext. getContext().put("dList", departments);
return listAction ;
}
public String delete() throws Exception {
Department department2 = departmentService.getDepartmentById(this.getModel().getDid());
departmentService.deleteDepartment(department2.getDid());
return action2action ;
}
public String addUI() throws Exception {
return add_ui ;
}
public String add() throws Exception {
Department department = new Department();
BeanUtils. copyProperties(this.getModel(), department);
departmentService.saveDepartment(department);
ActionContext. getContext().put("department", department);
return action2action ;
}
public String updateUI() throws Exception {
Department department = departmentService.getDepartmentById(this.getModel().getDid());
ActionContext. getContext().getValueStack().push(department);
return update_ui ;
}
public String update() throws Exception {
Department department = new Department();
BeanUtils. copyProperties(this.getModel(), department);
departmentService.updateDepartment(department);
return action2action ;
}
}
4、struts-department.xml
<?xml version ="1.0" encoding="UTF-8" ?> /WEB-INF/jsp/department/list.jsp departmentAction_showDepartments.action /WEB-INF/jsp/department/addUI.jsp departmentAction_add.action /WEB-INF/jsp/department/updateUI.jsp12 将Dao层用泛型实现
1、泛型的扩展知识
<1>泛型是Java中的一种类型。
<2>泛型是ParameterizedType
* 泛型的组成
Class(类或接口)<T,E,F>
Class 类或者接口
T,E,F 类或者接口的参数
<3>参数的传递方式
* 在创建对象的时候把参数传递进去。
* public interface A
public class B implements A
public class D extends B
<4>得到泛型的方式
clazz.getGenericSuperclass();
注:如果clazz的类型不是泛型,那么返回将是其父类的class。
2、cn.itheima.oa.dao.BaseDao.java
public interface BaseDao {
public Collection getAllEntities() throws Exception;
public void saveEntity(T t) throws Exception;
public void deleteEntity(Serializable id) throws Exception;
public void updateEntity(T t) throws Exception;
public T getEntityById(Serializable id) throws Exception;
}
cn.itheima.oa.dao.impl.BaseDaoImpl.java
public class BaseDaoImpl extends HibernateDaoSupport implements BaseDao {
private Class classt ;
public BaseDaoImpl(){
ParameterizedType clazz = (ParameterizedType)this .getClass().getGenericSuperclass();
classt = (Class)clazz.getActualTypeArguments()[0];
System. out.println( classt.getName());
System. out.println(clazz.getRawType());
}
public Collection<T> getAllEntities() throws Exception {
return this .getHibernateTemplate().find("from " + classt.getName());
}
public void saveEntity(T t) throws Exception {
this.getHibernateTemplate().save(t);
}
public void deleteEntity(Serializable id) throws Exception {
T t = (T) this.getEntityById(id);
this.getHibernateTemplate().delete(t);
}
public void updateEntity(T t) throws Exception {
this.getHibernateTemplate().update(t);
}
public T getEntityById(Serializable id) throws Exception {
return (T)this.getHibernateTemplate().get( classt, id);
}
}
cn.itheima.oa.dao.impl.PostDaoImpl.java
public class PostDaoImpl extends BaseDaoImpl {
}
spring/application-post.xml
<?xml version ="1.0" encoding="UTF-8" ?> <bean id ="postDao" class="cn.itheima.oa.dao.impl.PostDaoImpl" >
<property name ="sessionFactory" >
<ref bean ="sessionFactory" />
</property>
</bean>
/spring/applicationContext.xml
<?xml version ="1.0" encoding="UTF-8" ?> <import resource ="applicationContext-db.xml" />
<import resource ="applicationContext-department.xml" />
<import resource ="applicationContext-post.xml" />
cn.itheima.oa.test.PostTest.java
public class PostTest extends BaseSpring {
@Test
public void test(){
PostDaoImpl postDao = (PostDaoImpl)context .getBean(“postDao”);
}
}
执行结果:
第二种配置方式:
spring/applicationContext-post.xml
<!-- 这里一定要设置abstract='true',否则spring容器已启动就会创建baseDaoImpl对象,而这时候泛型没有确定类型,所以会报错 -->
<bean id ="baseDao" class="cn.itheima.oa.dao.impl.BaseDaoImpl" abstract="true" >
<property name ="sessionFactory" >
<ref bean ="sessionFactory" />
</property>
</bean>
<!-- 这里一定要写上parent,否则无法继承baseDao的property -->
<bean id ="postDao" class="cn.itheima.oa.dao.impl.PostDaoImpl" parent="baseDao" >
</bean>
13 利用BaseDao实现Post的Dao
cn.itheima.oa.dao.PostDao.java
public interface PostDao extends BaseDao{
}
cn.itheima.oa.dao.impl.PostDaoImpl.java
public class PostDaoImpl extends BaseDaoImpl< Post> implements PostDao {
}
cn.itheima.oa.service.PostService.java
public interface PostService {
public Collection getAllPosts() throws Exception;
public void savePost(Post post) throws Exception;
public void deletePost(Serializable pid) throws Exception;
public void updatePost(Post post) throws Exception;
public Post getPostById(Serializable pid) throws Exception;
}
cn.itheima.oa.service.impl.PostServiceImpl.java
public class PostServiceImpl implements PostService {
private PostDao postDao ;
public PostDao getPostDao() {
return postDao ;
}
public void setPostDao(PostDao postDao) {
this.postDao = postDao;
}
public void deletePost(Serializable pid) throws Exception {
this.postDao .deleteEntity(pid);
}
public Collection<Post> getAllPosts() throws Exception {
return postDao .getAllEntities();
}
public Post getPostById(Serializable pid)
throws Exception {
return (Post) postDao .getEntityById(pid);
}
public void savePost(Post post) throws Exception {
postDao.saveEntity(post);
}
public void updatePost(Post post) throws Exception {
postDao.updateEntity(post);
}
}
/spring/applicationContext-post.xml
<?xml version ="1.0" encoding="UTF-8" ?> <bean id ="baseDao" class="cn.itheima.oa.dao.impl.BaseDaoImpl" abstract="true" >
<property name ="sessionFactory" >
<ref bean ="sessionFactory" />
</property>
</bean>
<bean id ="postDao" class="cn.itheima.oa.dao.impl.PostDaoImpl" parent="baseDao" >
</bean>
<bean id ="postService" class="cn.itheima.oa.service.impl.PostServiceImpl" >
<property name ="postDao" >
<ref bean ="postDao" />
</property>
</bean>
cn.itheima.oa.test.PostTest.java
public class PostTest extends BaseSpring {
@Test
public void test(){
PostService postService = (PostService)context .getBean(“postService”);
System. out.println(postService);
}
}
执行结果:
注:之所以有了BaseDao之后还去写其他的Dao的原因是因为这些另建的Dao接口可以添加一些BaseDao没有的方法。
14 利用BaseDao实现Department的Dao
cn.itheima.oa.action.BaseAction.java
public class BaseAction extends ActionSupport implements ModelDriven {
private Class classt ;
private T t ;
public BaseAction() {
ParameterizedType clazz = (ParameterizedType)this .getClass().getGenericSuperclass();
classt = (Class)clazz.getActualTypeArguments()[0];
try {
t = (T) classt.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
public T getModel() {
return t ;
}
public static final String LISTACTION = "listAction";
public static final String ADD_UI = "addUI";
public static final String UPDATE_UI = "updateUI";
public static final String ACTION2ACTION = "action2action";
public static String listAction = LISTACTION;
public static String add_ui = ADD_UI;
public static String update_ui = UPDATE_UI;
public static String action2action = ACTION2ACTION;
}
cn.itheima.oa.dao.DepartmentDao.java
public interface DepartmentDao extends BaseDao{
}
cn.itheima.oa.dao.impl.DepartmentDaoImpl.java
public class DepartmentDaoImpl extends BaseDaoImpl implements DepartmentDao {
}
cn.itheima.oa.service.impl.DepartmentServiceImpl.java
public class DepartmentServiceImpl implements DepartmentService {
private DepartmentDao departmentDao ;
public DepartmentDao getDepartmentDao() {
return departmentDao ;
}
public void setDepartmentDao(DepartmentDao departmentDao) {
this.departmentDao = departmentDao;
}
public void deleteDepartment(Serializable departmentId) throws Exception {
departmentDao.deleteEntity(departmentId);
}
public Collection<Department> getAllDepartments() throws Exception {
return departmentDao .getAllEntities();
}
public Department getDepartmentById(Serializable departmentId )
throws Exception {
return (Department) departmentDao.getEntityById(departmentId);
}
public void saveDepartment(Department department) throws Exception {
departmentDao.saveEntity(department);
}
public void updateDepartment(Department department) throws Exception {
departmentDao.updateEntity(department);
}
}
cn.itheima.oa.action.DepartmentAction.java
public class DepartmentAction extends BaseAction {
private DepartmentService departmentService ;
public DepartmentService getDepartmentService() {
return departmentService ;
}
public void setDepartmentService(DepartmentService departmentService) {
this.departmentService = departmentService;
}
public String showDepartments() throws Exception {
Collection<Department> departments = departmentService.getAllDepartments();
ActionContext. getContext().put("dList", departments);
return listAction ;
}
public String delete() throws Exception {
Department department2 = departmentService.getDepartmentById(this.getModel().getDid());
departmentService.deleteDepartment(department2.getDid());
return action2action ;
}
public String addUI() throws Exception {
return add_ui ;
}
public String add() throws Exception {
Department department = new Department();
BeanUtils. copyProperties(this.getModel(), department);
departmentService.saveDepartment(department);
return action2action ;
}
public String updateUI() throws Exception {
Department department = departmentService.getDepartmentById(this.getModel().getDid());
ActionContext. getContext().getValueStack().push(department);
return update_ui ;
}
public String update() throws Exception {
Department department = new Department();
BeanUtils. copyProperties(this.getModel(), department);
departmentService.updateDepartment(department);
return action2action ;
}
}
执行结果:
15 将已经实现的业务改为用注解的方式实现
cn.itheima.oa.dao.impl.BaseDaoImpl.java
public class BaseDaoImpl implements BaseDao {
//这里的属性虽然自己并不能注入,但是子类可以注入
@Resource(name="hibernateTemplate" )
private HibernateTemplate hibernateTemplate ;
private Class classt ;
public BaseDaoImpl(){
ParameterizedType clazz = (ParameterizedType)this .getClass().getGenericSuperclass();
classt = (Class)clazz.getActualTypeArguments()[0];
}
public Collection<T> getAllEntities() throws Exception {
return this .hibernateTemplate .find("from " + classt.getName());
}
public void saveEntity(T t) throws Exception {
this.hibernateTemplate .save(t);
}
public void deleteEntity(Serializable id) throws Exception {
T t = (T )this .getEntityById(id);
this.hibernateTemplate .delete(t);
}
public void updateEntity(T t) throws Exception {
this.hibernateTemplate .update(t);
}
public T getEntityById(Serializable id) throws Exception {
return (T) this.hibernateTemplate .get(classt, id);
}
}
cn.itheima.oa.dao.impl.DepartmentDaoImpl.java
@Repository(“departmentDao” )
public class DepartmentDaoImpl extends BaseDaoImpl implements DepartmentDao {
}
cn.itheima.oa.service.impl.DepartmentServiceImpl.java
@Service(“departmentService” )
public class DepartmentServiceImpl implements DepartmentService {
@Resource(name="departmentDao" )
private DepartmentDao departmentDao ;
public DepartmentDao getDepartmentDao() {
return departmentDao ;
}
public void setDepartmentDao(DepartmentDao departmentDao) {
this.departmentDao = departmentDao;
}
@Transactional(readOnly=false)
public void deleteDepartment(Serializable departmentId) throws Exception {
departmentDao.deleteEntity(departmentId);
}
public Collection<Department> getAllDepartments() throws Exception {
return departmentDao .getAllEntities();
}
public Department getDepartmentById(Serializable departmentId)
throws Exception {
return (Department) departmentDao.getEntityById(departmentId);
}
@Transactional(readOnly=false)
public void saveDepartment(Department department) throws Exception {
departmentDao.saveEntity(department);
}
@Transactional(readOnly=false)
public void updateDepartment(Department department) throws Exception {
departmentDao.updateEntity(department);
}
}
cn.itheima.oa.action.DepartmentAction.java
@Controller(“departmentAction” )
@Scope(“prototype” )
public class DepartmentAction extends BaseAction {
@Resource(name="departmentService" )
private DepartmentService departmentService ;
public DepartmentService getDepartmentService() {
return departmentService ;
}
public void setDepartmentService(DepartmentService departmentService) {
this.departmentService = departmentService;
}
public String showDepartments() throws Exception {
Collection<Department> departments = departmentService.getAllDepartments();
ActionContext. getContext().put("dList", departments);
return listAction ;
}
public String delete() throws Exception {
Department department2 = departmentService.getDepartmentById(this.getModel().getDid());
departmentService.deleteDepartment(department2.getDid());
return action2action ;
}
public String addUI() throws Exception {
return add_ui;
}
public String add() throws Exception {
Department department = new Department();
BeanUtils. copyProperties(this.getModel(), department);
departmentService.saveDepartment(department);
ActionContext. getContext().put("department", department);
return action2action ;
}
public String updateUI() throws Exception {
Department department = departmentService.getDepartmentById(this.getModel().getDid());
ActionContext. getContext().getValueStack().push(department);
return update_ui ;
}
public String update() throws Exception {
Department department = new Department();
BeanUtils. copyProperties(this.getModel(), department);
departmentService.updateDepartment(department);
ActionContext. getContext().put("department", department);
return action2action ;
}
}
16 通过注解的方式完成Post所有的业务逻辑
cn.itheima.oa.dao.impl.BaseDaoImpl.java
public class BaseDaoImpl implements BaseDao {
@Resource(name="hibernateTemplate" )
public HibernateTemplate hibernateTemplate ;
private Class classt ;
public BaseDaoImpl(){
ParameterizedType clazz = (ParameterizedType)this .getClass().getGenericSuperclass();
classt = (Class)clazz.getActualTypeArguments()[0];
}
public Collection<T> getAllEntities() throws Exception {
return this .hibernateTemplate .find("from " + classt.getName());
}
public void saveEntity(T t) throws Exception {
this.hibernateTemplate .save(t);
}
public void deleteEntity(Serializable id) throws Exception {
T t = (T) this.getEntityById(id);
this.hibernateTemplate .delete(t);
}
public void updateEntity(T t) throws Exception {
this.hibernateTemplate .update(t);
}
public T getEntityById(Serializable id) throws Exception {
return (T)this .hibernateTemplate .get(classt, id);
}
}
cn.itheima.oa.dao.PostDao.java
public interface PostDao extends BaseDao{
public Set getUsersByPid(Serializable pid);
}
cn.itheima.oa.dao.impl.PostDaoImpl.java
@Repository(“postDao” )
public class PostDaoImpl extends BaseDaoImpl implements PostDao {
//之所以会有这个方法是因为从页面上得到的Post不包含User,这样的话,如果直接调用PostServiceImpl,就会将关系表中所有的关系解除。
public void updateEntity(Post post) throws Exception {
Long pid = post.getPid();
List list = this.hibernateTemplate .find("from Post p left outer join fetch p.users u where p.pid=" + pid);
Post post2 = (Post)list.get(0);
post.setUser(post2.getUsers());
super.updateEntity(post);
}
public Set<User> getUsersByPid(Serializable pid) {
List userList = this.hibernateTemplate .find("from User u inner join fetch u.posts p where p.pid=" + pid);
return new HashSet(userList);
}
}
cn.itheima.oa.dao.PostService.java
public interface PostService {
public Collection getAllPosts() throws Exception;
public void savePost(Post post) throws Exception;
public void deletePost(Serializable pid) throws Exception;
public void updatePost(Post post) throws Exception;
public Post getPostById(Serializable pid) throws Exception;
public Set<User> getUsersByPid(Serializable pid);
}
cn.itheima.oa.dao.impl.PostServiceImpl.java
@Service(“postService” )
public class PostServiceImpl implements PostService {
@Resource(name="postDao" )
private PostDao postDao ;
@Transactional(readOnly=false)
public void deletePost(Serializable pid) throws Exception {
this.postDao .deleteEntity(pid);
}
public Collection<Post> getAllPosts() throws Exception {
return postDao .getAllEntities();
}
public Post getPostById(Serializable pid)
throws Exception {
return (Post) postDao .getEntityById (pid);
}
@Transactional(readOnly=false)
public void savePost(Post post) throws Exception {
postDao.saveEntity(post);
}
@Transactional(readOnly=false)
public void updatePost(Post post) throws Exception {
postDao.updateEntity (post);
}
public Set<User> getUsersByPid(Serializable pid) {
return postDao .getUsersByPid(pid);
}
}
cn.itheima.oa.dao.action.PostAction.java
@Controller(“postAction” )
@Scope(“prototype” )
public class PostAction extends BaseAction {
@Resource(name="postService" )
private PostService postService ;
public PostService getPostService() {
return postService ;
}
public void setPostService(PostService postService) {
this.postService = postService;
}
public String showPosts() throws Exception {
Collection<Post> posts = postService.getAllPosts();
ActionContext. getContext().put("pList", posts);
return listAction ;
}
public String delete() throws Exception {
Set<User> users = postService .getUsersByPid(this.getModel().getPid());
if(users == null||users.size() == 0){
postService.deletePost(this.getModel().getPid());
} else{
ActionContext. getContext().put("url", "postAction_showPosts.action" );
throw new RuntimeException("此岗位下还有员工,不能删除!" );
}
return action2action ;
}
public String addUI() throws Exception {
return add_ui ;
}
public String add() throws Exception {
Post post = new Post();
BeanUtils. copyProperties(this.getModel(), post);
postService.savePost(post);
return action2action ;
}
public String updateUI() throws Exception {
Post post = postService .getPostById(this.getModel().getPid());
ActionContext. getContext().getValueStack().push(post);
return update_ui ;
}
public String update() throws Exception {
Post post = new Post();
BeanUtils. copyProperties(this.getModel(), post);
postService.updatePost(post);
return action2action ;
}
}
spring/applicationContext.xml
<?xml version ="1.0" encoding="UTF-8" ?> <import resource ="applicationContext-db.xml" />
struts/struts.xml
<?xml version ="1.0" encoding="UTF-8" ?> <package name ="struts-global" namespace="/" extends="struts-default" >
<global-exception-mappings>
<exception-mapping result ="errHandler" exception="java.lang.Exception" >
</exception-mapping>
</global-exception-mappings>
<global-results>
<result name ="errHandler" type="chain" >
<param name ="actionName" >errorProcessor</ param>
</result>
</global-results>
<action name ="errorProcessor" class="cn.itheima.oa.error.ErrorProcessor" >
<result name ="error" >error.jsp</ result>
</action>
</package>
struts/struts-post.xml
<?xml version ="1.0" encoding="UTF-8" ?> /WEB-INF/jsp/post/list.jsp postAction_showPosts.action /WEB-INF/jsp/post/addUI.jsp postAction_add.action /WEB-INF/jsp/post/updateUI.jspWEB-INF/js/post.post.js
$().ready(function(){
$.oaconfirm();
});
WEB-INF/jsp/post/list.jsp
<%@ page language =“java” import=“java.util.*” pageEncoding=“UTF-8” %>
<%@ include file =“/WEB-INF/jsp/common/common.jsp” %>

<!-- 表头-->
<thead>
<tr align ="CENTER" valign="MIDDLE" id= "TableTitle">
<td width ="200px" >岗位名称</ td>
<td width ="300px" >岗位说明</ td>
<td> 相关操作</td >
</tr>
</thead>
<!--显示数据列表-->
<tbody id ="TableData" class="dataContainer" datakey="roleList" >
<s:iterator value ="#pList" >
<tr class ="TableDetail1 template" >
<td>< s:property value="pname"/></ td>
<td>< s:property value="description"/></ td>
<td>< s:a action="postAction_delete?pid=%{pid}" >删除</ s:a>
<s:a action="postAction_updateUI?pid=%{pid}" >修改</ s:a>
</td>
</tr>
</s:iterator>
</tbody>
</table >
<!-- 其他功能超链接 -->
<div id= "TableTail">
<div id ="TableTail_inside" >
<a href ="postAction_addUI.action" ><img src=" ${pageContext.request.contextPath}/css/images/createNew.png" /></ a>
</div>
</div >
WEB-INF/jsp/post/addUI.jsp
<%@ page language =“java” import=“java.util.*” pageEncoding=“UTF-8” %>
<%@ include file =“/WEB-INF/jsp/common/common.jsp” %>

<!-- 表单内容显示 -->
<div class ="ItemBlockBorder" >
<div class ="ItemBlock" >
<table cellpadding ="0" cellspacing="0" class="mainForm" >
<tr>
<td width ="100" >岗位名称</ td>
<td>< s:textfield name="pname" value ="" cssClass="InputStyle" /></td>
</tr>
<tr>
<td> 岗位说明</td >
<td>< s:textarea name="description" value ="" cssClass="description" /></td>
</tr>
</table>
</div>
</div>
<!-- 表单操作 -->
<div id ="InputDetailBar" >
<input type ="image" src=" ${pageContext.request.contextPath}/css/images/save.png" />
<a href ="javascript:history.go(-1);" ><img src=" ${pageContext.request.contextPath}/css/images/goBack.png" /></a>
</div>
</s:form >
WEB-INF/jsp/post/updateUI.jsp
<%@ page language =“java” import=“java.util.*” pageEncoding=“UTF-8” %>
<%@ include file =“/WEB-INF/jsp/common/common.jsp” %>

<!-- 表单内容显示 -->
<div class ="ItemBlockBorder" >
<div class ="ItemBlock" >
<table cellpadding ="0" cellspacing="0" class="mainForm" >
<tr>
<td width ="100" >岗位名称</ td>
<td>< s:textfield name="pname" cssClass="InputStyle" /></td>
</tr>
<tr>
<td> 岗位说明</td >
<td>< s:textarea name="description" cssClass="description" /></td>
</tr>
</table>
</div>
</div>
<!-- 表单操作 -->
<div id ="InputDetailBar" >
<input type ="image" src=" ${pageContext.request.contextPath}/css/images/save.png" />
<a href ="javascript:history.go(-1);" ><img src=" ${pageContext.request.contextPath}/css/images/goBack.png" /></a>
</div>
</s:form >
/error.jsp
<%@ page language =“java” import=“java.util.*” pageEncoding=“UTF-8” %>
<%@ include file =“/WEB-INF/jsp/common/common.jsp” %>
cn.itheima.oa.error.ErrorProcessor.java
public class ErrorProcessor extends ActionSupport {
private Exception exception ;
public Exception getException() {
return exception ;
}
public void setException(Exception exception) {
this.exception = exception;
}
public String execute(){
ActionContext. getContext().getValueStack().push(exception.getMessage());
return ERROR;
}
}
17 完成用户的显示
用户的查询
- 页面上的数据来自于后台两张表及以上
- 在页面上迭代数据的数据结构和hibernate的持久化类的结构是一样的,但是要找到核心表
要注意的问题:
User中的Department department和Set posts的懒加载问题。
解决方法是采用OpenSessionInView的方式或者左外连接或者内连接的方式(这时候懒加载无效)
cn.itheima.oa.dao.UserDao.java
public interface UserDao extends BaseDao{
//使用Set的好处在于能够将使用hql查询出来的重复数据去除
public Set getUsers();
}
cn.itheima.oa.dao.impl.UserDaoImpl.java
@Repository(“userDao” )
public class UserDaoImpl extends BaseDaoImpl implements UserDao {
public Set<User> getUsers() {
return new HashSet(this. hibernateTemplate.find("from User u left outer join fetch u.department d left outer join fetch u.posts p"));
}
}
cn.itheima.oa.service.UserService.java
public interface UserService {
public Set getAllUsers() throws Exception;
}
cn.itheima.oa.service.impl.UserServiceImpl.java
@Service(“userService” )
public class UserServiceImpl implements UserService {
@Resource(name="userDao" )
private UserDao userDao ;
public UserDao getUserDao() {
return userDao ;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public Set<User> getAllUsers() throws Exception {
return new HashSet(userDao.getUsers());
}
}
cn.itheima.oa.action.UserAction.java
@Controller(“userAction” )
@Scope(“prototype” )
public class UserAction extends BaseAction {
@Resource(name="userService" )
private UserService userService ;
public UserService getUserService() {
return userService ;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
public String showUsers() throws Exception {
Collection<User> users = userService.getAllUsers();
ActionContext. getContext().put("uList", users);
return listAction ;
}
}
/struts/struts-user.xml
<?xml version ="1.0" encoding="UTF-8" ?> /WEB-INF/jsp/user/list.jsp userAction_showPosts.action /WEB-INF/jsp/user/addUI.jsp userAction_add.action /WEB-INF/jsp/user/updateUI.jsplist.jsp
<%@ page language =“java” import=“java.util.*” pageEncoding=“UTF-8” %>
<%@ include file =“/WEB-INF/jsp/common/common.jsp” %>

<!-- 表头-->
<thead>
<tr align =center valign=middle id= TableTitle>
<td width ="100" >姓名</ td>
<td width ="100" >所属部门</ td>
<td> 备注</td >
<td> 相关操作</td >
</tr>
</thead>
<!--显示数据列表-->
<tbody id ="TableData" class="dataContainer" datakey="userList" >
<s:iterator value ="#uList" >
<tr class ="TableDetail1 template" >
<td>< s:property value="username"/></ td>
<td>< s:property value="department.dname"/></ td>
<td>
<s:iterator value ="posts" >
<s:property value ="pname" />
</s:iterator>
</td>
<td>
<a onClick ="return delConfirm()" href="list.html" >删除</ a>
<a href ="saveUI.html" >修改</ a>
<a href="javascript:privilegeclick();" >设置权限</ a>
</td>
</tr>
</s:iterator>
</tbody>
</table >
<div id= "TableTail">
<div id ="TableTail_inside" >
<a href ="saveUI.html" ><img src=" ${pageContext.request.contextPath}/css/images/createNew.png" /></ a>
</div>
</div >
<div class="ItemBlock_Title1" id= "userTitle" style="display: none;"><!-- 信息说明 --><div class="ItemBlock_Title1" >
<img border ="0" width="4" height="7" src=" ${pageContext.request.contextPath}/css/blue/images/item_point.gif" />用户:王欣然
<div id ="userImage" ></div>
</div>
<div class="ItemBlock_Title1" id= "privilegeTitle" style="display: none;"><div class ="ItemBlock_Title1" >
<img border ="0" width="4" height="7" src=" ${pageContext.request.contextPath}/css/blue/images/item_point.gif" />选择权限</ div>
</div>
<!-- 表单内容显示 -->
<div class ="ItemBlockBorder" style="display: none;" id="privilegeContent" >
<div class ="ItemBlock" >
<table cellpadding ="0" cellspacing="0" class="mainForm" >
<!--表头-->
<thead>
<tr align ="LEFT" valign="MIDDLE" id="TableTitle" >
<td width ="300px" style="padding-left: 7px;" >
<!-- 如果把全选元素的id指定为selectAll,并且有函数selectAll(),就会有错。因为有一种用法:可以直接用id引用元素 -->
<input type ="checkbox" id="allchecked" onchange="privilegeCheckedAll(this.checked,this.id)" />
<label for="cbSelectAll" >全选</ label>
</td>
</tr>
</thead>
<!--显示数据列表-->
<tbody id ="TableData" >
<tr class ="TableDetail1" >
<!-- 显示权限树 -->
<td>
<ul id ='privilegeTree' class="tree" >
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- 表单操作 -->
<div id ="InputDetailBar" >
<image onclick ="savePrivilege()" src=" ${pageContext.request.contextPath}/css/images/save.png" />
</div>
个人评论:真正的模型驱动必须通过getMode方式返回给Struts内部压入栈顶,如果自己写了很多vo,则需要自己手动压入栈顶,使其属性曝光。
也可以在jsp中通过类似department.dname作为标签name属性值,赋值给vo的属性。
cn.itheima.oa.dao.UserDao.java
public interface UserDao extends BaseDao{
public Set getUsers();
}
cn.itheima.oa.dao.impl.UserDaoImpl.java
@Repository(“userDao” )
public class UserDaoImpl extends BaseDaoImpl implements UserDao {
public Set<User> getUsers() {
return new HashSet(this. hibernateTemplate.find("from User u left outer join fetch u.department d left outer join fetch u.posts p"));
}
}
cn.itheima.oa.service.UserService.java
public interface UserService {
public Set getAllUsers() throws Exception;
public void saveUser(User user) throws Exception;
public void deleteUser(Serializable uid) throws Exception;
public void updateUser(User user) throws Exception;
public User getUserById(Serializable uid) throws Exception;
}
cn.tiehima.oa.service.impl.UserServiceImpl.java
@Service(“userService” )
public class UserServiceImpl implements UserService {
@Resource(name="userDao" )
private UserDao userDao ;
public UserDao getUserDao() {
return userDao ;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Transactional(readOnly=false)
public void deleteUser(Serializable uid) throws Exception {
this.userDao .deleteEntity(uid);
}
public Set<User> getAllUsers() throws Exception {
return new HashSet( userDao.getAllEntities());
}
public User getUserById(Serializable uid)
throws Exception {
return (User) userDao .getEntityById(uid);
}
@Transactional(readOnly=false)
public void saveUser(User user) throws Exception {
this.userDao .saveEntity(user);
}
@Transactional(readOnly=false)
public void updateUser(User user) throws Exception {
userDao.updateEntity(user);
}
}
cn.itheima.oa.action.BaseAction.java
public class BaseAction extends ActionSupport implements ModelDriven {
private Class classt ;
private T t ;
public BaseAction() {
ParameterizedType clazz = (ParameterizedType)this .getClass().getGenericSuperclass();
classt = (Class)clazz.getActualTypeArguments()[0];
try {
t = (T) classt.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
public T getModel() {
return t ;
}
public static final String LISTACTION = "listAction";
public static final String ADD_UI = "addUI";
public static final String UPDATE_UI = "updateUI";
public static final String ACTION2ACTION = "action2action";
public static String listAction = LISTACTION;
public static String add_ui = ADD_UI;
public static String update_ui = UPDATE_UI;
public static String action2action = ACTION2ACTION;
@Resource(name="userService" )
public UserService userService ;
@Resource(name="postService" )
public PostService postService ;
@Resource(name="departmentService" )
public DepartmentService departmentService ;
}
cn.itheima.oa.action.UserAction.java
@Controller(“userAction” )
@Scope(“prototype” )
public class UserAction extends BaseAction {
private Long did ;
//action中可以创建基本类型的数组形式的属性,模型驱动也可以进行转化
private Long[] pids ;
public Long getDid() {
return did ;
}
public void setDid(Long did) {
this.did = did;
}
public Long[] getPids() {
return pids ;
}
public void setPids(Long[] pids) {
this.pids = pids;
}
public String showUsers() throws Exception {
Collection<User> users = userService.getAllUsers();
ActionContext. getContext().put("uList", users);
return listAction ;
}
public String delete() throws Exception {
return action2action ;
}
public String addUI() throws Exception {
Collection<Department> dList = this.departmentService .getAllDepartments();
Collection<Post> pList = this.postService .getAllPosts();
ActionContext. getContext().put("dList", dList);
ActionContext. getContext().put("pList", pList);
return add_ui ;
}
public String add() throws Exception {
/**
* 因为用户和部门之间是多对一的关系,用户负责维护关系,所以在保存用户后,会自动建立用户和部门之间的关系。
* 因为用户和岗位之间是多对多的关系,谁维护关系都行,所以在保存用户的时候,会自动建立用户和岗位之间的关系。
*/
Department department = this.departmentService .getDepartmentById (this .did );
Set<Post> posts = this.postService .getPostsByIds(pids);
User user = new User();
BeanUtils. copyProperties(this.getModel(), user);
user.setDepartment(department);
user.setPosts(posts);
this.userService .saveUser (user);
return action2action;
}
public String updateUI() throws Exception {
User user = userService.getUserById(this.getModel().getUid());
ActionContext. getContext().getValueStack().push(user);
return update_ui ;
}
public String update() throws Exception {
User user = new User();
BeanUtils. copyProperties(this.getModel(), user);
userService.updateUser(user);
return action2action ;
}
}
/struts/struts-user.xml
<?xml version ="1.0" encoding="UTF-8" ?> /WEB-INF/jsp/user/list.jsp userAction_showUsers.action /WEB-INF/jsp/user/addUI.jsp userAction_add.action /WEB-INF/jsp/user/updateUI.jsp/struts/struts.xml
<?xml version ="1.0" encoding="UTF-8" ?> <package name ="struts-global" namespace="/" extends="struts-default" >
<global-results>
<result name ="errHandler" type="chain" >
<param name ="actionName" >errorProcessor</ param>
</result>
</global-results>
<global-exception-mappings>
<exception-mapping result ="errHandler" exception="java.lang.Exception" >
</exception-mapping>
</global-exception-mappings>
<action name ="errorProcessor" class="cn.itheima.oa.error.ErrorProcessor" >
<result name ="error" >error.jsp</ result>
</action>
</package>
/WEB-INF/jsp/user/list.jsp
<%@ page language =“java” import=“java.util.*” pageEncoding=“UTF-8” %>
<%@ include file =“/WEB-INF/jsp/common/common.jsp” %>

<!-- 表头-->
<thead>
<tr align =center valign=middle id= TableTitle>
<td width ="100" >姓名</ td>
<td width ="100" >所属部门</ td>
<td> 备注</td >
<td> 相关操作</td >
</tr>
</thead>
<!--显示数据列表-->
<tbody id ="TableData" class="dataContainer" datakey="userList" >
<s:iterator value ="#uList" >
<tr class ="TableDetail1 template" >
<td>< s:property value="username"/></ td>
<td>< s:property value="department.dname"/></ td>
<td>
<s:iterator value ="posts" >
<s:property value ="pname" />
</s:iterator>
</td>
<td>
<a onClick ="return delConfirm()" href="list.html" >删除</ a>
<a href ="saveUI.html" >修改</ a>
<a href="javascript:privilegeclick();" >设置权限</ a>
</td>
</tr>
</s:iterator>
</tbody>
</table >
<div id= "TableTail">
<div id ="TableTail_inside" >
<a href ="userAction_addUI.action" ><img src=" ${pageContext.request.contextPath}/css/images/createNew.png" /></ a>
</div>
</div >
<div class="ItemBlock_Title1" id= "userTitle" style="display: none;"><!-- 信息说明 --><div class="ItemBlock_Title1" >
<img border ="0" width="4" height="7" src=" ${pageContext.request.contextPath}/css/blue/images/item_point.gif" />用户:王欣然
<div id ="userImage" ></div>
</div>
<div class="ItemBlock_Title1" id= "privilegeTitle" style="display: none;"><div class ="ItemBlock_Title1" >
<img border ="0" width="4" height="7" src=" ${pageContext.request.contextPath}/css/blue/images/item_point.gif" />选择权限</ div>
</div>
<!-- 表单内容显示 -->
<div class ="ItemBlockBorder" style="display: none;" id="privilegeContent" >
<div class ="ItemBlock" >
<table cellpadding ="0" cellspacing="0" class="mainForm" >
<!--表头-->
<thead>
<tr align ="LEFT" valign="MIDDLE" id="TableTitle" >
<td width ="300px" style="padding-left: 7px;" >
<!-- 如果把全选元素的id指定为selectAll,并且有函数selectAll(),就会有错。因为有一种用法:可以直接用id引用元素 -->
<input type ="checkbox" id="allchecked" onchange="privilegeCheckedAll(this.checked,this.id)" />
<label for="cbSelectAll" >全选</ label>
</td>
</tr>
</thead>
<!--显示数据列表-->
<tbody id ="TableData" >
<tr class ="TableDetail1" >
<!-- 显示权限树 -->
<td>
<ul id ='privilegeTree' class="tree" >
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- 表单操作 -->
<div id ="InputDetailBar" >
<image onclick ="savePrivilege()" src=" ${pageContext.request.contextPath}/css/images/save.png" />
</div>
/WEB-INF/jsp/user/addUI.jsp
<%@ page language =“java” import=“java.util.*” pageEncoding=“UTF-8” %>
<%@ include file =“/WEB-INF/jsp/common/common.jsp” %>


<!-- 表单内容显示 -->
<div class ="ItemBlockBorder" >
<div class ="ItemBlock" >
<table cellpadding ="0" cellspacing="0" class="mainForm" >
<tr>< td width="100"> 所属部门</td >
<td>< s:select list="#dList" listKey ="did" listValue="dname" name="did" cssClass="SelectStyle" />
</td>
</tr>
<tr>< td>登录名 </td>
<td>< s:textfield name="username" cssClass="InputStyle" />
(登录名要唯一)
</td>
</tr>
<tr>< td>性别 </td>
<td>< s:radio list="{'男','女'}" name="sex" /></td>
</tr>
<tr>< td>联系电话 </td>
<td>< s:textfield name="phone" cssClass="InputStyle" /></td>
</tr>
<tr>< td>E-mail </td>
<td>< s:textfield name="email" cssClass="InputStyle" /></td>
</tr>
</table>
</div>
</div>
<div class ="ItemBlock_Title1" ><!-- 信息说明 --><div class="ItemBlock_Title1" >
<img border ="0" width="4" height="7" src=" ${pageContext.request.contextPath}/css/blue/images/item_point.gif" /> 岗位设置 </ div>
</div>
<!-- 表单内容显示 -->
<div class ="ItemBlockBorder" >
<div class ="ItemBlock" >
<table cellpadding ="0" cellspacing="0" class="mainForm" >
<tr>
<td width ="100" >岗位</ td>
<td>< s:select list="#pList" listKey ="pid" listValue="pname" multiple="true" size="10" cssClass="SelectStyle" name="pids" ></s:select>
按住Ctrl键可以多选或取消选择
</td>
</tr>
</table>
</div>
</div>
<!-- 表单操作 -->
<div id ="InputDetailBar" >
<input type ="image" src=" ${pageContext.request.contextPath}/css/images/save.png" />
<a href ="javascript:history.go(-1);" ><img src=" ${pageContext.request.contextPath}/css/images/goBack.png" /></a>
</div>
</s:form >
1,用户的登录名要唯一,在填写时要同时检测是否可用。
2,新建用户后,密码被初始化为"1234"。
3,密码在数据库中存储的是MD5摘要(不是存储明文密码)。
4,用户登录系统后可以使用“个人设置→修改密码”功能修改密码。
5,新建用户后,会自动指定默认的头像。用户可以使用“个人设置→个人信息”功能修改自已的头像
6,修改用户信息时,登录名不可修改。
cn.itheima.oa.dao.UserDao.java
public interface UserDao extends BaseDao{
public Set getUsers();
public User getUserById(Serializable uid);
}
cn.itheima.oa.dao.impl.UserDaoImpl.java
@Repository(“userDao” )
public class UserDaoImpl extends BaseDaoImpl implements UserDao {
public Set<User> getUsers() {
return new HashSet(this. hibernateTemplate.find("from User u left outer join fetch u.department d left outer join fetch u.posts p"));
}
public User getUserById(Serializable uid) {
List<User> uList = this.hibernateTemplate .find("from User u left outer join fetch u.posts p left outer join fetch u.department d where u.uid=" + uid);
if(uList.size()==0){
return null ;
} else{
return uList.get(0);
}
}
}
cn.itheima.oa.service.UserService.java
public interface UserService {
public Set getAllUsers() throws Exception;
public void saveUser(User user) throws Exception;
public void deleteUser(Serializable uid) throws Exception;
public void updateUser(User user) throws Exception;
public User getUserById(Serializable uid) throws Exception;
}
cn.itheima.oa.service.impl.UserServceImpl.java
@Service(“userService” )
public class UserServiceImpl implements UserService {
@Resource(name="userDao" )
private UserDao userDao ;
public UserDao getUserDao() {
return userDao ;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Transactional(readOnly=false)
public void deleteUser(Serializable uid) throws Exception {
this.userDao .deleteEntity(uid);
}
public Set<User> getAllUsers() throws Exception {
return new HashSet(userDao.getAllEntities());
}
public User getUserById(Serializable uid)
throws Exception {
return (User) userDao .getUserById(uid);
}
@Transactional(readOnly=false)
public void saveUser(User user) throws Exception {
this.userDao .saveEntity(user);
}
@Transactional(readOnly=false)
public void updateUser(User user) throws Exception {
userDao.updateEntity(user);
}
}
cn.itheima.oa.action.java
@Controller(“userAction” )
@Scope(“prototype” )
public class UserAction extends BaseAction {
private Long did ;
private Long[] pids ;
public Long getDid() {
return did ;
}
public void setDid(Long did) {
this.did = did;
}
public Long[] getPids() {
return pids ;
}
public void setPids(Long[] pids) {
this.pids = pids;
}
public String showUsers() throws Exception {
Collection<User> users = userService.getAllUsers();
ActionContext. getContext().put("uList", users);
return listAction ;
}
public String delete() throws Exception {
return action2action ;
}
public String addUI() throws Exception {
Collection<Department> dList = this.departmentService .getAllDepartments();
Collection<Post> pList = this.postService .getAllPosts();
ActionContext. getContext().put("dList", dList);
ActionContext. getContext().put("pList", pList);
return add_ui ;
}
public String add() throws Exception {
/**
* 因为用户和部门之间是多对一的关系,用户负责维护关系,所以在保存用户的坏死后,会自动建立用户和部门之间的关系。
* 因为用户和岗位之间是多对多的关系,谁维护关系都行,所以在保存用户的时候,会自动建立用户和岗位之间的关系。
*/
Department department = this.departmentService .getDepartmentById(this. did);
Set<Post> posts = this.postService .getPostsByIds(pids);
User user = new User();
BeanUtils. copyProperties(this.getModel(), user);
user.setDepartment(department);
user.setPosts(posts);
this.userService .saveUser(user);
return action2action ;
}
public String updateUI() throws Exception {
User user = userService.getUserById( this.getModel().getUid());
ActionContext. getContext().getValueStack().push(user);
this.did = user.getDepartment().getDid();
Set<Post> posts = user.getPosts();
this.pids = new Long[posts.size()];
int index = 0;
for(Post post : posts){
pids[index++] = post.getPid();
}
Collection<Department> dList = this.departmentService .getAllDepartments ();
Collection<Post> pList = this.postService .getAllPosts ();
ActionContext. getContext().put("dList", dList);
ActionContext. getContext().put("pList", pList);
return update_ui;
}
public String update() throws Exception {
User user = userService.getUserById(this.getModel().getUid());
BeanUtils. copyProperties(this.getModel(), user);
Department department = departmentService.getDepartmentById(this.did);
user.setDepartment(department);
Set<Post> posts = postService.getPostsByIds(pids );
user.setPosts(posts);
userService.updateUser(user);
return action2action ;
}
}
struts/struts-user.xml
<?xml version ="1.0" encoding="UTF-8" ?> /WEB-INF/jsp/user/list.jsp userAction_showUsers.action /WEB-INF/jsp/user/addUI.jsp userAction_add.action /WEB-INF/jsp/user/updateUI.jsp/WEB-INF/jsp/user/list.jsp
<%@ page language =“java” import=“java.util.*” pageEncoding=“UTF-8” %>
<%@ include file =“/WEB-INF/jsp/common/common.jsp” %>

<!-- 表头-->
<thead>
<tr align =center valign=middle id= TableTitle>
<td width ="100" >姓名</ td>
<td width ="100" >所属部门</ td>
<td> 备注</td >
<td> 相关操作</td >
</tr>
</thead>
<!--显示数据列表-->
<tbody id ="TableData" class="dataContainer" datakey="userList" >
<s:iterator value ="#uList" >
<tr class ="TableDetail1 template" >
<td>< s:property value="username"/></ td>
<td>< s:property value="department.dname"/></ td>
<td>
<s:iterator value ="posts" >
<s:property value ="pname" />
</s:iterator>
</td>
<td>
<a onClick ="return delConfirm()" href="list.html" >删除</ a>
<s:a action="userAction_updateUI?uid=%{uid}" >修改</ s:a>
<a href="javascript:privilegeclick();" >设置权限</ a>
</td>
</tr>
</s:iterator>
</tbody>
</table >
<div id= "TableTail">
<div id ="TableTail_inside" >
<a href ="userAction_addUI.action" ><img src=" ${pageContext.request.contextPath}/css/images/createNew.png" /></ a>
</div>
</div >
<div class="ItemBlock_Title1" id= "userTitle" style="display: none;"><!-- 信息说明 --><div class="ItemBlock_Title1" >
<img border ="0" width="4" height="7" src=" ${pageContext.request.contextPath}/css/blue/images/item_point.gif" />用户:王欣然
<div id ="userImage" ></div>
</div>
<div class="ItemBlock_Title1" id= "privilegeTitle" style="display: none;"><div class ="ItemBlock_Title1" >
<img border ="0" width="4" height="7" src=" ${pageContext.request.contextPath}/css/blue/images/item_point.gif" />选择权限</ div>
</div>
<!-- 表单内容显示 -->
<div class ="ItemBlockBorder" style="display: none;" id="privilegeContent" >
<div class ="ItemBlock" >
<table cellpadding ="0" cellspacing="0" class="mainForm" >
<!--表头-->
<thead>
<tr align ="LEFT" valign="MIDDLE" id="TableTitle" >
<td width ="300px" style="padding-left: 7px;" >
<!-- 如果把全选元素的id指定为selectAll,并且有函数selectAll(),就会有错。因为有一种用法:可以直接用id引用元素 -->
<input type ="checkbox" id="allchecked" onchange="privilegeCheckedAll(this.checked,this.id)" />
<label for="cbSelectAll" >全选</ label>
</td>
</tr>
</thead>
<!--显示数据列表-->
<tbody id ="TableData" >
<tr class ="TableDetail1" >
<!-- 显示权限树 -->
<td>
<ul id ='privilegeTree' class="tree" >
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- 表单操作 -->
<div id ="InputDetailBar" >
<image onclick ="savePrivilege()" src=" ${pageContext.request.contextPath}/css/images/save.png" />
</div>
/WEB-INF/jsp/user/updateUI.jsp
<%@ page language =“java” import=“java.util.*” pageEncoding=“UTF-8” %>
<%@ include file =“/WEB-INF/jsp/common/common.jsp” %>


<!-- 表单内容显示 -->
<div class ="ItemBlockBorder" >
<div class ="ItemBlock" >
<table cellpadding ="0" cellspacing="0" class="mainForm" >
<tr>< td width="100"> 所属部门</td >
<td>< s:select list="#dList" listKey ="did" listValue="dname" name="did" cssClass="SelectStyle" />
</td>
</tr>
<tr>< td>登录名 </td>
<td>< s:textfield name="username" cssClass="InputStyle" />
(登录名要唯一)
</td>
</tr>
<tr>< td>性别 </td>
<td>< s:radio list="{'男','女'}" name="sex" /></td>
</tr>
<tr>< td>联系电话 </td>
<td>< s:textfield name="phone" cssClass="InputStyle" /></td>
</tr>
<tr>< td>E-mail </td>
<td>< s:textfield name="email" cssClass="InputStyle" /></td>
</tr>
</table>
</div>
</div>
<div class ="ItemBlock_Title1" ><!-- 信息说明 --><div class="ItemBlock_Title1" >
<img border ="0" width="4" height="7" src=" ${pageContext.request.contextPath}/css/blue/images/item_point.gif" /> 岗位设置 </ div>
</div>
<!-- 表单内容显示 -->
<div class ="ItemBlockBorder" >
<div class ="ItemBlock" >
<table cellpadding ="0" cellspacing="0" class="mainForm" >
<tr>
<td width ="100" >岗位</ td>
<td>< s:select list="#pList" listKey ="pid" listValue="pname" multiple="true" size="10" cssClass="SelectStyle" name="pids" ></s:select>
按住Ctrl键可以多选或取消选择
</td>
</tr>
</table>
</div>
</div>
<!-- 表单操作 -->
<div id ="InputDetailBar" >
<input type ="image" src=" ${pageContext.request.contextPath}/css/images/save.png" />
<a href ="javascript:history.go(-1);" ><img src=" ${pageContext.request.contextPath}/css/images/goBack.png" /></a>
</div>
</s:form >
1,用户的登录名要唯一,在填写时要同时检测是否可用。
2,新建用户后,密码被初始化为"1234"。
3,密码在数据库中存储的是MD5摘要(不是存储明文密码)。
4,用户登录系统后可以使用“个人设置→修改密码”功能修改密码。
5,新建用户后,会自动指定默认的头像。用户可以使用“个人设置→个人信息”功能修改自已的头像
6,修改用户信息时,登录名不可修改。
private Long did ;
private Long[] pids ;
public Long getDid() {
return did ;
}
public void setDid(Long did) {
this.did = did;
}
public Long[] getPids() {
return pids ;
}
public void setPids(Long[] pids) {
this.pids = pids;
}
@Resource(name="userService" )
private UserService userService ;
public UserService getUserService() {
return userService ;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
public String showUsers() throws Exception {
Collection<User> users = userService.getAllUsers();
ActionContext. getContext().put("uList", users);
return listAction ;
}
public String delete() throws Exception {
this.userService .deleteUser(this.getModel().getUid());
return action2action ;
}
public String addUI() throws Exception {
Collection<Department> dList = this.departmentService .getAllDepartments();
Collection<Post> pList = this.postService .getAllPosts();
ActionContext. getContext().put("dList", dList);
ActionContext. getContext().put("pList", pList);
return add_ui ;
}
public String add() throws Exception {
Department department = this.departmentService .getDepartmentById(this. did);
Set<Post> posts = this.postService .getPostsByIds(pids);
User user = new User();
BeanUtils. copyProperties(this.getModel(), user);
user.setDepartment(department);
user.setPosts(posts);
this.userService .saveUser(user);
return action2action ;
}
public String updateUI() throws Exception {
User user = userService.getUserById(this.getModel().getUid());
ActionContext. getContext().getValueStack().push(user);
this.did = user.getDepartment().getDid();
Set<Post> posts = user.getPosts();
this.pids = new Long[posts.size()];
int index = 0;
for(Post post : posts){
pids[index++] = post.getPid();
}
Collection<Department> dList = this.departmentService .getAllDepartments();
Collection<Post> pList = this.postService .getAllPosts();
ActionContext. getContext().put("dList", dList);
ActionContext. getContext().put("pList", pList);
return update_ui ;
}
public String update() throws Exception {
User user = userService.getUserById(this.getModel().getUid());
BeanUtils. copyProperties(this.getModel(), user);
Department department = departmentService.getDepartmentById(this.did);
user.setDepartment(department);
Set<Post> posts = postService.getPostsByIds(pids );
user.setPosts(posts);
userService.updateUser(user);
return action2action ;
}
}
/WEB-INF/js/user/user.js
$().ready(function(){
$.oaconfirm();
});
/WEB-INF/jsp/user/list.jsp
<%@ page language =“java” import=“java.util.*” pageEncoding=“UTF-8” %>
<%@ include file =“/WEB-INF/jsp/common/common.jsp” %>

<!-- 表头-->
<thead>
<tr align =center valign=middle id= TableTitle>
<td width ="100" >姓名</ td>
<td width ="100" >所属部门</ td>
<td> 备注</td >
<td> 相关操作</td >
</tr>
</thead>
<!--显示数据列表-->
<tbody id ="TableData" class="dataContainer" datakey="userList" >
<s:iterator value ="#uList" >
<tr class ="TableDetail1 template" >
<td>< s:property value="username"/></ td>
<td>< s:property value="department.dname"/></ td>
<td>
<s:iterator value ="posts" >
<s:property value ="pname" />
</s:iterator>
</td>
<td>
<s:a action ="userAction_delete?uid=%{uid}" >删除</ s:a>
<s:a action="userAction_updateUI?uid=%{uid}" >修改</ s:a>
<a href="javascript:privilegeclick();" >设置权限</ a>
</td>
</tr>
</s:iterator>
</tbody>
</table >
<div id= "TableTail">
<div id ="TableTail_inside" >
<a href ="userAction_addUI.action" ><img src=" ${pageContext.request.contextPath}/css/images/createNew.png" /></ a>
</div>
</div >
<div class="ItemBlock_Title1" id= "userTitle" style="display: none;"><!-- 信息说明 --><div class="ItemBlock_Title1" >
<img border ="0" width="4" height="7" src=" ${pageContext.request.contextPath}/css/blue/images/item_point.gif" />用户:王欣然
<div id ="userImage" ></div>
</div>
<div class="ItemBlock_Title1" id= "privilegeTitle" style="display: none;"><div class ="ItemBlock_Title1" >
<img border ="0" width="4" height="7" src=" ${pageContext.request.contextPath}/css/blue/images/item_point.gif" />选择权限</ div>
</div>
<!-- 表单内容显示 -->
<div class ="ItemBlockBorder" style="display: none;" id="privilegeContent" >
<div class ="ItemBlock" >
<table cellpadding ="0" cellspacing="0" class="mainForm" >
<!--表头-->
<thead>
<tr align ="LEFT" valign="MIDDLE" id="TableTitle" >
<td width ="300px" style="padding-left: 7px;" >
<!-- 如果把全选元素的id指定为selectAll,并且有函数selectAll(),就会有错。因为有一种用法:可以直接用id引用元素 -->
<input type ="checkbox" id="allchecked" onchange="privilegeCheckedAll(this.checked,this.id)" />
<label for="cbSelectAll" >全选</ label>
</td>
</tr>
</thead>
<!--显示数据列表-->
<tbody id ="TableData" >
<tr class ="TableDetail1" >
<!-- 显示权限树 -->
<td>
<ul id ='privilegeTree' class="tree" >
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- 表单操作 -->
<div id ="InputDetailBar" >
<image onclick ="savePrivilege()" src=" ${pageContext.request.contextPath}/css/images/save.png" />
</div>
21 完成对用户信息的验证
1、导入3个jar包。
json-lib-2.1.jar
struts2-json-plugin-2.1.8.1.jar
struts2-junit-plugin-2.1.8.1.jar
注:<1>打开struts2-json-plugin-2.1.8.1.jar,观察里面的struts-plugin.xml文件,可以看到它定义了一个拦截器和一个结果集json。
<2>因为该包继承了struts-default,所以该包拥有struts2的package为struts-default的功能,所以该包同样适用于属性驱动和模型驱动。
<3>因为是ajax操作,所以不需要刷新页面,所以不需要获取result标签中的内容,所以JSONResult只需要实现Result接口即可。
<4>自定义了一个拦截器,如果客户端向服务器端传递复杂格式的类型,这个时候需要用到拦截器。
<5>在ajax与struts结合的使用中,只要action中有get方法,那么这个属性就会返回给回调函数中的data中,如果一个方法的返回值不需要返回给客户端,最好不要以get方法开头。如果一定要使用get方法,那么不要忘记在get方法上面添加@JSON(Serializable=false),这时候它就不会包含在回调函数的参数data中了。
重点:如果在使用struts和ajax结合的过程中,如果使用$.post发送一个请求,如果出现错误,那么首先应该把这个请求的连接粘贴到浏览器中执行,看能否执行成功,如果能执行成功,那么说明是js出了问题。否则,说明js和服务器都有可能,这时候,将struts配置文件中的继承json-default改为struts-default,看是否能够跳转到相关的方法执行,如果可以,说明json的包有问题。
注:在导入包之后一定要重新部署,否则,无法生效。
<6>如果返回的是一个代理对象(例如已经添加事务的service对象),而不是数据,这个时候根本处理不了,那么就会报错。这时候就需要在这个代理对象的get方法上加上@JSON(serialize=false)。
cn.itheima.oa.dao.UserDao.java
public interface UserDao extends BaseDao{
public Set getUsers();
public User getUserById(Serializable uid);
public User getUserByName(String username);
}
cn.itheima.oa.dao.impl.UserDaoImpl.java
@Repository(“userDao” )
public class UserDaoImpl extends BaseDaoImpl implements UserDao {
public Set<User> getUsers() {
return new HashSet(this. hibernateTemplate.find("from User u left outer join fetch u.department d left outer join fetch u.posts p"));
}
public User getUserById(Serializable uid) {
List<User> uList = this.hibernateTemplate .find("from User u left outer join fetch u.posts p left outer join fetch u.department d where u.uid=" + uid);
if(uList.size()==0){
return null ;
} else{
return uList.get(0);
}
}
public User getUserByName(String username) {
List<User> uList = this. hibernateTemplate.find("from User u where u.username=?",username);
if(uList.size()==0){
return null ;
} else{
return uList.get(0);
}
}
}
cn.itheima.oa.service.UserService.java
public interface UserService {
public Set getAllUsers() throws Exception;
public void saveUser(User user) throws Exception;
public void deleteUser(Serializable uid) throws Exception;
public void updateUser(User user) throws Exception;
public User getUserById(Serializable uid) throws Exception;
public User getUserByName(String username) throws Exception;
}
cn.itheima.oa.service.impl.UserServiceImpl.java
@Service(“userService” )
public class UserServiceImpl implements UserService {
@Resource(name="userDao" )
private UserDao userDao ;
public UserDao getUserDao() {
return userDao ;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Transactional(readOnly=false)
public void deleteUser(Serializable uid) throws Exception {
this.userDao .deleteEntity(uid);
}
public Set<User> getAllUsers() throws Exception {
return new HashSet(userDao.getAllEntities());
}
public User getUserById(Serializable uid)
throws Exception {
return (User) userDao .getUserById(uid);
}
@Transactional(readOnly=false)
public void saveUser(User user) throws Exception {
this.userDao .saveEntity(user);
}
@Transactional(readOnly=false)
public void updateUser(User user) throws Exception {
userDao.updateEntity(user);
}
public User getUserByName(String username) throws Exception {
return userDao .getUserByName (username);
}
}
cn.itheima.action.UserAction.java
@Controller(“userAction” )
@Scope(“prototype” )
public class UserAction extends BaseAction {
private Long did ;
//action中可以创建基本类型的数组形式的属性,模型驱动也可以进行转化
private Long[] pids ;
private String message ;
public String getMessage() {
return message ;
}
public void setMessage(String message) {
this.message = message;
}
public Long getDid() {
return did ;
}
public void setDid(Long did) {
this.did = did;
}
public Long[] getPids() {
return pids ;
}
public void setPids(Long[] pids) {
this.pids = pids;
}
@Resource(name="userService" )
private UserService userService ;
@JSON(serialize=false)
public UserService getUserService() {
return userService ;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
public String showUsers() throws Exception {
Collection<User> users = userService.getAllUsers();
ActionContext. getContext().put("uList", users);
return listAction ;
}
public String delete() throws Exception {
this.userService .deleteUser(this.getModel().getUid());
return action2action ;
}
public String addUI() throws Exception {
Collection<Department> dList = this.departmentService .getAllDepartments();
Collection<Post> pList = this.postService .getAllPosts();
ActionContext. getContext().put("dList", dList);
ActionContext. getContext().put("pList", pList);
return add_ui ;
}
public String add() throws Exception {
Department department = this.departmentService .getDepartmentById(this. did);
Set<Post> posts = this.postService .getPostsByIds(pids);
User user = new User();
BeanUtils. copyProperties(this.getModel(), user);
user.setDepartment(department);
user.setPosts(posts);
this.userService .saveUser(user);
return action2action ;
}
public String updateUI() throws Exception {
User user = userService.getUserById(this.getModel().getUid());
ActionContext. getContext().getValueStack().push(user);
this.did = user.getDepartment().getDid();
Set<Post> posts = user.getPosts();
this.pids = new Long[posts.size()];
int index = 0;
for(Post post : posts){
pids[index++] = post.getPid();
}
Collection<Department> dList = this.departmentService .getAllDepartments();
Collection<Post> pList = this.postService .getAllPosts();
ActionContext. getContext().put("dList", dList);
ActionContext. getContext().put("pList", pList);
return update_ui ;
}
public String update() throws Exception {
User user = userService.getUserById(this.getModel().getUid());
BeanUtils. copyProperties(this.getModel(), user);
Department department = departmentService.getDepartmentById(this.did);
user.setDepartment(department);
Set<Post> posts = postService.getPostsByIds(pids );
user.setPosts(posts);
userService.updateUser(user);
return action2action ;
}
public String checkUser() throws Exception {
User user = this.userService .getUserByName(this.getModel().getUsername());
if(user == null){
message = "此用户名可以使用" ;
} else{
message = "此用户名已被占用,不能使用!" ;
}
return SUCCESS ;
}
}
struts/struts-user.xml
<?xml version ="1.0" encoding="UTF-8" ?> /WEB-INF/jsp/user/list.jsp userAction_showUsers.action /WEB-INF/jsp/user/addUI.jsp userAction_add.action /WEB-INF/jsp/user/updateUI.jsp <package name ="userjson" namespace="/" extends="json-default" >
<action name ="userJsonAction_*" method="{1}" class="userAction" >
<result type ="json" ></result>
</action>
</package>
/WEB-INF/js/user/user.js
var user = {
initEvent:function(){
$(“input[name=‘username’]”).unbind(“blur”);
KaTeX parse error: Expected '}', got 'EOF' at end of input: … //这里的this就是(“input[name=‘username’]”)这个组件
user.checkUser.call(this);
//方法二:user.checkUser(
(
t
h
i
s
)
.
v
a
l
(
)
)
;
/
/
方
法
三
:
u
s
e
r
.
c
h
e
c
k
U
s
e
r
(
(this).val()); //方法三:user.checkUser(
(this).val());//方法三:user.checkUser((this));
});
},
checkUser:function(){
var username = $(this).val();
//方法二:alert(arguments[0]);
//方法三:alert(arguments[0].val());
$.post(“userJsonAction_checkUser.action”,{
username:username
},function(data){
//注意:只要action中有get方法的属性都会作为参数封装到data中
//所以如果不需要传入回调函数中的属性最好不要写get方法
$(“#message”).text(data.message);
if(data.message==‘此用户名可以使用’){
$(“#message”).css(“color”,“green”);
}else{
$(“#message”).css(“color”,“red”);
}
});
}
};
$().ready(function(){
$.oaconfirm();
user.initEvent();
});
/WEB-INF/jsp/user/updateUI.jsp
<%@ page language =“java” import=“java.util.*” pageEncoding=“UTF-8” %>
<%@ include file =“/WEB-INF/jsp/common/common.jsp” %>


<!-- 表单内容显示 -->
<div class ="ItemBlockBorder" >
<div class ="ItemBlock" >
<table cellpadding ="0" cellspacing="0" class="mainForm" >
<tr>< td width="100"> 所属部门</td >
<td>< s:select list="#dList" listKey ="did" listValue="dname" name="did" cssClass="SelectStyle" />
</td>
</tr>
<tr>< td>登录名 </td>
<td>< s:textfield name="username" cssClass="InputStyle" />
<s:label id="message" ></s:label>
</td>
</tr>
<tr>< td>性别 </td>
<td>< s:radio list="{'男','女'}" name="sex" /></td>
</tr>
<tr>< td>联系电话 </td>
<td>< s:textfield name="phone" cssClass="InputStyle" /></td>
</tr>
<tr>< td>E-mail </td>
<td>< s:textfield name="email" cssClass="InputStyle" /></td>
</tr>
</table>
</div>
</div>
<div class ="ItemBlock_Title1" ><!-- 信息说明 --><div class="ItemBlock_Title1" >
<img border ="0" width="4" height="7" src=" ${pageContext.request.contextPath}/css/blue/images/item_point.gif" /> 岗位设置 </ div>
</div>
<!-- 表单内容显示 -->
<div class ="ItemBlockBorder" >
<div class ="ItemBlock" >
<table cellpadding ="0" cellspacing="0" class="mainForm" >
<tr>
<td width ="100" >岗位</ td>
<td>< s:select list="#pList" listKey ="pid" listValue="pname" multiple="true" size="10" cssClass="SelectStyle" name="pids" ></s:select>
按住Ctrl键可以多选或取消选择
</td>
</tr>
</table>
</div>
</div>
<!-- 表单操作 -->
<div id ="InputDetailBar" >
<input type ="image" src=" ${pageContext.request.contextPath}/css/images/save.png" />
<a href ="javascript:history.go(-1);" ><img src=" ${pageContext.request.contextPath}/css/images/goBack.png" /></a>
</div>
</s:form >
1,用户的登录名要唯一,在填写时要同时检测是否可用。
2,新建用户后,密码被初始化为"1234"。
3,密码在数据库中存储的是MD5摘要(不是存储明文密码)。
4,用户登录系统后可以使用“个人设置→修改密码”功能修改密码。
5,新建用户后,会自动指定默认的头像。用户可以使用“个人设置→个人信息”功能修改自已的头像
6,修改用户信息时,登录名不可修改。
22 学习使用zTree(一次性全部加载)
1、zTree的加载
<1>加载三个文件
jquery-1.4.2.js
jquery-ztree-2.5.js
zTreeStyle.css
<2>在页面上设置树的容器
找到页面上的一个对象,class属性为’tree’。
<3>树的容器调用zTree方法把生成的树挂在容器上。
<4>细节
setting的配置是用来描述树的整体的特性。
zNodes描述树上的每一个节点。
isParent
描述当前节点是否为子节点
zTree会自动根据该节点是否有子节点,来判断isParent的值。
如果没有子节点,则isParent的值为false。
如果有子节点,则isParent的值为true。
为了保证该节点肯定是父节点,可以直接设置其值为true。
name 节点的名称
id 是根据treeNodeKey定义的。
2、具体步骤
<1>首先将相关的js文件和css文件导入。然后在页面上进行引用。并且设置zTree的容器
<%@ page language =“java” import=“java.util.*” pageEncoding=“UTF-8” %>
<2>写持久化类、映射文件并且导入到hibernate.cfg.xml中。
cn.itheima.oa.domain.MenuItem.java
public class MenuItem implements Serializable {
private Long mid ;
private Long pid ;
private String name ;
private Boolean isParent ;
private String icon ;
public String getIcon() {
return icon ;
}
public void setIcon(String icon) {
this.icon = icon;
}
public Long getMid() {
return mid ;
}
public void setMid(Long mid) {
this.mid = mid;
}
public Long getPid() {
return pid ;
}
public void setPid(Long pid) {
this.pid = pid;
}
public String getName() {
return name ;
}
public void setName(String name) {
this.name = name;
}
public Boolean getIsParent() {
return isParent ;
}
public void setIsParent(Boolean isParent) {
this.isParent = isParent;
}
}
cn.itheima.oa.domain.MenuItem.hbm.xml
<?xml version ="1.0" encoding="UTF-8" ?>hibernate/hibernate.cfg.xml
<?xml version ="1.0" encoding="UTF-8" ?> org.hibernate.dialect.MySQLDialect <property name ="hibernate.connection.driver_class" >
com.mysql.jdbc.Driver
</property>
<property name ="show_sql" >true</ property>
<property name ="hibernate.connection.username" >root</ property>
<property name ="hibernate.connection.password" >sorry</ property>
<property name ="hibernate.connection.url" >
jdbc:mysql://localhost:3306/oa
</property>
<property name ="hbm2ddl.auto" >update</ property>
<mapping resource ="cn/itheima/oa/domain/Department.hbm.xml" />
<mapping resource ="cn/itheima/oa/domain/Post.hbm.xml" />
<mapping resource ="cn/itheima/oa/domain/User.hbm.xml" />
<mapping resource ="cn/itheima/oa/domain/MenuItem.hbm.xml" />
<3>写一个test
cn.itheima.oa.test.MenuItemTest.java
public class MenuitemTest {
@Test
public void addMenuItem(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(“spring/applicationContext.xml” );
SessionFactory sessionFactory = (SessionFactory)applicationContext.getBean(“sessionFactory” );
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
/***********************************************************************************/
/*
* 个人办公
*/
MenuItem Menuitemitem1 = new MenuItem();
Menuitemitem1.setMid(1L);
Menuitemitem1.setIcon( “css/images/MenuIcon/FUNC20082.gif” );
Menuitemitem1.setName( “办公自动化” );
Menuitemitem1.setPid(0L);
//Menuitemitem1.setChecked(false);
Menuitemitem1.setIsParent( true);
MenuItem Menuitem2 = new MenuItem();
Menuitem2.setMid(2L);
Menuitem2.setIcon( "css/images/MenuIcon/FUNC20001.gif" );
Menuitem2.setName( "个人办公" );
//Menuitem2.setChecked(false);
Menuitem2.setPid(1L);
Menuitem2.setIsParent( true);
MenuItem Menuitem21 = new MenuItem();
Menuitem21.setMid(21L);
Menuitem21.setIcon( "css/images/MenuIcon/FUNC20054.gif" );
Menuitem21.setName( "个人考勤" );
//Menuitem21.setChecked(false);
Menuitem21.setPid(2L);
Menuitem21.setIsParent( false);
MenuItem Menuitem22 = new MenuItem();
Menuitem22.setMid(22L);
Menuitem22.setIcon( "css/images/MenuIcon/FUNC23700.gif" );
Menuitem22.setName( "日程安排" );
//Menuitem22.setChecked(false);
Menuitem22.setPid(2L);
Menuitem22.setIsParent( false);
MenuItem Menuitem23 = new MenuItem();
Menuitem23.setMid(23L);
Menuitem23.setIcon( "css/images/MenuIcon/FUNC20069.gif" );
Menuitem23.setName( "工作计划" );
//Menuitem23.setChecked(false);
Menuitem23.setPid(2L);
Menuitem23.setIsParent( false);
MenuItem Menuitem24 = new MenuItem();
Menuitem24.setMid(24L);
Menuitem24.setIcon( "css/images/MenuIcon/FUNC20056.gif" );
Menuitem24.setName( "工作日记" );
//Menuitem24.setChecked(false);
Menuitem24.setPid(2L);
Menuitem24.setIsParent( false);
MenuItem Menuitem25 = new MenuItem();
Menuitem25.setMid(25L);
Menuitem25.setIcon( "css/images/MenuIcon/time_date.gif" );
Menuitem25.setName( "通讯录");
//Menuitem25.setChecked(false);
Menuitem25.setPid(2L);
Menuitem25.setIsParent( false);
/********************************************************************************/
/
* 审批流转
*/
MenuItem Menuitem3 = new MenuItem();
Menuitem3.setMid(3L);
///Menuitem3.setChecked(false);
Menuitem3.setIsParent( true);
Menuitem3.setPid(1L);
Menuitem3.setName( “审批流转” );
Menuitem3.setIcon( “css/images/MenuIcon/FUNC20057.gif” );
MenuItem Menuitem31 = new MenuItem();
Menuitem31.setMid(31L);
//Menuitem31.setChecked(false);
Menuitem31.setIsParent( false);
Menuitem31.setPid(3L);
Menuitem31.setName( "审批流程管理" );
Menuitem31.setIcon( "css/images/MenuIcon/manager.gif" );
MenuItem Menuitem32 = new MenuItem();
Menuitem32.setMid(32L);
//Menuitem32.setChecked(false);
Menuitem32.setIsParent( false);
Menuitem32.setPid(3L);
Menuitem32.setName( "表单模板管理" );
Menuitem32.setIcon( "css/images/MenuIcon/formmodel.gif" );
MenuItem Menuitem33 = new MenuItem();
Menuitem33.setMid(33L);
Menuitem33.setIsParent( false);
//Menuitem33.setChecked(false);
Menuitem33.setPid(3L);
Menuitem33.setName( "发起申请" );
Menuitem33.setIcon( "css/images/MenuIcon/FUNC241000.gif" );
MenuItem Menuitem34 = new MenuItem();
Menuitem34.setMid(34L);
Menuitem34.setIsParent( false);
//Menuitem34.setChecked(false);
Menuitem34.setPid(3L);
Menuitem34.setName( "审批申请" );
Menuitem34.setIcon( "css/images/MenuIcon/FUNC20029.gif" );
MenuItem Menuitem35 = new MenuItem();
Menuitem35.setMid(35L);
Menuitem35.setIsParent( false);
//Menuitem35.setChecked(false);
Menuitem35.setPid(3L);
Menuitem35.setName( "状态查询" );
Menuitem35.setIcon( "css/images/MenuIcon/FUNC20029.gif" );
/****/
/
* 知识管理
/
MenuItem Menuitem4 = new MenuItem();
Menuitem4.setMid(4L);
Menuitem4.setIsParent( false);
//Menuitem4.setChecked(false);
Menuitem4.setPid(1L);
Menuitem4.setName( “知识管理” );
Menuitem4.setIcon( “css/images/MenuIcon/FUNC20056.gif” );
//
/
* 综合行政
*/
MenuItem Menuitem5 = new MenuItem();
Menuitem5.setMid(5L);
Menuitem5.setIsParent( true);
//Menuitem5.setChecked(false);
Menuitem5.setPid(1L);
Menuitem5.setName( “管理行政” );
Menuitem5.setIcon( “css/images/MenuIcon/manager.gif” );
MenuItem Menuitem51 = new MenuItem();
Menuitem51.setMid(51L);
Menuitem51.setIsParent( false);
//Menuitem51.setChecked(false);
Menuitem51.setPid(5L);
Menuitem51.setName( "考勤管理" );
Menuitem51.setIcon( "css/images/MenuIcon/FUNC20070.gif" );
MenuItem Menuitem52 = new MenuItem();
Menuitem52.setMid(52L);
Menuitem52.setIsParent( false);
//Menuitem52.setChecked(false);
Menuitem52.setPid(5L);
Menuitem52.setName( "会议管理" );
Menuitem52.setIcon( "css/images/MenuIcon/FUNC20064.gif" );
MenuItem Menuitem53 = new MenuItem();
Menuitem53.setMid(53L);
Menuitem53.setIsParent( false);
//Menuitem53.setChecked(false);
Menuitem53.setPid(5L);
Menuitem53.setName( "车辆管理" );
Menuitem53.setIcon( "css/images/MenuIcon/radio_blue.gif" );
/**************************************************************************************/
/*
* 人力资源管理
* 档案管理
* 培训记录
* 奖金记录
* 职位变更
* 人事合同
* 薪酬制度
*/
MenuItem Menuitem6 = new MenuItem();
Menuitem6.setMid(6L);
Menuitem6.setIsParent( true);
//Menuitem6.setChecked(false);
Menuitem6.setPid(1L);
Menuitem6.setName( “人力资源” );
Menuitem6.setIcon( “css/images/MenuIcon/FUNC20001.gif” );
MenuItem Menuitem61 = new MenuItem();
Menuitem61.setMid(61L);
Menuitem61.setIsParent( false);
//Menuitem61.setChecked(false);
Menuitem61.setPid(6L);
Menuitem61.setName( "档案管理" );
Menuitem61.setIcon( "css/images/MenuIcon/FUNC20076.gif" );
MenuItem Menuitem62 = new MenuItem();
Menuitem62.setMid(62L);
Menuitem62.setIsParent( false);
//Menuitem62.setChecked(false);
Menuitem62.setPid(6L);
Menuitem62.setName( "培训记录" );
Menuitem62.setIcon( "css/images/MenuIcon/FUNC55000.gif" );
MenuItem Menuitem63 = new MenuItem();
Menuitem63.setMid(63L);
Menuitem63.setIsParent( false);
//Menuitem63.setChecked(false);
Menuitem63.setPid(6L);
Menuitem63.setName( "奖赏记录" );
Menuitem63.setIcon( "css/images/MenuIcon/FUNC55000.gif" );
MenuItem Menuitem64 = new MenuItem();
Menuitem64.setMid(64L);
Menuitem64.setIsParent( false);
//Menuitem64.setChecked(false);
Menuitem64.setPid(6L);
Menuitem64.setName( "职位变更" );
Menuitem64.setIcon( "css/images/MenuIcon/FUNC55000.gif" );
MenuItem Menuitem65 = new MenuItem();
Menuitem65.setMid(65L);
Menuitem65.setIsParent( false);
//Menuitem65.setChecked(false);
Menuitem65.setPid(6L);
Menuitem65.setName( "人事合同" );
Menuitem65.setIcon( "css/images/MenuIcon/FUNC55000.gif" );
MenuItem Menuitem66 = new MenuItem();
Menuitem66.setMid(66L);
Menuitem66.setIsParent( false);
//Menuitem66.setChecked(false);
Menuitem66.setPid(6L);
Menuitem66.setName( "薪酬制度" );
Menuitem66.setIcon( "css/images/MenuIcon/FUNC20001.gif" );
/*****************************************************************************************/
/*
* 电子邮件
*/
MenuItem Menuitem7 = new MenuItem();
Menuitem7.setMid(7L);
Menuitem7.setIsParent( false);
//Menuitem7.setChecked(false);
Menuitem7.setPid(1L);
Menuitem7.setName( “电子邮件” );
Menuitem7.setIcon( “css/images/MenuIcon/eml.gif” );
//
/
* 实用工具
* 车票预定
* GIS查询
* 邮政编码
/
MenuItem Menuitem8 = new MenuItem();
Menuitem8.setMid(8L);
Menuitem8.setIsParent( true);
//Menuitem8.setChecked(false);
Menuitem8.setPid(1L);
Menuitem8.setName( “实用工具” );
Menuitem8.setIcon( “css/images/MenuIcon/FUNC20076.gif” );
MenuItem Menuitem81 = new MenuItem();
Menuitem81.setMid(81L);
Menuitem81.setIsParent( false);
//Menuitem81.setChecked(false);
Menuitem81.setPid(8L);
Menuitem81.setName( “车票预定” );
Menuitem81.setIcon( “css/images/MenuIcon/FUNC220000.gif” );
MenuItem Menuitem82 = new MenuItem();
Menuitem82.setMid(82L);
Menuitem82.setIsParent( false);
//Menuitem82.setChecked(false);
Menuitem82.setPid(8L);
Menuitem82.setName( “GIS查询”);
Menuitem82.setIcon( “css/images/MenuIcon/search.gif” );
MenuItem Menuitem83 = new MenuItem();
Menuitem83.setMid(83L);
Menuitem83.setIsParent( false);
//Menuitem83.setChecked(false);
Menuitem83.setPid(8L);
Menuitem83.setName( “邮政编码” );
Menuitem83.setIcon( “css/images/MenuIcon/FUNC249000.gif” );
/**************************************************************************/
/
* 个人设置
* 个人信息
* 密码修改
/
MenuItem Menuitem9 = new MenuItem();
Menuitem9.setMid(9L);
Menuitem9.setIsParent( true);
//Menuitem9.setChecked(false);
Menuitem9.setPid(1L);
Menuitem9.setName( “个人设置” );
Menuitem9.setIcon( “css/images/MenuIcon/FUNC20001.gif” );
MenuItem Menuitem91 = new MenuItem();
Menuitem91.setMid(91L);
Menuitem91.setIsParent( false);
//Menuitem91.setChecked(false);
Menuitem91.setPid(9L);
Menuitem91.setName( “个人信息” );
Menuitem91.setIcon( “css/images/MenuIcon/FUNC20001.gif” );
MenuItem Menuitem92 = new MenuItem();
Menuitem92.setMid(92L);
Menuitem92.setIsParent( false);
//Menuitem92.setChecked(false);
Menuitem92.setPid(9L);
Menuitem92.setName( “密码修改” );
Menuitem92.setIcon( “css/images/MenuIcon/FUNC241000.gif” );
/***********************************************************************************/
/
* 系统管理
* 岗位管理
* 部门管理
* 用户管理
/
MenuItem Menuitem10 = new MenuItem();
Menuitem10.setMid(10L);
Menuitem10.setIsParent( true);
//Menuitem10.setChecked(false);
Menuitem10.setPid(1L);
Menuitem10.setName( “系统管理” );
Menuitem10.setIcon( “css/images/MenuIcon/system.gif” );
MenuItem Menuitem101 = new MenuItem();
Menuitem101.setMid(101L);
Menuitem101.setIsParent( false);
//Menuitem101.setChecked(false);
Menuitem101.setPid(10L);
Menuitem101.setName( “岗位管理” );
Menuitem101.setIcon( “css/images/MenuIcon/FUNC20001.gif” );
MenuItem Menuitem102 = new MenuItem();
Menuitem102.setMid(102L);
Menuitem102.setIsParent( false);
//Menuitem102.setChecked(false);
Menuitem102.setPid(10L);
Menuitem102.setName( “部门管理” );
Menuitem102.setIcon( “css/images/MenuIcon/department.gif” );
MenuItem Menuitem103 = new MenuItem();
Menuitem103.setMid(103L);
Menuitem103.setIsParent( false);
//Menuitem103.setChecked(false);
Menuitem103.setPid(10L);
Menuitem103.setName( “用户管理” );
Menuitem103.setIcon( “css/images/MenuIcon/FUNC20001.gif” );
/**/
/
* {
* 1,1
* 2,5
* 3,5
* 4,1
* 5,3
* 6,6
* 7,1
* 8,3
* 9,2
* 10,3
* }
*/
session.save(Menuitemitem1);
session.save(Menuitem2);
session.save(Menuitem21);
session.save(Menuitem22);
session.save(Menuitem23);
session.save(Menuitem24);
session.save(Menuitem25);
session.save(Menuitem3);
session.save(Menuitem31);
session.save(Menuitem32);
session.save(Menuitem33);
session.save(Menuitem34);
session.save(Menuitem35);
session.save(Menuitem4);
session.save(Menuitem5);
session.save(Menuitem51);
session.save(Menuitem52);
session.save(Menuitem53);
session.save(Menuitem6);
session.save(Menuitem61);
session.save(Menuitem62);
session.save(Menuitem63);
session.save(Menuitem64);
session.save(Menuitem65);
session.save(Menuitem66);
session.save(Menuitem7);
session.save(Menuitem8);
session.save(Menuitem81);
session.save(Menuitem82);
session.save(Menuitem83);
session.save(Menuitem9);
session.save(Menuitem91);
session.save(Menuitem92);
session.save(Menuitem10);
session.save(Menuitem101);
session.save(Menuitem102);
session.save(Menuitem103);
transaction.commit();
session.close();
}
@Test
public void saveMenuitem_Privilege(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring/applicationContext.xml" );
SessionFactory sessionFactory = (SessionFactory)applicationContext.getBean("sessionFactory" );
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
MenuItem Menuitem10 = new MenuItem();
Menuitem10.setMid(11L);
Menuitem10.setIsParent( true);
//Menuitem10.setChecked(false);
Menuitem10.setPid(1L);
Menuitem10.setName( "权限管理" );
Menuitem10.setIcon( "css/images/MenuIcon/system.gif" );
session.save(Menuitem10);
transaction.commit();
session.close();
}
@Test
public void updateMenuitem_Privilege(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring/applicationContext.xml" );
SessionFactory sessionFactory = (SessionFactory)applicationContext.getBean("sessionFactory" );
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
MenuItem Menuitem10 = new MenuItem();
Menuitem10.setMid(11L);
Menuitem10.setIsParent( false);
//Menuitem10.setChecked(false);
Menuitem10.setPid(1L);
Menuitem10.setName( "权限管理" );
Menuitem10.setIcon( "css/images/MenuIcon/system.gif" );
session.update(Menuitem10);
transaction.commit();
session.close();
}
}
<4>写Dao和Service
cn.itheima.oa.dao.MenuItemDao.java
public interface MenuItemDao extends BaseDao{
}
cn.itheima.oa.dao.impl.MenuItemDaoImpl.java
@Repository(“menuItemDao” )
public class MenuItemDaoImpl extends BaseDaoImpl implements MenuItemDao {
}
cn.itheima.oa.service.MenuItemService.java
public interface MenuItemService {
public List getAllMenuItems() throws Exception ;
}
cn.itheima.oa.service.impl.MenuItemServiceImpl.java
@Service (“menuItemService” )
public class MenuItemServiceImpl implements MenuItemService {
@Resource (name="menuItemDao" )
private MenuItemDao menuItemDao ;
public MenuItemDao getMenuItemDao() {
return menuItemDao ;
}
public List<MenuItem> getAllMenuItems() throws Exception {
return (List<MenuItem>) menuItemDao .getAllEntities();
}
}
<5>写Action文件,并且写好配置文件
cn.itheima.oa.action.BaseAction.java
public class BaseAction extends ActionSupport implements ModelDriven {
public Class classt ;
public T t ;
public BaseAction() {
ParameterizedType clazz = (ParameterizedType)this .getClass().getGenericSuperclass();
classt = (Class)clazz.getActualTypeArguments()[0];
try {
t = (T) classt.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
public T getModel() {
return t ;
}
public static final String LISTACTION = "listAction";
public static final String ADD_UI = "addUI";
public static final String UPDATE_UI = "updateUI";
public static final String ACTION2ACTION = "action2action";
public static String listAction = LISTACTION;
public static String add_ui = ADD_UI;
public static String update_ui = UPDATE_UI;
public static String action2action = ACTION2ACTION;
@Resource(name="userService" )
public UserService userService ;
@Resource(name="postService" )
public PostService postService ;
@Resource(name="departmentService" )
public DepartmentService departmentService ;
@Resource(name="menuItemService" )
public MenuItemService menuItemService ;
}
cn.itheima.oa.action.MenuItemAction.java
@Controller(“menuItemAction” )
@Scope(“prototype” )
public class MenuItemAction extends BaseAction {
private List<MenuItem> menuItemList ;
public List<MenuItem> getMenuItemList() {
return menuItemList ;
}
public String getAllMenuItems() throws Exception{
menuItemList = this .menuItemService .getAllMenuItems();
return SUCCESS ;
}
}
struts/struts-menuItem.xml
<?xml version ="1.0" encoding="UTF-8" ?>struts/struts.xml
<?xml version ="1.0" encoding="UTF-8" ?> <package name ="struts-global" namespace="/" extends="struts-default" >
<global-results>
<result name ="errHandler" type="chain" >
<param name ="actionName" >errorProcessor</ param>
</result>
</global-results>
<global-exception-mappings>
<exception-mapping result ="errHandler" exception="java.lang.Exception" >
</exception-mapping>
</global-exception-mappings>
<action name ="errorProcessor" class="cn.itheima.oa.error.ErrorProcessor" >
<result name ="error" >error.jsp</ result>
</action>
</package>
<6>写一个JS文件
var tree = {
setting:{
isSimpleData:true,
treeNodeKey:“mid”,
treeNodeParentKey:“pid”,
showLine:true,
root:{
isRoot:true,
nodes:[]
}
},
loadTree:function(){
$.post(“menuItemAction_getAllMenuItems.action”,null,function(data){
$(“#tree”).zTree(tree.setting,data.menuItemList);
});
}
};
$().ready(function(){
tree.loadTree();
});
运行结果:
23 学习使用zTree(由点击事件触发加载)
.
p
o
s
t
中
的
回
调
函
数
∗
回
调
函
数
是
由
服
务
器
触
发
的
,
所
以
回
调
函
数
的
执
行
和
J
S
客
户
端
的
执
行
是
异
步
的
过
程
,
如
果
J
S
客
户
端
的
代
码
用
到
回
调
函
数
的
值
,
那
么
J
S
的
这
些
代
码
的
执
行
必
须
在
回
调
函
数
执
行
完
毕
以
后
执
行
。
∗
回
调
函
数
的
参
数
不
能
在
.post中的回调函数 * 回调函数是由服务器触发的,所以回调函数的执行和JS客户端的执行是异步的过程,如果JS客户端的代码用到回调函数的值,那么JS的这些代码的执行必须在回调函数执行完毕以后执行。 * 回调函数的参数不能在
.post中的回调函数∗回调函数是由服务器触发的,所以回调函数的执行和JS客户端的执行是异步的过程,如果JS客户端的代码用到回调函数的值,那么JS的这些代码的执行必须在回调函数执行完毕以后执行。∗回调函数的参数不能在.post以外的地方使用。
cn.itheima.oa.dao.MenuItemDao.java
public interface MenuItemDao extends BaseDao{
public List getMenuItemsByPid(Long pid);
}
cn.itheima.oa.dao.impl.MenuItemDaoImpl.java
@Repository(“menuItemDao” )
public class MenuItemDaoImpl extends BaseDaoImpl implements MenuItemDao {
public List<MenuItem> getMenuItemsByPid(Long pid) {
return hibernateTemplate .find("from MenuItem where pid=?",pid);
}
}
cn.itheima.oa.service.MenuItemService.java
public interface MenuItemService {
public List getAllMenuItems() throws Exception ;
public List<MenuItem> getMenuItemsByPid(Long pid);
}
cn.itheima.oa.service.impl.MenuItemServiceImpl.java
@Service(“menuItemService” )
public class MenuItemServiceImpl implements MenuItemService {
@Resource(name="menuItemDao" )
private MenuItemDao menuItemDao ;
public MenuItemDao getMenuItemDao() {
return menuItemDao ;
}
public List<MenuItem> getAllMenuItems() throws Exception {
return (List<MenuItem>) menuItemDao .getAllEntities();
}
public List<MenuItem> getMenuItemsByPid(Long pid) {
return menuItemDao .getMenuItemsByPid(pid);
}
}
cn.itheima.oa.action.MenuItemAction.java
@Controller(“menuItemAction” )
@Scope(“prototype” )
public class MenuItemAction extends BaseAction {
private List<MenuItem> menuItemList ;
public List<MenuItem> getMenuItemList() {
return menuItemList ;
}
public String showAllMenuItems() throws Exception{
menuItemList = this .menuItemService .getAllMenuItems();
return SUCCESS ;
}
public String showMenuItemsByPid() {
menuItemList = menuItemService.getMenuItemsByPid(this.getModel().getPid());
return SUCCESS ;
}
}
/WEB-INF/js/tree.js
var tree = {
zTree:‘’ ,
pNode:‘’ ,
setting:{
isSimpleData:true ,
treeNodeKey:“mid” ,
treeNodeParentKey:“pid” ,
showLine:true ,
root:{
isRoot:true ,
nodes:[]
},callback :{
/**
* @param {Object } event 鼠标事件
* @param {Object } treeId 容器ID
* @param {Object } treeNode 当前点击的节点
*/
expand:function (event ,treeId ,treeNode ){
tree.pNode = treeNode ;
tree.loadSubNodes ();
}
}
},
loadRoot:function (){
$. post(“menuItemAction_showMenuItemsByPid.action” ,{pid :0}, function(data){
tree.zTree = $(“#tree” ).zTree (tree .setting ,data .menuItemList );
});
},
loadSubNodes:function (){
if (! tree.zTree.getNodeByParam (“pid”, tree.pNode.mid )) { //当前点击节点不存在子节点
$. post(“menuItemAction_showMenuItemsByPid.action” , {
pid: tree.pNode.mid
}, function (data ){
//把子节点追加到父节点上
tree.zTree.addNodes (tree.pNode , data.menuItemList , true );
});
}
}
};
$().ready(function (){
tree.loadRoot ();
});
/tree.jsp
<%@ page language =“java” import=“java.util.*” pageEncoding=“UTF-8” %>
执行结果:
24 设置权限的初始化部分
1、设置权限五步骤
<1>显示DIV
<2>动态的实现用户名称
<3>全选复选框功能的实现
<4>显示菜单树
<5>保存功能(建立用户和权限之间的关系)
2、具体步骤:
<1>事件的声明
当整个页面加载的时候,声明事件
<2>数据的传递(传递用户的id和menuItemList,插入到数据库)
<3>业务逻辑功能
cn.itheima.oa.domain.User.java
public class User implements Serializable {
private Long uid ;
private String username ;
private String password ;
private String sex ;
private String phone ;
private String email ;
private Department department ;
private Set posts ;
private Set menuItems ;
public Set<MenuItem> getMenuItems() {
return menuItems ;
}
public void setMenuItems (Set<MenuItem> menuItems) {
this.menuItems = menuItems;
}
public Long getUid() {
return uid ;
}
public void setUid(Long uid) {
this.uid = uid;
}
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 String getSex() {
return sex ;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getPhone() {
return phone ;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email ;
}
public void setEmail(String email) {
this.email = email;
}
public Department getDepartment() {
return department ;
}
public void setDepartment(Department department) {
this.department = department;
}
public Set<Post> getPosts() {
return posts ;
}
public void setPosts(Set<Post> posts) {
this.posts = posts;
}
}
cn.itheima.oa.doamin.user.User.hbm.xml
<?xml version ="1.0" encoding="UTF-8" ?> <many-to-one name ="department" class="cn.itheima.oa.domain.Department" column="did" ></many-to-one>
<set name ="posts" table="user_post" >
<key>
<column name ="uid" ></column>
</key>
<many-to-many class ="Post" column="pid" ></many-to-many>
</set>
<set name ="menuItems" table="user_menuItem" >
<key>
<column name ="uid" ></column>
</key>
<many-to-many class ="MenuItem" column="mid" />
</set>
</class>
cn.itheima.oa.domain.MenuItem.java
public class MenuItem implements Serializable {
private Long mid ;
private Long pid ;
private String name ;
private Boolean isParent ;
private String icon ;
private Set users ;
public Set<User> getUsers() {
return users ;
}
public void setUsers(Set<User> users) {
this.users = users;
}
public String getIcon() {
return icon ;
}
public void setIcon(String icon) {
this.icon = icon;
}
public Long getMid() {
return mid ;
}
public void setMid(Long mid) {
this.mid = mid;
}
public Long getPid() {
return pid ;
}
public void setPid(Long pid) {
this.pid = pid;
}
public String getName() {
return name ;
}
public void setName(String name) {
this.name = name;
}
public Boolean getIsParent() {
return isParent ;
}
public void setIsParent(Boolean isParent) {
this.isParent = isParent;
}
}
cn.itheima.oa.domain.MenuItem.hbml.xml
<?xml version ="1.0" encoding="UTF-8" ?>cn.itheima.oa.test.SessionFactoryTest.java
public class SessionFactoryTest extends BaseSpring {
@Test
public void testSessionFactory(){
SessionFactory sessionFactory = (SessionFactory)context .getBean(“sessionFactory”);
}
}
/WEB-INF/js/privilege
var privilege = {
/**
* 初始化的功能
*/
init:{
initCss:function(){
$(“a”).css(“cursor”,“pointer”);
},
initData:function(){
},
initEvent:function(){
/**
* 给设置权限添加单击事件
*/
$("a").unbind("click");
$("a").bind("click",function(){
if($(this).text()=="设置权限"){
//动态显示div
privilege.option.divOption.showDiv();
//给privilege.data.user赋值
privilege.option.userOption.assignUser.apply(this);
//动态显示用户名(这时候this就是这个超链接)
privilege.option.userOption.showUser();
//加载权限树
$("#allchecked").unbind("change");
$("#allchecked").bind("change",function(){
alert(11);
});
$("#savePrivilege").unbind("click");
$("#savePrivilege").bind("click",function(){
alert(12);
});
}
});
}
},
/**
* 数据的声明
*/
data:{
user:{
username:'',
uid:''
},
menuitem_ids:''
},
/**
* 功能的声明
*/
option:{
/**
* div的操作
*/
divOption:{
/**
* 显示div
*/
showDiv:function(){
// $(“#userTitle”).show();
// $(“#privilegeTitle”).show();
// $(“#privilegeContent”).show();
$(“div:hidden”).show();
}
},
/**
* 用户的操作
/
userOption:{
/*
* 动态的显示用户
/
showUser:function(){
$(“#userImage”).text(“用户:” + privilege.data.user.username);
},
assignUser:function(){
privilege.data.user.username = $(this).parent().siblings(“td:first”).text();
privilege.data.user.uid = $(this).parent().siblings(“input[type=‘hidden’]”).val();
}
},
/*
* 权限的操作
/
privilegeTree:{
/*
* 全选功能的实现
*/
checkAll:function(){
},
/**
* 加载权限树
*/
loadPrivilegeTree:function(){
},
/**
* 保存权限
*/
savePrivilege:function(){
}
}
}
}
$().ready(function(){
privilege.init.initCss();
privilege.init.initEvent();
});
/WEB-INF/jsp/user/list.jsp
<%@ page language =“java” import=“java.util.*” pageEncoding=“UTF-8” %>
<%@ include file =“/WEB-INF/jsp/common/common.jsp” %>

<!-- 表头-->
<thead>
<tr align =center valign=middle id= TableTitle>
<td width ="100" >姓名</ td>
<td width ="100" >所属部门</ td>
<td> 备注</td >
<td> 相关操作</td >
</tr>
</thead>
<!--显示数据列表-->
<tbody id ="TableData" class="dataContainer" datakey="userList" >
<s:iterator value ="#uList" >
<tr class ="TableDetail1 template" >
<td>< s:property value="username"/></ td>
<s:hidden name ="uid" ></s:hidden>
<td>< s:property value="department.dname"/></ td>
<td>
<s:iterator value ="posts" >
<s:property value ="pname" />
</s:iterator>
</td>
<td>
<s:a action ="userAction_delete?uid=%{uid}" >删除</ s:a>
<s:a action="userAction_updateUI?uid=%{uid}" >修改</ s:a>
<a> 设置权限</a >
</td>
</tr>
</s:iterator>
</tbody>
</table >
<div id= "TableTail">
<div id ="TableTail_inside" >
<a href ="userAction_addUI.action" ><img src=" ${pageContext.request.contextPath}/css/images/createNew.png" /></ a>
</div>
</div >
<div class="ItemBlock_Title1" id= "userTitle" style="display: none;"><!-- 信息说明 --><div class="ItemBlock_Title1" >
<div>< img border="0" width ="4" height="7" src=" ${pageContext.request.contextPath}/css/blue/images/item_point.gif" />
<s:label name ="userImage" ></s:label>
</div>
</div>
<div class="ItemBlock_Title1" id= "privilegeTitle" style="display: none;"><div class ="ItemBlock_Title1" >
<img border ="0" width="4" height="7" src=" ${pageContext.request.contextPath}/css/blue/images/item_point.gif" />选择权限</ div>
</div>
<!-- 表单内容显示 -->
<div class ="ItemBlockBorder" style="display: none;" id="privilegeContent" >
<div class ="ItemBlock" >
<table cellpadding ="0" cellspacing="0" class="mainForm" >
<!--表头-->
<thead>
<tr align ="LEFT" valign="MIDDLE" id="TableTitle" >
<td width ="300px" style="padding-left: 7px;" >
<!-- 如果把全选元素的id指定为selectAll,并且有函数selectAll(),就会有错。因为有一种用法:可以直接用id引用元素 -->
<input type ="checkbox" id="allchecked" />
<label for="cbSelectAll" >全选</ label>
</td>
</tr>
</thead>
<!--显示数据列表-->
<tbody id ="TableData" >
<tr class ="TableDetail1" >
<!-- 显示权限树 -->
<td>
<ul id ='privilegeTree' class="tree" >
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- 表单操作 -->
<div id ="InputDetailBar" >
<image id ="savePrivilege" src=" ${pageContext.request.contextPath}/css/images/save.png" />
</div>
/WEB-INF/js/privilege.js
var privilege = {
/**
* 初始化的功能
*/
init:{
initCss:function(){
$(“a”).css(“cursor”,“pointer”);
},
initData:function(){
},
initEvent:function(){
/**
* 给设置权限添加单击事件
*/
$("a").unbind("click");
$("a").bind("click",function(){
if($(this).text()=="设置权限"){
//动态显示div
privilege.option.divOption.showDiv();
//给privilege.data.user赋值
privilege.option.userOption.assignUser.apply(this);
//动态显示用户名(这时候this就是这个超链接)
privilege.option.userOption.showUser();
//加载权限树
privilege.option.privilegeTree.loadPrivilegeTree();
/**
* 全选功能的设定
*/
$("#allchecked").unbind("change");
$("#allchecked").bind("change",function(){
privilege.option.privilegeTree.checkAll();
});
}
});
}
},
/**
* 数据的声明
*/
data:{
user:{
username:'',
uid:''
},
menuitem_ids:''
},
/**
* 功能的声明
*/
option:{
/**
* div的操作
*/
divOption:{
/**
* 显示div
*/
showDiv:function(){
$("div:hidden").show();
}
},
/**
* 用户的操作
*/
userOption:{
/**
* 动态的显示用户
*/
showUser:function(){
$("#userImage").text("用户:" + privilege.data.user.username);
},
assignUser:function(){
privilege.data.user.username = $(this).parent().siblings("td:first").text();
privilege.data.user.uid = $(this).parent().siblings("input[type='hidden']").val();
}
},
/**
* 权限的操作
*/
privilegeTree:{
zTree:'',
setting:{
isSimpleData:true,
treeNodeKey:"mid",
treeNodeParentKey:"pid",
showLine:true,
root:{
isRoot:true,
nodes:[]
},
//确定zTree的节点上是否显示Checkbox
checkable:true
},
/**
* 全选功能的实现
*/
checkAll:function(){
if(!$("#allchecked").attr("checked")){
privilege.option.privilegeTree.zTree.checkAllNodes(false);
}else{
privilege.option.privilegeTree.zTree.checkAllNodes(true);
}
},
/**
* 加载权限树
*/
loadPrivilegeTree:function(){
$.post("menuItemAction_showAllMenuItems.action",null,function(data){
privilege.option.privilegeTree.zTree = $("#privilegeTree").zTree(privilege.option.privilegeTree.setting,data.menuItemList);
});
},
/**
* 保存权限
*/
savePrivilege:function(){
}
}
}
}
$().ready(function(){
privilege.init.initCss();
privilege.init.initEvent();
});
/WEB-INF/jsp/common/common.jsp
<%@ taglib uri =“/struts-tags” prefix=“s” %>
/WEB-INF/jsp/user/list.jsp
<%@ page language =“java” import=“java.util.*” pageEncoding=“UTF-8” %>
<%@ include file =“/WEB-INF/jsp/common/common.jsp” %>

<!-- 表头-->
<thead>
<tr align =center valign=middle id= TableTitle>
<td width ="100" >姓名</ td>
<td width ="100" >所属部门</ td>
<td> 备注</td >
<td> 相关操作</td >
</tr>
</thead>
<!--显示数据列表-->
<tbody id ="TableData" class="dataContainer" datakey="userList" >
<s:iterator value ="#uList" >
<tr class ="TableDetail1 template" >
<td>< s:property value="username"/></ td>
<s:hidden name ="uid" ></s:hidden>
<td>< s:property value="department.dname"/></ td>
<td>
<s:iterator value ="posts" >
<s:property value ="pname" />
</s:iterator>
</td>
<td>
<s:a action ="userAction_delete?uid=%{uid}" >删除</ s:a>
<s:a action="userAction_updateUI?uid=%{uid}" >修改</ s:a>
<a> 设置权限</a >
</td>
</tr>
</s:iterator>
</tbody>
</table >
<div id= "TableTail">
<div id ="TableTail_inside" >
<a href ="userAction_addUI.action" ><img src=" ${pageContext.request.contextPath}/css/images/createNew.png" /></ a>
</div>
</div >
<div class="ItemBlock_Title1" id= "userTitle" style="display: none;"><!-- 信息说明 --><div class="ItemBlock_Title1" >
<div>< img border="0" width ="4" height="7" src=" ${pageContext.request.contextPath}/css/blue/images/item_point.gif" />
<s:label name ="userImage" ></s:label>
</div>
</div>
<div class="ItemBlock_Title1" id= "privilegeTitle" style="display: none;"><div class ="ItemBlock_Title1" >
<img border ="0" width="4" height="7" src=" ${pageContext.request.contextPath}/css/blue/images/item_point.gif" />选择权限</ div>
</div>
<!-- 表单内容显示 -->
<div class ="ItemBlockBorder" style="display: none;" id="privilegeContent" >
<div class ="ItemBlock" >
<table cellpadding ="0" cellspacing="0" class="mainForm" >
<!--表头-->
<thead>
<tr align ="LEFT" valign="MIDDLE" id="TableTitle" >
<td width ="300px" style="padding-left: 7px;" >
<!-- 如果把全选元素的id指定为selectAll,并且有函数selectAll(),就会有错。因为有一种用法:可以直接用id引用元素 -->
<input type ="checkbox" id="allchecked" />
<label for="cbSelectAll" >全选</ label>
</td>
</tr>
</thead>
<!--显示数据列表-->
<tbody id ="TableData" >
<tr class ="TableDetail1" >
<!-- 显示权限树 -->
<td>
<ul id ='privilegeTree' class="tree" >
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- 表单操作 -->
<div id ="InputDetailBar" >
<image id ="savePrivilege" src=" ${pageContext.request.contextPath}/css/images/save.png" />
</div>
26 根据用户的权限是否全部选中来确定全选checkbox状态
<1>设置全选checkbox为不可编辑状态
<2>权限树加载完毕之后,再设置为可编辑状态。
<3>并且判断是不是所有的节点选中了,如果选中了,则全选checkbox也设置为选中,否则,设置为未选中。
/WEB-INF/js/privilege.js
var privilege = {
init:{
initCss:function(){
$(“a”).css(“cursor”,“pointer”);
},
initData:function(){
},
initEvent:function(){
$("a").unbind("click");
$("a").bind("click",function(){
if($(this).text()=="设置权限"){
privilege.option.divOption.showDiv();
privilege.option.userOption.assignUser.apply(this);
privilege.option.userOption.showUser();
privilege.option.privilegeTree.loadPrivilegeTree();
$("#allchecked").unbind("change");
$("#allchecked").bind("change",function(){
privilege.option.privilegeTree.checkAll();
});
}
});
}
},
data:{
user:{
username:'',
uid:''
},
menuitem_ids:''
},
option:{
divOption:{
showDiv:function(){
$("div:hidden").show();
}
},
userOption:{
showUser:function(){
$("#userImage").text("用户:" + privilege.data.user.username);
},
assignUser:function(){
privilege.data.user.username = $(this).parent().siblings("td:first").text();
privilege.data.user.uid = $(this).parent().siblings("input[type='hidden']").val();
}
},
privilegeTree:{
zTree:'',
setting:{
isSimpleData:true,
treeNodeKey:"mid",
treeNodeParentKey:"pid",
showLine:true,
root:{
isRoot:true,
nodes:[]
},
checkable:true
},
checkAll:function(){
if(!$("#allchecked").attr("checked")){
privilege.option.privilegeTree.zTree.checkAllNodes(false);
}else{
privilege.option.privilegeTree.zTree.checkAllNodes(true);
}
},
loadPrivilegeTree:function(){
$.post("menuItemAction_showAllMenuItems.action",null,function(data){
privilege.option.privilegeTree.zTree = $("#privilegeTree").zTree(privilege.option.privilegeTree.setting,data.menuItemList);
$("#allchecked").attr("disabled","");
if(privilege.option.privilegeTree.allChecked()){
$("#allchecked").attr("checked","checked");
}else{
$("#allchecked").attr("checked","");
}
});
},
savePrivilege:function(){
},
/**
* 判断树上所有的菜单是不是全部选中了
*/
allChecked:function(){
var uncheckedNodes = privilege.option.privilegeTree.zTree.getCheckedNodes(false);
if(uncheckedNodes.length == 0){
return true;
}else{
return false;
}
}
}
}
}
$().ready(function(){
privilege.init.initCss();
privilege.init.initEvent();
});
/WEB-INF/jsp/user/list.jsp
<%@ page language =“java” import=“java.util.*” pageEncoding=“UTF-8” %>
<%@ include file =“/WEB-INF/jsp/common/common.jsp” %>

<!-- 表头-->
<thead>
<tr align =center valign=middle id= TableTitle>
<td width ="100" >姓名</ td>
<td width ="100" >所属部门</ td>
<td> 备注</td >
<td> 相关操作</td >
</tr>
</thead>
<!--显示数据列表-->
<tbody id ="TableData" class="dataContainer" datakey="userList" >
<s:iterator value ="#uList" >
<tr class ="TableDetail1 template" >
<td>< s:property value="username"/></ td>
<s:hidden name ="uid" ></s:hidden>
<td>< s:property value="department.dname"/></ td>
<td>
<s:iterator value ="posts" >
<s:property value ="pname" />
</s:iterator>
</td>
<td>
<s:a action ="userAction_delete?uid=%{uid}" >删除</ s:a>
<s:a action="userAction_updateUI?uid=%{uid}" >修改</ s:a>
<a> 设置权限</a >
</td>
</tr>
</s:iterator>
</tbody>
</table >
<div id= "TableTail">
<div id ="TableTail_inside" >
<a href ="userAction_addUI.action" ><img src=" ${pageContext.request.contextPath}/css/images/createNew.png" /></ a>
</div>
</div >
<div class="ItemBlock_Title1" id= "userTitle" style="display: none;"><!-- 信息说明 --><div class="ItemBlock_Title1" >
<div>< img border="0" width ="4" height="7" src=" ${pageContext.request.contextPath}/css/blue/images/item_point.gif" />
<s:label name ="userImage" ></s:label>
</div>
</div>
<div class="ItemBlock_Title1" id= "privilegeTitle" style="display: none;"><div class ="ItemBlock_Title1" >
<img border ="0" width="4" height="7" src=" ${pageContext.request.contextPath}/css/blue/images/item_point.gif" />选择权限</ div>
</div>
<!-- 表单内容显示 -->
<div class ="ItemBlockBorder" style="display: none;" id="privilegeContent" >
<div class ="ItemBlock" >
<table cellpadding ="0" cellspacing="0" class="mainForm" >
<!--表头-->
<thead>
<tr align ="LEFT" valign="MIDDLE" id="TableTitle" >
<td width ="300px" style="padding-left: 7px;" >
<!-- 如果把全选元素的id指定为selectAll,并且有函数selectAll(),就会有错。因为有一种用法:可以直接用id引用元素 -->
<input type ="checkbox" id="allchecked" disabled="disabled" />
<label for="cbSelectAll" >全选</ label>
</td>
</tr>
</thead>
<!--显示数据列表-->
<tbody id ="TableData" >
<tr class ="TableDetail1" >
<!-- 显示权限树 -->
<td>
<ul id ='privilegeTree' class="tree" >
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- 表单操作 -->
<div id ="InputDetailBar" >
<image id ="savePrivilege" src=" ${pageContext.request.contextPath}/css/images/save.png" />
</div>
27 改变选中某个checkbox的影响逻辑
<1>改变zTree的checkbox的选中与未选中的影响逻辑:被选中之后,则父节点被选中,子节点无影响。但是如果解除选中,则父节点无影响,子节点全部改为未选中状态。
<2>这时候可以利用checkType改变这个影响逻辑,但是一旦改变之后又会影响全选checkbox的逻辑,所以必须在全选checkbox之前再把checkType改回去。
<3>最后要解决的一个问题是,如果子节点如果并没有完全选中,那么全选checkbox也要做出相应的改变。
/WEB-INF/js/privilege.js
var privilege = {
init:{
initCss:function(){
$(“a”).css(“cursor”,“pointer”);
},
initData:function(){
},
initEvent:function(){
$("a").unbind("click");
$("a").bind("click",function(){
if($(this).text()=="设置权限"){
privilege.option.divOption.showDiv();
privilege.option.userOption.assignUser();
privilege.option.userOption.showUser();
privilege.option.privilegeTree.loadPrivilegeTree();
$("#allchecked").unbind("change");
$("#allchecked").bind("change",function(){
privilege.option.privilegeTree.checkAll();
});
}
});
}
},
data:{
user:{
username:'',
uid:''
},
menuitem_ids:''
},
option:{
divOption:{
showDiv:function(){
$("div:hidden").show();
}
},
userOption:{
showUser:function(){
$("#userImage").text("用户:" + privilege.data.user.username);
},
assignUser:function(){
privilege.data.user.username = $(this).parent().siblings("td:first").text();
privilege.data.user.uid = $(this).parent().siblings("input[type='hidden']").val();
}
},
privilegeTree:{
zTree:'',
setting:{
isSimpleData:true,
treeNodeKey:"mid",
treeNodeParentKey:"pid",
showLine:true,
root:{
isRoot:true,
nodes:[]
},
checkable:true,
callback:{
beforeChange:function(){
privilege.option.privilegeTree.changeCheckType({
'Y':'p',
'N':'s'
});
},change:function(){
if(privilege.option.privilegeTree.allChecked()){
$("#allchecked").attr("checked","checked");
}else{
$("#allchecked").attr("checked","");
}
}
}
},
checkAll:function(){
privilege.option.privilegeTree.changeCheckType({
'Y':'ps',
'N':'ps'
});
if(!$("#allchecked").attr("checked")){
privilege.option.privilegeTree.zTree.checkAllNodes(false);
}else{
privilege.option.privilegeTree.zTree.checkAllNodes(true);
}
},
loadPrivilegeTree:function(){
$.post("menuItemAction_showAllMenuItems.action",null,function(data){
privilege.option.privilegeTree.zTree = $("#privilegeTree").zTree(privilege.option.privilegeTree.setting,data.menuItemList);
$("#allchecked").attr("disabled","");
if(privilege.option.privilegeTree.allChecked()){
$("#allchecked").attr("checked","checked");
}else{
$("#allchecked").attr("checked","");
}
});
},
savePrivilege:function(){
},
/**
* 判断树上所有的菜单是不是全部选中了
*/
allChecked:function(){
var uncheckedNodes = privilege.option.privilegeTree.zTree.getCheckedNodes(false);
if(uncheckedNodes.length == 0){
return true;
}else{
return false;
}
},
/**
* 改变setting中的checkType
*/
changeCheckType:function(checkType){
var setting = privilege.option.privilegeTree.zTree.setting;
setting.checkType = checkType;
privilege.option.privilegeTree.zTree.updateSetting(setting);
}
}
}
}
$().ready(function(){
privilege.init.initCss();
privilege.init.initEvent();
});
28 保存用户与菜单之间的关系
注:JSONResult没有加载懒加载集合代理的能力,所以,一旦出现情况就会报错。以前使用的结果集有这种功能,所以没有报错。
cn.itheima.oa.dao.UserDao.java
public interface UserDao extends BaseDao{
public Set getUsers();
public User getUserById(Serializable uid);
public User getUserByName(String username);
public Set<MenuItem> getMenuItemsByMids(String mids);
}
cn.itheima.oa.dao.impl.UserDaoImpl.java
@Repository(“userDao” )
public class UserDaoImpl extends BaseDaoImpl implements UserDao {
public Set<User> getUsers() {
return new HashSet(this. hibernateTemplate.find("from User u left outer join fetch u.department d left outer join fetch u.posts p"));
}
public User getUserById(Serializable uid) {
List<User> uList = this.hibernateTemplate .find("from User u left outer join fetch u.posts p left outer join fetch u.department d where u.uid=" + uid);
if(uList.size()==0){
return null ;
} else{
return uList.get(0);
}
}
public User getUserByName(String username) {
List<User> uList = this.hibernateTemplate .find("from User u where u.username=?",username);
if(uList.size()==0){
return null ;
} else{
return uList.get(0);
}
}
public Set<MenuItem> getMenuItemsByMids(String mids) {
//这里一定要小心如果是通过?参数传递进去,就会自动加上单引号,一定要小心!
return new HashSet<MenuItem>(this .hibernateTemplate .find("from MenuItem m where m.mid in (" + mids + ")"));
}
}
cn.itheima.oa.service.UserService.java
public interface UserService {
public Set getAllUsers() throws Exception;
public void saveUser(User user) throws Exception;
public void deleteUser(Serializable uid) throws Exception;
public void updateUser(User user) throws Exception;
public User getUserById(Serializable uid) throws Exception;
public User getUserByName(String username) throws Exception;
public Set<MenuItem> getMenuItemsByMids (String mids);
}
cn.itheima.oa.service.impl.UserServiceImpl.java
@Service(“userService” )
public class UserServiceImpl implements UserService {
@Resource(name="userDao" )
private UserDao userDao ;
public UserDao getUserDao() {
return userDao ;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Transactional(readOnly=false)
public void deleteUser(Serializable uid) throws Exception {
this.userDao .deleteEntity(uid);
}
public Set<User> getAllUsers() throws Exception {
return new HashSet(userDao.getAllEntities());
}
public User getUserById(Serializable uid)
throws Exception {
return (User) userDao .getUserById(uid);
}
@Transactional(readOnly=false)
public void saveUser(User user) throws Exception {
this.userDao .saveEntity(user);
}
@Transactional(readOnly=false)
public void updateUser(User user) throws Exception {
userDao.updateEntity(user);
}
public User getUserByName(String username) throws Exception {
return userDao .getUserByName(username);
}
public Set<MenuItem> getMenuItemsByMids(String mids) {
return userDao .getMenuItemsByMids(mids);
}
}
cn.itheima.oa.action.UserAction.java
@Controller(“userAction” )
@Scope(“prototype” )
public class UserAction extends BaseAction {
private String mids ;
public String getMids() {
return mids ;
}
public void setMids(String mids) {
this.mids = mids;
}
private Long did ;
//action中可以创建基本类型的数组形式的属性,模型驱动也可以进行转化
private Long[] pids ;
private String message ;
public String getMessage() {
return message ;
}
public void setMessage(String message) {
this.message = message;
}
public Long getDid() {
return did ;
}
public void setDid(Long did) {
this.did = did;
}
public Long[] getPids() {
return pids ;
}
public void setPids(Long[] pids) {
this.pids = pids;
}
@Resource(name="userService" )
private UserService userService ;
@JSON(serialize=false)
public UserService getUserService() {
return userService ;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
public String showUsers() throws Exception {
Collection<User> users = userService.getAllUsers();
ActionContext. getContext().put("uList", users);
return listAction ;
}
public String delete() throws Exception {
this.userService .deleteUser(this.getModel().getUid());
return action2action ;
}
public String addUI() throws Exception {
Collection<Department> dList = this.departmentService .getAllDepartments();
Collection<Post> pList = this.postService .getAllPosts();
ActionContext. getContext().put("dList", dList);
ActionContext. getContext().put("pList", pList);
return add_ui ;
}
public String add() throws Exception {
/**
* 因为用户和部门之间是多对一的关系,用户负责维护关系,所以在保存用户的坏死后,会自动建立用户和部门之间的关系。
* 因为用户和岗位之间是多对多的关系,谁维护关系都行,所以在保存用户的时候,会自动建立用户和岗位之间的关系。
*/
Department department = this.departmentService .getDepartmentById(this. did);
Set<Post> posts = this.postService .getPostsByIds(pids);
User user = new User();
BeanUtils. copyProperties(this.getModel(), user);
user.setDepartment(department);
user.setPosts(posts);
this.userService .saveUser(user);
return action2action ;
}
public String updateUI() throws Exception {
User user = userService.getUserById(this.getModel().getUid());
ActionContext. getContext().getValueStack().push(user);
this.did = user.getDepartment().getDid();
Set<Post> posts = user.getPosts();
this.pids = new Long[posts.size()];
int index = 0;
for(Post post : posts){
pids[index++] = post.getPid();
}
Collection<Department> dList = this.departmentService .getAllDepartments();
Collection<Post> pList = this.postService .getAllPosts();
ActionContext. getContext().put("dList", dList);
ActionContext. getContext().put("pList", pList);
return update_ui ;
}
public String update() throws Exception {
User user = userService.getUserById(this.getModel().getUid());
BeanUtils. copyProperties(this.getModel(), user);
Department department = departmentService.getDepartmentById(this.did);
user.setDepartment(department);
Set<Post> posts = postService.getPostsByIds(pids );
user.setPosts(posts);
userService.updateUser(user);
return action2action ;
}
public String checkUser() throws Exception {
User user = this.userService .getUserByName(this.getModel().getUsername());
if(user == null){
message = "此用户名可以使用" ;
} else{
message = "此用户名已被占用,不能使用!" ;
}
return SUCCESS ;
}
public String savePrivileges() throws Exception{
User user = this.userService .getUserById(this.getModel().getUid());
Set<MenuItem> menuItems = this.userService .getMenuItemsByMids(mids);
user.setMenuItems( menuItems);
userService.updateUser(user);
this.message = "保存成功";
return SUCCESS ;
}
}
/WEB-INF/js/privilege.js
var privilege = {
init:{
initCss:function(){
$(“a”).css(“cursor”,“pointer”);
},
initData:function(){
},
initEvent:function(){
$("a").unbind("click");
$("a").bind("click",function(){
if($(this).text()=="设置权限"){
privilege.option.divOption.showDiv();
privilege.option.userOption.assignUser.apply(this);
privilege.option.userOption.showUser();
privilege.option.privilegeTree.loadPrivilegeTree();
$("#allchecked").unbind("change");
$("#allchecked").bind("change",function(){
privilege.option.privilegeTree.checkAll();
});
$("#savePrivilege").unbind("click");
$("#savePrivilege").bind("click",function(){
privilege.option.privilegeTree.savePrivilege();
});
}
});
}
},
data:{
user:{
username:'',
uid:''
},
menuitem_ids:''
},
option:{
divOption:{
showDiv:function(){
$("div:hidden").show();
}
},
userOption:{
showUser:function(){
$("#userImage").text("用户:" + privilege.data.user.username);
},
assignUser:function(){
privilege.data.user.username = $(this).parent().siblings("td:first").text();
privilege.data.user.uid = $(this).parent().siblings("input[type='hidden']").val();
}
},
privilegeTree:{
zTree:'',
setting:{
isSimpleData:true,
treeNodeKey:"mid",
treeNodeParentKey:"pid",
showLine:true,
root:{
isRoot:true,
nodes:[]
},
checkable:true,
callback:{
beforeChange:function(){
privilege.option.privilegeTree.changeCheckType({
'Y':'p',
'N':'s'
});
},change:function(){
if(privilege.option.privilegeTree.allChecked()){
$("#allchecked").attr("checked","checked");
}else{
$("#allchecked").attr("checked","");
}
}
}
},
checkAll:function(){
privilege.option.privilegeTree.changeCheckType({
'Y':'ps',
'N':'ps'
});
if(!$("#allchecked").attr("checked")){
privilege.option.privilegeTree.zTree.checkAllNodes(false);
}else{
privilege.option.privilegeTree.zTree.checkAllNodes(true);
}
},
loadPrivilegeTree:function(){
$.post("menuItemAction_showAllMenuItems.action",null,function(data){
privilege.option.privilegeTree.zTree = $("#privilegeTree").zTree(privilege.option.privilegeTree.setting,data.menuItemList);
$("#allchecked").attr("disabled","");
if(privilege.option.privilegeTree.allChecked()){
$("#allchecked").attr("checked","checked");
}else{
$("#allchecked").attr("checked","");
}
});
},
/**
* 保存权限
*/
savePrivilege:function(){
var mids="";
var checkedNodes = privilege.option.privilegeTree.zTree.getCheckedNodes(true);
for(var i = 0; i < checkedNodes.length; i++){
if(i == checkedNodes.length-1){
mids += checkedNodes[i].mid;
}else{
mids += checkedNodes[i].mid + ",";
}
}
var parameter = {
mids:mids,
uid:privilege.data.user.uid
}
$.post("userJsonAction_savePrivileges.action",parameter,function(data){
alert(data.message);
});
},
allChecked:function(){
var uncheckedNodes = privilege.option.privilegeTree.zTree.getCheckedNodes(false);
if(uncheckedNodes.length == 0){
return true;
}else{
return false;
}
},
changeCheckType:function(checkType){
var setting = privilege.option.privilegeTree.zTree.setting;
setting.checkType = checkType;
privilege.option.privilegeTree.zTree.updateSetting(setting);
}
}
}
}
$().ready(function(){
privilege.init.initCss();
privilege.init.initEvent();
});
执行结果:
成功插入数据:
但是当再点击超链接的时候,就看不到菜单了。
这时候有三种方案解决问题,一种是在MenuItemAction中的showAllMenuItems方法中设置User为null。
第二种是在MenuItem中在User属性上打上@JSON标记。
以上这两种方法都相当于将User属性过滤掉。就不会出现懒加载的问题了。
第三种是使用inner join或者lefter outer join一次性将所有的内容加载出来。这样就避免了懒加载,但是这时候仍然会失败,因为User中还有Posts这个Set类型属性,所以依然会出现懒加载问题,这时候也必须按照以上三种方式之一再处理一次。
29 用户可用菜单的回显
如果一个treeNode的checked属性设置为true,那么这个菜单就会选中。所以需要给MenuItem设置一个checked属性。
cn.itheima.oa.domain.MenuItem.java
public class MenuItem implements Serializable {
private Long mid ;
private Long pid ;
private String name ;
private Boolean isParent ;
private String icon ;
private Set users ;
private Boolean checked ;
public Boolean getChecked() {
return checked ;
}
public void setChecked(Boolean checked) {
this.checked = checked;
}
@JSON(serialize=false)
public Set<User> getUsers() {
return users ;
}
public void setUsers(Set<User> users) {
this.users = users;
}
public String getIcon() {
return icon ;
}
public void setIcon(String icon) {
this.icon = icon;
}
public Long getMid() {
return mid ;
}
public void setMid(Long mid) {
this.mid = mid;
}
public Long getPid() {
return pid ;
}
public void setPid(Long pid) {
this.pid = pid;
}
public String getName() {
return name ;
}
public void setName(String name) {
this.name = name;
}
public Boolean getIsParent() {
return isParent ;
}
public void setIsParent(Boolean isParent) {
this.isParent = isParent;
}
}
cn.itheima.oa.dao.MenuItem.hbm.xml
<?xml version ="1.0" encoding="UTF-8" ?>cn.itheima.oa.dao.MenuItemDao.java
public interface MenuItemDao extends BaseDao{
public List getMenuItemsByPid(Long pid);
public Set<MenuItem> getMenuItemsByUid (Long uid) throws Exception;
}
cn.itheima.oa.dao.impl.MenuItemDaoImpl.java
@Repository(“menuItemDao” )
public class MenuItemDaoImpl extends BaseDaoImpl implements MenuItemDao {
public List<MenuItem> getMenuItemsByPid(Long pid) {
return hibernateTemplate .find("from MenuItem where pid=?",pid);
}
public Set<MenuItem> getMenuItemsByUid(Long uid) throws Exception {
Set<MenuItem> allMenuItems = new HashSet<MenuItem>(this .getAllEntities());
Set<MenuItem> menuItems = new HashSet<MenuItem>(hibernateTemplate .find("from MenuItem m inner join fetch m.users u where u.uid=?",uid));
for(MenuItem menuItem : allMenuItems){
for(MenuItem menuItem2 : menuItems){
if(menuItem.getMid().longValue() == menuItem2.getMid().longValue()){
menuItem.setChecked( true);
break;
}
}
}
return allMenuItems;
}
}
cn.itheima.oa.service.MenuItemService.java
public interface MenuItemService {
public List getAllMenuItems() throws Exception ;
public List<MenuItem> getMenuItemsByPid(Long pid);
public Set<MenuItem> getMenuItemsByUid(Long uid) throws Exception ;
}
cn.itheima.oa.service.impl.MenuItemServiceImpl.java
@Service(“menuItemService” )
public class MenuItemServiceImpl implements MenuItemService {
@Resource(name="menuItemDao" )
private MenuItemDao menuItemDao ;
public MenuItemDao getMenuItemDao() {
return menuItemDao ;
}
public List<MenuItem> getAllMenuItems() throws Exception {
return (List<MenuItem>) menuItemDao .getAllEntities();
}
public List<MenuItem> getMenuItemsByPid(Long pid) {
return menuItemDao .getMenuItemsByPid(pid);
}
public Set<MenuItem> getMenuItemsByUid (Long uid) throws Exception {
return menuItemDao .getMenuItemsByUid(uid);
}
}
cn.itheima.action.MenuItemAction.java
@Controller(“menuItemAction” )
@Scope(“prototype” )
public class MenuItemAction extends BaseAction {
private Long uid ;
private List<MenuItem> menuItemList ;
public Long getUid() {
return uid ;
}
public void setUid(Long uid) {
this.uid = uid;
}
public void setMenuItemList(List<MenuItem> menuItemList) {
this.menuItemList = menuItemList;
}
public List<MenuItem> getMenuItemList() {
return menuItemList ;
}
public String showAllMenuItems() throws Exception{
menuItemList = this .menuItemService .getAllMenuItems();
return SUCCESS ;
}
public String showMenuItemsByPid() {
menuItemList = menuItemService.getMenuItemsByPid(this.getModel().getPid());
return SUCCESS ;
}
public String showMenuItems() throws Exception{
menuItemList = new ArrayList(this.menuItemService .getMenuItemsByUid(this. uid));
return SUCCESS ;
}
}
/WEB-INF/js/privilege.js
var privilege = {
init:{
initCss:function(){
$("a").css("cursor","pointer");
},
initData:function(){
},
initEvent:function(){
$("a").unbind("click");
$("a").bind("click",function(){
if($(this).text()=="设置权限"){
privilege.option.divOption.showDiv();
privilege.option.userOption.assignUser.apply(this);
privilege.option.userOption.showUser();
privilege.option.privilegeTree.loadPrivilegeTree();
$("#allchecked").unbind("change");
$("#allchecked").bind("change",function(){
privilege.option.privilegeTree.checkAll();
});
$("#savePrivilege").unbind("click");
$("#savePrivilege").bind("click",function(){
privilege.option.privilegeTree.savePrivilege();
});
}
});
}
},
data:{
user:{
username:'',
uid:''
},
menuitem_ids:''
},
option:{
divOption:{
showDiv:function(){
$("div:hidden").show();
}
},
userOption:{
showUser:function(){
$("#userImage").text("用户:" + privilege.data.user.username);
},
assignUser:function(){
privilege.data.user.username = $(this).parent().siblings("td:first").text();
privilege.data.user.uid = $(this).parent().siblings("input[type='hidden']").val();
}
},
privilegeTree:{
zTree:'',
setting:{
isSimpleData:true,
treeNodeKey:"mid",
treeNodeParentKey:"pid",
showLine:true,
root:{
isRoot:true,
nodes:[]
},
checkable:true,
callback:{
beforeChange:function(){
privilege.option.privilegeTree.changeCheckType({
'Y':'p',
'N':'s'
});
},change:function(){
if(privilege.option.privilegeTree.allChecked()){
$("#allchecked").attr("checked","checked");
}else{
$("#allchecked").attr("checked","");
}
}
}
},
checkAll:function(){
privilege.option.privilegeTree.changeCheckType({
'Y':'ps',
'N':'ps'
});
if(!$("#allchecked").attr("checked")){
privilege.option.privilegeTree.zTree.checkAllNodes(false);
}else{
privilege.option.privilegeTree.zTree.checkAllNodes(true);
}
},
loadPrivilegeTree:function(){
$.post("menuItemAction_showMenuItems.action",{
uid:privilege.data.user.uid
},function(data){
privilege.option.privilegeTree.zTree = $("#privilegeTree").zTree(privilege.option.privilegeTree.setting,data.menuItemList);
$("#allchecked").attr("disabled","");
if(privilege.option.privilegeTree.allChecked()){
$("#allchecked").attr("checked","checked");
}else{
$("#allchecked").attr("checked","");
}
});
},
/**
* 保存权限
*/
savePrivilege:function(){
var mids="";
var checkedNodes = privilege.option.privilegeTree.zTree.getCheckedNodes(true);
for(var i = 0; i < checkedNodes.length; i++){
if(i == checkedNodes.length-1){
mids += checkedNodes[i].mid;
}else{
mids += checkedNodes[i].mid + ",";
}
}
var parameter = {
mids:mids,
uid:privilege.data.user.uid
}
$.post("userJsonAction_savePrivileges.action",parameter,function(data){
alert(data.message);
});
},
allChecked:function(){
var uncheckedNodes = privilege.option.privilegeTree.zTree.getCheckedNodes(false);
if(uncheckedNodes.length == 0){
return true;
}else{
return false;
}
},
changeCheckType:function(checkType){
var setting = privilege.option.privilegeTree.zTree.setting;
setting.checkType = checkType;
privilege.option.privilegeTree.zTree.updateSetting(setting);
}
}
}
}
$().ready(function(){
privilege.init.initCss();
privilege.init.initEvent();
});
30 登陆页面
LoginAction{
login(){
//判断用户名和密码是否正确
如果正确
把user放入到session中
如果不正确
跳转到登陆页面
}
logout(){
把session中的资源进行清空
}
}
/WEB-INF/web.xml
/WEB-INF/jsp/frame/login.jsp
<%@ page language =“java” import=“java.util.*” pageEncoding=“UTF-8” %>
<%@ include file =“/WEB-INF/jsp/common/common.jsp” %>

![]() | < s:textfield cssClass= "TextField" name="username" size="20" > | |
![]() | < s:password cssClass= "TextField" name="password" size="20" > |
/WEB-INF/jsp/frame/index.jsp
<%@ page language =“java” import=“java.util.*” pageEncoding=“UTF-8” %>
<%@ include file =“/WEB-INF/jsp/common/common.jsp” %>
/WEB-INF/jsp/frame/top.jsp
<%@ page language =“java” import=“java.util.*” pageEncoding=“UTF-8” %>
<%@ include file =“/WEB-INF/jsp/common/common.jsp” %>
<div id ="Head1" >
<div id ="Logo" >
<a id ="msgLink" href="javascript:void(0)" ></a>
<font color ="#0000CC" style="color:#F1F9FE; font-size:28px; font-family:Arial Black, Arial"> Itcast OA</font >
<!--<img border="0" src="${pageContext.request.contextPath}/css/blue/images/logo.png" />-->
</div>
<div id ="Head1Right" >
<div id ="Head1Right_UserName" >
<img border ="0" width="13" height="14" src=" ${pageContext.request.contextPath}/css/images/top/user.gif" /> 您好,<b >管理员</ b>
</div>
<div id ="Head1Right_UserDept" ></div>
<div id ="Head1Right_UserSetup" >
<a href ="javascript:void(0)" >
<img border ="0" width="13" height="14" src=" ${pageContext.request.contextPath}/css/images/top/user_setup.gif" /> 个人设置
</a>
</div>
<div id ="Head1Right_Time" ></div>
</div>
<div id ="Head1Right_SystemButton" >
<a target ="_parent" href="System_User/logout.html" >
<img width ="78" height="20" alt="退出系统" src=" ${pageContext.request.contextPath}/css/blue/images/top/logout.gif" />
</a>
</div>
<div id ="Head1Right_Button" >
<a target ="desktop" href="/desktop?method=show" >
<img width ="65" height="20" alt="显示桌面" src=" ${pageContext.request.contextPath}/css/blue/images/top/desktop.gif" />
</a>
</div>
</div>
<div id= "Head2">
<div id ="Head2_Awoke" >
<ul id ="AwokeNum" >
<li>< a target="desktop" href ="javascript:void(0)" >
<img border ="0" width="11" height="13" src=" ${pageContext.request.contextPath}/css/images/top/msg.gif" /> 消息
<span id ="msg" ></span>
</a>
</li>
<li class ="Line" ></li>
<li>< a target="desktop" href ="javascript:void(0)" >
<img border ="0" width="16" height="11" src=" ${pageContext.request.contextPath}/css/images/top/mail.gif" /> 邮件
<span id ="mail" ></span>
</a>
</li>
<li class ="Line" ></li>
<!-- 是否有待审批文档的提示1,数量 -->
<li>< a href="Flow_Formflow/myTaskList.html" target="desktop" >
<img border ="0" width="12" height="14" src=" ${pageContext.request.contextPath}/css/images/top/wait.gif" />
待办事项( <span id ="wait" class="taskListSize" >1</ span>)
</a>
</li>
<!-- 是否有待审批文档的提示2,提示审批 -->
<li id ="messageArea" >您有 1 个待审批文档,请及时审批!★★★★★ </li>
</ul>
</div>
<div id ="Head2_FunctionList" >
<marquee style ="WIDTH: 100%;" onMouseOver="this.stop()" onMouseOut="this.start()"
scrollamount=1 scrolldelay=30 direction=left >
<b> 这是滚动的消息 </b>
</marquee>
</div>
</div>
/WEB-INF/jsp/frame/left.jsp
<%@ page language =“java” import=“java.util.*” pageEncoding=“UTF-8” %>
<%@ include file =“/WEB-INF/jsp/common/common.jsp” %>
|
/WEB-INF/jsp/frame/right.jsp
<%@ page language =“java” import=“java.util.*” pageEncoding=“UTF-8” %>
<%@ include file =“/WEB-INF/jsp/common/common.jsp” %>
/WEB-INF/jsp/frame/bottom.jsp
<%@ page language =“java” import=“java.util.*” pageEncoding=“UTF-8” %>
<%@ include file =“/WEB-INF/jsp/common/common.jsp” %>
cn.itheima.oa.dao.LoginDao.java
public interface LoginDao {
public User getUserByUAndP(String username,String password);
}
cn.itheima.oa.dao.impl.LoginDaoImpl.java
@Repository(“loginDao” )
public class LoginDaoImpl implements LoginDao {
@Resource(name="hibernateTemplate" )
private HibernateTemplate hibernateTemplate ;
public User getUserByUAndP(String username, String password ) {
List<User> user = hibernateTemplate.find("from User where username=? and password=?",new Object[]{username, password});
if(user.size()==0){
return null ;
} else{
return user.get(0);
}
}
}
cn.itheima.oa.service.LoginService.java
public interface LoginService {
public User login(String username,String password);
}
cn.itheima.oa.service.impl.LoginServiceImpl.java
@Service(“loginService” )
public class LoginServiceImpl implements LoginService {
@Resource(name="loginDao" )
private LoginDao loginDao ;
public User login(String username, String password) {
return loginDao .getUserByUAndP(username, password);
}
}
cn.itheima.oa.action.LoginAction.java
@Controller(“loginAction” )
@Scope(“prototype” )
public class LoginAction extends ActionSupport implements ModelDriven {
private User user = new User();
@Resource(name="loginService" )
private LoginService loginService ;
public User getModel() {
return user ;
}
public String login(){
User user = loginService.login(this.getModel().getUsername(), this.getModel().getPassword());
if(user==null){
return "login" ;
} else{
ServletActionContext. getRequest().getSession().setAttribute("user", user);
return "index" ;
}
}
public String logout(){
ServletActionContext. getRequest().getSession().removeAttribute("user");
return "login" ;
}
}
cn.itheima.oa.action.ForwardAction.java
@Controller(“forwardAction” )
@Scope(“prototype” )
public class ForwardAction extends ActionSupport {
private String method ;
public String getMethod() {
return method ;
}
public void setMethod(String method) {
this.method = method;
}
public String forward(){
return method ;
}
}
/WEB-INF/jsp/common/common.jsp
<%@ taglib uri =“/struts-tags” prefix=“s” %>
/config/struts/struts-login.xml
<?xml version ="1.0" encoding="UTF-8" ?> login.jsp WEB-INF/jsp/frame/index.jsp/config/struts/struts-forward.xml
<?xml version ="1.0" encoding="UTF-8" ?> WEB-INF/jsp/frame/top.jsp WEB-INF/jsp/frame/left.jsp WEB-INF/jsp/frame/right.jsp WEB-INF/jsp/frame/bottom.jsp/config/struts.xml
<?xml version ="1.0" encoding="UTF-8" ?> <package name ="struts-global" namespace="/" extends="struts-default" >
<global-results>
<result name ="errHandler" type="chain" >
<param name ="actionName" >errorProcessor</ param>
</result>
</global-results>
<global-exception-mappings>
<exception-mapping result ="errHandler" exception="java.lang.Exception" >
</exception-mapping>
</global-exception-mappings>
<action name ="errorProcessor" class="cn.itheima.oa.error.ErrorProcessor" >
<result name ="error" >error.jsp</ result>
</action>
</package>
执行效果:
31 根据用户的id和与菜单之间的关系加载菜单树
cn.itheima.dao.MenuItemDao.java
public interface MenuItemDao extends BaseDao{
public List getMenuItemsByPid(Long pid);
public Set<MenuItem> getMenuItemsByUid(Long uid) throws Exception;
public Set<MenuItem> getMenuItemsByUid ();
}
cn.itheima.dao.impl.MenuItemDaoImpl.java
@Repository(“menuItemDao” )
public class MenuItemDaoImpl extends BaseDaoImpl implements MenuItemDao {
public List<MenuItem> getMenuItemsByPid(Long pid) {
return hibernateTemplate .find("from MenuItem where pid=?",pid);
}
public Set<MenuItem> getMenuItemsByUid(Long uid) throws Exception {
Set<MenuItem> allMenuItems = new HashSet<MenuItem>(this