Reputation: 353
I am working on a Java Web Application in NetBeans. I have made a JSP page that can add a row to a SQL database, but I want to allow for user input. To this end, I have made some Text Input boxes. I want the user to be able to enter in a string and then have those strings saved as varchar data to the SQL database. Is there a way to make this happen?
Here is the code for making one of the text input:
<p>Name</p>
<input type="text" name="Name" value="" size="100"/>
Here is the code for adding a row to the database:
<sql:update var="attempt1" dataSource="jdbc/testaddressbook">
INSERT INTO people (fullName, address, telephone, email)
VALUES ("testerName3", "testerAddress", "testerPhone", "testerEmail")
</sql:update>
Upvotes: 0
Views: 3888
Reputation: 41133
You need some basic understanding of JDBC (Java Data Base Connectivity) and Servlet. There are tons of way to achieve what you want, but below is a minimal example to give you some idea:
1. Create a servlet to handle the user input and insert the data into 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. Declare and map the servlet on your WEB-INF/web.xml deployment descriptor
Below setting will map the servlet into 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. Configure your form to post into the servlet
<form method="post" action="register">
....
</form>
Few words of warning:
Upvotes: 1