Java+MyEclipse+Tomcat (四)Servlet提交表單和資料庫操作

Eastmount發表於2015-05-15
        前面三篇文章講述瞭如何配置MyEclipse和Tomcat開發JSP網站、如何配置Servlet簡單實現表單提交、如何配置MySQL實現JSP資料庫查詢。
        這篇文章主要講述Servlet表單的提交、Java中實現資料庫的查詢操作和自己遇到的瓶頸及理解。Java Web基礎性文章,希望對大家有所幫助~
        Java+MyEclipse+Tomcat (一)配置過程及jsp網站開發入門
        Java+MyEclipse+Tomcat (二)配置Servlet及簡單實現表單提交
        Java+MyEclipse+Tomcat (三)配置MySQL及查詢資料顯示在JSP網頁中
        兩個專案的免費下載地址(希望對你有所幫助):
        http://download.csdn.net/detail/eastmount/8701707

一. Servlet表單提交

        新建Web Project,專案名稱為TestServlet01。專案結構如下圖所示:

        然後修改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>My JSP 'index.jsp' starting page</title>
	<style>
		body, div, td, input {font-size:18px; margin:0px; }
		.line {margin:2px; }
	</style>
  </head>
  
  <body>
  <form action="/TestServlet01/servlet/PostServlet" method="POST">
  <div align="center">
	<br/>
	<fieldset style='width:60%'>
		<legend>填寫使用者資訊</legend>
		<br/>
		<div class='line'>
			<div align="left">出發地:
				<input type="text" id="start" name="start" style='font-size:18px' width=200/>
			</div>
		</div>
		<div class='line'>
			<div align="left">到達地:
				<input type="text" id="end" name="end" style='font-size:18px'/>
			</div>
		</div>
		<div class='line'>
			<br />
			<div align="left">請選擇性別:
				<input type="radio" name="sex" value="男" id="sexMale">
				<label for="sexMale">男</label>
				<input type="radio" name="sex" value="女" id="sexFemale">
				<label for="sexFemale">女</label>
		    </div>
		</div>
		<div class='line'>
			<div align="left">請選擇您的愛好:
				<input type="checkbox" name="interesting" value="音樂" id="i1">
				<label for="i1">音樂</label> 
				<input type="checkbox" name="interesting" value="旅遊" id="i2">
				<label for="i2">旅遊</label> 
				<input type="checkbox" name="interesting" value="運動" id="i3">
				<label for="i3">運動</label> 
			</div>
		</div>
		<div class='line'>
			<div align="left">請選擇車票型別:
				<select name="seat">
					<option>---請選擇乘坐型別---</option>
					<optgroup label="臥鋪">
						<option value="上鋪">上鋪</option>
						<option value="中鋪">中鋪</option>
						<option value="下鋪">下鋪</option>
					</optgroup>
					<optgroup label="其他">
						<option value="硬座">硬座</option>
						<option value="軟座">軟座</option>
						<option value="站票">站票</option>
					</optgroup>
				</select>
			</div>
		</div>
		<div class='line'>
			<br />
			<div align="left" class='leftDiv'>備註資訊:</div>
			<div align="left" class='rightDiv'>
				<textarea name="description" rows="8" style="width:300px; ">請填寫備註資訊... </textarea>
			</div>
		</div>
		<div class='line'>
			<div align="left">
				<br/><input type="submit" name="Select" value="提交資訊" style='font-size:18px'/><br/>
			</div>
		</div>
	</fieldset>
</div>
</form>
</body>
</html>
        執行效果如下圖所示:
        核心程式碼:
        <form action="/TestServlet01/servlet/PostServlet" method="POST">
            出發地:<input type="text" id="start" name="start" style='font-size:18px'/>
            <input type="submit" name="Select" value="提交資訊"/>
        </form>

        然後再src中右鍵新增Package,包名為servlet;再新增Servlet檔案,檔名PostServlet.java。選擇圖示。前面文章講述過Servlet的手動配置過程,包括servlet類、對映等,現在它自動生成的WebRoot/WEB-INF/web.xml檔案如下:
<?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>
  
  
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>PostServlet</servlet-name>
    <servlet-class>servlet.PostServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>PostServlet</servlet-name>
    <url-pattern>/servlet/PostServlet</url-pattern>
  </servlet-mapping>	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
        同時修改src/servlet/PostServlet.java檔案,採用POST方法顯示錶單資料:
package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class PostServlet extends HttpServlet {

	public PostServlet() {
		super();
	}

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the GET method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setCharacterEncoding("UTF-8"); //設定輸出編碼
		request.setCharacterEncoding("UTF-8");
		
		String startName = request.getParameter("start"); //獲取出發地
		String endName = request.getParameter("end");     //獲取到達地
		String sex = request.getParameter("sex");         //獲取性別
		String [] interest = request.getParameterValues("interesting"); //獲取興趣
		String seat = request.getParameter("seat");        //獲取座位
		String info = request.getParameter("description"); //獲取備註資訊
		
		response.setContentType("text/html");  //設定輸出型別
		PrintWriter out = response.getWriter(); //獲取out物件
		
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.println("<H2>出發地:"+ startName +"</H2>");
		out.println("<H2>到達地:"+ endName +"</H2>");
		out.println("<H2>性別:"+ sex +"</H2>");
		out.println("<H2>興趣");
		for(String str:interest) {
			out.println(str+" ");
		}
		out.println("</H2><H2>座位型別:"+ seat +"</H2>");
		out.println("<H2>備註資訊:"+ info +"</H2>");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
        執行效果如下圖所示:
        

二. Servlet資料庫查詢

        還是使用上面的專案進行修改,實現Servlet資料庫查詢操作。資料庫配置可以參照上一篇部落格配置MySQL的過程,我新建資料庫test01,插入表Train,表中資料如下圖:

        然後修改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>My JSP 'index.jsp' starting page</title>
	<style>
		body, div, td, input {font-size:18px; margin:0px; }
		.line {margin:2px; }
	</style>
  </head>
  
  <body>
  <form action="/TestServlet01/servlet/PostServlet" method="POST">
  <div align="center">
	<br/>
	<fieldset style='width:60%'>
		<legend>填寫使用者資訊</legend>
		<br/>
		<div class='line'>
			<div align="left">出發地:
				<input type="text" id="start" name="start" style='font-size:18px' width=200/>
			</div>
		</div>
		<div class='line'>
			<div align="left">
				<br/><input type="submit" name="Select" value="提交資訊" style='font-size:18px'/><br/>
			</div>
		</div>
	</fieldset>
</div>
</form>
</body>
</html>
        修改的PostServlet.java程式碼如下:
package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class PostServlet extends HttpServlet {

	//自定義變數
	private Connection connection = null; //定義資料庫連線物件
	private String driverName = "com.mysql.jdbc.Driver"; //資料庫驅動器
	private String userName = "root"; //資料庫使用者名稱
	private String userPasswd = "123456"; //密碼
	private String dbName = "test01"; //資料庫名稱
	private String tableName = "Train"; //表明
	//連線字串 資料庫地址URL MySQL資料庫埠3306
	private String url = "jdbc:mysql://localhost:3306/" + dbName + "?user="    
            + userName + "&password=" + userPasswd;
		
	//初始化方法
	public void init(ServletConfig config) throws ServletException
	{
		super.init(config);
	}
	
	public PostServlet() {
		super();
	}

	//處理GET請求方法
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		response.setCharacterEncoding("UTF-8"); //設定輸出編碼
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");  //設定輸出型別
		PrintWriter out = response.getWriter(); //獲取out物件
		
		try {
			//資料庫操作
			Class.forName(driverName).newInstance();
			connection = DriverManager.getConnection(url);
			Statement statement = connection.createStatement();
			String startName = request.getParameter("start"); //獲取出發地
			//注意:startName需要加單引號 否則報錯 ——錯誤:Unknown column 'BeiJing' in 'where clause'
			String sql = "SELECT * FROM " + tableName +" WHERE startname='" + startName+"';";
			if(startName=="") {
				sql = "SELECT * FROM " + tableName;
			}
			ResultSet rs = statement.executeQuery(sql); 
			
			out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
			out.println("<HTML>");
			out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
			out.println("  <BODY>");
			out.println("  <fieldset style='width:60%' ><legend>搜尋結果</legend><br />");
			out.println("	<TABLE align='center'border='1' cellspacing='1' cellpadding='1'>");
			out.println("		<TR><TH>車號</TH><TH>出發地</TH><TH>到達地</TH></TR>");
			//迴圈輸出查詢結果
			while(rs.next()) {
				out.println("		<TR><TD>" + rs.getString(1) + "</TD>");
				out.println("		<TD>" + rs.getString(2) + "</TD>");
				out.println("		<TD>" + rs.getString(3) + "</TD></TR>");
			}
			out.println("  </TABLE>");
			out.println("  </fieldset>");
			out.println("  </BODY>");
			out.println("</HTML>");
			out.flush();
			out.close();
			rs.close(); // 關閉記錄集
			statement.close(); // 關閉宣告
		
		} 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(); // Just puts "destroy" string in log
		try {
			connection.close(); // 關閉連線物件
		}catch(Exception e) {
			System.out.println("關閉資料庫錯誤:"+e.getMessage());
		}
	}
}
        同時WebRoot/WEB-INF/web.xml檔案Servlet對映都沒有變化,需要在WebRoot/WEB-INF/lib中新增mysql-connector-java-5.1.15-bin.jar,否則會報錯“com.mysql.jdbc.Driver錯誤”。
        執行效果如下圖所示:




        寫到此處我產生了一個疑問,當表單提交資訊時,獲取資料庫的結果有兩種方法:
        1.第一種是上一篇部落格中寫到的,在JSP中通過<% ....%>呼叫Java程式碼實現連線資料庫,獲取MySQL表中資料並顯示;
        2.第二種就是這篇部落格中寫到的,在JSP中通過Post方法提交表單Form,在Java中通過Servlet獲取請求/響應,再通過Java中out.println("<HTML>...")輸出資料庫中值。

        就這兩種方法而言,我想實現的功能是:JSP就賦值佈局,顯示介面;Java就負責連線資料庫、資料庫增刪改查,處理結果再返回給JSP中顯示,而不是相互巢狀的。換句話說:JSP中點選“提交”按鈕,TextBox中傳遞出發地,Java中介紹請求,資料庫查詢,得到的結果再返回給JSP中顯示。
        那怎麼實現呢?後面的文章可能會講到。
        DAO和Java Bean是對JDBC進行分層、模組化的最有效兩個方法。DAO(資料庫操作物件,Database Access Object)是JDBC下常用模式,DAO出現之前,運算元據庫的程式碼與業務程式碼都出現在Servlet或者JSP中,不利用業務程式碼的分離。DAO出現後,所有與資料庫相關的操作全被拿到了DAO層實現,Servlet或JSP只操作Java Bean或者DAP層,而DAO層值運算元據庫。

        PS:非常高興我自己通過實際專案找到了這個難點,然後又找到了解決方法。雖然才學習Java Web一週時間,還是學到很多東西的。個人感覺DAO類似於中介軟體的東西吧!最後希望文章對你有所幫助,這篇文章是講述Servlet連線MySQL資料庫及表單互動之間的知識。如果文章有不足或錯誤的地方,還請海涵!下一篇文章講講Session和一個典型簡單的介面佈局等相關知識吧!
        (By:Eastmount 2015-5-15 半夜1點   http://blog.csdn.net/eastmount/



相關文章