基于 Servlet 的技术问答网站系统实现

752 阅读1小时+
原文链接: blog.csdn.net

这一篇博客将详细介绍一个基于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:

  1. @WebServlet"/list.do" )  
  2. public class ListServlet  extends HttpServlet {  
  3.     private static final long serialVersionUID = 810339694607399128L;  
  4.     @Override  
  5.     protected void service( HttpServletRequest request , HttpServletResponse response )  
  6.             throws ServletException, IOException {  
  7.     String question=request.getParameter("quest");  
  8.     System.out.println(question);  
  9.     if(StringHelper.notEmpty(question)){  
  10.         final String SQL = "SELECT id , title ,content, publish_time , publish_ip , user_id FROM t_topic where title =? " ;  
  11.         ResultSet rs = JdbcHelper.query( SQL,question );  
  12.             // 创建一个 List 对象,用来保存一批 Topic 对象  
  13.         final List<Topic> topics = new ArrayList<>();  
  14.         try {  
  15.             // 每循环一次,光标下移一行,如果该行有数据返回 true  
  16.             while( rs.next() ){  
  17.                 Topic t = new Topic(); // 创建对象  
  18.                 t.setId( rs.getInt( 1 ) ); // 将 结果集 中的 该行数据 封装到 t 对象的 id 属性中  
  19.                 t.setTitle( rs.getString( 2 ) );  
  20.                 t.setContent(rs.getString(3));  
  21.                 t.setPublishTime( rs.getTimestamp( 4 ));  
  22.                 t.setPublishIp( rs.getString( 5 ) );  
  23.                 User u = new User(); // 创建 一个 User 对象  
  24.                 u.setId( rs.getInt( 6 ) ); // 将 t_topic 表中的 user_id 放入到 User 对象的 id 属性中  
  25.                 t.setUser( u );  // 将 User 对象 设置到 Topic 对象上  
  26.                 /** 将 本次循环 创建的对象(已经封装数据) 添加到 List 集合中 */  
  27.                 topics.add( t );  
  28.                 }  
  29.             } catch (SQLException e) {  
  30.                 e.printStackTrace();  
  31.             }  
  32.             JdbcHelper.release( rs ); // 关闭 结果集,释放相关的资源  
  33.             /**** 为每个问题寻找提问者  ***********************************/  
  34.             //for( int i = 0 ; i < topics.size() ; i++ ){  
  35.             forint i = 0 , len = topics.size() ; i < len ; i++ ){  
  36.                 Topic t = topics.get( i ) ; // 获得 题目  
  37.                 User u = t.getUser(); // 获得当前题目的User对象 ( 该对象中只有 id 没有其它数据 )  
  38.                 // 根据 用户对象的 id 来查询 用户的信息  
  39.                 String querySQL = "SELECT id , username , password FROM t_user WHERE id = ? " ;  
  40.                 ResultSet userRs = JdbcHelper.query( querySQL , u.getId() );  
  41.                 try {  
  42.                     if( userRs.next() ) {  // 如果查询到用户信息  
  43.                         // 注意,这里应该使用 userRs  
  44.                         u.setUsername( userRs.getString( 2 ) );  // 将 username 列的值设置到 用户对象的 username 属性中  
  45.                         u.setPassword( userRs.getString( 3 ));  // 将 password 列的值设置到 用户对象的 password 属性中  
  46.                     }  
  47.                 } catch (SQLException e) {  
  48.                     e.printStackTrace();  
  49.                 }  
  50.                 JdbcHelper.release( userRs ); // 关闭 结果集,释放相关的资源  
  51.             }  
  52.             ServletContext application = request.getServletContext();  
  53.             /** 将这些数据保存到 application **/  
  54.             application.setAttribute( "topics" , topics );  
  55.             System.out.println( "问题列表: " + topics );  
  56.             // 去 list.html 页面  
  57.             response.sendRedirect( request.getContextPath() + "/list.html");  
  58.         }else{  
  59.             /**** 查询数据库中的所有问题  ***********************************/  
  60.             final String SQL = "SELECT id , title ,content ,publish_time , publish_ip , user_id FROM t_topic ORDER BY publish_time DESC" ;  
  61.             ResultSet rs = JdbcHelper.query( SQL );  
  62.             // 创建一个 List 对象,用来保存一批 Topic 对象  
  63.             final List<Topic> topics = new ArrayList<>();  
  64.             try {  
  65.                 // 每循环一次,光标下移一行,如果该行有数据返回 true  
  66.                 while( rs.next() ){  
  67.                     Topic t = new Topic();  // 创建对象  
  68.                     t.setId( rs.getInt( 1 ) );  // 将 结果集 中的 该行数据 封装到 t 对象的 id 属性中  
  69.                     t.setTitle( rs.getString( 2 ) );  
  70.                     t.setContent(rs.getString(3));  
  71.                     t.setPublishTime( rs.getTimestamp( 4 ));  
  72.                     t.setPublishIp( rs.getString( 5 ) );  
  73.                     User u = new User();  // 创建 一个 User 对象  
  74.                     u.setId( rs.getInt( 6) );  // 将 t_topic 表中的 user_id 放入到 User 对象的 id 属性中  
  75.                     t.setUser( u );  // 将 User 对象 设置到 Topic 对象上  
  76.                     /** 将 本次循环 创建的对象(已经封装数据) 添加到 List 集合中 */  
  77.                     topics.add( t );  
  78.                 }  
  79.             } catch (SQLException e) {  
  80.                 e.printStackTrace();  
  81.             }  
  82.             JdbcHelper.release( rs ); // 关闭 结果集,释放相关的资源  
  83.             /**** 为每个问题寻找提问者  ***********************************/  
  84.             //for( int i = 0 ; i < topics.size() ; i++ ){  
  85.             forint i = 0 , len = topics.size() ; i < len ; i++ ){  
  86.                 Topic t = topics.get( i ) ; // 获得 题目  
  87.                 User u = t.getUser(); // 获得当前题目的User对象 ( 该对象中只有 id 没有其它数据 )  
  88.                 // 根据 用户对象的 id 来查询 用户的信息  
  89.                 String querySQL = "SELECT id , username , password FROM t_user WHERE id = ? " ;  
  90.                 ResultSet userRs = JdbcHelper.query( querySQL , u.getId() );  
  91.                 try {  
  92.                     if( userRs.next() ) {  // 如果查询到用户信息  
  93.                         // 注意,这里应该使用 userRs  
  94.                         u.setUsername( userRs.getString( 2 ) );  // 将 username 列的值设置到 用户对象的 username 属性中  
  95.                         u.setPassword( userRs.getString( 3 ));  // 将 password 列的值设置到 用户对象的 password 属性中  
  96.                     }  
  97.                 } catch (SQLException e) {  
  98.                     e.printStackTrace();  
  99.                 }  
  100.                 JdbcHelper.release( userRs ); // 关闭 结果集,释放相关的资源  
  101.             }  
  102.             ServletContext application = request.getServletContext();  
  103.             /** 将这些数据保存到 application **/  
  104.             application.setAttribute( "topics" , topics );  
  105.             System.out.println( "问题列表: " + topics );  
  106.             // 去 list.html 页面  
  107.             response.sendRedirect( request.getContextPath() + "/list.html");  
  108.     }  
  109.     }  
  110. }  
@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 title =? " ;
		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");
	}
	}
}

主页列表显示界面代码:

  1. <!DOCTYPE html>  
  2. <html>  
  3.     <head>  
  4.         <meta charset="UTF-8" >  
  5.         <title>首页</title >  
  6.         <link rel="stylesheet"  href="$path/styles/general.css">  
  7.         <link rel="stylesheet"  href="$path/styles/cell.css">  
  8.         <link rel="stylesheet"  href="$path/styles/wen.css">  
  9.     </head>  
  10.     <body>  
  11.       
  12.         ## 登录状态栏 开始  
  13.         <div class="login-status-container  auto-height" >  
  14.                 <span class= "welcome cell-8">  
  15.                     ## 在 $ 之后 表达式之前使用 ! 表示 安静模式 ( 静默模式 )  
  16.                     <b>欢迎$!user.username来到爱问社区 </b>  
  17.                 </span>  
  18.                 <span class= "login-operation cell-4">  
  19.                     #if( $user )  
  20.                         <a  href="$path/ask.html">提问</a>  
  21.                         <em >| </em>  
  22.                         <a  href="$path/myQuestion.do">我的提问</a >  
  23.                         <em >| </em>  
  24.                         <a  href="$path/logout.do">注销</a>  
  25.                     #else  
  26.                         <a  href="$path/login.html">登录</a >  
  27.                         <em >| </em>  
  28.                         <a  href="$path/regist.html">注册</a >  
  29.                     #end  
  30.                 </span>  
  31.         </div> ## 登录状态栏 结束  
  32.           
  33.         ## 标志区域  
  34.         <div class="brand-container  auto-height" >  
  35.             <div class= "cell-2" >  
  36.                 <a href= "$path"></a>  
  37.             </div>  
  38.             <div class= "slogan cell-10" >  
  39.                 <div>  
  40.                 爱问社区,这里可放logo  
  41.                 </div>  
  42.             </div>  
  43.         </div>  
  44.           
  45.         ## 列表区域  
  46.         <div class="topic-list-container clear" >  
  47.             <!-- 问题列表的标题 -->  
  48.             <div class= "topic-list-header row clear" >  
  49.                 <span class= "topic-item-index cell-1">序号</span>  
  50.                 <span class= "topic-item-title cell-5" style="text-align: left ;">标题 </span>  
  51.                 <span class= "topic-item-time cell-3">提问时间</span>  
  52.                 <span class= "topic-item-user cell-2">提问者</span>  
  53.                 <span class= "topic-item-operation cell-1">  
  54.                     #if( $user )  
  55.                         解答问题  
  56.                     #end  
  57.                 </span>  
  58.             </div>  
  59.   
  60.                 ## 问题列表开始  
  61.                     ##  每循环一次从 $topics 集合中取出一个 Topic 对象 放到 $topic 中  
  62.                     #foreach( $topic in $topics )  
  63.               
  64.                     <div  class= "topic-item row clear odd">  
  65.                             < span  class="topic-item-index cell-1">$topic.id </span >  
  66.                             < span  class="topic-item-title cell-5" style= "text-align: left ;" >  
  67.                                 < a href="$path/detail.do?id=$topic.id">$topic.title </a>  
  68.                             </ span >  
  69.                             < span  class="topic-item-time cell-3"> $topic.publishTime  </span >  
  70.                             < span  class="topic-item-user cell-2"> $topic.user.username </span >  
  71.                             < span  class="topic-item-operation cell-1">   
  72.                                 #if( $user )  
  73.                                     < a href="$path/answer.do?id=$topic.id">解答 </ a>  
  74.                                 #end  
  75.                             </ span >  
  76.                     </div >  
  77.                       
  78.           
  79.                 #end  
  80.             ## 问题列表结束  
  81.               
  82.         </div>## 列表区域结束  
  83.           
  84.         <div class= "line" ></div>  
  85.           
  86.         <div class= "container link-container" >  
  87.             <a href= "$path/ask.html"  >发起新问题</a>  
  88.             |  
  89.             <a href= "$path/index.html"  >返回首页</a>  
  90.         </div>  
  91.           
  92.         <div class= "container copyright-container" >  
  93.             &copy; 2017 爱问社区版权所有  
  94.         </div>  
  95.       
  96.     </body>  
  97. </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">
		    &copy; 2017 爱问社区版权所有
		</div>
	
	</body>
</html>

提问Servlet处理代码(对用户进行了过滤,未登录用户不能发起提问)

  1. @WebServlet"/ask.do" )  
  2. public class AskServlet   extends HttpServlet {  
  3.   
  4.     private static final long serialVersionUID = -4777642507114213231L;  
  5.   
  6.     @Override  
  7.     protected void service( HttpServletRequest request , HttpServletResponse response )   
  8.             throws ServletException, IOException {  
  9.           
  10.         HttpSession session = request.getSession();  
  11.         User user = (User) session.getAttribute( "user" ); // 在登录时将 User 对象放入了 会话 中  
  12.           
  13.         // 先检查用户是否已经登录 ( 看 会话 中是否 拥有 User 对象 )  
  14.         if( user != null ) {  
  15.             // 接受来自页面的数据  
  16.             String title = request.getParameter( "title" );  
  17.             String content = request.getParameter( "content" );  
  18.               
  19.             System.out.println( "title : " + title );  
  20.             System.out.println( "content : " + content );  
  21.               
  22.             // 判断 title 和 content 是否不为 空 ( 不等于 null 不是空白字符串, 也不是空串)  
  23.             if( StringHelper.notEmpty( title ) && StringHelper.notEmpty( content ) ){  
  24.                 // 获得 客户端 的 IP 地址  
  25.                 String ip = request.getRemoteAddr();  
  26.                 System.out.println( "ip : " + ip );  
  27.                   
  28.                 // 获得 从 历元 到当前时刻所经历的毫米数  
  29.                 long ms = System.currentTimeMillis();  
  30.                 Timestamp currentTime = new Timestamp( ms ) ;  
  31.                   
  32.                 final String SQL = "INSERT INTO t_topic ( title , content , publish_time , publish_ip , user_id ) VALUES ( ? , ? , ? , ? , ? )" ;  
  33.                 int n = JdbcHelper.insert(SQL, false, title , content , currentTime , ip ,  user.getId() );  
  34.                   
  35.                 if( n > 0 ){  
  36.                     // 如果提问成功,则去往列表页面  
  37.                     response.sendRedirect( request.getContextPath() + "/list.do" );  
  38.                 } else {  
  39.                     // 用户已经登录了,但是没有填入 title 和 content  
  40.                     session.setAttribute( "askFail" ,  "提问失败了" );  
  41.                     response.sendRedirect( request.getContextPath() + "/ask.html" );  
  42.                 }  
  43.                   
  44.             } else {  
  45.                 // 用户已经登录了,但是没有填入 title 和 content  
  46.                 session.setAttribute( "askFail" , "标题和内容都不能为空" );  
  47.                 response.sendRedirect( request.getContextPath() + "/ask.html" );  
  48.             }  
  49.           
  50.         } else {  
  51.             // 用户没有登录,需要给出提示并回到登录页面去  
  52.             session.setAttribute( "loginFail" , "没有登录不能提问,请先登录" );  
  53.             response.sendRedirect( request.getContextPath() + "/login.html" );  
  54.         }  
  55.           
  56.     }  
  57.   
  58. }  
@WebServlet( "/ask.do" )
public class AskServlet   extends HttpServlet {

	private static final long serialVersionUID = -4777642507114213231L;

	@Override
	protected void service( HttpServletRequest request , HttpServletResponse response ) 
			throws ServletException, IOException {
		
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute( "user" ); // 在登录时将 User 对象放入了 会话 中
		
		// 先检查用户是否已经登录 ( 看 会话 中是否 拥有 User 对象 )
		if( user != null ) {
			// 接受来自页面的数据
			String title = request.getParameter( "title" );
			String content = request.getParameter( "content" );
			
			System.out.println( "title : " + title );
			System.out.println( "content : " + content );
			
			// 判断 title 和 content 是否不为 空 ( 不等于 null 不是空白字符串, 也不是空串)
			if( StringHelper.notEmpty( title ) && StringHelper.notEmpty( content ) ){
				// 获得 客户端 的 IP 地址
				String ip = request.getRemoteAddr();
				System.out.println( "ip : " + ip );
				
				// 获得 从 历元 到当前时刻所经历的毫米数
				long ms = System.currentTimeMillis();
				Timestamp currentTime = new Timestamp( ms ) ;
				
				final String SQL = "INSERT INTO t_topic ( title , content , publish_time , publish_ip , user_id ) VALUES ( ? , ? , ? , ? , ? )" ;
				int n = JdbcHelper.insert(SQL, false, title , content , currentTime , ip ,  user.getId() );
				
				if( n > 0 ){
					// 如果提问成功,则去往列表页面
					response.sendRedirect( request.getContextPath() + "/list.do" );
				} else {
					// 用户已经登录了,但是没有填入 title 和 content
					session.setAttribute( "askFail" , "提问失败了" );
					response.sendRedirect( request.getContextPath() + "/ask.html" );
				}
				
			} else {
				// 用户已经登录了,但是没有填入 title 和 content
				session.setAttribute( "askFail" , "标题和内容都不能为空" );
				response.sendRedirect( request.getContextPath() + "/ask.html" );
			}
		
		} else {
			// 用户没有登录,需要给出提示并回到登录页面去
			session.setAttribute( "loginFail" , "没有登录不能提问,请先登录" );
			response.sendRedirect( request.getContextPath() + "/login.html" );
		}
		
	}

}

