BOS項目 第2天(BaseDao、BaseAction、用戶登錄、自定義strust登錄攔截器)
BOS項目 第2天
今天內容安排:
1、根據提供的pdm文件生成sql
2、持久層和表現層設計---BaseDao、BaseAction
3、實現用戶登錄功能
4、jQuery EasyUI 消息提示控件
5、jQuery EasyUI menubutton菜單按鈕
6、自定義struts2攔截器,實現用戶未登錄自動跳轉到登錄頁面
7、基於ajax實現修改密碼功能
1. 根據pdm生成sql腳本
2. 設計持久層和表現層
2.1 持久層設計(基於泛型+反射)
通用接口:
/** * 抽取持久層通用方法 * @author zhaoqx * * @param */ public interface IBaseDao<T> { public void save(T entity); public void delete(T entity); public void update(T entity); public T findById(Serializable id); public List<T> findAll(); } |
通用實現:
/** * 持久層通用實現 * @author zhaoqx * */ public class BaseDaoImpl<T> extends //實體類型 private Class<T> entityClass; //使用註解方式進行依賴註入 @Resource public void setMySessionFactory(SessionFactory sessionFactory){ super.setSessionFactory(sessionFactory); }
/** * 在構造方法中動態獲得操作的實體類型 */ public BaseDaoImpl() { //獲得父類(BaseDaoImpl<T>)類型 ParameterizedType genericSuperclass = (ParameterizedType) this.getClass().getGenericSuperclass(); //獲得父類上的泛型數組 Type[] actualTypeArguments = genericSuperclass.getActualTypeArguments(); entityClass = (Class<T>) actualTypeArguments[0]; }
public void save(T entity) { this.getHibernateTemplate().save(entity); }
public void delete(T entity) { this.getHibernateTemplate().delete(entity); }
public void update(T entity) { this.getHibernateTemplate().update(entity); }
public T findById(Serializable id) { return this.getHibernateTemplate().get(entityClass, id); }
public List<T> findAll() {//FROM User String hql = "FROM " + entityClass.getSimpleName(); return this.getHibernateTemplate().find(hql); } } |
2.2 表現層設計
public class BaseAction<T> extends ActionSupport implements ModelDriven<T>{ //模型對象 private T model; public T getModel() { return model; } /** * 在構造方法中動態獲得實現類型,通過反射創建模型對象 */ public BaseAction() { ParameterizedType genericSuperclass = (ParameterizedType) this.getClass().getGenericSuperclass(); Type[] actualTypeArguments = genericSuperclass.getActualTypeArguments(); //獲得實體類型 Class<T> entityClass = (Class<T>) actualTypeArguments[0]; try { //通過反射創建對象 model = entityClass.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } |
3. 基於baseDao和BaseAction實現用戶登錄
第一步:修改login.jsp頁面,點擊登錄按鈕,提交表單
<a onclick="document.forms[0].submit()" id="loginform:j_id19" name="loginform:j_id19"> <span id="loginform:loginBtn" class="btn btn-login" style="margin-top:-36px;">登錄</span> </a> |
第二步:在UserAction中提供login方法
@Resource private IUserService userService;
//通過屬性驅動接收驗證碼 private String checkcode; public void setCheckcode(String checkcode) { this.checkcode = checkcode; } public String login(){ //生成的驗證碼 String key = (String) ServletActionContext.getRequest().getSession().getAttribute("key");
//判斷用戶輸入的驗證碼是否正確 if(StringUtils.isNotBlank(checkcode) && checkcode.equals(key)){ //驗證碼正確 User user = userService.login(model); if(user != null){ //登錄成功,將User放入session域,跳轉到系統首頁 ServletActionContext.getRequest().getSession().setAttribute("loginUser", user); return "home"; }else{ //登錄失敗,設置錯誤提示信息,跳轉到登錄頁面 this.addActionError(this.getText("loginError")); return "login"; } }else{ //驗證碼錯誤,設置錯誤提示信息,跳轉到登錄頁面 this.addActionError(this.getText("validateCodeError")); return "login"; } } |
第三步:提供UserService類
@Service @Transactional public class UserServiceImpl implements IUserService{ //註入dao @Autowired private IUserDao userDao; public User login(User user) { String username = user.getUsername(); String password = user.getPassword();//明文 password = MD5Utils.md5(password);//md5加密 return userDao.findByUsernameAndPassword(username,password); } } |
第四步:在UserDao中擴展方法,根據用戶名和密碼查詢用戶
/** * 根據用戶名和密碼查詢用戶 */ public User findByUsernameAndPassword(String username, String password) { String hql = "FROM User u WHERE u.username = ? AND u.password = ?"; List<User> list = this.getHibernateTemplate().find(hql, username,password); if(list != null && list.size() > 0){ return list.get(0); } return null; } |
第五步:在struts.xml中註冊國際化文件
第六步:在login.jsp頁面中使用struts2提供的標簽展示錯誤提示信息
4. jQuery EasyUI消息提示控件
4.1 alert方法
$.messager.alert("標題","內容信息","question");
4.2 show方法
window.setTimeout(function(){
$.messager.show({
title:‘歡迎信息‘,
msg:‘歡迎張三登錄系統‘,
timeout:3000,
showType:‘slide‘
});
}, 3000);
效果:
4.3 confirm方法
$.messager.confirm("提示信息","你確定刪除當前數據嗎?",function(r){
alert(r);
});
4.4 prompt方法
$.messager.prompt("提示信息","你確定刪除當前數據嗎?",function(r){
alert(r);
});
效果:
4.5 progress
$.messager.progress();
window.setTimeout(function(){
$.messager.progress(‘close‘);
}, 3000);
效果:
5. jQuery EasyUI 下拉菜單制作
<a data-options="iconCls:‘icon-help‘,menu:‘#mm‘" class="easyui-menubutton">控制面板</a> <!-- 使用div制作下拉菜單選項 --> <div id="mm"> <!-- 使用子div制作具體的一個選項 --> <div onclick="alert(111)" data-options="iconCls:‘icon-edit‘">修改密碼</div> <div>聯系管理員</div> <div class="menu-sep"></div> <div>退出系統</div> </div> |
效果:
6. 自定義struts2攔截器
第一步:定義一個攔截器類
public class BOSLoginInterceptor extends MethodFilterInterceptor { // 攔截方法 protected String doIntercept(ActionInvocation invocation) throws Exception { User user = (User) ServletActionContext.getRequest().getSession() .getAttribute("loginUser"); if(user == null){ //未登錄,跳轉到登錄頁面 return "login"; } return invocation.invoke();// 放行 } } |
第二步:在struts.xml中註冊攔截器
<interceptors> <!-- 註冊攔截器 --> <interceptor name="BOSLoginInterceptor" class="com.itheima.bos.web.interceptor.BOSLoginInterceptor"> <param name="excludeMethods">login</param> </interceptor> <!-- 攔截器棧 --> <interceptor-stack name="myStack"> <interceptor-ref name="BOSLoginInterceptor"/> <interceptor-ref name="defaultStack"/> </interceptor-stack> </interceptors> <!-- 指定默認棧 --> <default-interceptor-ref name="myStack"/> <global-results> <result name="login">/login.jsp</result> </global-results> |
7. 基於ajax實現修改密碼
/WEB-INF/pages/common/index.jsp
第一步:為密碼輸入框進行輸入校驗,使用easyUI提供的easyui-validatebox
<table cellpadding=3> <tr> <td>新密碼:</td> <td><input id="txtNewPass" type="Password" class="txt01 easyui-validatebox" required="true" data-options="validType:‘length[4,8]‘" /></td> </tr> <tr> <td>確認密碼:</td> <td><input id="txtRePass" type="Password" class="txt01 easyui-validatebox" required="true" data-options="validType:‘length[4,8]‘" /></td> </tr> </table> |
第二步:為“確定”按鈕綁定事件
<script type="text/javascript"> //為“確定”按鈕綁定事件 $("#btnEp").click(function(){ //進行表單校驗 var v = $("#editPasswordForm").form("validate");//對應表單中的所有輸入框進行校驗 if(v){//表單校驗通過 //判斷兩次輸入是否一致 var v1 = $("#txtNewPass").val(); var v2 = $("#txtRePass").val(); if(v1 == v2){ //輸入一致,發送ajax請求,修改當前用戶的密碼 var url = "${pageContext.request.contextPath}/userAction_editPassword.action"; $.post(url,{"password":v1},function(data){ if(data == ‘1‘){ //修改密碼成功 $.messager.alert("提示信息","密碼修改成功!","info"); }else{ //修改失敗 $.messager.alert("提示信息","密碼修改失敗!","warning"); } //關閉修改密碼的窗口 $("#editPwdWindow").window("close"); }); }else{ //輸入不一致,提示用戶輸入不一致 $.messager.alert("提示信息","兩次輸入密碼不一致!","warning"); } } }); </script> |
第三步:在UserAction中提供editPassword方法,修改密碼
/** * 修改當前登錄用戶密碼 * @throws IOException */ public String editPassword() throws IOException{ User user = (User) ServletActionContext.getRequest().getSession().getAttribute("loginUser"); String password = model.getPassword();//新密碼 password = MD5Utils.md5(password); String flag = "1"; try{ userService.editPassword(password,user.getId()); }catch (Exception e) { //修改密碼失敗 flag = "0"; } ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8"); ServletActionContext.getResponse().getWriter().print(flag); return NONE; } |
第四步:在BaseDao中擴展一個通用的更新方法
/** * 通用更新方法 */ public void executeUpdate(String queryName, Object... objects) { Session session = this.getSession();// 從本地線程中獲得session對象 // 使用命名查詢語句獲得一個查詢對象 Query query = session.getNamedQuery(queryName); // 為HQL語句中的?賦值 int i = 0; for (Object arg : objects) { query.setParameter(i++, arg); } query.executeUpdate();// 執行更新 } |
第五步:在User.hbm.xml中定義一個HQL語句,用於修改密碼
BOS項目 第2天(BaseDao、BaseAction、用戶登錄、自定義strust登錄攔截器)