用servlet进行用户名和密码校验

 目录结构:

 

一、在Email_Login.jsp中,创建表单

 

 

当输入账号和密码,提交到${pageContext.request.contextPath }/LoginTestServlet"

二、创建servlet:LoginTestServlet

代码如下

  1. 修改编码方式
  2. 使用request.getParameter()方法获取表单中的name和password
  3. 实例化UserServiceImpl方法,调用其方法findUserByNameAndPwd(User user),返回值为int num,如果数据库中包含符合条件的User,则num的值大于零,页面转到邮箱界面(由于仅为模拟情况,实际操作其转到百度首页)
  4. 调用UserService、UserDao等请看后续

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

        // TODO Auto-generated method stub

        response.setContentType("test/html;charset=utf-8");

        request.setCharacterEncoding("utf-8");

        //获取前台的数据

        String name=null;

        name=request.getParameter("name");

        System.out.println(name);

        String password=null;

        password=request.getParameter("password");

        //查询数据库中与name和password匹配的数量,不等于零代表正确

        int num=0;

        UserService uService=new UserServiceImpl();

        num=uService.getUserByNameAndPwd(name,password);

        if(num==0) {

            System.out.println("密码错误,请检查账号和密码");

            request.getRequestDispatcher("/EmailLogin.jsp").forward(request, response);

        }else {

            System.out.println("密码正确,欢迎");

            request.getRequestDispatcher("/EmailLogin.jsp").forward(request, response);

        }

三、创建UserService接口及其实现类UserServiceImpl

 

 

四、创建UserDao接口及其实现类UserDaoImpl类

使用JDBC方法在User表中对比是否存在相应的用户,返回int值给LoginTestServlet交给其判断

public class UserDaoImpl implements UserDao{

 

    @Override

    public int getUserByNameAndPwd(String name, String password) {

        // TODO Auto-generated method stub

        //使用JDBC实现

        int count=0;

        try {

            Class.forName("com.mysql.jdbc.Driver");

            Connection connection=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/db1?useUnicode=true&characterEncoding=utf-8","root","123");

            PreparedStatement pStatement=connection.prepareStatement("select count(*) from user where name='"+name+"'"+"and password='"+password+"'");

            ResultSet rSet=pStatement.executeQuery();

            while(rSet.next()) {count++;}

        } catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

       

        return count;

    }

   

}

五、运行效果

 

 密码正确

 用户名和密码正确,重定向到http://www.baidu.com

 

posted @ 2019-03-17 16:39  借我两块买雪糕  阅读(3594)  评论(0编辑  收藏  举报