BOS项目2:base dao/action、登陆、消息提示框、菜单按钮、修改密码、登陆拦截器



1.    根据pdm导出sql文件生成表

   1.1  导出sql文件

   1.2 使用MySQL命令运行sql脚本

   1.3 sourc空格+全路径.sql

   1.4 使用反转工具生成实体类和hbm文件

     使用方法:day38

2.    抽取持久层代码(BaseDao&BaseDaoImpl)

    接口

[java]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * 通用Dao接口 
  3.  *  
  4.  * 
  5.  * @param <T> 
  6.  */  
  7. public interface IBaseDao<T> {  
  8.     public void save(T entity);  
  9.     public void update(T entity);  
  10.     public void delete(T entity);  
  11.     public T findById(String id);  
  12.     public List<T> findAll();  
  13.     public void executeUpdate(String queryName,Object...args);  
  14. }  

    实现类(BaseDaoImpl) 

[java]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * 通用dao实现 
  3.  *  
  4.  * 
  5.  */  
  6. public class BaseDaoImpl<T> extends HibernateDaoSupport implements IBaseDao<T>{  
  7.     Class<T> entityClass;//实体类型   
  8.       
  9.     //注入SessionFactory对象  
  10.     @Resource  
  11.     public void setSF(SessionFactory sessionFactory){  
  12.         super.setSessionFactory(sessionFactory);  
  13.     }  
  14.       
  15.     /** 
  16.      * 在构造方法中获取实体类型 
  17.      */  
  18.     public BaseDaoImpl() {  
  19.         //获得父类(BaseDaoImpl)类型  
  20.         ParameterizedType superclass = (ParameterizedType) this.getClass().getGenericSuperclass();  
  21.         //获得泛型数组  
  22.         Type[] typeArguments = superclass.getActualTypeArguments();  
  23.         //获得实体类型  
  24.         entityClass = (Class<T>) typeArguments[0];  
  25.     }  
  26.       
  27.     public void save(T entity) {  
  28.         this.getHibernateTemplate().save(entity);  
  29.     }  
  30.   
  31.     public void update(T entity) {  
  32.         this.getHibernateTemplate().update(entity);  
  33.     }  
  34.   
  35.     public void delete(T entity) {  
  36.         this.getHibernateTemplate().delete(entity);  
  37.     }  
  38.   
  39.     public T findById(String id) {  
  40.         return this.getHibernateTemplate().get(entityClass, id);  
  41.     }  
  42.   
  43.     public List<T> findAll() {  
  44.         String hql = "FROM " + entityClass.getSimpleName();  
  45.         return this.getHibernateTemplate().find(hql);  
  46.     }  
  47.   
  48.     //执行任意HQL  
  49.     public void executeUpdate(String queryName, Object... args) {  
  50.         Session session = this.getSession();  
  51.         //命名查询  
  52.         Query query = session.getNamedQuery(queryName);  
  53.         int length = args.length;  
  54.         int i = 0;  
  55.         for (Object arg : args) {  
  56.             //为?赋值  
  57.             query.setParameter(i++, arg);  
  58.         }  
  59.         query.executeUpdate();  
  60.     }  
  61. }  

3.    抽取表现层(BaseAction)

[java]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * 通用Action 
  3.  *  
  4.  * 
  5.  */  
  6. public class BaseAction<T> extends ActionSupport implements ModelDriven<T> {  
  7.     protected T model;//模型对象  
  8.     public T getModel() {  
  9.         return model;  
  10.     }  
  11.   
  12.     /** 
  13.      * 获得实体类型,通过反射创建模型对象 
  14.      */  
  15.     public BaseAction() {  
  16.         //获得父类(BaseAction) 类型  
  17.         ParameterizedType superclass = (ParameterizedType) this.getClass().getGenericSuperclass();  
  18.         //获得父类上的泛型数组  
  19.         Type[] typeArguments = superclass.getActualTypeArguments();  
  20.         //获得实体类型  
  21.         Class<T> domainClass = (Class<T>) typeArguments[0];  
  22.         try {  
  23.             model = domainClass.newInstance();  
  24.         } catch (InstantiationException e) {  
  25.             e.printStackTrace();  
  26.         } catch (IllegalAccessException e) {  
  27.             e.printStackTrace();  
  28.         }  
  29.     }  
  30. }  

