2021-08-16

登录功能优化

注销功能:

思路移除Session,返回登录页面

 @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //移除session中的内容
        req.getSession().removeAttribute(Constants.USER_SESSION);
        //返回登录页面
        String contextPath = req.getContextPath();
        resp.sendRedirect(contextPath+"/login.jsp");
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

注册xml

<servlet>
        <servlet-name>LogoutServlet</servlet-name>
        <servlet-class>com.feng.servlet.user.LogoutServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LogoutServlet</servlet-name>
        <url-pattern>/user/logout</url-pattern>
    </servlet-mapping>

登录拦截优化:

编写一个过滤器,并注册

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response =(HttpServletResponse) servletResponse;

        User user = (User) request.getSession().getAttribute(Constants.USER_SESSION);
        if (user!=null){//用户被移除了
            //这里不能这样在这样写了,因为在LoginServlet类中登录成功后会重定向到frame.jsp页面,
            //经过过滤器之后,我们只需要让他继续走下去就行,而不需要再一次让他重定向到frame.jsp页面,这样就会在网页上显示,重定向太多次了。
            //response.sendRedirect(request.getContextPath()+"/frame.jsp");
            //让请求继续往下走
            filterChain.doFilter(request,response);
        }else {
            response.sendRedirect(request.getContextPath()+"/error.jsp");
        }
    }

<!--用户登录过滤器-->
    <filter>
        <filter-name>SysFilter</filter-name>
        <filter-class>com.feng.filter.SysFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>SysFilter</filter-name>
        <url-pattern>/jsp/*</url-pattern>
    </filter-mapping>

密码修改

  1. 导入前端素材

                  <li><a href="${pageContext.request.contextPath }/user/pwdmodify">密码修改</a></li>
    
    
  2. 写项目,建议从底层网上写

    在这里插入图片描述

  3. UserDao接口

    //随着项目的进行,底层接口中的方法,也越来越多
    public interface UserDao {
        //从数据库中拿到一个用户(包含此用户的所有的信息)
        public User getLoginUser(Connection connection ,String userCode) throws SQLException;
        //修改当前用户密码(在底层中返回的是一个修改的行数)
        public int UpdatePwd(Connection connection,String userPassword,String userCode) throws SQLException;
    }
    
  4. UserDao接口实现类

        public int UpdatePwd(Connection connection, String userPassword, String userCode) throws SQLException {
    
            PreparedStatement statement = null;
            int i = 0;
            if (connection!=null){
                //首先写出修改的sql语句
                String sql = "update smbms_user set userPassword=? where userCode=?";
                //传入参数
                Object[] objects={userPassword,userCode};
                //调用底层BaseDao的方法
                //返回受影响的行数
                i = BaseDao.updateResultSet(connection, sql, objects, statement);
            }
            //关闭资源
            BaseDao.close(null,statement,null);
            return i;
        }
    
    
  5. UserServlet层

    public interface UserService {
        //用户登录
        public User login(String userCode,String userPassword);
        //根据用户名修改密码
        public boolean UpdatePwd(String userCode,String userPassword);
    }
    
  6. UserService实现类

       public boolean UpdatePwd(String userCode, String userPassword) {
            Connection connection = BaseDao.getConnection();
            boolean flag = false;
            try {
                //调用dao层的方法进行修改
                if (userDao.UpdatePwd(connection,userPassword,userCode)>0){
                    flag = true;
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }finally {
                BaseDao.close(connection,null,null);
            }
            return flag;
        }
    
    
  7. 记得实现复用,需要提取方法!

     @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            String method = req.getParameter("method");
            if (method!=null && ("savepwd").equals(method)){
                this.updatepwd(req,resp);
            }
        }
    
    
    
        public void updatepwd(HttpServletRequest req, HttpServletResponse resp){
            //自己的思想,从前端拿数据
    //        //获得前端传来的数据
    //        String newpassword = req.getParameter("newpassword");//新密码
    //        String userCode = req.getParameter("userCode");
    //        //将数据放如业务层的方法中
    //        UserService serviceImp1 = new UserServiceImp1();
    //        boolean b = serviceImp1.UpdatePwd(userCode, newpassword);
    //        System.out.println(b);
            //老师的思想,从Session中拿数据
            //先拿到user
            Object o =  req.getSession().getAttribute(Constants.USER_SESSION);
            //新密码
            String newpassword = req.getParameter("newpassword");
            boolean flag = false;
            //判断,如果用户是存在的,并且新密码不为空则
            //StringUtils.isNullOrEmpty(newpassword)这个方法不为空返回false,我们这里是不为空的,所以也会返回false,所以要取反
            if (o!=null && !StringUtils.isNullOrEmpty(newpassword)){
                UserServiceImp1 userServiceImp1 = new UserServiceImp1();
                flag = userServiceImp1.UpdatePwd(((User) o).getUserCode(), newpassword);
                if (flag){//修改成功
                    req.setAttribute("message","密码修改成功,请重新登录!");
                    //移除session,通过过滤器用户重新登陆
                    req.getSession().removeAttribute(Constants.USER_SESSION);
                }else{
                    req.setAttribute("message","密码修改失败!!");
                }
            }else {
                req.setAttribute("message","新密码有问题!");
            }
            try {
                req.getRequestDispatcher("/jsp/pwdmodify.jsp").forward(req,resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
    
  8. 测试

优化密码修改使用Ajax

  1. 阿里巴巴的fastjson

    <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>fastjson</artifactId>
          <version>1.2.76</version>
        </dependency>
    
  2. 后台代码修改

    //验证旧密码,session中有旧密码
        public void pwdModify(HttpServletRequest req, HttpServletResponse resp){
            //从session中拿值
            Object o = req.getSession().getAttribute(Constants.USER_SESSION);
            String oldpassword = req.getParameter("oldpassword");//拿到ajax中的变量
    
            //万能的Map : 结果集
            Map<String, String> resultMap = new HashMap<String, String>();
            if (o==null){//Session失效了,过期了
                resultMap.put("result","sessionerror");
            }else if (StringUtils.isNullOrEmpty(oldpassword)){//输入的旧密码为空
                resultMap.put("result","error");
            }else {//拿到o中的密码,来比较
                String userPassword = ((User) o).getUserPassword();
                if (userPassword.equals(oldpassword)){//如果密码一致
                    resultMap.put("result","true");
                }else {
                    resultMap.put("result","false");
                }
            }
    
            //返回上面的到的结果集
            resp.setContentType("application/json");
            try {
                PrintWriter writer = resp.getWriter();
                //JSONArray 阿里巴巴 的JSON工具类,转换格式
                /*
                resultMap=["result","error"],这是Map对象,我们这里想要JSON字符串
                * */
                //将resultMap对象通过toJSONString()转换成JSON字符串
                writer.write(JSONArray.toJSONString(resultMap));
                writer.flush();
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值