登录注册案例

登录注册案例

页面准备


    <form action="LoginServlet" method="post">
        user:<input type="text" name="username"><br>
        pwd:<input type="text" name="password"><br>
        验证码:<input type="text" name="_img">
        <img src="/Checkcode"  id="_img"><br>
        <input type="submit">
    form>
    <script>
        window.onload = function () {
            var _img = document.getElementById("_img");
            _img.onclick = function () {
                var date = new Date();
                _img.src ="/Checkcode?"+date.getTime();
            };
        }
    script>

数据库

CREATE TABLE `t_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(25) DEFAULT NULL,
  `password` varchar(25) DEFAULT NULL,
  `nickname` varchar(25) DEFAULT NULL,
  `createdtime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `updatedtime` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

druid.properties

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///test
username=root
password=root

# 初始化连接数量
initialSize=5
# 最大连接数
maxActive=10
# 最大等待时间
maxWait=3000

实现类

public class User {
    private int id;
    private String username;
    private String password;
    private String nickname;
    //提供有参无参构造方法
    //提供get set方法
    //提供 toString方法
}

验证码

@WebServlet(urlPatterns = "/Checkcode")
public class Checkcode extends HttpServlet {
    private static final int WIDTH = 100;//设置验证码图片宽度
    private static final int HEIGHT = 30;//设置验证码图片高度
    private static final int LENGTH = 4;//设置验证码长度
    public static final int LINECOUNT=20;//干扰线的数目

    //验证码的字符库
    private static final String str="0123456789"+
            "ABCDEFGHIJKLMNOPQRSTUVWXYZ"+
            "abcdefghijklmnopqrstuvwxyz";

    //通过随机数取字符库中的字符组合成4位验证码
    private static Random random=new Random();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置数据类型为图片
        resp.setContentType("image/jpeg");

        //设置不进行缓存
        resp.setHeader("pragma", "no-cache");
        resp.setHeader("cache-control", "no-cache");
        resp.setHeader("expires", "0");

        //获取画笔
        BufferedImage image=new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_3BYTE_BGR);
        Graphics g=image.getGraphics();

        //设置背景颜色并绘制矩形背景
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, WIDTH, HEIGHT);

        //验证码的绘制
        String code=drawChar(g);
        System.out.println("验证码:"+code);

        //随机线的绘制
        for (int i=0;i<LINECOUNT;i++){
            drawLine(g);
        }

        //在session中存入当前的code码,便于验证
        req.getSession().setAttribute("code",code);

        //绘制图片
        g.dispose();

        //将图片输出到response中
        ImageIO.write(image, "JPEG", resp.getOutputStream());
    }


    //获取不同颜色
    public  Color getColor(){
        return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
    }

    //获取字体样式
    public Font getFont() {
        return new Font("Fixedsys", Font.CENTER_BASELINE, 20);
    }

    //绘制字符
    public String drawChar(Graphics g){
        String code="";
        g.setFont(getFont());
        for (int i=0;i<LENGTH;i++){
            char c=str.charAt(random.nextInt(str.length()));
            g.setColor(getColor());
            g.drawString(c+"", 20* i + 10, 20);
            code=code+c;
        }
        return code;
    }

    //绘制随机线
    public  void drawLine(Graphics g) {
        int x = random.nextInt(WIDTH);
        int y = random.nextInt(HEIGHT);
        int xl = random.nextInt(13);
        int yl = random.nextInt(15);
        g.setColor(getColor());
        g.drawLine(x, y, x + xl, y + yl);
    }
}

工具类

public class JDBCUtils {
    //1.定义成员变量 DataSource
    private static DataSource ds ;