4.    登录功能

 验证码validatecode.jsp

[plain]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. <%@ page import="java.util.Random"%>  
  4. <%@ page import="java.io.OutputStream"%>  
  5. <%@ page import="java.awt.Color"%>  
  6. <%@ page import="java.awt.Font"%>  
  7. <%@ page import="java.awt.Graphics"%>  
  8. <%@ page import="java.awt.image.BufferedImage"%>  
  9. <%@ page import="javax.imageio.ImageIO"%>  
  10. <%  
  11.     int width = 80;  
  12.     int height = 32;  
  13.     //create the image  
  14.     BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
  15.     Graphics g = image.getGraphics();  
  16.     // set the background color  
  17.     g.setColor(new Color(0xDCDCDC));  
  18.     g.fillRect(0, 0, width, height);  
  19.     // draw the border  
  20.     g.setColor(Color.black);  
  21.     g.drawRect(0, 0, width - 1, height - 1);  
  22.     // create a random instance to generate the codes  
  23.     Random rdm = new Random();  
  24.     String hash1 = Integer.toHexString(rdm.nextInt());  
  25.     // make some confusion  
  26.     for (int i = 0; i < 50; i++) {  
  27.         int x = rdm.nextInt(width);  
  28.         int y = rdm.nextInt(height);  
  29.         g.drawOval(x, y, 0, 0);  
  30.     }  
  31.     // generate a random code  
  32.     String capstr = hash1.substring(0, 4);  
  33.     session.setAttribute("key", capstr);  
  34.     g.setColor(new Color(0, 100, 0));  
  35.     g.setFont(new Font("Candara", Font.BOLD, 24));  
  36.     g.drawString(capstr, 8, 24);  
  37.     g.dispose();  
  38.     response.setContentType("image/jpeg");  
  39.     out.clear();  
  40.     out = pageContext.pushBody();  
  41.     OutputStream strm = response.getOutputStream();  
  42.     ImageIO.write(image, "jpeg", strm);  
  43.     strm.close();  
  44. %>  
登陆页面接收验证码

[html]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. <input id="loginform:codeInput" class="loginFormTdIpt" type="text"  
  2.     name="checkcode" title="请输入验证码" />  
  3.   
  4. <img id="loginform:vCode" src="${pageContext.request.contextPath }/validatecode.jsp"  
  5.     onclick="javascript:document.getElementById('loginform:vCode')  
  6.     .src='${pageContext.request.contextPath }/validatecode.jsp?'+Math.random();" />  

登陆:

第一步:修改login.jsp页面中action提交地址

[html]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. <a href="#"  onclick="document.forms[0].submit();" id="loginform:j_id19" name="loginform:j_id19">  

第二步:创建UserAction,提供login方法

