Java+MyEclipse+Tomcat (四)Servlet提交表单和数据库操作

转载来源: https://blog.csdn.net/Eastmount/article/details/45725077

版权声明:本文为博主原创文章,转载请注明CSDN博客源地址!共同学习,一起进步~ https://blog.csdn.net/Eastmount/article/details/45725077

        前面三篇文章讲述了如何配置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代码如下:

 
 
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
  2. <%
  3. String path = request.getContextPath();
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  5. %>
  6. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  7. <html>
  8. <head>
  9. <base href="<%=basePath%>">
  10. <title>My JSP 'index.jsp' starting page </title>
  11. <style>
  12. body, div, td, input { font-size: 18px; margin: 0px; }
  13. .line { margin: 2px; }
  14. </style>
  15. </head>
  16. <body>
  17. <form action="/TestServlet01/servlet/PostServlet" method="POST">
  18. <div align="center">
  19. <br/>
  20. <fieldset style='width:60%'>
  21. <legend>填写用户信息 </legend>
  22. <br/>
  23. <div class='line'>
  24. <div align="left">出发地:
  25. <input type="text" id="start" name="start" style='font-size:18px' width=200/>
  26. </div>
  27. </div>
  28. <div class='line'>
  29. <div align="left">到达地:
  30. <input type="text" id="end" name="end" style='font-size:18px'/>
  31. </div>
  32. </div>
  33. <div class='line'>
  34. <br />
  35. <div align="left">请选择性别:
  36. <input type="radio" name="sex" value="男" id="sexMale">
  37. <label for="sexMale"></label>
  38. <input type="radio" name="sex" value="女" id="sexFemale">
  39. <label for="sexFemale"></label>
  40. </div>
  41. </div>
  42. <div class='line'>
  43. <div align="left">请选择您的爱好:
  44. <input type="checkbox" name="interesting" value="音乐" id="i1">
  45. <label for="i1">音乐 </label>
  46. <input type="checkbox" name="interesting" value="旅游" id="i2">
  47. <label for="i2">旅游 </label>
  48. <input type="checkbox" name="interesting" value="运动" id="i3">
  49. <label for="i3">运动 </label>
  50. </div>
  51. </div>
  52. <div class='line'>
  53. <div align="left">请选择车票类型:
  54. <select name="seat">
  55. <option>---请选择乘坐类型--- </option>
  56. <optgroup label="卧铺">
  57. <option value="上铺">上铺 </option>
  58. <option value="中铺">中铺 </option>
  59. <option value="下铺">下铺 </option>
  60. </optgroup>
  61. <optgroup label="其他">
  62. <option value="硬座">硬座 </option>
  63. <option value="软座">软座 </option>
  64. <option value="站票">站票 </option>
  65. </optgroup>
  66. </select>
  67. </div>
  68. </div>
  69. <div class='line'>
  70. <br />
  71. <div align="left" class='leftDiv'>备注信息: </div>
  72. <div align="left" class='rightDiv'>
  73. <textarea name="description" rows="8" style="width:300px; ">请填写备注信息... </textarea>
  74. </div>
  75. </div>
  76. <div class='line'>
  77. <div align="left">
  78. <br/> <input type="submit" name="Select" value="提交信息" style='font-size:18px'/> <br/>
  79. </div>
  80. </div>
  81. </fieldset>
  82. </div>
  83. </form>
  84. </body>
  85. </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文件如下:

  
  
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app version="3.0"
  3. xmlns= "http://java.sun.com/xml/ns/javaee"
  4. xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation= "http://java.sun.com/xml/ns/javaee
  6. http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  7. <display-name> </display-name>
  8. <servlet>
  9. <description>This is the description of my J2EE component </description>
  10. <display-name>This is the display name of my J2EE component </display-name>
  11. <servlet-name>PostServlet </servlet-name>
  12. <servlet-class>servlet.PostServlet </servlet-class>
  13. </servlet>
  14. <servlet-mapping>
  15. <servlet-name>PostServlet </servlet-name>
  16. <url-pattern>/servlet/PostServlet </url-pattern>
  17. </servlet-mapping>
  18. <welcome-file-list>
  19. <welcome-file>index.jsp </welcome-file>
  20. </welcome-file-list>
  21. </web-app>
        同时修改src/servlet/PostServlet.java文件,采用POST方法显示表单数据:

  
  
  1. package servlet;
  2. import java.io.IOException;
  3. import java.io.PrintWriter;
  4. import javax.servlet.ServletException;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. public class PostServlet extends HttpServlet {
  9. public PostServlet() {
  10. super();
  11. }
  12. public void destroy() {
  13. super.destroy(); // Just puts "destroy" string in log
  14. // Put your code here
  15. }
  16. public void doGet(HttpServletRequest request, HttpServletResponse response)
  17. throws ServletException, IOException {
  18. response.setContentType( "text/html");
  19. PrintWriter out = response.getWriter();
  20. out.println( "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
  21. out.println( "<HTML>");
  22. out.println( " <HEAD><TITLE>A Servlet</TITLE></HEAD>");
  23. out.println( " <BODY>");
  24. out.print( " This is ");
  25. out.print( this.getClass());
  26. out.println( ", using the GET method");
  27. out.println( " </BODY>");
  28. out.println( "</HTML>");
  29. out.flush();
  30. out.close();
  31. }
  32. /**
  33. * The doPost method of the servlet. <br>
  34. *
  35. * This method is called when a form has its tag value method equals to post.
  36. *
  37. * @param request the request send by the client to the server
  38. * @param response the response send by the server to the client
  39. * @throws ServletException if an error occurred
  40. * @throws IOException if an error occurred
  41. */
  42. public void doPost(HttpServletRequest request, HttpServletResponse response)
  43. throws ServletException, IOException {
  44. response.setCharacterEncoding( "UTF-8"); //设置输出编码
  45. request.setCharacterEncoding( "UTF-8");
  46. String startName = request.getParameter( "start"); //获取出发地
  47. String endName = request.getParameter( "end"); //获取到达地
  48. String sex = request.getParameter( "sex"); //获取性别
  49. String [] interest = request.getParameterValues( "interesting"); //获取兴趣
  50. String seat = request.getParameter( "seat"); //获取座位
  51. String info = request.getParameter( "description"); //获取备注信息
  52. response.setContentType( "text/html"); //设置输出类型
  53. PrintWriter out = response.getWriter(); //获取out对象
  54. out.println( "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
  55. out.println( "<HTML>");
  56. out.println( " <HEAD><TITLE>A Servlet</TITLE></HEAD>");
  57. out.println( " <BODY>");
  58. out.println( "<H2>出发地:"+ startName + "</H2>");
  59. out.println( "<H2>到达地:"+ endName + "</H2>");
  60. out.println( "<H2>性别:"+ sex + "</H2>");
  61. out.println( "<H2>兴趣");
  62. for(String str:interest) {
  63. out.println(str+ " ");
  64. }
  65. out.println( "</H2><H2>座位类型:"+ seat + "</H2>");
  66. out.println( "<H2>备注信息:"+ info + "</H2>");
  67. out.println( " </BODY>");
  68. out.println( "</HTML>");
  69. out.flush();
  70. out.close();
  71. }
  72. /**
  73. * Initialization of the servlet. <br>
  74. *
  75. * @throws ServletException if an error occurs
  76. */
  77. public void init() throws ServletException {
  78. // Put your code here
  79. }
  80. }
        运行效果如下图所示:
        

二. Servlet数据库查询

        还是使用上面的项目进行修改,实现Servlet数据库查询操作。数据库配置可以参照上一篇博客配置MySQL的过程,我新建数据库test01,插入表Train,表中数据如下图:

        然后修改index.jsp,代码如下:

  
  
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
  2. <%
  3. String path = request.getContextPath();
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  5. %>
  6. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  7. <html>
  8. <head>
  9. <base href="<%=basePath%>">
  10. <title>My JSP 'index.jsp' starting page </title>
  11. <style>
  12. body, div, td, input { font-size: 18px; margin: 0px; }
  13. .line { margin: 2px; }
  14. </style>
  15. </head>
  16. <body>
  17. <form action="/TestServlet01/servlet/PostServlet" method="POST">
  18. <div align="center">
  19. <br/>
  20. <fieldset style='width:60%'>
  21. <legend>填写用户信息 </legend>
  22. <br/>
  23. <div class='line'>
  24. <div align="left">出发地:
  25. <input type="text" id="start" name="start" style='font-size:18px' width=200/>
  26. </div>
  27. </div>
  28. <div class='line'>
  29. <div align="left">
  30. <br/> <input type="submit" name="Select" value="提交信息" style='font-size:18px'/> <br/>
  31. </div>
  32. </div>
  33. </fieldset>
  34. </div>
  35. </form>
  36. </body>
  37. </html>
        修改的PostServlet.java代码如下:

  
  
  1. package servlet;
  2. import java.io.IOException;
  3. import java.io.PrintWriter;
  4. import java.sql.Connection;
  5. import java.sql.DriverManager;
  6. import java.sql.ResultSet;
  7. import java.sql.SQLException;
  8. import java.sql.Statement;
  9. import javax.servlet.ServletConfig;
  10. import javax.servlet.ServletException;
  11. import javax.servlet.http.HttpServlet;
  12. import javax.servlet.http.HttpServletRequest;
  13. import javax.servlet.http.HttpServletResponse;
  14. public class PostServlet extends HttpServlet {
  15. //自定义变量
  16. private Connection connection = null; //定义数据库连接对象
  17. private String driverName = "com.mysql.jdbc.Driver"; //数据库驱动器
  18. private String userName = "root"; //数据库用户名
  19. private String userPasswd = "123456"; //密码
  20. private String dbName = "test01"; //数据库名称
  21. private String tableName = "Train"; //表明
  22. //连接字符串 数据库地址URL MySQL数据库端口3306
  23. private String url = "jdbc:mysql://localhost:3306/" + dbName + "?user="
  24. + userName + "&password=" + userPasswd;
  25. //初始化方法
  26. public void init(ServletConfig config) throws ServletException
  27. {
  28. super.init(config);
  29. }
  30. public PostServlet() {
  31. super();
  32. }
  33. //处理GET请求方法
  34. public void doGet(HttpServletRequest request, HttpServletResponse response)
  35. throws ServletException, IOException
  36. {
  37. response.setCharacterEncoding( "UTF-8"); //设置输出编码
  38. request.setCharacterEncoding( "UTF-8");
  39. response.setContentType( "text/html"); //设置输出类型
  40. PrintWriter out = response.getWriter(); //获取out对象
  41. try {
  42. //数据库操作
  43. Class.forName(driverName).newInstance();
  44. connection = DriverManager.getConnection(url);
  45. Statement statement = connection.createStatement();
  46. String startName = request.getParameter( "start"); //获取出发地
  47. //注意:startName需要加单引号 否则报错 ——错误:Unknown column 'BeiJing' in 'where clause'
  48. String sql = "SELECT * FROM " + tableName + " WHERE startname='" + startName+ "';";
  49. if(startName== "") {
  50. sql = "SELECT * FROM " + tableName;
  51. }
  52. ResultSet rs = statement.executeQuery(sql);
  53. out.println( "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
  54. out.println( "<HTML>");
  55. out.println( " <HEAD><TITLE>A Servlet</TITLE></HEAD>");
  56. out.println( " <BODY>");
  57. out.println( " <fieldset style='width:60%' ><legend>搜索结果</legend><br />");
  58. out.println( " <TABLE align='center'border='1' cellspacing='1' cellpadding='1'>");
  59. out.println( " <TR><TH>车号</TH><TH>出发地</TH><TH>到达地</TH></TR>");
  60. //循环输出查询结果
  61. while(rs.next()) {
  62. out.println( " <TR><TD>" + rs.getString( 1) + "</TD>");
  63. out.println( " <TD>" + rs.getString( 2) + "</TD>");
  64. out.println( " <TD>" + rs.getString( 3) + "</TD></TR>");
  65. }
  66. out.println( " </TABLE>");
  67. out.println( " </fieldset>");
  68. out.println( " </BODY>");
  69. out.println( "</HTML>");
  70. out.flush();
  71. out.close();
  72. rs.close(); // 关闭记录集
  73. statement.close(); // 关闭声明
  74. } catch(Exception e) {
  75. System.out.println( "错误:"+e.getMessage());
  76. response.sendRedirect( "index.jsp");
  77. }
  78. }
  79. //处理POST请求方法
  80. public void doPost(HttpServletRequest request, HttpServletResponse response)
  81. throws ServletException, IOException
  82. {
  83. doGet(request,response);
  84. }
  85. //销毁方法
  86. public void destroy() {
  87. super.destroy(); // Just puts "destroy" string in log
  88. try {
  89. connection.close(); // 关闭连接对象
  90. } catch(Exception e) {
  91. System.out.println( "关闭数据库错误:"+e.getMessage());
  92. }
  93. }
  94. }
        同时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/



转载来源: https://blog.csdn.net/Eastmount/article/details/45725077

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值