一、登录
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交流的同时,还要与数据库中的数据打交道。
二、注册
1、Servlet实现注册的思路:
2、工程结构
3、功能实现:
(1)html实现对数据的收集:
<body bgcolor="aqua">
<center>
<h3>注册</h3>
<form action="/Register_servlet_war_exploded/register" method="post">
用户名:<input type="text" name="account" size="12"><br><br>
密码:<input type="password" name="password" size="12">
<input type="submit" value="注册">
<input type="reset" value="取消">
</form>
</center>
</body>
(2)Servlet:获取表单提交的数据,并将他们封装到Map集合中(可以减少代码量)
public class ServletRegister extends javax.servlet.http.HttpServlet {
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
request.setCharacterEncoding("UTF-8");
Map<String, String[]> properties=request.getParameterMap();//将表单中的数据封装到Map中
Login log= new Login();
try {
BeanUtils.populate(log, properties);
} catch (IllegalAccessException|InvocationTargetException e) {
e.printStackTrace();
}
try {
regist(log);
} catch (SQLException e) {
e.printStackTrace();
}
response.sendRedirect(request.getContextPath()+"/log.html");//重定向
}
public void regist(Login log) throws SQLException{//数据库
Connection con=null;
try {
con = C3p0Utils.getConnection();
QueryRunner qr = new QueryRunner();
String sql = "insert into Login values(?,?)";
Object[] insert = {log.getAccount(), log.getPassword()};
qr.update(con, sql, insert);
}
catch (SQLException e){
throw new RuntimeException(e);
}
}