標籤:java myeclipse jsp網站 表單提交 資料庫操作
前面三篇文章講述了如何配置MyEclipse和Tomcat開發JSP網站、如何配置Servlet簡單實現表單提交、如何配置MySQL實現JSP資料庫查詢。
這篇文章主要講述Servlet表單的提交、Java中實現資料庫的查詢操作和自己遇到的瓶頸及理解。Java Web基礎性文章,希望對大家有所協助~
Java+MyEclipse+Tomcat (一)配置過程及jsp網站開發入門
Java+MyEclipse+Tomcat (二)配置Servlet及簡單實現表單提交
Java+MyEclipse+Tomcat (三)配置MySQL及查詢資料顯示在JSP網頁中
兩個項目的免費(希望對你有所協助):
一. 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資料庫連接埠3306private 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 logtry {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/)
Java+MyEclipse+Tomcat (四)Servlet提交表單和資料庫操作