单列模式下的数据库连接与Servlet之间页面访问用户登录的小例子
下面是我自己写的一个关于servlet的例子
首先是数据库配置,使用的是静态的单例模式
代码如下:
/ 数据库地址连接 // 使用静态单列模式 public class JdbcUtil { private static String driverName; private static String url; private static String username; private static String password; private static Properties properties = new Properties(); private static JdbcUtil jdbcUtil; private JdbcUtil() { } public static JdbcUtil getInstance() { if (jdbcUtil == null) { jdbcUtil = new JdbcUtil(); } return jdbcUtil; } public static void main(String[] args) { JdbcUtil model = new JdbcUtil(); } static { try { // 调用resource包下的dbconfig.properties文件 InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("dbconfig.properties"); properties.load(in); driverName = properties.getProperty("driverName"); url = properties.getProperty("url"); username = properties.getProperty("username"); password = properties.getProperty("password"); // 注册 Class.forName(driverName); } catch (Exception e) { e.printStackTrace(); } } public Connection getConnection() { Connection connection = null; try { // 连接 connection = DriverManager.getConnection(url, username, password); } catch (Exception e) { e.printStackTrace(); } return connection; } public void close(Connection connection, Statement stmt, ResultSet rs) { // 关闭 if (rs != null) { try { rs.close(); } catch (Exception e) { e.printStackTrace(); } } if (stmt != null) { try { stmt.close(); } catch (Exception e) { e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (Exception e) { e.printStackTrace(); } } } }
创建一个source文件夹命名为resources,在其创建dbconfig.properties文件,里面写的是你数据库的地址、用户和密码
![](https://images2015.cnblogs.com/blog/919023/201603/919023-20160328142255207-214025763.png)
driverName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
username=root
password=1
接着,创建实体类User
// POJO实体类 public class User { // 用户名 private String username; // 密码 private String password; public User() { super(); } // get、set方法 public User(String username, String password) { super(); this.username = username; this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } // toString方法 @Override public String toString() { return "User [username=" + username + ", password=" + password + "]"; } }
创建接口的dao包
// 接口 public interface IUserDao { // 增加 public abstract boolean insertUser(User model); // 删除 public abstract boolean deleteUser(String userName); // 修改 public abstract boolean updateUser(User model); // 查询(所有) public abstract List<User> findAll(); // 查询(条件) public abstract boolean findByTerm(User model); }
然后实现接口的方法,里面直接写sql语句
// 接口实现 public class UserDaoImpl implements IUserDao { /** * 用户增加 */ @Override public boolean insertUser(User model) { boolean flag = false; Connection connection = null; PreparedStatement pstmt = null; try { // 连接 connection = JdbcUtil.getInstance().getConnection(); // SQL语句 String sql = " INSERT INTO user (username,`password`) VALUES (?,?)"; // 创建Statement对象 pstmt = connection.prepareStatement(sql); pstmt.setString(1, model.getUsername()); pstmt.setString(2, model.getPassword()); // 执行 int result = pstmt.executeUpdate(); System.out.println("受影响的行数" + result); flag = true; } catch (Exception e) { flag = false; e.printStackTrace(); } finally { // 关闭 JdbcUtil.getInstance().close(connection, pstmt, null); } return flag; } /** * 用户删除 */ @Override public boolean deleteUser(String userName) { boolean flag = false; Connection connection = null; PreparedStatement pstmt = null; try { // 连接 connection = JdbcUtil.getInstance().getConnection(); // SQL语句 String sql = "DELETE FROM user WHERE username = ? "; // 创建Statement对象 pstmt = connection.prepareStatement(sql); pstmt.setString(1, userName); // 执行 int result = pstmt.executeUpdate(); System.out.println("受影响的行数" + result); flag = true; } catch (Exception e) { flag = false; e.printStackTrace(); } finally { // 关闭 JdbcUtil.getInstance().close(connection, pstmt, null); } return flag; } /** * 用户修改 */ @Override public boolean updateUser(User model) { boolean flag = false; Connection connection = null; PreparedStatement pstmt = null; try { // 连接 connection = JdbcUtil.getInstance().getConnection(); // SQL语句 String sql = "UPDATE user SET `password` = ? WHERE username = ? "; // 创建Statement对象 pstmt = connection.prepareStatement(sql); pstmt.setString(1, model.getPassword()); pstmt.setString(2, model.getUsername()); System.err.println(pstmt); // 执行 int result = pstmt.executeUpdate(); System.out.println("受影响的行数" + result); flag = true; } catch (Exception e) { flag = false; e.printStackTrace(); } finally { // 关闭 JdbcUtil.getInstance().close(connection, pstmt, null); } return flag; } /** * 用户查询(所有) */ @Override public List<User> findAll() { List<User> list = new ArrayList<User>(); Connection connection = null; PreparedStatement pstmt = null; ResultSet rs = null; try { // 连接 connection = JdbcUtil.getInstance().getConnection(); // SQL语句 String sql = "SELECT * FROM user"; // 创建Statement对象 pstmt = connection.prepareStatement(sql); // 执行 rs = pstmt.executeQuery(); // 游标向下移动一行 while (rs.next()) { User model = new User(); model.setUsername(rs.getString("username")); model.setPassword(rs.getString("password")); // 添加到集合 list.add(model); } } catch (Exception e) { e.printStackTrace(); } finally { JdbcUtil.getInstance().close(connection, pstmt, null); } return list; } /** * 用户查询(根据条件) */ public boolean findByTerm(User model) { boolean flag = false; Connection connection = null; PreparedStatement pstmt = null; ResultSet rs = null; try { // 连接 connection = JdbcUtil.getInstance().getConnection(); // SQL语句 String sql = "SELECT * FROM user WHERE username=? AND `password` = ? "; // 创建Statement对象 pstmt = connection.prepareStatement(sql); pstmt.setString(1, model.getUsername()); pstmt.setString(2, model.getPassword()); // 执行 rs = pstmt.executeQuery(); // 判断数据库是否为空 if (rs != null && rs.next()) { flag = true; } } catch (Exception e) { e.printStackTrace(); } finally { // 关闭 JdbcUtil.getInstance().close(connection, pstmt, null); } return flag; } }
最后写servlet
/** * Servlet implementation class Login 登录页面 */ @WebServlet("/Login") public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 在reques请求接收参数之前,先设置请求的字符编码为UTF-8 request.setCharacterEncoding("UTF-8"); // 在response响应返回数据时,也要设置 response.setContentType("text/html; charset=UTF-8"); response.setCharacterEncoding("UTF-8"); // 调用实体类 User model = new User(); // 获取http提交过来的数据 model.setUsername(request.getParameter("username")); model.setPassword(request.getParameter("password")); // 调用接口实现的方法 IUserDao dao = new UserDaoImpl(); // 判断是否为空 if (model.getUsername() == null || model.getPassword() == null) { // 转发到登录界面 request.getRequestDispatcher("jsp/login.jsp").forward(request, response); } else { // 调用条件查找的方法,判断数据库有无该数据 if (dao.findByTerm(model)) { // 重定向到进入页面 response.sendRedirect("jsp/index.jsp"); } else { request.setAttribute("msg", "帐户或密码出错!"); // 还是留在登录界面 request.getRequestDispatcher("jsp/login.jsp").forward(request, response); } } } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }
login.jsp下面的代码
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>C9登录界面</title> <meta charset="UTF-8" /> <link href="css/bootstrap.min.css" rel="stylesheet"> <link href="css/login.css" rel="stylesheet" type="text/css" /> <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script> <script src="js/login.js" type="text/javascript"></script> <script src="js/image.js" type="text/javascript"></script> </head> <body id="main" onload="showBgImage();init();"> <form action="Login" method="post"> <div class="login_m"> <div class="login_logo"> <h1 style="font-family: '宋体'; font-size: 36px;">C9决策分析门户登录</h1> </div> <div class="login_boder"> <div class="login_padding"> <div class="form-group"> <label for="userName"></label> <input type="text" class="form-control " id="txtUserName" name="username" placeholder="用户名"> </div> <div class="form-group"> <label for="passWord"></label> <input type="password" class="form-control" id="txtPassWord" name="password" placeholder="密码"> </div> <div class="rem_sub"> <div class="rem_sub_l"> <input type="checkbox" name="checkbox" id="chkRemember"> <label for="chkRemember">下次自动登录</label> </div> <div class="join"> <input type="submit" id="btnSubmit" name="submit" class="btn btn_block btn_success" value="登录" /> </div> </div> <div class="forgot"> <a href="jsp/forget.jsp">忘记密码?</a> <span class="split"></span> <a href="jsp/register.jsp">免费注册</a> </div> </div> <footer class="footer"> <i><a href="http://www.cnbisoft.com">经邦信息技术有限公司</a></i> <br> <span>经邦软件 2010 ©2008-2016 皖ICP备15018743号</span> <div class="time" id="txt"></div> </footer> </div> </div> </form> <div class="msg"> <span style="color: red; margin-top: 10px;"> <% String msg = (String) request.getAttribute("msg"); if (msg == null) { out.println(); } else { out.println(msg); } %> </span> </div> </body> </html>
访问localhost:8080/项目名/Login,就能看到
注意:上面重定向之后的页面我都没传,这个要自己写jsp
说的不是怎么好,看注释应该可以理解到~~