【问题标题】:How do I insert data from JSP to MySQL database?如何将数据从 JSP 插入 MySQL 数据库?
【发布时间】:2021-08-31 23:19:54
【问题描述】:

我已经制作了jsp文件(从html表单接收数据)和数据库(使用MySQL工作台)。

contact.jsp 代码:

<%@page contentType="text/html" pageEncoding="UTF-8"  errorPage="errorpage.jsp" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h3>Messages from contact us page</h3>
      <ul>
         <li><p><b>Name:</b>
            <%= request.getParameter("name")%>
         </p></li>
         <li><p><b>Email:</b>
            <%= request.getParameter("txtEmail")%>
         </p></li>
         <li><p><b>Message:</b>
            <%= request.getParameter("txtMessage")%>
         </p></li>
      </ul>
    </body>
</html>

数据库名称:KSG_Database
架构:web_data
表:contact_messages
列: c_name 、 email 、 txtmessage

现在我只需要将输入数据从表单插入到数据库中。有人可以帮帮我吗?

【问题讨论】:

  • 不要把Java放到JSP中。将 html 发布到 servlet 并从那里插入数据库。 MVC
  • @BLAZE MASON 如果您已经使用 Mysql 的 JDBC 驱动程序建立了从 JSP 代码到 Mysql 数据库的连接?

标签: java html mysql database jsp


【解决方案1】:

首先,导入 JDBC 驱动:

<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>

其他

<%@page import="java.sql.*"%>

其次,重视你的字符串:

    String your_name       = request.getParameter("name");
    String your_Email      = request.getParameter("txtEmail");
    String your_txtMessage = request.getParameter("txtMessage");

然后,创建与数据库的连接:

try{

    Class.forName("com.mysql.jdbc.Driver");// Driver to establish connection to the database
    Connection con1=DriverManager.getConnection("jdbc:mysql://localhost:3306/KSG_Database","your_id","your_pass"); //Create connection using your ID and Password
    Statement st1=con1.createStatement();
    ResultSet rs1=st1.executeQuery("SELECT * FROM contact_messages");
    while(rs1.next()){

    //-----------------------------Then, Create an InsertQuery using a String:---------------------

    String InsertQuery = "insert into contact_messages (c_name,email,txtmessage) values('"+your_name+"','"+your_Email+"','','"+your_txtMessage+"');";

    //-----------------------------Finally, Execute your Insert Query:-----------------------------

    st1.executeUpdate(InsertQuery);}}

catch(Exception error){
    out.println(error);}

它对我有用。 有疑问可以问我! :-)

【讨论】:

    【解决方案2】:

    您必须从 JSP 并通过表单调用“动作”。该“动作”将处理它从 jsp 获取的数据并做任何需要做的事情(与数据库的连接),最后将 nextPage 返回到 servlet。

    jsp中的表单应该是这样的:

    <form action="<%= response.encodeURL("/path/nameOfController?action=accions.nameAction") %>" method="POST"> 
    // whatever data you want to send to db in inputs like this:
    <input type="HIDDEN" name="name" value=<%=variableName%>>
    </form>
    

    action 中的内容是您要调用的“action”的路径。您将在控制器中处理它,并使用该“nameAction”来调用您喜欢的动作(这里我使用工厂来调用类)。以下是我的管理方式:

    在控制器的doGet中:

    Action action=null;
    String nextPage=null;
    String nameAction = request.getParameter("action");
    // get the action acording to what was sent through the jsp form
    action= FactoryImpl.getReference().getAction(nameAction);
    // run the action with whatever method, in this case it's called execute
    nextPage = action.execute(request, response);
    // nextPage has returned the name of the next jsp, now just sent the redirect
    RequestDispatcher rd = getServletContext().getRequestDispatcher(response.encodeURL(nextPage));
    rd.forward(request, response);
    

    现在,您只需创建“动作”,然后在执行方法中,连接到数据库并进行所需的插入。另外,我建议在另一个类中建立连接并从操作中获取它,这样您就不会在同一个类中拥有所有这些。

    Action 类应该是这样的:

    package whatever;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import presentacio.Action;
    
    public class nameOfTheAction implements Action {
    
        public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
            //connection with db
            return "nameOfNextJspToSendToClient";
        }
    
    }
    

    现在,如果您想知道,我使用的是 Action 接口,所有操作都实现了该接口。如果你想知道界面是什么样子的,这里是,但你不需要像我一样:

    package presentacio;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public interface Action{
        public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception;
    
    }
    

    如果我对自己的解释不够清楚,或者你想让我详细说明一些事情,尽管问。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-08
      • 2018-05-30
      • 1970-01-01
      • 2011-08-06
      • 2013-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多