[原创]java WEB学习笔记12:一个简单的serlet连接数据库实验

本博客为原创:综合 尚硅谷(http://www.atguigu.com)的系统教程(深表感谢)和 网络上的现有资源(博客,文档,图书等),资源的出处我会标明

本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用

内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系。

本人互联网技术爱好者,互联网技术发烧友

微博:伊直都在0221

QQ:951226918

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 1.需求和步骤

1)在MySql 数据库中创建users:id ,user,password 。添加记录

2)定义一个login.html ,定义两个字段:user,password 。发送请求到LoginServlet

3)创建一个LoginServlet(继承HttpServlet,重写doPost方法),在其中获取请求的user,password

4) 利用JDBC 从users 中查询有没有和页面输入的user,password 对应的记录。若有,响应hello:xxx,若没有,sorry:xxx ,其中xxx为user

 

2.代码结构

1)com.jason.testweb.LoginServlet:Servlet类,处理前台提交的数据

 1 package com.jason.testweb;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 import java.sql.Connection;
 6 import java.sql.PreparedStatement;
 7 import java.sql.ResultSet;
 8 import java.sql.SQLException;
 9 
10 import javax.servlet.ServletException;
11 import javax.servlet.http.HttpServlet;
12 import javax.servlet.http.HttpServletRequest;
13 import javax.servlet.http.HttpServletResponse;
14 
15 import com.jason.util.JDBCUtil;
16 
17 public class LoginServlet extends HttpServlet {
18 
19     /**
20      * 
21      */
22     private static final long serialVersionUID = 2197552322420611512L;
23 
24     @Override
25     protected void doPost(HttpServletRequest request,
26             HttpServletResponse response) throws ServletException, IOException {
27 
28         String userName = request.getParameter("username");
29         String passWord = request.getParameter("password");
30         PrintWriter printWriter = response.getWriter();
31 
32         Connection connection = null;
33         PreparedStatement preparedStatement = null;
34         ResultSet resultSet = null;
35 
36         try {
37             connection = JDBCUtil.getConnection();
38             String sql = "SELECT count(id) FROM users WHERE username = ? AND password = ? ";
39             preparedStatement = connection.prepareStatement(sql);
40             preparedStatement.setString(1, userName);
41             preparedStatement.setString(2, passWord);
42 
43             resultSet = preparedStatement.executeQuery();
44 
45             if (resultSet.next()) {
46                 int count = resultSet.getInt(1);
47                 if (count > 0) {
48                     printWriter.print("hello : " + userName);
49                 } else {
50                     printWriter.print("sorry : " + userName);
51                 }
52             }
53 
54         } catch (Exception e) {
55             e.printStackTrace();
56         } finally {
57             JDBCUtil.closeAll(connection, preparedStatement, resultSet);
58         }
59 
60     }
61 
62 }

 

 

2)com.jason.testweb.JDBCUtil:JDBU工具类,获取连接,和关闭资源

 

 1 package com.jason.util;
 2 
 3 import java.sql.Connection;
 4 import java.sql.DriverManager;
 5 import java.sql.PreparedStatement;
 6 import java.sql.ResultSet;
 7 import java.sql.SQLException;
 8 
 9 public class JDBCUtil {
10 
11     // 获取连接
12     public static Connection getConnection() throws Exception {
13 
14         String driverClass = "com.mysql.jdbc.Driver";
15         String JDBCurl = "jdbc:mysql://127.0.0.1:3306/atguigu";
16         String user = "root";
17         String password2 = "zhangzhen";
18         Class.forName(driverClass);
19         return DriverManager.getConnection(JDBCurl, user, password2);
20     }
21 
22     // 关闭流
23     public static void closeAll(Connection con, PreparedStatement ps,
24             ResultSet rs) {
25 
26         if (rs != null) {
27             try {
28                 rs.close();
29             } catch (SQLException e) {
30                 // TODO Auto-generated catch block
31                 e.printStackTrace();
32             }
33         }
34         if (ps != null) {
35             try {
36                 ps.close();
37             } catch (SQLException e) {
38                 // TODO Auto-generated catch block
39                 e.printStackTrace();
40             }
41         }
42         if (con != null) {
43             try {
44                 con.close();
45             } catch (SQLException e) {
46                 // TODO Auto-generated catch block
47                 e.printStackTrace();
48             }
49         }
50 
51     }
52 
53 }

 

 

3)login.html:显示页面

 

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 2 <html>
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 5 <title>this is a test </title>
 6 </head>
 7 <body>
 8     <form action="login" method="post">
 9     
10         user:<input type="text" name="username"/>
11         password:<input type="password" name="password"/>
12             
13         <input type="submit" value="submit"/>
14         
15     </form>
16 </body>
17 </html>

 

 

4)web.xml:配置Servlet 和 映射 Servlet

 

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3     xmlns="http://java.sun.com/xml/ns/javaee"
 4     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 5     id="WebApp_ID" version="3.0">    
 6 <!-- 配置和映射servlet -->
 7     <servlet>
 8         <servlet-name>LoginServlet</servlet-name>
 9         <servlet-class>com.jason.testweb.LoginServlet</servlet-class>
10     </servlet>
11     
12     <servlet-mapping>
13         <servlet-name>LoginServlet</servlet-name>
14         <url-pattern>/login</url-pattern> <!-- 和提表单提交的 action 一致 -->
15     </servlet-mapping>
16     
17 </web-app>

 

 

  

 3.总结分析

1)本实验只是模拟了一次完整的由 view -> control -> model

2) 本实验未使用连接池:c3p0

3)缺少模块化设计

 

posted @ 2016-05-19 22:16  jason_zhangz  阅读(345)  评论(0编辑  收藏  举报