    static{
        try {
            //1.加载配置文件
            Properties pro = new Properties();
            pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            //2.获取DataSource
            ds = DruidDataSourceFactory.createDataSource(pro);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接池方法
     */
    public static DataSource getDataSource(){
        return  ds;
    }

}

web层

@WebServlet(urlPatterns = "/ServletLogin")
public class ServletLogin extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置字符集
        request.setCharacterEncoding("utf-8");

        //TODO 测试阶段,不用验证码
        /*
        //判断验证码是否正确
        //获取用户输入的验证码
        String _img = request.getParameter("_img");
        //获取服务器生成的验证码
        HttpSession session = request.getSession();
        String code = (String) session.getAttribute("code");
        //为了保证验证是有效的唯一,把上一个给清了
        session.removeAttribute("code");

        //判断
        if(!_img.equalsIgnoreCase(code)){
            //提示用户
            request.setAttribute("msg","验证码不正确!");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
            return;
        }*/

        /*//获取用户输入的数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //封装
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);*/

        //获取用户输入所有的数据
        Map<String, String[]> map = request.getParameterMap();
        //封装
        User user = new User();

        try {
            //通过BeanUtils自动封装
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


        //注入业务层
        UserService service = new UserServiceImpl();

        //调用业务层方法
        User u = service.loginUser(user);

        //判断
        if(u != null){
            //表示登录成功
            System.out.println("登录成功");
            request.getRequestDispatcher("/success.html").forward(request,response);
        }else {
            //登录失败
            System.out.println("登录失败");
            request.getRequestDispatcher("/login.html").forward(request,response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

@WebServlet(urlPatterns = "/registUserServlet")
public class registUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //解决post请求乱码问题
        request.setCharacterEncoding("utf-8");

        //判断验证码是否正确
        //获取用户输入的验证码
        String _img = request.getParameter("_img");
        //获取服务器生成的验证码
        HttpSession session = request.getSession();
        String code = (String) session.getAttribute("code");
        //为了保证验证是有效的唯一,把上一个给清了
        session.removeAttribute("code");

        //判断
        if(!_img.equalsIgnoreCase(code)){
            //提示用户
            request.setAttribute("msg","验证码不正确!");
            request.getRequestDispatcher("/regist.jsp").forward(request,response);
            return;
        }

        /*//获取用户注册的所有数据
        String username = request.getParameter("username");
        String nickname = request.getParameter("nickname");
        String password = request.getParameter("password");

        //进行封装
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setNickname(nickname);*/

        //以上这些代码好,但是如果要获了的数据比较多,那就不态好用显的麻烦

        //获取用户提交过来所有数据
        Map<String, String[]> map = request.getParameterMap();
        //进行封装
        User user = new User();

        try {
            //使用beanutils工具类。可以帮我获取所有数据进行自动封装,前提获取的输入框的名字要和实体类中的名一致
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


        //注入业务层
        UserService service = new UserServiceImpl();

        //传递业务层
        Boolean blg =  service.registUser(user);

        if(blg){
            //注册成功之后跳到login.html
            System.out.println("注册成功");
            request.getRequestDispatcher("/login.html").forward(request,response);
        }else{
            System.out.println("用户名已存在!!");
            request.getRequestDispatcher("/regist.html").forward(request,response);
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

service层

public interface UserService {

    //注册
    Boolean registUser(User user);

    //登录
    User loginUser(User user);
}
public class UserServiceImpl implements UserService {

    //注入dao
    private UserDao dao = new UserDaoImpl();

    //注册
    @Override
    public Boolean registUser(User user) {

        //注册不能注册相同的用户名
        User u = dao.findByUserName(user.getUsername());
        if(u == null){
            //可以注册
            dao.registUser(user);
            return true;
        }
        return false;
    }

    //登录
    @Override
    public User loginUser(User user) {
        return this.dao.loginUser(user);
    }
}

dao层

public interface UserDao {

    //注册去重名
    User findByUserName(String username);

    //直接注册
    void registUser(User user);

    //登录
    User loginUser(User user);
}
public class UserDaoImpl implements UserDao {

    //注入jdbcTemplate
    private JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());

    //根据用户查询用户名
    @Override
    public User findByUserName(String username) {
        try {
            String sql ="select * from user where username = ?";
            return this.jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), username);
        } catch (Exception e) {
            return  null;
        }
    }

    //注册
    @Override
    public void registUser(User user) {

        String sql ="INSERT INTO `customer`.`user`(`id`, `username`, `password`, `nickname`, `createdtime`, `updatedtime`) VALUES (?, ?, ?, ?, ?, ?)";
        this.jdbcTemplate.update(sql,null,user.getUsername(),user.getPassword(),user.getNickname(),new Date(),new Date());

    }

    //登录
    @Override
    public User loginUser(User user) {
        try {
            String sql = "select * from user where username =? and password = ?";
            return this.jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class),user.getUsername(),user.getPassword());
        } catch (Exception e) {
            return null;
        }

    }
}

测试

你可能感兴趣的:(tomcat)