提问前台界面代码:

  1. <!DOCTYPE html>  
  2.   
  3. <html>  
  4.     <head>  
  5.         <meta charset="UTF-8" >  
  6.         <title>提问</title >  
  7.         <link rel="stylesheet"  href="$path/styles/general.css">  
  8.         <link rel="stylesheet"  href="$path/styles/cell.css">  
  9.         <link rel="stylesheet"  href="$path/styles/wen.css">  
  10.         <link rel="stylesheet"  href="$path/styles/btn.css">  
  11.           
  12.         <!-- 链接 simditor 的样式库 -->  
  13.         <link rel="stylesheet"   href="$path/simditor/styles/simditor.css" type="text/css" >  
  14.         <!-- 导入 simditor 的 JavaScript 库 -->  
  15.         <script type="text/javascript"  src="$path/simditor/scripts/jquery.min.js"></script >  
  16.         <script type="text/javascript"  src="$path/simditor/scripts/module.js"></script >  
  17.         <script type="text/javascript"  src="$path/simditor/scripts/hotkeys.js"></script >  
  18.         <script type="text/javascript"  src="$path/simditor/scripts/uploader.js"></script >  
  19.         <script type="text/javascript"  src="$path/simditor/scripts/simditor.min.js"></script >  
  20.           
  21.     </head>  
  22.     <body>  
  23.       
  24.         ## 登录状态栏 开始  
  25.         <div class="id="topnav" class="f_r" >  
  26.                 <span class= "welcome cell-8">  
  27.                     ## 在 $ 之后 表达式之前使用 ! 表示 安静模式 ( 静默模式 )  
  28.                     <b>欢迎$!user.username来到爱问社区 </b>  
  29.                 </span>  
  30.                 <span class= "login-operation cell-4">  
  31.                     #if( $user )  
  32.                         <a  href="$path/ask.html">提问</a>  
  33.                         <em >| </em>  
  34.                         <a  href="$path/myQuestion.do">我的提问</a >  
  35.                         <em >| </em>  
  36.                         <a  href="$path/logout.do">注销</a>  
  37.                     #else  
  38.                         <a  href="$path/login.html">登录</a >  
  39.                         <em >| </em>  
  40.                         <a  href="$path/regist.html">注册</a >  
  41.                     #end  
  42.                 </span>  
  43.         </div> ## 登录状态栏 结束  
  44.           
  45.         <div class="brand-container  auto-height" >  
  46.             <div class= "cell-2" >  
  47.                 <a href= "$path"></a>  
  48.             </div>  
  49.             <div class= "slogan cell-10" >  
  50.                 <div>  
  51.                 爱问社区,这里可以logo  
  52.                 </div>  
  53.             </div>  
  54.         </div>  
  55.           
  56.         <div class="container message-container" >  
  57.             <!-- 显示提示信息的地方 -->  
  58.             #if( $askFail )   
  59.                 $askFail  
  60.                 $scope.remove( $session , 'askFail' )  
  61.             #end  
  62.         </div>  
  63.           
  64.         #if( $user )   
  65.         <!-- 提问表单 提交给 ask.do 对应的 Servlet 处理  -->  
  66.         <form action="$path/ask.do"  method="post" >  
  67.         <!-- 提问区域 开始 -->  
  68.         <div class="container  topic-ask-container clear shadow-outside auto-height"  >  
  69.             <!-- 问题的标题 和 提问按钮 -->  
  70.             <div class= "container  title-container" >  
  71.                 <div class= "cell-11">  
  72.                     <input  type= "text" name="title" placeholder= "请输入你要提问的问题的标题"  class="u-ipt">  
  73.                 </div>  
  74.                 <div class= "cell-1">  
  75.                     <input  type= "submit" value="提问" class= "u-btn u-btn-c4" >  
  76.                 </div>  
  77.             </div>  
  78.               
  79.             <div class= "line" ></div>  
  80.               
  81.             <!-- 问题的内容 -->  
  82.             <div>  
  83.                 <textarea name= "content" id="contentEditor" > </ textarea>  
  84.                 <script type= "text/javascript" >  
  85.                     var editor = new Simditor( {  
  86.                         textarea : $('#contentEditor'),  
  87.                         placeholder : '请在这里输入问题的内容...',  
  88.                         toolbar : true   
  89.                     } );  
  90.                 </script>  
  91.             </div>  
  92.               
  93.             <div class= "line"></div>  
  94.               
  95.             <!-- 最底部的提问按钮 -->  
  96.             <div class= "container  title-container">  
  97.                 <div class= "cell-11" style="height: 1px ;"> </ div>  
  98.                 <div class= "cell-1">  
  99.                     <input  type="submit" value="提问"  class= "u-btn u-btn-c4">  
  100.                 </div>  
  101.             </div>  
  102.         </div> <!-- 提问区域 结束 -->  
  103.         </form>  
  104.         #else  
  105.             <div style= "text-align:center ; min-height: 400px ; line-height: 400px ;">  
  106.                 登录以后才能发起提问,请<a  href= "$path/login.html" >登录</a >  
  107.             </div>  
  108.         #end  
  109.           
  110.         <div class="line" ></div>  
  111.           
  112.         <div class="container link-container" >  
  113.             <a href= "$path/list.do" >问题列表</a>  
  114.             |  
  115.             <a href= "$path/index.html" >返回首页</a>  
  116.         </div>  
  117.           
  118.         <div class="container copyright-container" >  
  119.             &copy; 2017 爱问社区版权所有  
  120.         </div>  
  121.           
  122.     </body>  
  123. </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">
		    &copy; 2017 爱问社区版权所有
		</div>
		
	</body>
</html>

