下面是我自己寫的一個關於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文件,裡面寫的是你數據庫的地址、用戶和密碼
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 >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 >
<%
String msg = (String) request.getAttribute("msg");
if (msg == null) {
out.println();
} else {
out.println(msg);
}
%>
</span>
</div>
</body>
</html>
訪問localhost:8080/項目名/Login,就能看到
注意:上面重定向之後的頁面我都沒傳,這個要自己寫jsp
說的不是怎麼好,看注釋應該可以理解到~~