smbms

//BaseDao.java

package com.charles.dao;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

//操作数据库公共类
public class BaseDao {

    private static String driver;
    private static String url;
    private static String username;
    private static String password;


    //静态代码块启动就会初始化
    static {
        //通过类加载器读取对应资源
        InputStream is = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
        Properties properties = new Properties();//获取一个资源对象
        try {
            properties.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //属性赋值
        driver = properties.getProperty("driver");
        url = properties.getProperty("url");
        username = properties.getProperty("username");
        password = properties.getProperty("password");
    }


    //获取数据库的链接

    public static Connection getConnection() {
        Connection connection = null;
        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, username, password);


        } catch (Exception e) {
            e.printStackTrace();
        }

        return connection;
    }


    //编写查询公共类
    public static ResultSet execute(Connection connection, String sql, Object[] params, ResultSet resultSet, PreparedStatement preparedStatement) throws SQLException {
        preparedStatement = connection.prepareStatement(sql);

        for (int i = 0; i < params.length; i++) {
            //设置占位符从1开始,但是数组从0开始,便于计数
            preparedStatement.setObject(i + 1, params[i]);
        }

        resultSet = preparedStatement.executeQuery();
        return resultSet;

    }

    //编写增删改公共方法

    public static int execute(Connection connection, String sql, Object[] params, PreparedStatement preparedStatement) throws SQLException {
        preparedStatement = connection.prepareStatement(sql);

        for (int i = 0; i < params.length; i++) {
            //设置占位符从1开始,但是数组从0开始,便于计数
            preparedStatement.setObject(i + 1, params[i]);
        }

        int update = preparedStatement.executeUpdate();
        return update;

    }
    

    //关闭链接释放资源
    public  static boolean closeResource(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet){
        boolean flag=true;
        if(resultSet!=null){
            try {
                resultSet.close();
                resultSet=null;
            } catch (SQLException e) {
                e.printStackTrace();
                flag=false;
            }
        }
        if(preparedStatement!=null){
            try {
                preparedStatement.close();
                preparedStatement=null;
            } catch (SQLException e) {
                e.printStackTrace();
                flag=false;
            }
        }
        if(connection!=null){
            try {
                connection.close();
                connection=null;
            } catch (SQLException e) {
                e.printStackTrace();
                flag=false;
            }
        }
        
        return flag;
    }
    
}

//编写得到的用户
package com.charles.dao.user;

import com.charles.dao.BaseDao;
import com.charles.pojo.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaoImpl implements UserDao {
    @Override
    public User getLoginUser(Connection connection, String userCode) throws SQLException {

        PreparedStatement pstm = null;
        ResultSet rs = null;
        User user = null;
        String sql = "select * from smbms_user where userCode=?";
        Object[] parms = {userCode};

        if (connection != null) {

            rs = BaseDao.execute(connection, pstm, rs, sql, parms);
            if (rs.next()) {
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUserCode(rs.getString("userCode"));
                user.setUserName(rs.getString("userName"));
                user.setUserPassword(rs.getString("userPassword"));
                user.setGender(rs.getInt("gender"));
                user.setBirthday(rs.getDate("birthday"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
                user.setUserRole(rs.getInt("userRole"));
                user.setCreatedBy(rs.getInt("createdBy"));
                user.setCreationDate(rs.getTimestamp("creationDate"));
                user.setModifyBy(rs.getInt("modifyBy"));
                user.setModifyDate(rs.getTimestamp("modifyDate"));

            }
            BaseDao.closeResource(null, pstm, rs);


        }
        return user;
    }
}

下面写业务层:

编写servlet:

public class LoginServlet extends HttpServlet {
    //处理登陆请求
    //控制层调用业务层代码

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("进入loginservlet--start");
        //获取用户名密码
        String userCode = req.getParameter("userCode");

        String userPassword = req.getParameter("userPassword");

        //调用sql代码,看密码
        UserServiceImpl userService = new UserServiceImpl();
        User user = userService.login(userCode, userPassword);

        if(user!=null){
            //将用户信息放入session,随时查询
            req.getSession().setAttribute(Constants.USER_SESSION,user);
           // 跳转到别的页面
            resp.sendRedirect("jsp/frame.jsp");

        }else {
            //无法登陆,转发回去登陆页面,顺便提示用户名密码错误
            req.setAttribute("error","用户名或者密码错误");
            req.getRequestDispatcher("login.jsp").forward(req,resp);

        }


    }

拿到项目的路径

// 跳转到别的页面
 resp.sendRedirect(req.getContextPath()+"jsp/frame.jsp");

登录拦截优化

把要更新的东西丢进去数组里面执行

@Override
public int updatePwd(Connection connection, int id, int password) throws SQLException {
     String sql = "update smbms_user set userPassword =? where id=?";
        int excute=0;
        PreparedStatement pstm = null;
        if(connection!=null) {

            Object parms[] = {password, id};

             excute = BaseDao.excute(connection, pstm, sql, parms);

            BaseDao.closeResource(connection, pstm, null);
        }
        return excute;
}

关键修改

if(flag){
    req.setAttribute("message","修改密码成功,退出使用新密码登陆");
    //密码修改成功移除session的这个用户,然后过滤器给你弹回去error界面
    req.getSession().removeAttribute(Constants.USER_SESSION);
    
    
        if (user != null) {
            //没有这个人
            chain.doFilter(req, resp);

        } else {
            response.sendRedirect("error.jsp");
        }
    }

缓存,热更新

Ajax:优化密码验证,失去焦点的时候就会发送请求,与数据库的字段进行对比

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dkbs5HPb-1617466740928)(image-20210329001631681.png)]

