這一篇博客將詳細介紹一個基于servlet的問答網站的實現,有詳細的代碼。
可能篇幅較長,以代碼為主,有興趣的童鞋看完可以嘗試動手搭建一個屬于自己的問答社區。
工具:eclipse,數據庫用到了mysql,這次項目中未使用jsp,全部以servlet注解的方式連接html和servlet,jdk最好使用1.8,tomcat使用8.0。(注解方式為jdk1.5后的特性,最低要求1.5+,本項目使用jdk1.8)。
在這篇博客中可以學習到:
1,servlet中關于注解的使用,本項目沒有使用到傳統的servlet配置web.xml,全部使用注解的形式。
2,了解font awesome這一矢量圖標庫的使用,他基本提供了項目中所要使用到的所有圖標,方便,快捷。
3,了解simditor這一富文本編輯器的使用,網站中直接嵌入富文本編輯器,再也不用為讀取出來的文字格式不對發愁了。
4,關于項目中如何加入驗證碼,數據庫查詢之前先進行驗證碼驗證。
5,關于mvc框架顯示層——velocity技術的使用。
先看一下大體項目圖(由于主要做后臺,前臺可能略丑,大家可以自行找網站模板)
登錄界面:
注冊界面:
首頁,展示了大家的提問:
解答界面,點擊別人的提問后進入解答界面,使用了富文本編輯器。
我的解答界面,展示了我回答的歷史:
我的提問界面,展示了我提問的所有問題:
提問界面:進入網站點擊我要提問,加入當前頁編輯問題:
下面介紹主要代碼(代碼中加入了詳細注釋,所以不再做說明)
主頁列表servlet:
@webservlet( "/list.do" ) public class listservlet extends httpservlet { private static final long serialversionuid = 810339694607399128l; @override protected void service( httpservletrequest request , httpservletresponse response ) throws servletexception, ioexception { string question=request.getparameter("quest"); system.out.println(question); if(stringhelper.notempty(question)){ final string sql = "select id , title ,content, publish_time , publish_ip , user_id from t_topic where resultset rs = jdbchelper.query( sql,question ); // 創建一個 list 對象,用來保存一批 topic 對象 final list<topic> topics = new arraylist<>(); try { // 每循環一次,光標下移一行,如果該行有數據返回 true while( rs.next() ){ topic t = new topic(); // 創建對象 t.setid( rs.getint( 1 ) ); // 將 結果集 中的 該行數據 封裝到 t 對象的 id 屬性中 t.settitle( rs.getstring( 2 ) ); t.setcontent(rs.getstring(3)); t.setpublishtime( rs.gettimestamp( 4 )); t.setpubliship( rs.getstring( 5 ) ); user u = new user(); // 創建 一個 user 對象 u.setid( rs.getint( 6 ) ); // 將 t_topic 表中的 user_id 放入到 user 對象的 id 屬性中 t.setuser( u ); // 將 user 對象 設置到 topic 對象上 /** 將 本次循環 創建的對象(已經封裝數據) 添加到 list 集合中 */ topics.add( t ); } } catch (sqlexception e) { e.printstacktrace(); } jdbchelper.release( rs ); // 關閉 結果集,釋放相關的資源 /**** 為每個問題尋找提問者 ***********************************/ //for( int i = 0 ; i < topics.size() ; i++ ){ for( int i = 0 , len = topics.size() ; i < len ; i++ ){ topic t = topics.get( i ) ; // 獲得 題目 user u = t.getuser(); // 獲得當前題目的user對象 ( 該對象中只有 id 沒有其它數據 ) // 根據 用戶對象的 id 來查詢 用戶的信息 string querysql = "select id , username , password from t_user where id = ? " ; resultset userrs = jdbchelper.query( querysql , u.getid() ); try { if( userrs.next() ) { // 如果查詢到用戶信息 // 注意,這里應該使用 userrs u.setusername( userrs.getstring( 2 ) ); // 將 username 列的值設置到 用戶對象的 username 屬性中 u.setpassword( userrs.getstring( 3 )); // 將 password 列的值設置到 用戶對象的 password 屬性中 } } catch (sqlexception e) { e.printstacktrace(); } jdbchelper.release( userrs ); // 關閉 結果集,釋放相關的資源 } servletcontext application = request.getservletcontext(); /** 將這些數據保存到 application **/ application.setattribute( "topics" , topics ); system.out.println( "問題列表: " + topics ); // 去 list.html 頁面 response.sendredirect( request.getcontextpath() + "/list.html"); }else{ /**** 查詢數據庫中的所有問題 ***********************************/ final string sql = "select id , title ,content ,publish_time , publish_ip , user_id from t_topic order by publish_time desc" ; resultset rs = jdbchelper.query( sql ); // 創建一個 list 對象,用來保存一批 topic 對象 final list<topic> topics = new arraylist<>(); try { // 每循環一次,光標下移一行,如果該行有數據返回 true while( rs.next() ){ topic t = new topic(); // 創建對象 t.setid( rs.getint( 1 ) ); // 將 結果集 中的 該行數據 封裝到 t 對象的 id 屬性中 t.settitle( rs.getstring( 2 ) ); t.setcontent(rs.getstring(3)); t.setpublishtime( rs.gettimestamp( 4 )); t.setpubliship( rs.getstring( 5 ) ); user u = new user(); // 創建 一個 user 對象 u.setid( rs.getint( 6) ); // 將 t_topic 表中的 user_id 放入到 user 對象的 id 屬性中 t.setuser( u ); // 將 user 對象 設置到 topic 對象上 /** 將 本次循環 創建的對象(已經封裝數據) 添加到 list 集合中 */ topics.add( t ); } } catch (sqlexception e) { e.printstacktrace(); } jdbchelper.release( rs ); // 關閉 結果集,釋放相關的資源 /**** 為每個問題尋找提問者 ***********************************/ //for( int i = 0 ; i < topics.size() ; i++ ){ for( int i = 0 , len = topics.size() ; i < len ; i++ ){ topic t = topics.get( i ) ; // 獲得 題目 user u = t.getuser(); // 獲得當前題目的user對象 ( 該對象中只有 id 沒有其它數據 ) // 根據 用戶對象的 id 來查詢 用戶的信息 string querysql = "select id , username , password from t_user where id = ? " ; resultset userrs = jdbchelper.query( querysql , u.getid() ); try { if( userrs.next() ) { // 如果查詢到用戶信息 // 注意,這里應該使用 userrs u.setusername( userrs.getstring( 2 ) ); // 將 username 列的值設置到 用戶對象的 username 屬性中 u.setpassword( userrs.getstring( 3 )); // 將 password 列的值設置到 用戶對象的 password 屬性中 } } catch (sqlexception e) { e.printstacktrace(); } jdbchelper.release( userrs ); // 關閉 結果集,釋放相關的資源 } servletcontext application = request.getservletcontext(); /** 將這些數據保存到 application **/ application.setattribute( "topics" , topics ); system.out.println( "問題列表: " + topics ); // 去 list.html 頁面 response.sendredirect( request.getcontextpath() + "/list.html"); } } }
主頁列表顯示界面代碼:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>首頁</title> <link rel="stylesheet" href="$path/styles/general.css"> <link rel="stylesheet" href="$path/styles/cell.css"> <link rel="stylesheet" href="$path/styles/wen.css"> </head> <body> ## 登錄狀態欄 開始 <div class="login-status-container auto-height"> <span class="welcome cell-8"> ## 在 $ 之后 表達式之前使用 ! 表示 安靜模式 ( 靜默模式 ) <b>歡迎$!user.username來到愛問社區</b> </span> <span class="login-operation cell-4"> #if( $user ) <a href="$path/ask.html">提問</a> <em>|</em> <a href="$path/myquestion.do">我的提問</a> <em>|</em> <a href="$path/logout.do">注銷</a> #else <a href="$path/login.html">登錄</a> <em>|</em> <a href="$path/regist.html">注冊</a> #end </span> </div> ## 登錄狀態欄 結束 ## 標志區域 <div class="brand-container auto-height"> <div class="cell-2"> <a href="$path"></a> </div> <div class="slogan cell-10"> <div> 愛問社區,這里可放logo </div> </div> </div> ## 列表區域 <div class="topic-list-container clear"> <!-- 問題列表的標題 --> <div class="topic-list-header row clear"> <span class="topic-item-index cell-1">序號</span> <span class="topic-item-title cell-5" style="text-align: left ;">標題</span> <span class="topic-item-time cell-3">提問時間</span> <span class="topic-item-user cell-2">提問者</span> <span class="topic-item-operation cell-1"> #if( $user ) 解答問題 #end </span> </div> ## 問題列表開始 ## 每循環一次從 $topics 集合中取出一個 topic 對象 放到 $topic 中 #foreach( $topic in $topics ) <div class="topic-item row clear odd"> <span class="topic-item-index cell-1">$topic.id</span> <span class="topic-item-title cell-5" style="text-align: left ;"> <a href="$path/detail.do?id=$topic.id">$topic.title</a> </span> <span class="topic-item-time cell-3"> $topic.publishtime </span> <span class="topic-item-user cell-2"> $topic.user.username</span> <span class="topic-item-operation cell-1"> #if( $user ) <a href="$path/answer.do?id=$topic.id">解答</a> #end </span> </div> #end ## 問題列表結束 </div>## 列表區域結束 <div class="line"></div> <div class="container link-container"> <a href="$path/ask.html" >發起新問題</a> | <a href="$path/index.html" >返回首頁</a> </div> <div class="container copyright-container"> © 2017 愛問社區版權所有 </div> </body> </html>
提問前臺界面代碼:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>提問</title> <link rel="stylesheet" href="$path/styles/general.css"> <link rel="stylesheet" href="$path/styles/cell.css"> <link rel="stylesheet" href="$path/styles/wen.css"> <link rel="stylesheet" href="$path/styles/btn.css"> <!-- 鏈接 simditor 的樣式庫 --> <link rel="stylesheet" href="$path/simditor/styles/simditor.css" type="text/css"> <!-- 導入 simditor 的 javascript 庫 --> <script type="text/javascript" src="$path/simditor/scripts/jquery.min.js"></script> <script type="text/javascript" src="$path/simditor/scripts/module.js"></script> <script type="text/javascript" src="$path/simditor/scripts/hotkeys.js"></script> <script type="text/javascript" src="$path/simditor/scripts/uploader.js"></script> <script type="text/javascript" src="$path/simditor/scripts/simditor.min.js"></script> </head> <body> ## 登錄狀態欄 開始 <div class="id="topnav" class="f_r"> <span class="welcome cell-8"> ## 在 $ 之后 表達式之前使用 ! 表示 安靜模式 ( 靜默模式 ) <b>歡迎$!user.username來到愛問社區</b> </span> <span class="login-operation cell-4"> #if( $user ) <a href="$path/ask.html">提問</a> <em>|</em> <a href="$path/myquestion.do">我的提問</a> <em>|</em> <a href="$path/logout.do">注銷</a> #else <a href="$path/login.html">登錄</a> <em>|</em> <a href="$path/regist.html">注冊</a> #end </span> </div> ## 登錄狀態欄 結束 <div class="brand-container auto-height"> <div class="cell-2"> <a href="$path"></a> </div> <div class="slogan cell-10"> <div> 愛問社區,這里可以logo </div> </div> </div> <div class="container message-container"> <!-- 顯示提示信息的地方 --> #if( $askfail ) $askfail $scope.remove( $session , 'askfail' ) #end </div> #if( $user ) <!-- 提問表單 提交給 ask.do 對應的 servlet 處理 --> <form action="$path/ask.do" method="post" > <!-- 提問區域 開始 --> <div class="container topic-ask-container clear shadow-outside auto-height" > <!-- 問題的標題 和 提問按鈕 --> <div class="container title-container"> <div class="cell-11"> <input type="text" name="title" placeholder="請輸入你要提問的問題的標題" class="u-ipt"> </div> <div class="cell-1"> <input type="submit" value="提問" class="u-btn u-btn-c4"> </div> </div> <div class="line"></div> <!-- 問題的內容 --> <div> <textarea name="content" id="contenteditor" ></textarea> <script type="text/javascript" > var editor = new simditor( { textarea : $('#contenteditor'), placeholder : '請在這里輸入問題的內容...', toolbar : true } ); </script> </div> <div class="line"></div> <!-- 最底部的提問按鈕 --> <div class="container title-container"> <div class="cell-11" style="height: 1px ;"></div> <div class="cell-1"> <input type="submit" value="提問" class="u-btn u-btn-c4"> </div> </div> </div> <!-- 提問區域 結束 --> </form> #else <div style="text-align:center ; min-height: 400px ; line-height: 400px ;"> 登錄以后才能發起提問,請<a href="$path/login.html" >登錄</a> </div> #end <div class="line"></div> <div class="container link-container"> <a href="$path/list.do" >問題列表</a> | <a href="$path/index.html" >返回首頁</a> </div> <div class="container copyright-container"> © 2017 愛問社區版權所有 </div> </body> </html>
回答servlet處理代碼:
@webservlet("/answer.do") public class answerservlet extends httpservlet { private static final long serialversionuid = 8578962149437664830l; @override protected void service(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { // 從 請求中獲得請求參數的值 string id = request.getparameter("id"); if (stringhelper.notempty(id)) { try { int topicid = integer.parseint(id); // 將字符串按照 十進制 解析問 int 類型數值 // 根據得到的 問題的 主鍵 查詢數據庫,得到 詳細信息 final string sql = "select id , title , content , publish_time , publish_ip , user_id from t_topic where id = ? "; resultset rs = jdbchelper.query(sql, topicid); topic t = null; int userid = -1; if (rs.next()) { // 當 根據 問題的主鍵 獲取到 問題信息時 t = new topic(); // 創建 topic 對象 t.setid(rs.getint(1)); // 將 結果集 中的 該行數據 封裝到 t 對象的 id 屬性中 t.settitle(rs.getstring(2)); t.setcontent(rs.getstring(3)); t.setpublishtime(rs.gettimestamp(4)); t.setpubliship(rs.getstring(5)); userid = rs.getint(6); } jdbchelper.release(rs); // 關閉結果集 // 獲得提問者 final string getusersql = "select id , username , password from t_user where id = ? "; rs = jdbchelper.query(getusersql, userid); if (userid != -1 && rs.next()) { user u = new user(); // 封裝數據 u.setid(rs.getint(1)); u.setusername(rs.getstring(2)); u.setpassword(rs.getstring(3)); // 將獲取到的用戶數據設置到 topic 對象的 user 屬性中 t.setuser(u); } httpsession session = request.getsession(); session.setattribute("topic", t); response.sendredirect(request.getcontextpath() + "/answer.html"); return; // 讓方法立即結束 } catch (numberformatexception e) { e.printstacktrace(); // response.sendredirect( request.getcontextpath() + "/list.do" ); } catch (sqlexception e) { e.printstacktrace(); // response.sendredirect( request.getcontextpath() + "/list.do" ); } } else { // response.sendredirect( request.getcontextpath() + "/list.do" ); } response.sendredirect(request.getcontextpath() + "/list.do"); } }
回答前臺代碼:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>解答: $topic.title</title> <link rel="stylesheet" href="$path/styles/general.css"> <link rel="stylesheet" href="$path/styles/cell.css"> <link rel="stylesheet" href="$path/styles/wen.css"> <!-- 鏈接 simditor 的樣式庫 --> <link rel="stylesheet" href="$path/simditor/styles/simditor.css" type="text/css"> <!-- 導入 simditor 的 javascript 庫 --> <script type="text/javascript" src="$path/simditor/scripts/jquery.min.js"></script> <script type="text/javascript" src="$path/simditor/scripts/module.js"></script> <script type="text/javascript" src="$path/simditor/scripts/hotkeys.js"></script> <script type="text/javascript" src="$path/simditor/scripts/uploader.js"></script> <script type="text/javascript" src="$path/simditor/scripts/simditor.min.js"></script> </head> <body> ## 登錄狀態欄 開始 <div class="login-status-container auto-height"> <span class="welcome cell-8"> ## 在 $ 之后 表達式之前使用 ! 表示 安靜模式 ( 靜默模式 ) <b>歡迎$!user.username來到愛問社區</b> </span> <span class="login-operation cell-4"> #if( $user ) <a href="$path/ask.html">提問</a> <em>|</em> <a href="">我的提問</a> <em>|</em> <a href="$path/logout.do">注銷</a> #else <a href="$path/login.html">登錄</a> <em>|</em> <a href="$path/regist.html">注冊</a> #end </span> </div> ## 登錄狀態欄 結束 ## 標志區域 <div class="brand-container auto-height"> <div class="logo cell-2"> <a href="$path"></a> </div> <div class="slogan cell-10"> <div> 解答問題 </div> </div> </div> <div> <h3>$topic.title</h3> <div class="line"></div> <div> $topic.content </div> <div> 提問時間: $topic.publishtime / 提問者: $topic.user.username </div> </div> <!-- 解答的內容 --> <form action="$path/explain.do" method="post" > <input type="hidden" name="id" value="$topic.id" > <div> <textarea name="content" id="contenteditor" ></textarea> <script type="text/javascript" > var editor = new simditor( { textarea : $('#contenteditor'), placeholder : '請在這里輸入問題的內容...', toolbar : true } ); </script> </div> <input type="submit" value="提交解答"> </form> $scope.remove( $session , 'topic' ); <div class="line"></div> <div class="container link-container"> <a href="$path/ask.html" >發起新問題</a> | <a href="$path/index.html" >返回首頁</a> </div> <div class="container copyright-container"> © 2017 愛問社區版權所有 </div> </body> </html>
以下是使用simditor的方法,需要引入simditor中的css和js樣式。simditor
<textarea name="content" id="contenteditor" ></textarea> <script type="text/javascript" > var editor = new simditor( { textarea : $('#contenteditor'), placeholder : '請在這里輸入問題的內容...', toolbar : true } ); </script>
解答問題servlet處理,這里需要獲取提問者,提問問題以及該問題的已有答案,已有答案回答者。
@webservlet("/detail.do") public class detailservlet extends httpservlet { private static final long serialversionuid = -3202278077673657729l; @override protected void service(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { // 從 請求中獲得請求參數的值 string id = request.getparameter("id"); if (stringhelper.notempty(id)) { try { int topicid = integer.parseint(id); // 將字符串按照 十進制 解析問 int 類型數值 // 根據得到的 問題的 主鍵 查詢數據庫,得到 詳細信息 final string sql = "select id , title , content , publish_time , publish_ip , user_id from t_topic where id = ? "; resultset rs = jdbchelper.query(sql, topicid); topic t = null; /*int userid = -1;*/ if (rs.next()) { // 當 根據 問題的主鍵 獲取到 問題信息時 t = new topic(); // 創建 topic 對象 t.setid(rs.getint(1)); // 將 結果集 中的 該行數據 封裝到 t 對象的 id 屬性中 t.settitle(rs.getstring(2)); t.setcontent(rs.getstring(3)); t.setpublishtime(rs.gettimestamp(4)); t.setpubliship(rs.getstring(5)); user user = new user(); user.setid(rs.getint(6)); t.setuser(user); } jdbchelper.release(rs); // 關閉結果集 // 獲得提問者 final string getusersql = "select id , username , password from t_user where id = ? "; rs = jdbchelper.query(getusersql, t.getuser().getid()); if(rs.next()) { user u = new user(); // 封裝數據 u.setid(rs.getint(1)); u.setusername(rs.getstring(2)); u.setpassword(rs.getstring(3)); // 將獲取到的用戶數據設置到 topic 對象的 user 屬性中 t.setuser(u); system.out.println("message username:" + rs.getstring(2)); } jdbchelper.release(rs); // 關閉結果集 // 獲得當前的問題的所有解答 string explainsql = "select id , content , explain_time , explain_ip , user_id from t_explain where topic_id = ? "; rs = jdbchelper.query(explainsql, topicid); @suppresswarnings("unused") int explainerid = -1; list<explain> explains = new arraylist<>(); while (rs.next()) { explain e = new explain(); e.setid(rs.getint(1)); e.setcontent(rs.getstring(2)); e.setexplaintime(rs.gettimestamp(3)); e.setexplainip(rs.getstring(4)); user user=new user(); user.setid(rs.getint(5)); e.setuser(user); explains.add(e); system.out.println("explain userid:" + rs.getint(5)); } // 獲得解答者 list<explain>explainlist = new arraylist(); for(int i=0;i<explains.size();i++) { explain explain1 = explains.get(i); final string getexplainersql = "select id , username , password from t_user where id = ? "; rs = jdbchelper.query(getexplainersql, explain1.getuser().getid()); if (rs.next()) { user u = new user(); // 封裝數據 u.setid(rs.getint(1)); u.setusername(rs.getstring(2)); u.setpassword(rs.getstring(3)); // 將獲取到的用戶數據設置到 topic 對象的 user 屬性中 explain1.setuser(u); explainlist.add(explain1); system.out.println("explain username:" + rs.getstring(2)); } jdbchelper.release(rs); // 關閉結果集 /*t.setexplains(explains); // 將解答設置到 topic 對象上 */ } t.setexplains(explainlist); /*** 為 所有的解答,獲取解答者的詳細信息 ***/ httpsession session = request.getsession(); session.setattribute("topic", t); response.sendredirect( request.getcontextpath() + "/detail.html" ); return; // 讓方法立即結束 } catch (numberformatexception e) { e.printstacktrace(); } catch (sqlexception e) { e.printstacktrace(); } } else { } response.sendredirect(request.getcontextpath() + "/list.do"); } }
解答問題前臺顯示界面代碼;
<!doctype html> <html> <head> <meta charset="utf-8"> <title>$topic.title</title> <link rel="shortcut icon" href="$path/images/icon.png" type="image/png"> <link rel="stylesheet" href="$path/styles/general.css"> <link rel="stylesheet" href="$path/styles/cell.css"> <link rel="stylesheet" href="$path/styles/wen.css"> </head> <body> ## 登錄狀態欄 開始 <div class="login-status-container auto-height"> <span class="welcome cell-8"> ## 在 $ 之后 表達式之前使用 ! 表示 安靜模式 ( 靜默模式 ) <b>歡迎$!user.username來到問道</b> </span> <span class="login-operation cell-4"> #if( $user ) <a href="$path/ask.html">提問</a> <em>|</em> <a href="">我的提問</a> <em>|</em> <a href="$path/logout.do">注銷</a> #else <a href="$path/login.html">登錄</a> <em>|</em> <a href="$path/regist.html">注冊</a> #end </span> </div> ## 登錄狀態欄 結束 ## 標志區域 <div class="brand-container auto-height"> <div class="logo cell-2"> <a href="$path"></a> </div> <div class="slogan cell-10"> <div> </div> </div> </div> <div> <h3>$topic.title</h3> <div class="line"></div> <div> $topic.content </div> <div> 提問時間: $topic.publishtime / 提問者: $topic.user.username </div> </div> <div> #foreach( $ex in $topic.explains) <div> $ex.content </div> <div class="line"></div> #end </div> $scope.remove( $session , 'topic' ); <div class="line"></div> <div class="container link-container"> <a href="$path/ask.html" >發起新問題</a> | <a href="$path/index.html" >返回首頁</a> </div> <div class="container copyright-container"> © 2017 愛問社區版權所有 </div> </body> </html>
我的解答servlet處理代碼:
@webservlet("/myanswer.do") public class myanswerservlet extends httpservlet { private static final long serialversionuid = -3020889403557912216l; @override protected void service(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { httpsession session = request.getsession(); user user = (user) session.getattribute( "user" ); // 在登錄時將 user 對象放入了 會話 中 explain ex=null; final list<explain> exp = new arraylist<>(); if( user != null ) { int myid=user.getid(); final string sql = "select id ,content ,explain_time , explain_ip , user_id ,topic_id from t_explain where user_id = ? "; resultset rs = jdbchelper.query(sql, myid); //topic t=null; //final list<explain> explains = new arraylist<>(); @suppresswarnings("unused") int topicid=-1; try { while( rs.next() ) { ex=new explain(); ex.setid(rs.getint(1)); ex.setcontent(rs.getstring(2)); ex.setexplaintime(rs.gettimestamp( 3 )); ex.setexplainip(rs.getstring(4)); ex.setuser(user); topic to=new topic(); to.setid(rs.getint(6)); ex.settopic(to); topicid=rs.getint(6); exp.add(ex); } jdbchelper.release(rs); // 關閉結果集 for(int i = 0 , len = exp.size() ; i < len ; i++) { explain explain=exp.get(i); topic tid=explain.gettopic(); final string tsql = "select id , title , content , publish_time , publish_ip , user_id from t_topic where id = ? "; resultset trs = jdbchelper.query(tsql, tid.getid()); while(trs.next()) { topic t=new topic(); t.setid(1); t.settitle(trs.getstring(2)); t.setcontent(trs.getstring(3)); t.setpublishtime(trs.gettimestamp(4)); t.setpubliship(trs.getstring(5)); ex.settopic(t); // explains.add(ex); system.out.println( "我的tid: " + tid.getid()); } jdbchelper.release(trs); // 關閉結果集 } } catch (sqlexception e) { // todo auto-generated catch block e.printstacktrace(); } session.setattribute("explains", exp); system.out.println( "我的解答列表: " + exp ); system.out.println( "我的id: " + myid); response.sendredirect( request.getcontextpath() + "/myanswer.html"); } } }
我的解答前臺展示頁面代碼:
<!doctype html> <html> <head> <meta charset="utf-8" /> <title>解答</title> <link rel="stylesheet" href="$path/styles/top.css"> </head> <body> <div style="margin-left:320px;"> <nav id="topnav" class="f_r"> <ul> <a href="$path/index.html"">首頁</a> <a href="$path/myquestion.do" >我的提問</a> <a href="$path/ask.html" >提問</a> <a href="$path/logout.do">注銷</a> </ul> </nav> </div> #if( $user ) $user.username的所有回答: #end #foreach( $ex in $explains) <div class="blogs"> <ul> <p>$ex.content</p> <div class="content_time"> <p> 解答時間:<span class="dtime f_l"> $ex.explaintime</span></p> </div> <div class="line"></div> </ul> </div> #end </body> </html>
我的提問servlet處理:
@webservlet("/myquestion.do") public class myquestionservlet extends httpservlet { private static final long serialversionuid = -4110483126223561394l; @override protected void service(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { httpsession session = request.getsession(); user user = (user) session.getattribute( "user" ); // 在登錄時將 user 對象放入了 會話 中 if( user != null ) { int myid=user.getid(); final string sql = "select id , title , content, publish_time , publish_ip from t_topic where user_id = ? "; resultset rs = jdbchelper.query(sql, myid); final list<topic> qtopics = new arraylist<>(); try { while( rs.next() ){ topic t=new topic(); t.setid(rs.getint(1)); t.settitle(rs.getstring(2)); t.setcontent(rs.getstring(3)); t.setpublishtime(rs.gettimestamp(4)); t.setpubliship(rs.getstring(5)); qtopics.add(t); } } catch (sqlexception e) { // todo auto-generated catch block e.printstacktrace(); } session.setattribute("qtopics", qtopics); system.out.println( "我的提問列表: " + qtopics ); system.out.println( "我的id: " + myid); response.sendredirect( request.getcontextpath() + "/myquestion.html"); } } }
我的提問展示代碼:
<!doctype html> <html> <head> <meta charset="utf-8" /> <title>$user.username的提問 </title> <link rel="stylesheet" href="$path/styles/general.css"> <link rel="stylesheet" href="$path/styles/cell.css"> <link rel="stylesheet" href="$path/styles/wen.css"> <link rel="stylesheet" href="$path/styles/top.css"> </head> <body> <div style="margin-left:320px;"> <ul> #if($user) <nav id="topnav" class="f_r"> <ul> <a href="$path/index.html">首頁</a> <a href="$path/myanswer.do" >我的解答</a> <a href="$path/ask.html">提問</a> <a href="$path/logout.do" >注銷</a> </ul> </nav> #else <li class="presentation"><a href="$path/login.html" id="link" <li class="presentation"><a href="$path/regist.do" id="tools" #end </ul> </div> #if( $user ) $user.username的所有提問: #end #foreach( $qto in $qtopics) <div class="blogs"> <ul> <p>$qto.content</p> <p class="autor"><span class="lm f_l"><a>提問者:$user.username</a></span> <span class="dtime f_l">$qto.publishtime</span></p> </ul> </div> #end </body> </html>
驗證碼處理的servlet代碼:
@webservlet(urlpatterns= { "/verify/login.do" , "/verify/regist.do" } ) public class verifycodeservlet extends httpservlet { private static final long serialversionuid = 3398560501558431737l; @override protected void service( httpservletrequest request , httpservletresponse response ) throws servletexception, ioexception { // 獲得 當前請求 對應的 會話對象 httpsession session = request.getsession(); // 從請求中獲得 uri ( 統一資源標識符 ) string uri = request.getrequesturi(); system.out.println( "hello : " + uri ); final int width = 180 ; // 圖片寬度 final int height = 40 ; // 圖片高度 final string imgtype = "jpeg" ; // 指定圖片格式 (不是指mime類型) final outputstream output = response.getoutputstream(); // 獲得可以向客戶端返回圖片的輸出流 (字節流) // 創建驗證碼圖片并返回圖片上的字符串 string code = graphichelper.create( width, height, imgtype, output ); system.out.println( "驗證碼內容: " + code ); // 建立 uri 和 相應的 驗證碼 的關聯 ( 存儲到當前會話對象的屬性中 ) session.setattribute( uri , code ); system.out.println( session.getattribute( uri ) ); } }
注冊前臺界面,有驗證碼驗證功能:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>注冊愛問社區</title> <link rel="stylesheet" href="$path/styles/general.css"> <link rel="stylesheet" href="$path/styles/cell.css"> <link rel="stylesheet" href="$path/styles/form.css"> <link rel="stylesheet" href="$path/awesome/css/font-awesome.min.css"> <script type="text/javascript" src="$path/js/wen.js"></script> <style type="text/css" > .logo-container { margin-top: 50px ; } .logo-container img { width: 100px ; } .message-container { height: 80px ; } .link-container { height: 40px ; line-height: 40px ; } .link-container a { text-decoration: none ; } </style> </head> <body> <div class="container title-container" style="color:blue; margin-top:60px;">加入愛問社區,為您答疑解惑</div> <div class="container form-container"> <form action="$path/regist.do" method="post"> <div class="form"> <!-- 注冊表單開始 --> <div class="form-row"> <span class="cell-1"> <i class="fa fa-user"></i> </span> <span class="cell-11" style="text-align: left;"> <input type="text" name="username" placeholder="請輸入用戶名"> </span> </div> <div class="form-row"> <span class="cell-1"> <i class="fa fa-key"></i> </span> <span class="cell-11" style="text-align: left;"> <input type="password" name="password" placeholder="請輸入密碼"> </span> </div> <div class="form-row"> <span class="cell-1"> <i class="fa fa-keyboard-o"></i> </span> <span class="cell-11" style="text-align: left;"> <input type="password" name="confirm" placeholder="請確認密碼"> </span> </div> <div class="form-row"> <span class="cell-7"> <input type="text" name="verifycode" placeholder="請輸入驗證碼"> </span> <span class="cell-5" style="text-align: center;"> <img src="$path/verify/regist.do" onclick="myrefersh(this)"> </span> </div> <div class="form-row" style="border: none;"> <span class="cell-6" style="text-align: left"> <input type="reset" value="重置"> </span> <span class="cell-6" style="text-align:right;"> <input type="submit" value="注冊"> </span> </div> </div> <!-- 注冊表單結束 --> </form> </div> <div class="container message-container"> <!-- 顯示提示信息的地方 --> #if( $registfail ) $registfail $scope.remove( $session , 'registfail' ) #end </div> <div class="container link-container"> <a href="$path/login.html" > 已注冊愛問帳號,點擊這里登錄</a> | <a href="$path/index.html" >返回首頁</a> </div> <div class="container copyright-container"> © 2017 愛問社區版權所有 </div> </body> </html>
servlet處理注冊,實現驗證碼驗證:
@webservlet("/regist.do") public class registservlet extends httpservlet { private static final long serialversionuid = 7493633832455111617l; @override protected void service( httpservletrequest request , httpservletresponse response ) throws servletexception, ioexception { // 獲得來自 頁面 表單上的數據 string verifycode = request.getparameter( "verifycode" ) ; // 獲得由用戶輸入的那個驗證碼 string username = request.getparameter( "username" ) ; string password = request.getparameter( "password" ) ; string confirm = request.getparameter( "confirm" ) ; system.out.println( "username : " + username ); system.out.println( "password : " + password ); system.out.println( "confirm : " + confirm ); system.out.println( "verifycode : " + verifycode ); httpsession session = request.getsession(); // 獲得 在 會話 中存儲的那個 為登錄進行驗證的 驗證碼 final string code = (string)session.getattribute( "/wendao/verify/regist.do" ); system.out.println( "session code : " + code ); // 比較驗證碼 if( stringhelper.equals( verifycode , code ) ){ // 要保證 用戶名 不為空 、密碼不能為空 、兩次輸入的密碼必須一致 if( stringhelper.notempty( username ) && stringhelper.notempty( password ) && stringhelper.equals( password , confirm) ) { // 可以保存了 string sql = "insert into t_user ( username , password ) values ( ? , ? ) " ; int n = jdbchelper.insert( sql , false , username , stringhelper.md5(password)); if( n > 0 ) { // 如果 insert 返回 大于 0 的數字 , 則表示 插入成功 // 保存成功以后,應該去一個新的頁面 ( 比如去 登錄頁面 ) response.sendredirect( request.getcontextpath() + "/login.html" ); } else { // 回到注冊頁面去 session.setattribute( "registfail" , "注冊失敗,可能是用戶名被占用了" ); response.sendredirect( request.getcontextpath() + "/regist.html" ); } } else { // 回到注冊頁面去 session.setattribute( "registfail" , "用戶名或密碼為空,或者密碼不一致" ); response.sendredirect( request.getcontextpath() + "/regist.html" ); } } else { // 如果驗證碼不一致,設置提示信息后回到注冊頁面去 session.setattribute( "registfail" , "驗證碼輸入錯誤,請重新輸入" ); response.sendredirect( request.getcontextpath() + "/regist.html" ); } } }
登錄servlet處理代碼:
@webservlet("/login.do") public class loginservlet extends httpservlet { private static final long serialversionuid = 18854422651747352l; @override protected void service( httpservletrequest request , httpservletresponse response ) throws servletexception, ioexception { // 獲得來自 頁面 表單上的數據 string username = request.getparameter( "username" ) ; string password = stringhelper.md5(request.getparameter( "password" )) ; system.out.println( "username : " + username ); system.out.println( "password : " + password ); httpsession session = request.getsession(); // 登錄 : 根據 用戶名 和 密碼 從數據庫中查詢數據,如果都正確,就將這些數據放入到會話中,最后進入到指定頁面( list.html ) string sql = "select id , username , password from t_user where username = ? and password = ? " ; resultset rs = jdbchelper.query( sql, username , password ) ; try{ // 如果查詢到數據,就包裝到一個對象中 if( rs.next() ) { user user = new user(); // 創建對象 // 封裝數據 user.setid( rs.getint( 1 ) ); user.setusername( rs.getstring( 2 )); user.setpassword( rs.getstring( 3 ) ) ; //system.out.println("測試"+md5.convertmd5(md5.convertmd5(password))); /** 將 user 對象 放入到 會話中 **/ session.setattribute( "user" , user ); // 重定向到 list.do ( list.do 會先查詢數據后 再 重定向到 list.html ) response.sendredirect( request.getcontextpath() + "/list.do" ); } else { // 如果 用戶名 或 密碼 錯誤,重新返回到 登錄頁面 session.setattribute( "loginfail" , "用戶名或密碼錯誤" ); response.sendredirect( request.getcontextpath() + "/login.html" ); } } catch ( sqlexception e ){ e.printstacktrace(); } } }
登錄前臺展示界面代碼;
<!doctype html> <html> <head> <meta charset="utf-8"> <title>登錄</title> <link rel="stylesheet" href="styles/general.css"> <link rel="stylesheet" href="styles/cell.css"> <link rel="stylesheet" href="styles/form.css"> <link rel="stylesheet" href="awesome/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="css/login.css"> <script type="text/javascript" src="js/wen.js"></script> </head> <body> <div class="logina-logo" style="height: 55px"> <div id="venuslogo"><p><span>愛問社區</span></p></div> </div> <div class="logina-main main clearfix"> <div class="tab-con"> <form action="$path/login.do" method="post"> <div id='login-error' class="error-tip"></div> <table border="0" cellspacing="0" cellpadding="0"> <tbody> <tr> <th>賬戶</th> <td width="245"> <input type="text" name="username" id="username" placeholder="昵稱" /> <td> </td> </tr> <tr> <th>密碼</th> <td width="245"> <input type="password" name="password" id="password" placeholder="密碼" /> </td> <td> </td> </tr> <tr> <th></th> <td width="245"><input class="confirm" type="submit" value="登 錄"></td> <td></td> </tr> </tbody> </table> </form> </div> <div class="reg"> <p>還沒有賬號?<br>趕快免費注冊一個吧!</p> <a class="reg-btn" href="regist.html">立即免費注冊</a> </div> </div> <div id="footer"> <div class="copyright">copyright © 愛問社區 版權所有</div> </div> </body> </html>
好啦,基本的代碼就展示完了,還有比較通用的pojo類和jdbc連接數據庫的類就不做展示了,貼上數據庫sql代碼,需要的可以根據字段來寫
drop table if exists `t_explain`; create table `t_explain` ( `id` int(11) not null auto_increment, `content` text, `explain_time` timestamp null default null on update current_timestamp, `explain_ip` varchar(50) default null, `user_id` int(8) default null, `topic_id` int(8) default null, primary key (`id`), key `ex_id` (`user_id`), key `t_id` (`topic_id`), constraint `ex_id` foreign key (`user_id`) references `t_user` (`id`), constraint `t_id` foreign key (`topic_id`) references `t_topic` (`id`) ) engine=innodb auto_increment=14 default charset=utf8; -- ---------------------------- -- table structure for t_topic -- ---------------------------- drop table if exists `t_topic`; create table `t_topic` ( `id` int(10) not null auto_increment, `title` varchar(255) default null, `content` text, `publish_time` timestamp not null default current_timestamp on update current_timestamp, `publish_ip` varchar(100) default null, `user_id` int(10) default null, primary key (`id`), key `cid` (`user_id`), constraint `cid` foreign key (`user_id`) references `t_user` (`id`) ) engine=innodb auto_increment=15 default charset=utf8; -- ---------------------------- -- table structure for t_user -- ---------------------------- drop table if exists `t_user`; create table `t_user` ( `id` int(10) not null auto_increment, `username` varchar(20) not null, `password` varchar(255) not null, primary key (`id`), unique key `username` (`username`) ) engine=innodb auto_increment=24 default charset=utf8;
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://blog.csdn.net/weixin_36380516/article/details/70162151