public class MyDb {
public Connection getConnection() {
Connection connection=null;
try{
Class.forName("org.h2.Driver");
connection= DriverManager.getConnection("jdbc:h2:~/test");
System.out.println("Connection ok");
Statement stat = connection.createStatement();
stat.execute("create table test(id var(255) primary key, name varchar(255), age int)");
}
catch (ClassNotFoundException|SQLException e){e.printStackTrace();
System.out.println("Connection error");}
return connection;
}
}
@WebServlet("/sendform")
public class SendForm extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String formId;
String formName;
String formAge;
String formIdDB;
String formNameDB;
String formAgeDB;
formId=request.getParameter("id");
formName=request.getParameter("name");
formAge=request.getParameter("age");
MyDb db= new MyDb();
Connection con=db.getConnection();
PreparedStatement pr=null;
try {
pr= con.prepareStatement("INSERT INTO test (id,name,age) VALUES (?,?,?)");
pr.setString(1, formId);
pr.setString(2, formName);
pr.setString(3, formAge);
pr.executeUpdate();
}
catch (SQLException e) {
e.printStackTrace();
}
finally {
if (pr != null)
{
try {
pr.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
try {
ResultSet rs=pr.executeQuery("SELECT * FROM TEST");
while (rs.next()) {
formIdDB=rs.getString("id");
formNameDB=rs.getString("name");
formAgeDB=rs.getString("age");
request.setAttribute("id", formIdDB);
request.setAttribute("name", formNameDB);
request.setAttribute("age", formAgeDB);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.getRequestDispatcher("result.jsp").forward(request, response);
}