回答Servlet处理代码:

  1. @WebServlet("/answer.do")  
  2. public class AnswerServlet extends HttpServlet {  
  3.   
  4.     private static final long serialVersionUID = 8578962149437664830L;  
  5.   
  6.     @Override  
  7.     protected void service(HttpServletRequest request, HttpServletResponse response)  
  8.             throws ServletException, IOException {  
  9.   
  10.         // 从 请求中获得请求参数的值  
  11.         String id = request.getParameter("id");  
  12.   
  13.         if (StringHelper.notEmpty(id)) {  
  14.   
  15.             try {  
  16.                 int topicId = Integer.parseInt(id); // 将字符串按照 十进制 解析问 int 类型数值  
  17.   
  18.                 // 根据得到的 问题的 主键 查询数据库,得到 详细信息  
  19.                 final String SQL = "SELECT  id , title , content , publish_time , publish_ip , user_id  FROM t_topic WHERE id = ? ";  
  20.   
  21.                 ResultSet rs = JdbcHelper.query(SQL, topicId);  
  22.   
  23.                 Topic t = null;  
  24.                 int userId = -1;  
  25.   
  26.                 if (rs.next()) { // 当 根据 问题的主键 获取到 问题信息时  
  27.                     t = new Topic(); // 创建 Topic 对象  
  28.   
  29.                     t.setId(rs.getInt(1)); // 将 结果集 中的 该行数据 封装到 t 对象的 id 属性中  
  30.                     t.setTitle(rs.getString(2));  
  31.                     t.setContent(rs.getString(3));  
  32.                     t.setPublishTime(rs.getTimestamp(4));  
  33.                     t.setPublishIp(rs.getString(5));  
  34.   
  35.                     userId = rs.getInt(6);  
  36.                 }  
  37.   
  38.                 JdbcHelper.release(rs); // 关闭结果集  
  39.   
  40.                 // 获得提问者  
  41.                 final String getUserSQL = "SELECT id , username , password FROM t_user WHERE id = ? ";  
  42.                 rs = JdbcHelper.query(getUserSQL, userId);  
  43.                 if (userId != -1 && rs.next()) {  
  44.                     User u = new User();  
  45.                     // 封装数据  
  46.                     u.setId(rs.getInt(1));  
  47.                     u.setUsername(rs.getString(2));  
  48.                     u.setPassword(rs.getString(3));  
  49.                     // 将获取到的用户数据设置到 Topic 对象的 user 属性中  
  50.                     t.setUser(u);  
  51.                 }  
  52.   
  53.                 HttpSession session = request.getSession();  
  54.                 session.setAttribute("topic", t);  
  55.   
  56.                 response.sendRedirect(request.getContextPath() + "/answer.html");  
  57.   
  58.                 return// 让方法立即结束  
  59.             } catch (NumberFormatException e) {  
  60.                 e.printStackTrace();  
  61.                 // response.sendRedirect( request.getContextPath() + "/list.do" );  
  62.             } catch (SQLException e) {  
  63.                 e.printStackTrace();  
  64.                 // response.sendRedirect( request.getContextPath() + "/list.do" );  
  65.             }  
  66.   
  67.         } else {  
  68.             // response.sendRedirect( request.getContextPath() + "/list.do" );  
  69.         }  
  70.   
  71.         response.sendRedirect(request.getContextPath() + "/list.do");  
  72.   
  73.     }  
  74.   
  75. }  
@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");

	}

}


回答前台代码:

  1. <!DOCTYPE html>  
  2. <html>  
  3.     <head>  
  4.         <meta charset="UTF-8" >  
  5.         <title>解答: $topic.title</title >  
  6.         <link rel="stylesheet"  href="$path/styles/general.css">  
  7.         <link rel="stylesheet"  href="$path/styles/cell.css">  
  8.         <link rel="stylesheet"  href="$path/styles/wen.css">  
  9.           
  10.         <!-- 链接 simditor 的样式库 -->  
  11.         <link rel="stylesheet"   href="$path/simditor/styles/simditor.css" type="text/css" >  
  12.         <!-- 导入 simditor 的 JavaScript 库 -->  
  13.         <script type="text/javascript"  src="$path/simditor/scripts/jquery.min.js"></script >  
  14.         <script type="text/javascript"  src="$path/simditor/scripts/module.js"></script >  
  15.         <script type="text/javascript"  src="$path/simditor/scripts/hotkeys.js"></script >  
  16.         <script type="text/javascript"  src="$path/simditor/scripts/uploader.js"></script >  
  17.         <script type="text/javascript"  src="$path/simditor/scripts/simditor.min.js"></script >  
  18.           
  19.     </head>  
  20.     <body>  
  21.       
  22.         ## 登录状态栏 开始  
  23.         <div class="login-status-container  auto-height" >  
  24.                 <span class= "welcome cell-8">  
  25.                     ## 在 $ 之后 表达式之前使用 ! 表示 安静模式 ( 静默模式 )  
  26.                     <b>欢迎$!user.username来到爱问社区 </b>  
  27.                 </span>  
  28.                 <span class= "login-operation cell-4">  
  29.                     #if( $user )  
  30.                         <a  href="$path/ask.html">提问</a>  
  31.                         <em >| </em>  
  32.                         <a  href="">我的提问</a>  
  33.                         <em >| </em>  
  34.                         <a  href="$path/logout.do">注销</a>  
  35.                     #else  
  36.                         <a  href="$path/login.html">登录</a >  
  37.                         <em >| </em>  
  38.                         <a  href="$path/regist.html">注册</a >  
  39.                     #end  
  40.                 </span>  
  41.         </div> ## 登录状态栏 结束  
  42.           
  43.         ## 标志区域  
  44.         <div class="brand-container  auto-height" >  
  45.             <div class= "logo cell-2" >  
  46.                 <a href= "$path"></a>  
  47.             </div>  
  48.             <div class= "slogan cell-10" >  
  49.                 <div>  
  50.                 解答问题  
  51.                 </div>  
  52.             </div>  
  53.         </div>  
  54.           
  55.             <div>  
  56.                 <h3>$topic.title </h3>  
  57.                 <div class= "line"></div>  
  58.                 <div>  
  59.                     $topic.content  
  60.                 </div>  
  61.                 <div>  
  62.                     提问时间: $topic.publishTime / 提问者: $topic.user.username  
  63.                 </div>  
  64.             </div>  
  65.               
  66.             <!-- 解答的内容 -->  
  67.             <form action= "$path/explain.do"  method="post" >  
  68.                 <input type= "hidden" name="id" value= "$topic.id"  >  
  69.             <div>  
  70.                 <textarea name= "content" id="contentEditor" > </ textarea>  
  71.                 <script type= "text/javascript" >  
  72.                     var editor = new Simditor( {  
  73.                         textarea : $('#contentEditor'),  
  74.                         placeholder : '请在这里输入问题的内容...',  
  75.                         toolbar : true   
  76.                     } );  
  77.                 </script>  
  78.             </div>  
  79.             <input type= "submit" value="提交解答">  
  80.             </form>  
  81.           
  82.           
  83.           
  84.         $scope.remove( $session , 'topic' );  
  85.           
  86.         <div class="line" ></div>  
  87.           
  88.         <div class="container link-container" >  
  89.             <a href= "$path/ask.html" >发起新问题</a>  
  90.             |  
  91.             <a href= "$path/index.html" >返回首页</a>  
  92.         </div>  
  93.           
  94.         <div class="container copyright-container" >  
  95.             &copy; 2017 爱问社区版权所有  
  96.         </div>  
  97.       
  98.     </body>  
  99. </html>  
<!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">
		    &copy; 2017 爱问社区版权所有
		</div>
	
	</body>
</html>


以下是使用simditor的方法,需要引入simditor中的css和js样式。simditor下载地址:http://download.csdn.net/detail/weixin_36380516/9813448
  1. <textarea name="content" id= "contentEditor" ></textarea>  
  2.                 <script type= "text/javascript" >  
  3.                     var editor = new Simditor( {  
  4.                         textarea : $('#contentEditor'),  
  5.                         placeholder : '请在这里输入问题的内容...',  
  6.                         toolbar : true   
  7.                     } );  
  8.                 </script>  
<textarea name="content" id="contentEditor" ></textarea>
				<script type="text/javascript" >
					var editor = new Simditor( {
						textarea : $('#contentEditor'),
						placeholder : '请在这里输入问题的内容...',
						toolbar : true 
					} );
				</script>


