我正在使用NetBeans中的Java Web应用程序。我创建了一个JSP页面,可以向SQL数据库添加一行,但我想允许用户输入。为此,我制作了一些文本输入框。我希望用户能够输入一个字符串,然后将这些字符串保存为varchar数据到SQL数据库。有没有办法让这种情况发生?
以下是进行文本输入之一的代码:
<p>Name</p>
<input type="text" name="Name" value="" size="100"/>
以下是向数据库添加行的代码:
<sql:update var="attempt1" dataSource="jdbc/testaddressbook">
INSERT INTO people (fullName, address, telephone, email)
VALUES ("testerName3", "testerAddress", "testerPhone", "testerEmail")
</sql:update>
答案 0 :(得分:1)
您需要对JDBC (Java Data Base Connectivity)和Servlet有一些基本的了解。有很多方法可以达到你想要的效果,但下面是一个给出一些想法的最小例子:
<强> 1。创建一个servlet来处理用户输入并将数据插入SQL
package mycoolapp;
public RegistrationServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
// Obtain submitted form data
String name = req.getParameterName("Name");
String address = req.getParameterName("Address");
String phone = req.getParameterName("Phone");
String email = req.getParameterName("Email");
// Setup your database datasource, this is different for each db vendor. On production environment most likely you need a connection pooled datasource
DataSource ds = // setup ds here..
Connection conn = ds.getConnection();
// Prepare the SQL statement to insert, plug in the values
PreparedStatement stmt = conn.prepareStatement("INSERT INTO people (fullName, address, telephone, email) VALUES (?, ?, ?, ?)");
stmt.setString(1, name);
stmt.setString(2, address);
stmt.setString(3, phone);
stmt.setString(4, email);
// Execute the insert
stmt.executeUpdate();
conn.close();
// Dispatch into success page
RequestDispatcher requestDispatcher = req.getRequestDispatcher("/registerSuccess.jsp");
requestDispatcher.forward(req, res);
}
}
<强> 2。在WEB-INF / web.xml部署描述符
上声明和映射servlet下面的设置会将servlet映射到http://myhost/mywarname/register
<web-app>
<servlet>
<servlet-class>mycoolapp.RegistrationServlet</servlet-class>
<servlet-name>RegistrationServlet</servlet-name>
</servlet>
<servlet-mapping>
<servlet-name>RegistrationServlet</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
</web-app>
第3。配置表单以发布到servlet
<form method="post" action="register">
....
</form>
几句警告: