?? auto_save.jsp
字號:
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ page language="java"%>
<%@ page import="java.sql.*,ajax.db.DBUtils,java.text.SimpleDateFormat,java.util.Date"%>
<%!
//保存用戶輸入內容
void saveContent(String userName, String content) {
String sql = "update draft set draft = ? where username = ?";//定義更新數據庫的SQL語句
String sqlInsert = "insert into draft(username, draft) values (?,?)";//定義插入SQL語句
Connection conn = null; //聲明Connection對象
PreparedStatement pstmt = null; //聲明PreparedStatement對象
try {
conn = DBUtils.getConnection(); //獲取數據庫連接
pstmt = conn.prepareStatement(sql); //根據sql創建PreparedStatement
pstmt.setString(1, content); //設置草稿內容
pstmt.setString(2, userName); //設置用戶名
int rows = pstmt.executeUpdate(); //執行更新
//如果返回值為0,表示記錄尚不存在,改為執行插入語句
if (rows == 0) {
pstmt.close(); //關閉PreparedStatement
pstmt = conn.prepareStatement(sqlInsert);//根據sql創建PreparedStatement
pstmt.setString(1, userName); //設置用戶名
pstmt.setString(2, content); //設置草稿內容
pstmt.executeUpdate(); //執行插入
}
} catch (SQLException e) {
System.out.println(e.toString());
} finally {
DBUtils.close(pstmt); //關閉PreparedStatement
DBUtils.close(conn); //關閉連接
}
}
//獲取保存的草稿內容
String getContent(String userName) {
String content = null; //用于保存草稿內容
String sql = "select draft from draft where username = ?"; //定義查詢數據庫的SQL語句
Connection conn = null; //聲明Connection對象
PreparedStatement pstmt = null; //聲明PreparedStatement對象
ResultSet rs = null; //聲明ResultSet對象
try {
conn = DBUtils.getConnection(); //獲取數據庫連接
pstmt = conn.prepareStatement(sql); //根據sql創建PreparedStatement
pstmt.setString(1, userName); //設置用戶名
rs = pstmt.executeQuery(); //執行查詢
if (rs.next()) {
content = rs.getString(1); //保存獲取到的內容
}
//如果內容未獲取成功,將其改為空字符串
if (content == null) {
content = "";
}
} catch (SQLException e) {
System.out.println(e.toString());
} finally {
DBUtils.close(rs); //關閉結果集
DBUtils.close(pstmt); //關閉PreparedStatement
DBUtils.close(conn); //關閉連接
}
return content;
}
//按格式獲取當前時間
String getNowDate() {
SimpleDateFormat formatter = new SimpleDateFormat("MM月dd日 HH:mm:ss"); //聲明輸出格式
return formatter.format(new Date());
}
%>
<%
out.clear(); //清空當前的輸出內容(空格和換行符)
request.setCharacterEncoding("UTF-8"); //設置請求體字符編碼格式為UTF-8
String userName = request.getParameter("userName"); //獲取用戶名
String content = request.getParameter("content"); //獲取用戶輸入的文本
String action = request.getParameter("action"); //獲取要執行的操作
//執行保存操作
if ("save".equals(action)) {
saveContent(userName, content); //保存文本
out.print("最后保存于 " + getNowDate() + "。"); //輸出最后保存時間
//執行恢復保存結果操作
} else if ("restore".equals(action)) {
out.print(getContent(userName));
//顯示用戶最終提交內容
} else {
%>
<div>用戶名:<%=userName%></div>
<div>提交內容:</div>
<div><%=content%></div>
<%
}
%>
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -