1. 程式人生 > >Java+MyEclipse+Tomcat (二)配置Servlet及簡單實現表單提交

Java+MyEclipse+Tomcat (二)配置Servlet及簡單實現表單提交

        在WebRoot資料夾下建立images資料夾,並新增圖片logo.jpg。新增inc資料夾,新建style.css檔案,程式碼如下:
.main {
	width: 1024px;
	text-align:left;
}
.font {
	font-family: "Trebuchet MS";
	font-size: 14px;
	font-weight: bold;
	color: #FFFFFF;
}
.div {
	margin: 0px;
	padding: 0px;
	width: 1014px;
}
.tdBgColor{
	background-color:#6b1101;
}
a{
	font-family: "Trebuchet MS";
	font-size: 14px;
	font-weight: bold;
	color: #FFFFFF;
	line-height:50px;
	text-decoration:none;

}
a.hover{
	font-family: "Trebuchet MS";
	font-size:14px;
	font-weight: bold;
	color:#0000FF;
	line-height:50px;
	text-decoration:underline;
	padding-bottom:1px;

}
a.visited{
	font-family: "Trebuchet MS";
	font-size:14px;
	font-weight: bold;
	color:#000066;
	line-height:50px;
	text-decoration:none;
}
a.active{
	font-family: "Trebuchet MS";
	font-size:14px;
	font-weight: bold;
	color:#0000FF;
	line-height:50px;
	text-decoration:none;
	padding-bottom:1px;
}
        然後修改index.jsp主頁,程式碼如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>火車票訂票系統</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
	   <!-- 介面佈局 -->	
	   <div align="center">
	   <div class="style">
	   <table width="1024"  height="150" cellpadding="0" cellspacing="0" >
	   		<!-- 動態首頁訂票介面 同時獲取年月日和動態滾動訊息 -->
			<tr>
				<td colspan="2">
					<img src="./images/logo.jpg" alt="logo" width="1024" height="149">
				</td>
			</tr>		
			<tr>
				<td width="205"  bgcolor="#b7d7ec">
					<p align="center">
					<!-- 注意:方法today.getYear()已經過時,需要新增1900 -->
					<script language=JavaScript>
					today = new Date();
					function initArray(){
					this.length=initArray.arguments.length;
					for(var i=0;i<this.length;i++)
					this[i+1]=initArray.arguments[i];  }
					var d=new initArray(
					"星期日","星期一","星期二","星期三","星期四",	"星期五","星期六");
					document.write("<font color=##ff0000 style='font-size:12pt;font-family: 宋體'> ",
					today.getYear()+1900,"年",today.getMonth()+1,"月",today.getDate(),"日    ",d[today.getDay()+1],
								  "</font>" );
					</script> 
					</p>	
			    </td>	
				<td width="819" bgcolor="#b7d7ec">
					<marquee  direction="left" onmouseover=this.stop() onmouseout=this.start() scrollAmount=3 scrollDelay=100>
	             	<FONT style="FONT-SIZE: 18px"color=blue>歡迎使用火車票訂票系統管理系統 ,如有不足,敬請指導!</FONT>
	            	</marquee>
	            </td>
	        </tr>
	  </table>
	  </div>
	  
	  <table width="100%" height="75%" border="0" align="center">
		  <tr>
		    <td width="40%" height="20%"> </td>
		    <td width="20%" >	
          	<!-- 中間登入部分佈局 提交表單  配置web.xml -->
          	<form action="loginAction.do">
          	<table width="500" height="80%" border="2" bordercolor="#12A0F5"  bgcolor="#dfeaf1">
               <tr>
                 <td></td>
                 <td align="center"><br />系統管理員登入 <br/><br/>
       				使用者名稱:<input type="text" name="userid" size="19" maxlength="19" /><br/><br/>
       				密 碼:<input type="password" name="password" size="20" maxlength="19" /><br /><br />
                	<input type="submit" name="Submit" value="登入"/>    
                	<input type="reset" name="Submit" value="重置" /><br/>                           		
                </td>
                <td></td>
              </tr>
          </table>
          </form>
          </td>
		  <td width="40%"></td>
		  </tr>
		  <tr><td height="67" colspan="3">  
		 	<!-- 底部版權所有介面 -->
			<TABLE class=wrapper border=0 cellSpacing=0 cellPadding=0 width="100%" align=center>
			 <TBODY>
			  <TR>
			  	  <TD style="LINE-HEIGHT: 150%" align="center"> 
			      <HR style="WIDTH: 96%; HEIGHT: 4px; COLOR: #02457c">
			      <font size="2"> <SCRIPT language=javascript src=""></SCRIPT>
			      <!-- target=_blank開啟新的網頁 -->
			      <BR><A href="aboutme.jsp" target=_blank>關於我們</A> | <A href="wzsm.jsp">網站宣告</A>
			       <BR>版權所有&copy;2014-2015 北京理工大學 Eastmount <BR>京ICP備10009636號 </font>
			      </TD>
			  </TR>
			 </TBODY>
			</TABLE>
		  </td>
		 </tr>
		</table>
	  </div>
  </body>
</html>
        此時執行Web網站,點選Run As=》MyEclipse Server Application。如圖所示:


        此時,輸入使用者名稱和密碼登入效果如下圖所示:

        然後在src中新建資料夾Servlet,新建HomePageAction.java檔案,程式碼如下:
package servlet;

import java.io.IOException;
import java.sql.*; //匯入資料庫處理所有庫
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;

//使用者登入處理Servlet 系統登入主頁處理表單
public class HomePageAction extends HttpServlet {
	
	private Connection cn=null;     //定義資料庫連線物件
	private String driverName=null; //資料庫驅動器
	private String url=null;        //資料庫地址URL
	
	//初始化方法,取得資料庫連線物件
	public void init(ServletConfig config) throws ServletException
	{
		super.init(config);
		driverName=config.getInitParameter("driverName");
		url=config.getInitParameter("url");
		
		try {
			Class.forName(driverName);
			cn=DriverManager.getConnection(url);
		} catch(Exception e) {
			System.out.println("取得資料庫連線錯誤:"+e.getMessage());
		}
	}
	
	//處理GET請求方法
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException
	{
		//取得使用者登錄檔單提交的資料
		String userid=request.getParameter("userid");
		String password=request.getParameter("password");
		//判斷登入賬號為空,則自動跳轉到註冊頁面
		if(userid==null||userid.trim().length()==0) {
			response.sendRedirect("index.jsp");
			JOptionPane.showMessageDialog(null, "User name or password can't be empty!");
		}
		//判斷登入密碼為空
		if(password==null||password.trim().length()==0) {
			response.sendRedirect("index.jsp");
			JOptionPane.showMessageDialog(null, "User name or password can't be empty!");
		}
		//查詢資料庫和跳轉到登入主介面
		try {
			//查詢資料庫操作
			
			//跳轉到主介面
			response.sendRedirect("success.jsp");
		} catch(Exception e) {
			System.out.println("錯誤:"+e.getMessage());
			response.sendRedirect("index.jsp");
		}
	}
	
	//處理POST請求方法
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException 
	{
		doGet(request,response);
	}
	
	//銷燬方法
	public void destroy() {
		super.destroy();
		try {
			cn.close();
		}catch(Exception e) {
			System.out.println("關閉資料庫錯誤:"+e.getMessage());
		}
	}		
}
        同時在WEB-INF資料夾web.xml檔案中配置Servlet,程式碼如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name></display-name>	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- 配置Servlet -->
  <servlet>
  <servlet-name>HomePageAction</servlet-name>
  <servlet-class>servlet.HomePageAction</servlet-class>
  <init-param>
	<param-name>driveName</param-name>
 	<param-value>sun.jdbc.odbc.Jdbc0dbcDriver</param-value>
  </init-param>
  <init-param>
 	<param-name>url</param-name>
 	<param-value>jdbc:odbc:cityoa</param-value>
  </init-param>	
  </servlet>
  <servlet-mapping>
  	<servlet-name>HomePageAction</servlet-name>
  	<url-pattern>/loginAction.do</url-pattern>
  </servlet-mapping>
    
</web-app>
        最後新建success.java檔案,跳轉後顯示的頁面。
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>驗證成功介面</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
    	介面表單提交跳轉成功 <br>
    	<a href="index.jsp">返回</a>
  </body>
</html>
       顯示效果如下圖所示:


        此時Servlet配置成功,而且表單跳轉功能也實現了。你可能遇到如下錯誤:

        解決方案如下:
        最後希望文章對你有所幫助,下一篇文章準備講述JSP網站的一種經典網站模型和MyEclipse資料庫配置相關知識。如果文章有不足或錯誤的地方,還請海涵!
        (By:Eastmount 2015-5-7 清晨4點   http://blog.csdn.net/eastmount/