前面咱們已經學習了怎麼整合SSH框架了。是時候拿一個小項目來練練手了….咱們如今要設計一個企業人事管理系統…html
關於搭建配置環境可參考上一篇博文:http://blog.csdn.net/hon_3y/article/details/72190638java
Admin.javaspring
public class Admin { private int id; private String username; private String password; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
User.java數據庫
public class User { private int id; private String username; private Dept dept; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Dept getDept() { return dept; } public void setDept(Dept dept) { this.dept = dept; } }
Dept.javaapache
public class Dept { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Dept.hbm.xml服務器
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="zhongfucheng.entity"> <class name="Dept" table="t_dept"> <id name="id" > <generator class="native"></generator> </id> <property name="name" column="name"></property> </class> </hibernate-mapping>
User.hbm.xmlmarkdown
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="zhongfucheng.entity"> <class name="User" table="t_user"> <id name="id" column="id"> <generator class="native"></generator> </id> <property name="username" column="userName"></property> <many-to-one name="dept" class="Dept" column="dept_id"/> </class> </hibernate-mapping>
Admin.hbm.xmlsession
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="zhongfucheng.entity"> <class name="Admin" table="t_admin"> <id name="id" column="id"> <generator class="native"></generator> </id> <property name="username" column="userName"></property> <property name="password" column="password"></property> </class> </hibernate-mapping>
爲何要寫baseDao??能夠參考我這篇博文:http://blog.csdn.net/hon_3y/article/details/70243918app
package zhongfucheng.dao; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import java.lang.reflect.ParameterizedType; import java.util.List; /** * Created by ozc on 2017/5/16. */ public abstract class BaseDao<T> { // 容器注入sessionFactory @Autowired private SessionFactory sessionFactory; //子類的類型 private Class<T> clazz; //子類的名稱 private String clazzName; public BaseDao(){ clazz = (Class<T>) this.getClass(); //拿到的是子類 ParameterizedType pt = (ParameterizedType) clazz.getGenericSuperclass(); //拿到子類的真實類型 clazz = (Class) pt.getActualTypeArguments()[0]; //拿到子類的名稱【HQL都是經過類名來查詢的】 clazzName = clazz.getSimpleName(); } public void add(T t){ sessionFactory.getCurrentSession().save(t); } public T find(String id){ return (T) sessionFactory.getCurrentSession().get(clazz, id); } public void update(T t){ sessionFactory.getCurrentSession().update(t); } public void delete(String id){ T t = (T) sessionFactory.getCurrentSession().get(clazz, id); sessionFactory.getCurrentSession().delete(t); } public List<T> getAll() { return sessionFactory.getCurrentSession().createQuery("from" + clazzName).list(); } }
此時的UserDao已經有了baseDao的全部功能框架
/** * 1.添加員工--->add() * 2.修改員工--->find() * 3.刪除員工--->delete() * 4.獲得全部員工-->getAll() * 5.根據id獲得員工-->find() * */ @Repository public class UserDao extends BaseDao<User>{ }
/** * * 1.保存管理員【註冊】--->add() * 2.查找管理員【登錄】--->login() * * * */ @Repository public class AdminDao extends BaseDao<Admin> { @Autowired private SessionFactory sessionFactory; public Admin login(Admin admin) { return (Admin) sessionFactory. getCurrentSession(). createQuery("FROM Admin WHERE username=? AND password=?") .setParameter(0, admin.getUsername()) .setParameter(1, admin.getPassword()) .uniqueResult(); } }
import org.springframework.stereotype.Repository; import zhongfucheng.entity.Dept; /** * 1.查找全部的部門【在添加員工、修改員工時須要用】-->getAll() * 2.經過id查找所在的部門信息--->find() * * */ @Repository public class DeptDao extends BaseDao<Dept> { }
@Transactional @Service public class UserService { @Autowired private UserDao userDao; /** * 1.添加員工--->add() * 2.修改員工--->find() * 3.刪除員工--->delete() * 4.獲得全部員工-->getAll() * 5.根據id獲得員工-->find() */ public void addUser(User user) { userDao.add(user); } public void updateUser(User user) { userDao.update(user); } public void deleteUser(String id) { userDao.delete(id); } public List<User> getAllUsers() { return userDao.getAll(); } public User findUserById(String id) { return userDao.find(id); } }
@Transactional @Service public class AdminService { @Autowired private AdminDao adminDao; /** * 1.保存管理員【註冊】--->save() * 2.查找管理員【登錄】--->login() */ public void register(Admin admin) { adminDao.add(admin); } public Admin login(Admin admin) { return adminDao.login(admin); } }
@Transactional @Service public class DeptService { @Autowired private DeptDao deptDao; /** * 1.查找全部的部門【在添加員工、修改員工時須要用】-->getAll() * 2.經過id查找所在的部門信息--->find() */ public List<Dept> getAllDept() { return deptDao.getAll(); } public Dept findDeptById(String id) { return deptDao.find(id); } }
到目前爲止,咱們已經把後臺的邏輯已經寫完了,接下來就是寫Action和前臺的頁面數據了。首先來寫員工模塊吧。
package zhongfucheng.action; import com.opensymphony.xwork2.ActionSupport; import org.apache.struts2.interceptor.RequestAware; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import zhongfucheng.entity.User; import zhongfucheng.service.UserService; import java.util.List; import java.util.Map; /** * Created by ozc on 2017/5/15. */ @Controller @Scope("prototype") public class UserAction extends ActionSupport implements RequestAware{ @Autowired private UserService userService; //由於多處用到request對象,那就直接實現接口,來獲得request對象就好了 private Map<String, Object> request; @Override public void setRequest(Map<String, Object> map) { this.request = map; } /*列表展現*/ public String list() { List<User> list = userService.getAllUsers(); System.out.println(list); //把數據封裝到request對象上 request.put("list", list); return "list"; } }
Struts配置文件
<action name="user_*" class="userAction" method="{1}"> <!--列表展現--> <result name="list">/list.jsp</result> </action>
list.jsp頁面
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>列表展現</title> </head> <body> <s:if test="#request.list != null"> <table align="center" border="1"> <tr> <td>員工編號</td> <td>員工姓名</td> <td>員工部門編號</td> <td>操做</td> </tr> <s:iterator var="user" value="#request.list" status="st"> <tr> <td><s:property value="#user.id"/></td> <td><s:property value="#user.username"/></td> <td><s:property value="#user.dept.id"/> </td> <td><s:a href="#"> 修改,刪除</s:a></td> </tr> </s:iterator> </table> </s:if> <s:else>對不起,尚未員工的信息,請錄入</s:else> </body> </html>
效果:
添加員工,指定添加部門,跳轉到添加員工顯示頁面…
@Autowired private DeptService deptService; /*添加員工...給出添加的JSP頁面*/ public String viewAdd() { //在添加員工的時候須要獲得全部的部門信息 List<Dept> deptList = deptService.getAllDept(); //封裝到request域對象中 request.put("deptList", deptList); return "viewAdd"; }
<!--給出添加員工的界面--> <result name="viewAdd">/viewAdd.jsp</result>
顯示添加員工界面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>添加員工界面</title> </head> <body> <s:form method="POST" action="user_addUser.action" theme="simple"> <table align="center" border="1"> <tr> <td>員工名稱</td> <td><s:textfield name="username" id="username" value=""/></td> </tr> <tr> <td>員工部門</td> <!-- Struts下拉列表標籤: name="deptId" 下拉列表標籤的名稱(服務器根據這個名稱獲取選擇的項的實際的值value值) headerKey 默認選擇項的實際的值 headerValue 默認下拉列表顯示的內容 list 下拉列表顯示數據的集合 listKey 集合對象的哪一個屬性做爲下拉列表的實例的值,即value值 listValue 集合對象的哪一個屬性做爲下拉列表顯示的值 value 默認選擇的項的設置 --> <td><s:select list="#request.deptList" headerKey="-1" headerValue="請選擇" listKey="id" listValue="name" name="deptId"/></td> </tr> <tr> <td colspan="2"><s:submit value="添加員工"/></td> </tr> </table> </s:form> </body> </html>
//模型驅動 User user = new User(); public User getUser() { return user; } public void setUser(User user) { this.user = user; } @Override public Object getModel() { return user; } //自動封裝deptId private int deptId; public int getDeptId() { return deptId; } public void setDeptId(int deptId) { this.deptId = deptId; }
/*添加員工*/ public String addUser() { //根據部門id查找部門對象 Dept dept = deptService.findDeptById(deptId); //設置部門與員工的關係 user.setDept(dept); userService.addUser(user); //返回列表展現 return "listPage"; }
<!--返回列表展現頁面--> <result name="listPage" type="redirectAction">user_list</result>
<td> <s:a href="user_viewUpdate?id=%{#user.id}">修改</s:a> <s:a href="user_delete?id=%{#user.id}"> 刪除</s:a> </td>
/*爲修改提供頁面,其實就是回顯數據*/ public String viewUpdate() { //獲得user User user = userService.findUserById(this.user.getId()); //獲得全部的部門 List<Dept> deptList = deptService.getAllDept(); request.put("deptList", deptList); //使用Struts2的回顯技術 ValueStack valueStack = ActionContext.getContext().getValueStack(); valueStack.pop(); valueStack.push(user); return "viewUpdate"; }
<!--提供修改頁面--> <result name="viewUpdate">/viewUpdate.jsp</result>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>修改員工界面</title> </head> <body> <s:form method="POST" action="user_updateUser.action" theme="simple"> <table align="center" border="1"> <%--這裏要把id經過隱藏域帶過去--%> <s:hidden name="id" id="id" value="%{id}"/> <tr> <td>員工名稱</td> <td><s:textfield name="username" id="username"/></td> </tr> <tr> <td>員工部門</td> <td> <s:select name="deptId" list="#request.deptList" listKey="id" listValue="name" value="dept.id"/> </td> </tr> <tr> <td colspan="2"><s:submit value="修改員工"/></td> </tr> </table> </s:form> </body> </html>
/*確認修改員工,模型驅動會把數據直接封裝到user對象中*/ public String updateUser() { //獲得部門 Dept dept = deptService.findDeptById(deptId); //設置員工與部門的關係 user.setDept(dept); userService.updateUser(user); //修改完,返回展現列表 return "listPage"; }
/*刪除員工*/ public String delete() { userService.deleteUser(user.getId()); //修改完,返回展現列表 return "listPage"; }
<s:a href="register.jsp">註冊</s:a>
package zhongfucheng.action; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import zhongfucheng.entity.Admin; import zhongfucheng.service.AdminService; /** * Created by ozc on 2017/5/15. */ @Controller @Scope("prototype") public class AdminAction extends ActionSupport implements ModelDriven<Admin>{ /**********調用service**************/ @Autowired private AdminService adminService; /**************使用模型驅動******************/ Admin admin = new Admin(); public Admin getAdmin() { return admin; } public void setAdmin(Admin admin) { this.admin = admin; } @Override public Admin getModel() { return admin; } }
<!--############管理員模塊#################--> <action name="admin_*" class="adminAction" method="{1}"> </action>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>註冊界面</title> </head> <body> <s:form action="admin_register" method="POST" theme="simple"> <table border="1" align="center"> <tr> <td>管理員帳號:</td> <td><s:textfield name="username"/></td> </tr> <tr> <td>管理員密碼:</td> <td><s:textfield name="password"/></td> </tr> <tr> <td colspan="2"><s:submit value="註冊"/> </td> </tr> </table> </s:form> </body> </html>
/*獲得JSP頁面帶過來的數據、完成註冊*/ public String register() { adminService.register(admin); return "listPage"; }
<s:a href="login.jsp">登錄</s:a>
<%@ taglib prefix="s" uri="/struts-tags" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>登錄界面</title> </head> <body> <s:form action="admin_login" method="POST" theme="simple"> <table border="1" align="center"> <tr> <td>管理員帳號:</td> <td><s:textfield name="username" value=""/></td> </tr> <tr> <td>管理員密碼:</td> <td><s:textfield name="password" value=""/></td> </tr> <tr> <td colspan="2"><s:submit value="登錄"/> </td> </tr> </table> </s:form> </body> </html>
/*完成登錄*/ public String login() { adminService.login(admin); //把用戶保存在Sessiion中 ActionContext.getContext().getSession().put("admin", admin); return "listPage"; }
<s:if test="#session.admin !=null"> 歡迎您:<s:property value="%{#session.admin.username}"/> </s:if>
咱們寫一個攔截器,判斷是否調用登錄或者列表展現的方法,若是不是就查看該用戶有沒有登錄。沒有登錄就跳轉到登錄界面
package zhongfucheng.action; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; /** * Created by ozc on 2017/5/17. */ public class PrivilegeInterceptor extends AbstractInterceptor { @Override public String intercept(ActionInvocation actionInvocation) throws Exception { //獲得ActionContext ActionContext context = actionInvocation.getInvocationContext(); //獲得正在調用Action的方法名 String methodName = actionInvocation.getProxy().getMethod(); //獲取session中管理員的對象 Object o = context.getSession().get("admin"); //判斷正在調用什麼方法 if ("login".equals(methodName) || "list".equals(methodName)) { //調用了這兩個方法,不用權限,直接調用把 return actionInvocation.invoke(); } else { //若是不是,那麼檢查 // 沒有登錄,就跳轉到登錄界面唄 if (o == null) { return "login"; } else { // 有登錄,那麼就能夠執行唄 return actionInvocation.invoke(); } } } }
<!-- 攔截器配置 --> <interceptors> <interceptor name="userInterceptor" class="cn.itcast.action.UserInterceptor"></interceptor> <interceptor-stack name="myStack"> <interceptor-ref name="defaultStack"></interceptor-ref> <interceptor-ref name="userInterceptor"></interceptor-ref> </interceptor-stack> </interceptors> <!-- 執行指定的攔截器 --> <default-interceptor-ref name="myStack"></default-interceptor-ref>
<global-results> <!--回到展現列表頁面--> <result name="listPage" type="redirectAction">user_list</result> <!--攔截器返回login--> <result name="login" type="redirect">/login.jsp</result> </global-results>