解答问题Servlet处理,这里需要获取提问者,提问问题以及该问题的已有答案,已有答案回答者。

  1. @WebServlet("/detail.do")  
  2. public class DetailServlet extends HttpServlet {  
  3.     private static final long serialVersionUID = -3202278077673657729L;  
  4.     @Override  
  5.     protected void service(HttpServletRequest request, HttpServletResponse response)  
  6.         throws ServletException, IOException {  
  7.     // 从 请求中获得请求参数的值  
  8.     String id = request.getParameter("id");  
  9.     if (StringHelper.notEmpty(id)) {  
  10.         try {  
  11.         int topicId = Integer.parseInt(id); // 将字符串按照 十进制 解析问 int 类型数值  
  12.         // 根据得到的 问题的 主键 查询数据库,得到 详细信息  
  13.         final String SQL = "SELECT  id , title , content , publish_time , publish_ip , user_id  FROM t_topic WHERE id = ? ";  
  14.         ResultSet rs = JdbcHelper.query(SQL, topicId);  
  15.         Topic t = null;  
  16.         /*int userId = -1;*/  
  17.         if (rs.next()) { // 当 根据 问题的主键 获取到 问题信息时  
  18.             t = new Topic(); // 创建 Topic 对象  
  19.             t.setId(rs.getInt(1)); // 将 结果集 中的 该行数据 封装到 t 对象的 id 属性中  
  20.             t.setTitle(rs.getString(2));  
  21.             t.setContent(rs.getString(3));  
  22.             t.setPublishTime(rs.getTimestamp(4));  
  23.             t.setPublishIp(rs.getString(5));  
  24.             User user = new User();  
  25.             user.setId(rs.getInt(6));  
  26.             t.setUser(user);  
  27.         }  
  28.         JdbcHelper.release(rs); // 关闭结果集  
  29.         // 获得提问者  
  30.         final String getUserSQL = "SELECT id , username , password FROM t_user WHERE id = ? ";  
  31.         rs = JdbcHelper.query(getUserSQL, t.getUser().getId());  
  32.         if(rs.next())   
  33.         {  
  34.             User u = new User();  
  35.             // 封装数据  
  36.             u.setId(rs.getInt(1));  
  37.             u.setUsername(rs.getString(2));  
  38.             u.setPassword(rs.getString(3));  
  39.             // 将获取到的用户数据设置到 Topic 对象的 user 属性中  
  40.             t.setUser(u);  
  41.             System.out.println("message username:" + rs.getString(2));  
  42.         }  
  43.         JdbcHelper.release(rs); // 关闭结果集  
  44.         // 获得当前的问题的所有解答  
  45.         String explainSQL = "SELECT  id , content , explain_time , explain_ip , user_id  from t_explain where topic_id = ? ";  
  46.         rs = JdbcHelper.query(explainSQL, topicId);  
  47.         @SuppressWarnings("unused")  
  48.         int explainerId = -1;  
  49.         List<Explain> explains = new ArrayList<>();  
  50.         while (rs.next()) {  
  51.             Explain e = new Explain();  
  52.             e.setId(rs.getInt(1));  
  53.             e.setContent(rs.getString(2));  
  54.             e.setExplainTime(rs.getTimestamp(3));  
  55.             e.setExplainIp(rs.getString(4));  
  56.             User user=new User();  
  57.             user.setId(rs.getInt(5));  
  58.             e.setUser(user);  
  59.             explains.add(e);  
  60.             System.out.println("explain userID:" + rs.getInt(5));  
  61.         }  
  62.         // 获得解答者  
  63.         List<Explain>explainList = new ArrayList();  
  64.         for(int i=0;i<explains.size();i++)  
  65.         {  
  66.             Explain explain1 = explains.get(i);  
  67.             final String getExplainerSQL = "SELECT id , username , password FROM t_user WHERE id = ? ";  
  68.               
  69.             rs = JdbcHelper.query(getExplainerSQL, explain1.getUser().getId());  
  70.             if (rs.next()) {  
  71.                 User u = new User();  
  72.                 // 封装数据  
  73.                 u.setId(rs.getInt(1));  
  74.                 u.setUsername(rs.getString(2));  
  75.                 u.setPassword(rs.getString(3));  
  76.                 // 将获取到的用户数据设置到 Topic 对象的 user 属性中  
  77.                 explain1.setUser(u);  
  78.                 explainList.add(explain1);  
  79.                 System.out.println("explain username:" + rs.getString(2));  
  80.             }  
  81.             JdbcHelper.release(rs); // 关闭结果集  
  82.             /*t.setExplains(explains); // 将解答设置到 Topic 对象上 
  83. */      }  
  84.         t.setExplains(explainList);  
  85.           
  86.         /*** 为 所有的解答,获取解答者的详细信息 ***/  
  87.         HttpSession session = request.getSession();  
  88.         session.setAttribute("topic", t);  
  89.         response.sendRedirect( request.getContextPath() + "/detail.html" );  
  90.         return// 让方法立即结束  
  91.         } catch (NumberFormatException e) {  
  92.         e.printStackTrace();  
  93.   
  94.         } catch (SQLException e) {  
  95.         e.printStackTrace();  
  96.   
  97.         }  
  98.     } else {  
  99.     }  
  100.     response.sendRedirect(request.getContextPath() + "/list.do");  
  101.   
  102.     }  
  103.   
  104. }  
@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");

    }

}

解答问题前台显示界面代码;

  1. <!DOCTYPE html>  
  2.   
  3. <html>  
  4.     <head>  
  5.         <meta charset="UTF-8" >  
  6.         <title>$topic.title</title >  
  7.         <link rel="shortcut icon"  href="$path/images/icon.png" type="image/png" >  
  8.         <link rel="stylesheet"  href="$path/styles/general.css">  
  9.         <link rel="stylesheet"  href="$path/styles/cell.css">  
  10.         <link rel="stylesheet"  href="$path/styles/wen.css">  
  11.     </head>  
  12.     <body>  
  13.       
  14.         ## 登录状态栏 开始  
  15.         <div class="login-status-container  auto-height" >  
  16.                 <span class= "welcome cell-8">  
  17.                     ## 在 $ 之后 表达式之前使用 ! 表示 安静模式 ( 静默模式 )  
  18.                     <b>欢迎$!user.username来到问道 </b>  
  19.                 </span>  
  20.                 <span class= "login-operation cell-4">  
  21.                     #if( $user )  
  22.                         <a  href="$path/ask.html">提问</a>  
  23.                         <em >| </em>  
  24.                         <a  href="">我的提问</a>  
  25.                         <em >| </em>  
  26.                         <a  href="$path/logout.do">注销</a>  
  27.                     #else  
  28.                         <a  href="$path/login.html">登录</a >  
  29.                         <em >| </em>  
  30.                         <a  href="$path/regist.html">注册</a >  
  31.                     #end  
  32.                 </span>  
  33.         </div> ## 登录状态栏 结束  
  34.           
  35.         ## 标志区域  
  36.         <div class="brand-container  auto-height" >  
  37.             <div class= "logo cell-2" >  
  38.                 <a href= "$path"></a>  
  39.             </div>  
  40.             <div class= "slogan cell-10" >  
  41.                 <div>  
  42.                 </div>  
  43.             </div>  
  44.         </div>  
  45.           
  46.         <div>  
  47.             <h3>$topic.title</ h3>  
  48.             <div class= "line" ></div>  
  49.             <div>  
  50.                 $topic.content  
  51.             </div>  
  52.             <div>  
  53.                 提问时间: $topic.publishTime / 提问者: $topic.user.username  
  54.             </div>  
  55.         </div>  
  56.           
  57.         <div>  
  58.             #foreach( $ex in $topic.explains)  
  59.                 <div> $ex.content   </div>  
  60.                 <div class= "line"></div>  
  61.             #end  
  62.         </div>  
  63.           
  64.         $scope.remove( $session , 'topic' );  
  65.           
  66.         <div class="line" ></div>  
  67.           
  68.         <div class="container link-container" >  
  69.             <a href= "$path/ask.html"  >发起新问题</a>  
  70.             |  
  71.             <a href= "$path/index.html"  >返回首页</a>  
  72.         </div>  
  73.           
  74.         <div class="container copyright-container" >  
  75.             &copy; 2017 爱问社区版权所有  
  76.         </div>  
  77.       
  78.     </body>  
  79. </html>  
<!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">
		    &copy; 2017 爱问社区版权所有
		</div>
	
	</body>
</html>

我的解答Servlet处理代码:

  1. @WebServlet("/myAnswer.do")  
  2. public class MyAnswerServlet extends HttpServlet {  
  3.   
  4.     private static final long serialVersionUID = -3020889403557912216L;  
  5.   
  6.     @Override  
  7.     protected void service(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {       
  8.         HttpSession session = request.getSession();  
  9.         User user = (User) session.getAttribute( "user" ); // 在登录时将 User 对象放入了 会话 中  
  10.         Explain ex=null;  
  11.         final List<Explain> exp = new ArrayList<>();  
  12.         if( user != null ) {  
  13.         int myid=user.getId();  
  14.         final String SQL = "SELECT  id ,content ,explain_time , explain_ip , user_id ,topic_id  FROM t_explain WHERE user_id = ? ";  
  15.         ResultSet rs = JdbcHelper.query(SQL, myid);  
  16.         //Topic t=null;  
  17.         //final List<Explain> explains = new ArrayList<>();  
  18.         @SuppressWarnings("unused")  
  19.         int topicId=-1;  
  20.         try {  
  21.             while( rs.next() )  
  22.             {  
  23.             ex=new Explain();  
  24.             ex.setId(rs.getInt(1));  
  25.             ex.setContent(rs.getString(2));  
  26.             ex.setExplainTime(rs.getTimestamp( 3 ));  
  27.             ex.setExplainIp(rs.getString(4));  
  28.             ex.setUser(user);  
  29.             Topic to=new Topic();  
  30.             to.setId(rs.getInt(6));  
  31.             ex.setTopic(to);  
  32.             topicId=rs.getInt(6);  
  33.             exp.add(ex);  
  34.               
  35.             }  
  36.             JdbcHelper.release(rs); // 关闭结果集  
  37.               
  38.             for(int i = 0 , len = exp.size() ; i <  len ; i++)  
  39.             {  
  40.             Explain explain=exp.get(i);  
  41.             Topic tid=explain.getTopic();  
  42.             final String tSQL = "SELECT  id , title , content , publish_time , publish_ip , user_id  FROM t_topic WHERE id = ? ";  
  43.             ResultSet trs = JdbcHelper.query(tSQL, tid.getId());  
  44.             while(trs.next())  
  45.             {  
  46.                Topic t=new Topic();  
  47.                 t.setId(1);  
  48.                 t.setTitle(trs.getString(2));  
  49.                 t.setContent(trs.getString(3));  
  50.                 t.setPublishTime(trs.getTimestamp(4));  
  51.                 t.setPublishIp(trs.getString(5));  
  52.                 ex.setTopic(t);  
  53. //              explains.add(ex);  
  54.                 System.out.println( "我的tid: " + tid.getId());  
  55.             }  
  56.               
  57.             JdbcHelper.release(trs); // 关闭结果集  
  58.             }  
  59.               
  60.               
  61.         } catch (SQLException e) {  
  62.             // TODO Auto-generated catch block  
  63.             e.printStackTrace();  
  64.         }  
  65.           
  66.           
  67.         session.setAttribute("explains", exp);  
  68.           
  69.         System.out.println( "我的解答列表: " + exp );  
  70.         System.out.println( "我的id: " + myid);  
  71.         response.sendRedirect( request.getContextPath() + "/myAnswer.html");  
  72.         }  
  73.     }  
  74.        
  75.   
  76. }  
@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");
	    }
	}
     

}

我的解答前台展示页面代码:

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8"  />  
  5.     <title>解答</title>  
  6.     <link rel="stylesheet"  href="$path/styles/top.css">  
  7.       
  8. </head>  
  9. <body>  
  10. <div style="margin-left:320px;">  
  11. <nav id="topnav" class= "f_r">  
  12.     <ul>  
  13.       <a href="$path/index.html"">首页</a> <a href="$path/myQuestion.do"  >我的提问</a>  
  14.        <a href="$path/ask.html"  >提问</a> <a  href="$path/logout.do">注销</a>  
  15.     </ul>  
  16.   </nav>  
  17.  </div>  
  18. #if( $user )  
  19. $user.username的所有回答:  
  20. #end  
  21. #foreach( $ex in $explains)  
  22. <div class="blogs">  
  23. <ul>  
  24.     <p>$ex.content</p>  
  25.     <div class="content_time">  
  26.        <p> 解答时间:<span  class="dtime f_l"> $ex.explainTime</span > </p>  
  27.     </div>  
  28.     <div class="line"> </div>  
  29. </ul>  
  30. </div>  
  31. #end  
  32.   
  33. </body>  
  34. </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处理:

  1. @WebServlet("/myQuestion.do")  
  2. public class MyQuestionServlet extends HttpServlet {  
  3.   
  4.     private static final long serialVersionUID = -4110483126223561394L;  
  5.   
  6.     @Override  
  7.     protected void service(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {       
  8.         HttpSession session = request.getSession();  
  9.         User user = (User) session.getAttribute( "user" ); // 在登录时将 User 对象放入了 会话 中  
  10.         if( user != null ) {  
  11.         int myid=user.getId();  
  12.         final String SQL = "SELECT id , title , content, publish_time , publish_ip FROM t_topic WHERE user_id = ? ";  
  13.         ResultSet rs = JdbcHelper.query(SQL, myid);  
  14.         final List<Topic> qtopics = new ArrayList<>();  
  15.         try {  
  16.             while( rs.next() ){  
  17.             Topic t=new Topic();  
  18.             t.setId(rs.getInt(1));  
  19.             t.setTitle(rs.getString(2));  
  20.             t.setContent(rs.getString(3));  
  21.             t.setPublishTime(rs.getTimestamp(4));  
  22.             t.setPublishIp(rs.getString(5));  
  23.             qtopics.add(t);  
  24.               
  25.               
  26.             }  
  27.         } catch (SQLException e) {  
  28.             // TODO Auto-generated catch block  
  29.             e.printStackTrace();  
  30.         }  
  31.           
  32.           
  33.         session.setAttribute("qtopics", qtopics);  
  34.           
  35.         System.out.println( "我的提问列表: " + qtopics );  
  36.         System.out.println( "我的id: " + myid);  
  37.         response.sendRedirect( request.getContextPath() + "/myQuestion.html");  
  38.         }  
  39.     }  
  40.        
  41.   
  42. }  
@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");
	    }
	}
     

}

我的提问展示代码:

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8"  />  
  5.     <title>$user.username的提问 </title >  
  6.      <link rel="stylesheet"  href="$path/styles/general.css">  
  7.         <link rel="stylesheet"  href="$path/styles/cell.css">  
  8.         <link rel="stylesheet"  href="$path/styles/wen.css">  
  9.         <link rel="stylesheet"  href="$path/styles/top.css">  
  10. </head>  
  11. <body>  
  12.   
  13.   
  14. <div style="margin-left:320px;">  
  15.             <ul>  
  16.            #if($user)  
  17.                     <nav id= "topnav" class="f_r">  
  18.                         <ul>  
  19.                             <a  href="$path/index.html">首页</a >  
  20.                             <a  href="$path/myAnswer.do" >我的解答</a >  
  21.                             <a  href="$path/ask.html">提问</a>  
  22.                             <a  href="$path/logout.do" >注销</a >  
  23.                         </ul>  
  24.                     </nav>  
  25.                     #else  
  26.                  <li class= "presentation"><a href="$path/login.html"  id="link" title="提问">登录 </a></li>  
  27.                 <li class= "presentation"><a href="$path/regist.do"  id="tools" title="exit">注册 </a></li>  
  28.                 #end  
  29.             </ul>  
  30. </div>  
  31.   #if( $user )  
  32.                 $user.username的所有提问:  
  33.                 #end  
  34.                 #foreach( $qto in $qtopics)  
  35.   
  36. <div class="blogs">  
  37.         <ul>  
  38.             <p>$qto.content</ p>  
  39.           <p class="autor" ><span class="lm f_l" > <a>提问者:$user.username</a> </ span>  <span class= "dtime f_l" >$qto.publishTime</span></ p>  
  40.         </ul>  
  41.           
  42.       </div>  
  43.       #end  
  44.   
  45. </body>  
  46. </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" title="提问">登录</a></li>
                <li class="presentation"><a href="$path/regist.do" id="tools" title="exit">注册</a></li>
                #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代码:

  1. @WebServlet(urlPatterns= { "/verify/login.do" , "/verify/regist.do" } )  
  2. public class VerifyCodeServlet extends HttpServlet {  
  3.       
  4.     private static final long serialVersionUID = 3398560501558431737L;  
  5.   
  6.     @Override  
  7.     protected void service( HttpServletRequest request , HttpServletResponse response )   
  8.             throws ServletException, IOException {  
  9.           
  10.         // 获得 当前请求 对应的 会话对象  
  11.         HttpSession session = request.getSession();  
  12.           
  13.         // 从请求中获得 URI ( 统一资源标识符 )  
  14.         String uri = request.getRequestURI();  
  15.         System.out.println( "hello : " + uri );  
  16.           
  17.         final int width = 180 ;   // 图片宽度  
  18.         final int height = 40 ;  // 图片高度  
  19.         final String imgType = "jpeg" ; // 指定图片格式 (不是指MIME类型)  
  20.         final OutputStream output = response.getOutputStream(); // 获得可以向客户端返回图片的输出流 (字节流)  
  21.         // 创建验证码图片并返回图片上的字符串  
  22.         String code = GraphicHelper.create( width, height, imgType, output );  
  23.         System.out.println( "验证码内容: " + code );  
  24.           
  25.         // 建立 uri 和 相应的 验证码 的关联 ( 存储到当前会话对象的属性中 )  
  26.         session.setAttribute( uri , code );  
  27.           
  28.         System.out.println( session.getAttribute( uri ) );  
  29.           
  30.     }  
  31.   
  32. }  