[java]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. @Controller//("abc")  
  2. @Scope("prototype")  
  3. public class UserAction extends BaseAction<User>{  
  4.     //提供属性接收验证码  
  5.     private String checkcode;  
  6.     @Resource  
  7.     private IUserService userService;  
  8.     /** 
  9.      * 用户登录 
  10.      */  
  11.     public String login(){  
  12.         //从session中获取自动生成的验证码  
  13.         String key = (String) ActionContext.getContext().getSession().get("key");  
  14.         if(StringUtils.isNotBlank(checkcode) && checkcode.equals(key)){  
  15.             //验证码正确  
  16.             User user = userService.login(model);  
  17.             if(user != null){  
  18.                 //登录成功,将User对象放入session   
  19.                 ActionContext.getContext().getSession().put("loginUser", user);  
  20.                 return "home";  
  21.             }else{  
  22.                 //登录失败,添加错误信息,跳转到登录页面  
  23.                 this.addActionError(this.getText("loginError"));  
  24.                 return "login";  
  25.             }  
  26.         }else{  
  27.             //验证码有误,添加错误信息,跳转到登录页面  
  28.             this.addActionError(this.getText("checkcodeError"));  
  29.             return "login";  
  30.         }  
  31.     }  

第三步:创建UserService

[java]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. @Service  
  2. @Transactional  
  3. public class UserServiceImpl implements IUserService {  
  4.     @Autowired  
  5.     private IUserDao userDao;  
  6.   
  7.     public User login(User model) {  
  8.         String password = model.getPassword();  
  9.         //使用md5加密  
  10.         password = MD5Utils.md5(password);  
  11.         User user = userDao.findUserByUsernameAndPassword(model.getUsername(),password);  
  12.         return user;  
  13.     }  

第四步:创建UserDao

[java]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. @Repository  
  2. public class UserDaoImpl extends BaseDaoImpl<User> implements IUserDao{  
  3.     /** 
  4.      * 根据用户名和密码查询用户 
  5.      */  
  6.     public User findUserByUsernameAndPassword(String username, String password) {  
  7.         String hql = "FROM User u WHERE u.username = ? AND u.password = ?";  
  8.         List<User> list = this.getHibernateTemplate().find(hql,username,password);  
  9.         if(list != null && list.size() > 0){  
  10.             return list.get(0);  
  11.         }  
  12.         return null;  
  13.     }  
  14.   
  15. }  

第五步:配置struts.xml

[html]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. <!-- 用户管理Action -->  
  2. <action name="userAction_*" class="userAction" method="{1}">  
  3.     <result name="home">/index.jsp</result>  
  4. </action>  

5.    消息提示框messager

[html]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. <script type="text/javascript">  
  2.     $(function(){  
  3.         //屏幕右下角提示框  
  4.         window.setTimeout(function(){  
  5.             $.messager.show({  
  6.                   title:'欢迎信息',       
  7.                   msg:'欢迎张三登录成功',     
  8.                   timeout:5000,//5秒钟后消失  
  9.                   showType:'slide'    
  10.                 });  
  11.         }, 3000);  
  12.           
  13.         //普通提示框  
  14.         //$.messager.alert("提示信息","提示内容正文","question");  
  15.           
  16.         //确认框  
  17.         /**  
  18.         $.messager.confirm("确认信息","你确定删除当前数据吗?",function(r){  
  19.             alert(r);  
  20.         });  
  21.         **/  
  22.           
  23.         //带有输入功能的确认框  
  24.         /**  
  25.         $.messager.prompt("确认信息","你确定删除当前数据吗?",function(r){  
  26.             alert(r);  
  27.         });  
  28.         **/  
  29.           
  30.         //进度条  
  31.         $.messager.progress();  
  32.         window.setTimeout(function(){  
  33.             $.messager.progress('close');//关闭进度条  
  34.         }, 3000);  
  35.     });  
  36. </script>  

6.    菜单按钮menubutton


[html]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. <body>  
  2.     <a class="easyui-menubutton" data-options="menu:'#mm'">控制面板</a>  
  3.     <!-- 制作菜单 -->  
  4.     <div id="mm">  
  5.         <!-- 每个子div是一个菜单选项 -->  
  6.         <div onclick="alert('111')" data-options="iconCls:'icon-edit'">修改密码</div>  
  7.         <!--区域分隔线 -->  
  8.         <div class="menu-sep"></div>  
  9.         <div>退出系统</div>  
  10.         <div>联系管理员</div>  
  11.           
  12.     </div>  
  13. </body>  

7.    编写struts2拦截器实器实现未登录用户访问

第一步:编写拦截器

[html]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. public class LoginInterceptor extends MethodFilterInterceptor {  
  2.   
  3.     @Override  
  4.     protected String doIntercept(ActionInvocation ai) throws Exception {  
  5.         // 判断是否存在session  
  6.         Object session = ActionContext.getContext().getSession()  
  7.                 .get("session_user");  
  8.         if (session == null) {  
  9.             // 不存在转回登陆界面  
  10.             Object obj = ai.getAction();  
  11.             if (obj instanceof ActionSupport) {  
  12.                 ActionSupport action = (ActionSupport) obj;  
  13.                 //提示信息  
  14.                 action.addActionError(action.getText("mustLogin"));  
  15.             }  
  16.             return "login";  
  17.         }  
  18.         //放行  
  19.         return ai.invoke();  
  20.     }  
  21. }  

第二步:在struts.xml中注册拦截器

[html]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. <interceptors>  
  2.     <!-- 注册拦截器 -->  
  3.     <interceptor name="bosLogin" class="com.itheima.bos.web.interceptor.BOSLoginInerceptor">  
  4.         <param name="excludeMethods">login</param>  
  5.     </interceptor>  
  6.     <!-- 拦截器栈 -->  
  7.     <interceptor-stack name="bos">  
  8.         <interceptor-ref name="bosLogin"></interceptor-ref>  
  9.         <interceptor-ref name="defaultStack"></interceptor-ref>  
  10.     </interceptor-stack>  
  11. </interceptors>  
  12. <!-- 指定默认的拦截器 -->  
  13. <default-interceptor-ref name="bos"></default-interceptor-ref>  

8.    修改密码功能(ajax,命名修改)

第一步:调整index.jsp页面中修改密码窗口,添加校验

[html]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. <tr>  
  2.     <td>新密码:</td>  
  3.     <td><input id="txtNewPass" required="true"   
  4.     data-options="validType:'length[4,6]'" type="Password" class="txt01 easyui-validatebox" /></td>  
  5. </tr>  
  6. <tr>  
  7.     <td>确认密码:</td>  
  8.     <td><input id="txtRePass" required="true"   
  9.     data-options="validType:'length[4,6]'" type="Password" class="txt01 easyui-validatebox" /></td>  
  10. </tr>  

第二步:为修改密码窗口中的确定按钮绑定事件

[html]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1.     <script type="text/javascript">  
  2.   // 修改密码  
  3.     function editPassword() {  
  4.         $('#editPwdWindow').window('open');  
  5.         $("#txtNewPass").val("");  
  6. $("#txtRePass").val("");  
  7.     }  
  8.      $("#btnEp").click(function(){  
  9. //对表单中的元素进行校验  
  10. var v = $("#editForm").form("validate");  
  11. if(v){  
  12.     //手动校验两次输入是否一致  
  13.     var v1 = $("#txtNewPass").val();  
  14.     var v2 = $("#txtRePass").val();  
  15.     if(v1 == v2){  
  16.         //发送ajax请求,修改密码  
  17.         var url = "${pageContext.request.contextPath}/userAction_editPassword.action";  
  18.         $.post(url,{"password":v1},function(data){  
  19.             if(data == '1'){  
  20.                 //成功  
  21.                 $.messager.alert("提示信息","密码修改成功!","info");  
  22.             }else{  
  23.                 //失败  
  24.                 $.messager.alert("提示信息","密码修改失败!","warning");  
  25.             }  
  26.         });  
  27.         $("#editPwdWindow").window("close");  
  28.     }  
  29. }  
  30. );  
  31.     </script>  

第三步:在UserAction中提供editPassword方法

[java]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * 修改密码 
  3.  * @throws IOException  
  4.  */  
  5. public String editPassword() throws IOException{  
  6.     String password = model.getPassword();  
  7.     User user = BOSContext.getLoginUser();  
  8.     String id = user.getId();  
  9.     String flag = "1";  
  10.     try{  
  11.         userService.editPassword(password,id);  
  12.     }catch (Exception e) {  
  13.         flag = "0";  
  14.     }  
  15.     ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8");  
  16.     ServletActionContext.getResponse().getWriter().print(flag);  
  17.     return NONE;  
  18. }  
service
[java]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. //修改密码  
  2. public void editPassword(String password, String id) {  
  3.     password = MD5Utils.md5(password);  
  4.     userDao.executeUpdate("editPassword", password,id);  
  5. }  

第四步:在BaseDaoImpl中提供executeUpdate方法

[html]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. //执行任意HQL  
  2. public void executeUpdate(String queryName, Object... args) {  
  3.     Session session = this.getSession();  
  4.     //命名查询  
  5.     Query query = session.getNamedQuery(queryName);  
  6.     int length = args.length;  
  7.     int i = 0;  
  8.     for (Object arg : args) {  
  9.         //为?赋值  
  10.         query.setParameter(i++, arg);  
  11.     }  
  12.     query.executeUpdate();  
  13. }  

第五步:在User.hbm.xml中提供修改密码的HQL

[html]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. <!-- 修改密码HQL -->  
  2. <query name="editPassword">  
  3.     update User set password = ?  where id = ?  
  4. </query>  

1.    根据pdm导出sql文件生成表

   1.1  导出sql文件

   1.2 使用MySQL命令运行sql脚本

   1.3 sourc空格+全路径.sql

   1.4 使用反转工具生成实体类和hbm文件

     使用方法:day38

2.    抽取持久层代码(BaseDao&BaseDaoImpl)

    接口

[java]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * 通用Dao接口 
  3.  *  
  4.  * 
  5.  * @param <T> 
  6.  */  
  7. public interface IBaseDao<T> {  
  8.     public void save(T entity);  
  9.     public void update(T entity);  
  10.     public void delete(T entity);  
  11.     public T findById(String id);  
  12.     public List<T> findAll();  
  13.     public void executeUpdate(String queryName,Object...args);  
  14. }  

    实现类(BaseDaoImpl) 

[java]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * 通用dao实现 
  3.  *  
  4.  * 
  5.  */  
  6. public class BaseDaoImpl<T> extends HibernateDaoSupport implements IBaseDao<T>{  
  7.     Class<T> entityClass;//实体类型   
  8.       
  9.     //注入SessionFactory对象  
  10.     @Resource  
  11.     public void setSF(SessionFactory sessionFactory){  
  12.         super.setSessionFactory(sessionFactory);  
  13.     }  
  14.       
  15.     /** 
  16.      * 在构造方法中获取实体类型 
  17.      */  
  18.     public BaseDaoImpl() {  
  19.         //获得父类(BaseDaoImpl)类型  
  20.         ParameterizedType superclass = (ParameterizedType) this.getClass().getGenericSuperclass();  
  21.         //获得泛型数组  
  22.         Type[] typeArguments = superclass.getActualTypeArguments();  
  23.         //获得实体类型  
  24.         entityClass = (Class<T>) typeArguments[0];  
  25.     }  
  26.       
  27.     public void save(T entity) {  
  28.         this.getHibernateTemplate().save(entity);  
  29.     }  
  30.   
  31.     public void update(T entity) {  
  32.         this.getHibernateTemplate().update(entity);  
  33.     }  
  34.   
  35.     public void delete(T entity) {  
  36.         this.getHibernateTemplate().delete(entity);  
  37.     }  
  38.   
  39.     public T findById(String id) {  
  40.         return this.getHibernateTemplate().get(entityClass, id);  
  41.     }  
  42.   
  43.     public List<T> findAll() {  
  44.         String hql = "FROM " + entityClass.getSimpleName();  
  45.         return this.getHibernateTemplate().find(hql);  
  46.     }  
  47.   
  48.     //执行任意HQL  
  49.     public void executeUpdate(String queryName, Object... args) {  
  50.         Session session = this.getSession();  
  51.         //命名查询  
  52.         Query query = session.getNamedQuery(queryName);  
  53.         int length = args.length;  
  54.         int i = 0;  
  55.         for (Object arg : args) {  
  56.             //为?赋值  
  57.             query.setParameter(i++, arg);  
  58.         }  
  59.         query.executeUpdate();  
  60.     }  
  61. }  

3.    抽取表现层(BaseAction)

[java]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * 通用Action 
  3.  *  
  4.  * 
  5.  */  
  6. public class BaseAction<T> extends ActionSupport implements ModelDriven<T> {  
  7.     protected T model;//模型对象  
  8.     public T getModel() {  
  9.         return model;  
  10.     }  
  11.   
  12.     /** 
  13.      * 获得实体类型,通过反射创建模型对象 
  14.      */  
  15.     public BaseAction() {  
  16.         //获得父类(BaseAction) 类型  
  17.         ParameterizedType superclass = (ParameterizedType) this.getClass().getGenericSuperclass();  
  18.         //获得父类上的泛型数组  
  19.         Type[] typeArguments = superclass.getActualTypeArguments();  
  20.         //获得实体类型  
  21.         Class<T> domainClass = (Class<T>) typeArguments[0];  
  22.         try {  
  23.             model = domainClass.newInstance();  
  24.         } catch (InstantiationException e) {  
  25.             e.printStackTrace();  
  26.         } catch (IllegalAccessException e) {  
  27.             e.printStackTrace();  
  28.         }  
  29.     }  
  30. }  

4.    登录功能

 验证码validatecode.jsp

[plain]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. <%@ page import="java.util.Random"%>  
  4. <%@ page import="java.io.OutputStream"%>  
  5. <%@ page import="java.awt.Color"%>  
  6. <%@ page import="java.awt.Font"%>  
  7. <%@ page import="java.awt.Graphics"%>  
  8. <%@ page import="java.awt.image.BufferedImage"%>  
  9. <%@ page import="javax.imageio.ImageIO"%>  
  10. <%  
  11.     int width = 80;  
  12.     int height = 32;  
  13.     //create the image  
  14.     BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
  15.     Graphics g = image.getGraphics();  
  16.     // set the background color  
  17.     g.setColor(new Color(0xDCDCDC));  
  18.     g.fillRect(0, 0, width, height);  
  19.     // draw the border  
  20.     g.setColor(Color.black);  
  21.     g.drawRect(0, 0, width - 1, height - 1);  
  22.     // create a random instance to generate the codes  
  23.     Random rdm = new Random();  
  24.     String hash1 = Integer.toHexString(rdm.nextInt());  
  25.     // make some confusion  
  26.     for (int i = 0; i < 50; i++) {  
  27.         int x = rdm.nextInt(width);  
  28.         int y = rdm.nextInt(height);  
  29.         g.drawOval(x, y, 0, 0);  
  30.     }  
  31.     // generate a random code  
  32.     String capstr = hash1.substring(0, 4);  
  33.     session.setAttribute("key", capstr);  
  34.     g.setColor(new Color(0, 100, 0));  
  35.     g.setFont(new Font("Candara", Font.BOLD, 24));  
  36.     g.drawString(capstr, 8, 24);  
  37.     g.dispose();  
  38.     response.setContentType("image/jpeg");  
  39.     out.clear();  
  40.     out = pageContext.pushBody();  
  41.     OutputStream strm = response.getOutputStream();  
  42.     ImageIO.write(image, "jpeg", strm);  
  43.     strm.close();  
  44. %>  
登陆页面接收验证码

[html]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. <input id="loginform:codeInput" class="loginFormTdIpt" type="text"  
  2.     name="checkcode" title="请输入验证码" />  
  3.   
  4. <img id="loginform:vCode" src="${pageContext.request.contextPath }/validatecode.jsp"  
  5.     onclick="javascript:document.getElementById('loginform:vCode')  
  6.     .src='${pageContext.request.contextPath }/validatecode.jsp?'+Math.random();" />  

登陆:

第一步:修改login.jsp页面中action提交地址

[html]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. <a href="#"  onclick="document.forms[0].submit();" id="loginform:j_id19" name="loginform:j_id19">  

第二步:创建UserAction,提供login方法

[java]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. @Controller//("abc")  
  2. @Scope("prototype")  
  3. public class UserAction extends BaseAction<User>{  
  4.     //提供属性接收验证码  
  5.     private String checkcode;  
  6.     @Resource  
  7.     private IUserService userService;  
  8.     /** 
  9.      * 用户登录 
  10.      */  
  11.     public String login(){  
  12.         //从session中获取自动生成的验证码  
  13.         String key = (String) ActionContext.getContext().getSession().get("key");  
  14.         if(StringUtils.isNotBlank(checkcode) && checkcode.equals(key)){  
  15.             //验证码正确  
  16.             User user = userService.login(model);  
  17.             if(user != null){  
  18.                 //登录成功,将User对象放入session   
  19.                 ActionContext.getContext().getSession().put("loginUser", user);  
  20.                 return "home";  
  21.             }else{  
  22.                 //登录失败,添加错误信息,跳转到登录页面  
  23.                 this.addActionError(this.getText("loginError"));  
  24.                 return "login";  
  25.             }  
  26.         }else{  
  27.             //验证码有误,添加错误信息,跳转到登录页面  
  28.             this.addActionError(this.getText("checkcodeError"));  
  29.             return "login";  
  30.         }  
  31.     }  

第三步:创建UserService

[java]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. @Service  
  2. @Transactional  
  3. public class UserServiceImpl implements IUserService {  
  4.     @Autowired  
  5.     private IUserDao userDao;  
  6.   
  7.     public User login(User model) {  
  8.         String password = model.getPassword();  
  9.         //使用md5加密  
  10.         password = MD5Utils.md5(password);  
  11.         User user = userDao.findUserByUsernameAndPassword(model.getUsername(),password);  
  12.         return user;  
  13.     }  

第四步:创建UserDao

[java]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. @Repository  
  2. public class UserDaoImpl extends BaseDaoImpl<User> implements IUserDao{  
  3.     /** 
  4.      * 根据用户名和密码查询用户 
  5.      */  
  6.     public User findUserByUsernameAndPassword(String username, String password) {  
  7.         String hql = "FROM User u WHERE u.username = ? AND u.password = ?";  
  8.         List<User> list = this.getHibernateTemplate().find(hql,username,password);  
  9.         if(list != null && list.size() > 0){  
  10.             return list.get(0);  
  11.         }  
  12.         return null;  
  13.     }  
  14.   
  15. }  

第五步:配置struts.xml

[html]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. <!-- 用户管理Action -->  
  2. <action name="userAction_*" class="userAction" method="{1}">  
  3.     <result name="home">/index.jsp</result>  
  4. </action>  

5.    消息提示框messager

[html]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. <script type="text/javascript">  
  2.     $(function(){  
  3.         //屏幕右下角提示框  
  4.         window.setTimeout(function(){  
  5.             $.messager.show({  
  6.                   title:'欢迎信息',       
  7.                   msg:'欢迎张三登录成功',     
  8.                   timeout:5000,//5秒钟后消失  
  9.                   showType:'slide'    
  10.                 });  
  11.         }, 3000);  
  12.           
  13.         //普通提示框  
  14.         //$.messager.alert("提示信息","提示内容正文","question");  
  15.           
  16.         //确认框  
  17.         /**  
  18.         $.messager.confirm("确认信息","你确定删除当前数据吗?",function(r){  
  19.             alert(r);  
  20.         });  
  21.         **/  
  22.           
  23.         //带有输入功能的确认框  
  24.         /**  
  25.         $.messager.prompt("确认信息","你确定删除当前数据吗?",function(r){  
  26.             alert(r);  
  27.         });  
  28.         **/  
  29.           
  30.         //进度条  
  31.         $.messager.progress();  
  32.         window.setTimeout(function(){  
  33.             $.messager.progress('close');//关闭进度条  
  34.         }, 3000);  
  35.     });  
  36. </script>  

6.    菜单按钮menubutton


[html]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. <body>  
  2.     <a class="easyui-menubutton" data-options="menu:'#mm'">控制面板</a>  
  3.     <!-- 制作菜单 -->  
  4.     <div id="mm">  
  5.         <!-- 每个子div是一个菜单选项 -->  
  6.         <div onclick="alert('111')" data-options="iconCls:'icon-edit'">修改密码</div>  
  7.         <!--区域分隔线 -->  
  8.         <div class="menu-sep"></div>  
  9.         <div>退出系统</div>  
  10.         <div>联系管理员</div>  
  11.           
  12.     </div>  
  13. </body>  

7.    编写struts2拦截器实器实现未登录用户访问

第一步:编写拦截器

[html]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. public class LoginInterceptor extends MethodFilterInterceptor {  
  2.   
  3.     @Override  
  4.     protected String doIntercept(ActionInvocation ai) throws Exception {  
  5.         // 判断是否存在session  
  6.         Object session = ActionContext.getContext().getSession()  
  7.                 .get("session_user");  
  8.         if (session == null) {  
  9.             // 不存在转回登陆界面  
  10.             Object obj = ai.getAction();  
  11.             if (obj instanceof ActionSupport) {  
  12.                 ActionSupport action = (ActionSupport) obj;  
  13.                 //提示信息  
  14.                 action.addActionError(action.getText("mustLogin"));  
  15.             }  
  16.             return "login";  
  17.         }  
  18.         //放行  
  19.         return ai.invoke();  
  20.     }  
  21. }  

第二步:在struts.xml中注册拦截器

[html]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. <interceptors>  
  2.     <!-- 注册拦截器 -->  
  3.     <interceptor name="bosLogin" class="com.itheima.bos.web.interceptor.BOSLoginInerceptor">  
  4.         <param name="excludeMethods">login</param>  
  5.     </interceptor>  
  6.     <!-- 拦截器栈 -->  
  7.     <interceptor-stack name="bos">  
  8.         <interceptor-ref name="bosLogin"></interceptor-ref>  
  9.         <interceptor-ref name="defaultStack"></interceptor-ref>  
  10.     </interceptor-stack>  
  11. </interceptors>  
  12. <!-- 指定默认的拦截器 -->  
  13. <default-interceptor-ref name="bos"></default-interceptor-ref>  

8.    修改密码功能(ajax,命名修改)

第一步:调整index.jsp页面中修改密码窗口,添加校验

[html]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. <tr>  
  2.     <td>新密码:</td>  
  3.     <td><input id="txtNewPass" required="true"   
  4.     data-options="validType:'length[4,6]'" type="Password" class="txt01 easyui-validatebox" /></td>  
  5. </tr>  
  6. <tr>  
  7.     <td>确认密码:</td>  
  8.     <td><input id="txtRePass" required="true"   
  9.     data-options="validType:'length[4,6]'" type="Password" class="txt01 easyui-validatebox" /></td>  
  10. </tr>  

第二步:为修改密码窗口中的确定按钮绑定事件

[html]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1.     <script type="text/javascript">  
  2.   // 修改密码  
  3.     function editPassword() {  
  4.         $('#editPwdWindow').window('open');  
  5.         $("#txtNewPass").val("");  
  6. $("#txtRePass").val("");  
  7.     }  
  8.      $("#btnEp").click(function(){  
  9. //对表单中的元素进行校验  
  10. var v = $("#editForm").form("validate");  
  11. if(v){  
  12.     //手动校验两次输入是否一致  
  13.     var v1 = $("#txtNewPass").val();  
  14.     var v2 = $("#txtRePass").val();  
  15.     if(v1 == v2){  
  16.         //发送ajax请求,修改密码  
  17.         var url = "${pageContext.request.contextPath}/userAction_editPassword.action";  
  18.         $.post(url,{"password":v1},function(data){  
  19.             if(data == '1'){  
  20.                 //成功  
  21.                 $.messager.alert("提示信息","密码修改成功!","info");  
  22.             }else{  
  23.                 //失败  
  24.                 $.messager.alert("提示信息","密码修改失败!","warning");  
  25.             }  
  26.         });  
  27.         $("#editPwdWindow").window("close");  
  28.     }  
  29. }  
  30. );  
  31.     </script>  

第三步:在UserAction中提供editPassword方法

[java]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * 修改密码 
  3.  * @throws IOException  
  4.  */  
  5. public String editPassword() throws IOException{  
  6.     String password = model.getPassword();  
  7.     User user = BOSContext.getLoginUser();  
  8.     String id = user.getId();  
  9.     String flag = "1";  
  10.     try{  
  11.         userService.editPassword(password,id);  
  12.     }catch (Exception e) {  
  13.         flag = "0";  
  14.     }  
  15.     ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8");  
  16.     ServletActionContext.getResponse().getWriter().print(flag);  
  17.     return NONE;  
  18. }  
service
[java]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. //修改密码  
  2. public void editPassword(String password, String id) {  
  3.     password = MD5Utils.md5(password);  
  4.     userDao.executeUpdate("editPassword", password,id);  
  5. }  

第四步:在BaseDaoImpl中提供executeUpdate方法

[html]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. //执行任意HQL  
  2. public void executeUpdate(String queryName, Object... args) {  
  3.     Session session = this.getSession();  
  4.     //命名查询  
  5.     Query query = session.getNamedQuery(queryName);  
  6.     int length = args.length;  
  7.     int i = 0;  
  8.     for (Object arg : args) {  
  9.         //为?赋值  
  10.         query.setParameter(i++, arg);  
  11.     }  
  12.     query.executeUpdate();  
  13. }  

第五步:在User.hbm.xml中提供修改密码的HQL

[html]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. <!-- 修改密码HQL -->  
  2. <query name="editPassword">  
  3.     update User set password = ?  where id = ?  
  4. </query>  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值