alibaba的json工具类

try {
    resp.setContentType("application/json");
    PrintWriter writer = resp.getWriter();
    //转换格式用的,把map键值对转化成json
    /*
    resultmap:{result,a,result,b....}
    * json:{key,value}
    * 
    * 
    * */
     writer.write(JSONArray.toJSONString(resultMap));
    //文件流的常用
      writer.flush();
      writer.close();
            
} catch (IOException e) {
    e.printStackTrace();
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-l1DRNiSf-1617466740930)(image-20210329002301335.png)]

if (connection != null) {
    //拼接sql
    StringBuffer sql = new StringBuffer();

    sql.append("select count(1)from smbms_user u,smbms_role r where u.userRole =r.id");

    ArrayList<Object> List = new ArrayList<Object>();//存放我们的参数


    if (StringUtils.isNullOrEmpty(username)) {
        sql.append("and u.userName like ?");
        List.add("%" + username + "%");//模糊查询
    }

    if (userRole > 0) {
        sql.append("and u.userRole like ?");
        List.add(userRole);//模糊查询
    }
    //把list转换为数组
    Object[] parms = List.toArray();

    System.out.println("UseDao->getUserCount:" + sql.toString());

    rs = BaseDao.excute(connection, preparedStatement, rs, sql.toString(), parms);

    if (rs.next()) {
        count = rs.getInt("count");
    }

    BaseDao.closeResource(null, preparedStatement, rs);

}

理解这个sql的拼接和模糊查询

理解为什么要构造这个对象

public class RoleServiceImpl implements RoleService {
    private RoleDao roleDao;

    public RoleServiceImpl() {
        roleDao=new RoleDaoImpl();
    }

string to int

Integer.parseInt(temp)
package com.charles.dao;


import org.junit.Test;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class BaseDao {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    static {
        InputStream is = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
        Properties properties = new Properties();
        try {
            properties.load(is);
            driver=properties.getProperty("driver");
            url=properties.getProperty("url");
            username=properties.getProperty("user");
            password=properties.getProperty("password");
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public static Connection getConnection(){
        Connection connection = null;
        try {
            //加载驱动,实现数据库操作,实例化Driver类对应的Class对象
            Class.forName(driver);
            //获取数据库连接
            connection = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  connection;
    }

    /**sql查询语句的公共方法
     * @author Coderlin
     * */
    public static ResultSet excute(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet,String sql,Object[] params) throws SQLException {

        //connection= BaseDao.getConnection();
        preparedStatement = connection.prepareStatement(sql);

        for (int i = 0; i < params.length; i++) {
            preparedStatement.setObject(i+1,params[i]);
        }
        resultSet = preparedStatement.executeQuery();
        return resultSet;
    }

    /**sql增删改的公共方法
     * @author Coderlin
     * */
    public static int excute(Connection connection,PreparedStatement preparedStatement,String sql,Object[] params) throws SQLException {

        //connection= BaseDao.getConnection();
        preparedStatement = connection.prepareStatement(sql);

        for (int i = 0; i < params.length; i++) {
            preparedStatement.setObject(i+1,params[i]);
        }
        int updateRows = preparedStatement.executeUpdate();
        return updateRows;
    }

    /**释放资源方法
     *
     * */
    public static boolean closeResource(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet){
        //关闭方法是否成功
        boolean flag = true;

        if(resultSet!=null){
            try {
                resultSet.close();
                //GC会进行回收
                resultSet=null;
            } catch (SQLException throwables) {
                throwables.printStackTrace();
                flag = false;
            }
        }

        if(preparedStatement!=null){
            try {
                preparedStatement.close();
                //GC会进行回收
                preparedStatement=null;
            } catch (SQLException throwables) {
                throwables.printStackTrace();
                flag = false;
            }
        }

        if(connection!=null){
            try {
                connection.close();
                //GC会进行回收
                connection=null;
            } catch (SQLException throwables) {
                throwables.printStackTrace();
                flag = false;
            }
        }

        return flag;
    }

}
            } catch (SQLException throwables) {
                throwables.printStackTrace();
                flag = false;
            }
        }

        if(connection!=null){
            try {
                connection.close();
                //GC会进行回收
                connection=null;
            } catch (SQLException throwables) {
                throwables.printStackTrace();
                flag = false;
            }
        }

        return flag;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值