@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 ) );
		
	}

}

注册前台界面,有验证码验证功能:

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="UTF-8">  
  5.     <title>注册爱问社区</title>  
  6.   
  7.     <link rel="stylesheet"  href="$path/styles/general.css">  
  8.     <link rel="stylesheet"  href="$path/styles/cell.css">  
  9.     <link rel="stylesheet"  href="$path/styles/form.css">  
  10.   
  11.     <link rel="stylesheet"  href="$path/awesome/css/font-awesome.min.css">  
  12.       
  13.     <script type="text/javascript"  src="$path/js/wen.js"></script>  
  14.   
  15.     <style type="text/css"  >  
  16.   
  17.         .logo-container {  
  18.             margin-top: 50px ;  
  19.         }  
  20.         .logo-container img {  
  21.             width: 100px ;  
  22.         }  
  23.   
  24.         .message-container {  
  25.             height: 80px ;  
  26.         }  
  27.   
  28.         .link-container {  
  29.             height: 40px ;  
  30.             line-height: 40px ;  
  31.         }  
  32.   
  33.         .link-container a {  
  34.             text-decoration: none ;  
  35.         }  
  36.   
  37.     </style>  
  38.   
  39. </head>  
  40. <body>  
  41.   
  42. <div class="container title-container"  style="color:blue; margin-top:60px;">加入爱问社区,为您答疑解惑</div >  
  43. <div class="container form-container">  
  44.     <form action="$path/regist.do"  method="post">  
  45.         <div class="form" > <!-- 注册表单开始 -->  
  46.   
  47.             <div class="form-row" >  
  48.                         <span  class="cell-1">  
  49.                             <i  class="fa fa-user"></i>  
  50.                         </span >  
  51.                         <span  class="cell-11" style="text-align: left;" >  
  52.                             <input  type="text" name="username"  placeholder= "请输入用户名">  
  53.                         </span >  
  54.             </div>  
  55.   
  56.             <div class="form-row" >  
  57.                         <span  class="cell-1">  
  58.                             <i  class="fa fa-key"></i>  
  59.                         </span >  
  60.                         <span  class="cell-11" style="text-align: left;" >  
  61.                             <input  type="password" name="password"  placeholder= "请输入密码">  
  62.                         </span >  
  63.             </div>  
  64.   
  65.             <div class="form-row" >  
  66.                         <span  class="cell-1">  
  67.                             <i  class="fa fa-keyboard-o"></i>  
  68.                         </span >  
  69.                         <span  class="cell-11" style="text-align: left;" >  
  70.                             <input  type="password" name="confirm"  placeholder= "请确认密码">  
  71.                         </span >  
  72.             </div>  
  73.               
  74.             <div class="form-row" >  
  75.                         <span  class="cell-7">  
  76.                             <input  type="text" name="verifyCode"  placeholder= "请输入验证码">  
  77.                         </span >  
  78.                         <span  class="cell-5" style="text-align: center;" >  
  79.                             <img  src="$path/verify/regist.do"  onclick="myRefersh(this)" >  
  80.                         </span >  
  81.             </div>  
  82.   
  83.             <div class="form-row"  style="border: none;">  
  84.                         <span  class="cell-6" style="text-align: left" >  
  85.                            <input  type="reset" value="重置">  
  86.                         </span >  
  87.                         <span  class="cell-6"  style="text-align:right;" >  
  88.                             <input  type="submit" value="注册">  
  89.                         </span >  
  90.             </div>  
  91.   
  92.         </div> <!-- 注册表单结束 -->  
  93.     </form>  
  94. </div>  
  95. <div class="container message-container">  
  96.     <!-- 显示提示信息的地方 -->  
  97.     #if( $registFail )   
  98.         $registFail  
  99.         $scope.remove( $session , 'registFail' )  
  100.     #end  
  101. </div>  
  102. <div class="container link-container">  
  103.     <a href="$path/login.html"  > 已注册爱问帐号,点击这里登录</a>  
  104.     |  
  105.     <a href="$path/index.html"  >返回首页</a>  
  106. </div>  
  107. <div class="container copyright-container">  
  108.     &copy; 2017 爱问社区版权所有  
  109. </div>  
  110.   
  111. </body>  
  112. </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/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">
    &copy; 2017 爱问社区版权所有
</div>

</body>
</html>

Servlet处理注册,实现验证码验证:

  1. @WebServlet("/regist.do")  
  2. public class RegistServlet extends HttpServlet {  
  3.   
  4.     private static final long serialVersionUID = 7493633832455111617L;  
  5.   
  6.     @Override  
  7.     protected void service( HttpServletRequest request , HttpServletResponse response )   
  8.             throws ServletException, IOException {  
  9.           
  10.         // 获得来自 页面 表单上的数据  
  11.         String verifyCode = request.getParameter( "verifyCode" ) ; // 获得由用户输入的那个验证码  
  12.         String username = request.getParameter( "username" ) ;  
  13.         String password = request.getParameter( "password" ) ;  
  14.         String confirm = request.getParameter( "confirm" ) ;  
  15.           
  16.         System.out.println( "username : " + username );  
  17.         System.out.println( "password : " + password );  
  18.         System.out.println( "confirm : " + confirm );  
  19.         System.out.println( "verifyCode : " + verifyCode );  
  20.           
  21.         HttpSession session = request.getSession();  
  22.         // 获得 在 会话 中存储的那个 为登录进行验证的 验证码  
  23.         final String code = (String)session.getAttribute( "/wendao/verify/regist.do" );  
  24.         System.out.println( "session code : " + code );  
  25.           
  26.         // 比较验证码  
  27.         if( StringHelper.equals( verifyCode , code ) ){  
  28.             // 要保证 用户名 不为空 、密码不能为空 、两次输入的密码必须一致  
  29.             if( StringHelper.notEmpty( username )   
  30.                     && StringHelper.notEmpty( password )   
  31.                     && StringHelper.equals( password , confirm) ) {  
  32.                 // 可以保存了   
  33.                 String SQL = "INSERT INTO t_user ( username , password ) VALUES ( ? , ? ) " ;  
  34.                 int n = JdbcHelper.insert( SQL ,  false , username , StringHelper.MD5(password));  
  35.                 if( n > 0 ) {  // 如果 insert 返回 大于 0 的数字 , 则表示 插入成功  
  36.                     // 保存成功以后,应该去一个新的页面 ( 比如去 登录页面 )  
  37.                     response.sendRedirect( request.getContextPath() + "/login.html" );  
  38.                 } else {  
  39.                     // 回到注册页面去  
  40.                     session.setAttribute( "registFail" ,  "注册失败,可能是用户名被占用了" );  
  41.                     response.sendRedirect( request.getContextPath() + "/regist.html" );  
  42.                 }  
  43.             } else {  
  44.                 // 回到注册页面去  
  45.                 session.setAttribute( "registFail" , "用户名或密码为空,或者密码不一致" );  
  46.                 response.sendRedirect( request.getContextPath() + "/regist.html" );  
  47.             }  
  48.         } else {  
  49.             // 如果验证码不一致,设置提示信息后回到注册页面去  
  50.             session.setAttribute( "registFail" , "验证码输入错误,请重新输入" );  
  51.             response.sendRedirect( request.getContextPath() + "/regist.html" );  
  52.         }  
  53.           
  54.     }  
  55.          
  56. }  
