1、登录过程分析:
通过表单收集用户的数据,Servlet通过request对象获得用户提交的数据,服务器还需要从数据库中通过sql语句查询有没有表单提交的数据中的用户。有则登录成功,否则,登录失败。
2、工程结构:
3、主要代码分析:
<body bgcolor="aqua"> <center> <h3>登录</h3> <form action="/Login_war_exploded/log" method="get"> 用户名:<input type="text" name="username" size="12"><br> 密 码 :<input type="password" name="password" size="6" ><br><br> <input type="reset" value="取消"> <input type="submit" value="登录"> </form> </center> </body>
(1)通过定义表单为Servlet提供数据,其中的name属性的值与Servlet的request.getParameter的参数相同,实现了html页面与服务器的联系。
(2)action属性实现了页面的跳转,即提交数据之后去执行Servlet,action的属性值为工程名与Servlet名的组合。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Connection con=null; login log= null; String account=request.getParameter("username");//获得表单数据 String password=request.getParameter("password"); try { con=C3p0Utils.getConnection(); QueryRunner qr = new QueryRunner(); String sql = "Select * from login where account=? and password=?"; Object[] select = {account,password}; log = qr.query(con, sql, new BeanHandler<login>((login.class)), select); if(log!=null){ response.getWriter().write("nihao"+account); } else{ response.getWriter().write("wrong"); } } catch (SQLException e) { throw new RuntimeException(e); } }
Servlet在html页面与数据库之间,在完成与html交流的同时,还要与数据库中的数据打交道。