@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处理代码:

  1. @WebServlet("/login.do")  
  2. public class LoginServlet extends HttpServlet {  
  3.   
  4.     private static final long serialVersionUID = 18854422651747352L;  
  5.   
  6.     @Override  
  7.     protected void service( HttpServletRequest request , HttpServletResponse response )   
  8.             throws ServletException, IOException {  
  9.           
  10.         // 获得来自 页面 表单上的数据  
  11.         String username = request.getParameter( "username" ) ;  
  12.         String password = StringHelper.MD5(request.getParameter( "password" )) ;  
  13.           
  14.         System.out.println( "username : " + username );  
  15.         System.out.println( "password : " + password );  
  16.           
  17.         HttpSession session = request.getSession();  
  18.           
  19.               
  20.             // 登录 : 根据 用户名 和 密码 从数据库中查询数据,如果都正确,就将这些数据放入到会话中,最后进入到指定页面( list.html )  
  21.             String SQL = "SELECT id , username , password FROM t_user WHERE username = ? and password = ? " ;  
  22.             ResultSet rs = JdbcHelper.query( SQL,  username , password ) ;  
  23.               
  24.             try{  
  25.                 // 如果查询到数据,就包装到一个对象中  
  26.                 if( rs.next() ) {  
  27.                     User user = new User();  // 创建对象  
  28.                       
  29.                     // 封装数据  
  30.                     user.setId( rs.getInt( 1 ) );  
  31.                     user.setUsername( rs.getString( 2 ));  
  32.                     user.setPassword( rs.getString( 3 ) ) ;  
  33.                     //System.out.println("测试"+MD5.convertMD5(MD5.convertMD5(password)));  
  34.                     /** 将 User 对象 放入到 会话中 **/  
  35.                     session.setAttribute( "user" , user );  
  36.                     // 重定向到 list.do ( list.do 会先查询数据后 再 重定向到 list.html )  
  37.                     response.sendRedirect( request.getContextPath() + "/list.do" );  
  38.                 } else {  
  39.                     // 如果 用户名 或 密码 错误,重新返回到 登录页面  
  40.                         session.setAttribute( "loginFail" ,  "用户名或密码错误" );  
  41.                     response.sendRedirect( request.getContextPath() + "/login.html" );  
  42.                 }  
  43.             } catch ( SQLException e ){  
  44.                 e.printStackTrace();  
  45.             }  
  46.     }      
  47. }  
@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();
			}
	}    
}

登录前台展示界面代码;

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="UTF-8">  
  5.     <title>登录</title>  
  6.   
  7.     <link rel="stylesheet"  href="styles/general.css">  
  8.     <link rel="stylesheet"  href="styles/cell.css">  
  9.     <link rel="stylesheet"  href="styles/form.css">  
  10.   
  11.     <link rel="stylesheet"  href="awesome/css/font-awesome.min.css">  
  12.     <link rel="stylesheet"  type="text/css" href="css/login.css" >  
  13.     <script type="text/javascript"  src="js/wen.js"></script>  
  14.   
  15. </head>  
  16. <body>  
  17.     <div class="logina-logo"  style="height: 55px">  
  18.             <div id="venusLogo" ><p><span>爱问社区 </span></p></ div >  
  19.         </div>  
  20.         <div class="logina-main main clearfix" >  
  21.             <div class="tab-con" >  
  22.                 <form action= "$path/login.do" method="post">  
  23.                     <div id= 'login-error' class="error-tip"></ div >  
  24.                     <table border= "0" cellspacing="0" cellpadding= "0" >  
  25.                         <tbody >  
  26.                             <tr >  
  27.                                 < th>账户</th>  
  28.                                 < td width="245">  
  29.                                     < input type="text" name= "username"  id="username" placeholder="昵称"  />   
  30.                                 < td>  
  31.                                 </ td>  
  32.                             </tr >  
  33.                             <tr >  
  34.                                 < th>密码</th>  
  35.                                 < td width="245">  
  36.                                     < input type="password" name= "password"  id="password" placeholder="密码"  />  
  37.                                 </ td>  
  38.                                 < td>  
  39.                                 </ td>  
  40.                             </tr >  
  41.                             <tr >  
  42.                                 < th></th>  
  43.                                 < td width="245"><input  class="confirm" type="submit"  value= "登  录"></td>  
  44.                                 < td></td>  
  45.                             </tr >  
  46.                         </tbody >  
  47.                     </table>  
  48.                 </form>  
  49.             </div>  
  50.             <div class="reg" >  
  51.                 <p>还没有账号?< br>赶快免费注册一个吧!</p>  
  52.                 <a class= "reg-btn" href="regist.html">立即免费注册 </ a>  
  53.             </div>  
  54.         </div>  
  55.         <div id="footer" >  
  56.             <div class="copyright" >Copyright © 爱问社区 版权所有</div>  
  57.         </div>     
  58. </body>  
  59. </html>  
<!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代码,需要的可以根据字段来写

  1. DROP TABLE IF EXISTS `t_explain`;  
  2. CREATE TABLE `t_explain` (  
  3.   `id` int(11) NOT NULL AUTO_INCREMENT,  
  4.   `content` text,  
  5.   `explain_time` timestamp NULL DEFAULT NULL  ON UPDATE CURRENT_TIMESTAMP,  
  6.   `explain_ip` varchar(50) DEFAULT NULL,  
  7.   `user_id` int(8) DEFAULT NULL,  
  8.   `topic_id` int(8) DEFAULT NULL,  
  9.   PRIMARY KEY (`id`),  
  10.   KEY `ex_id` (`user_id`),  
  11.   KEY `t_id` (`topic_id`),  
  12.   CONSTRAINT `ex_id` FOREIGN KEY (`user_id`) REFERENCES `t_user` (`id`),  
  13.   CONSTRAINT `t_id` FOREIGN KEY (`topic_id`) REFERENCES `t_topic` (`id`)  
  14. ) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8;  
  15.   
  16. -- ----------------------------  
  17. -- Table structure for t_topic  
  18. -- ----------------------------  
  19. DROP TABLE IF EXISTS `t_topic`;  
  20. CREATE TABLE `t_topic` (  
  21.   `id` int(10) NOT NULL AUTO_INCREMENT,  
  22.   `title` varchar(255) DEFAULT NULL,  
  23.   `content` text,  
  24.   `publish_time` timestamp NOT NULL DEFAULT  CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,  
  25.   `publish_ip` varchar(100) DEFAULT NULL,  
  26.   `user_id` int(10) DEFAULT NULL,  
  27.   PRIMARY KEY (`id`),  
  28.   KEY `cid` (`user_id`),  
  29.   CONSTRAINT `cid` FOREIGN KEY (`user_id`) REFERENCES `t_user` (`id`)  
  30. ) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8;  
  31.   
  32. -- ----------------------------  
  33. -- Table structure for t_user  
  34. -- ----------------------------  
  35. DROP TABLE IF EXISTS `t_user`;  
  36. CREATE TABLE `t_user` (  
  37.   `id` int(10) NOT NULL AUTO_INCREMENT,  
  38.   `username` varchar(20) NOT NULL,  
  39.   `passwordvarchar(255) NOT NULL,  
  40.   PRIMARY KEY (`id`),  
  41.   UNIQUE KEY `username` (`username`)  
  42. ) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=utf8;  
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;

哪里有问题欢迎留言,看到第一时间解答。