获取输入的方式是什么

时间:2010-08-13 18:13:18

标签: java servlets

  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  Connection conn = null;
  String url = "jdbc:mysql://localhost:3306/";
  String dbName = "Employee";
  String driver = "com.mysql.jdbc.Driver";
  String userName = "root"; 
  String password = "1234";

  int Empid =Integer.parseInt(request.getParameter("Empid").toString()); 
  String Name = request.getParameter("Name").toString();
  int Age =Integer.parseInt(request.getParameter("Age").toString()); 
  int Salary =Integer.parseInt(request.getParameter("Salary").toString());
  Statement stmt;
  try {
   Class.forName(driver).newInstance();
   conn = DriverManager.getConnection(url+dbName,userName,password);
   System.out.println("Connected to the database");

   ArrayList al=null;
   ArrayList userList =new ArrayList();
   String query = "insert into employee set Empid='"+Empid+"',name='"+Name+"',Age='"+Age+"',Salary='"+Salary+"'";
   stmt = conn.createStatement();

      int i = stmt.executeUpdate(query);
   System.out.println("query" + query);
   if(i>0)
   {
    response.sendRedirect("servletRecord");
   }
   conn.close();
   System.out.println("Disconnected from database");
  } catch (Exception e) {
  e.printStackTrace();

我想获取值并使用此程序将其添加到数据库中,但我不知道它有什么错误。接下来我应该怎么做才能创建相应的网页来输入值并将其添加到表中?

1 个答案:

答案 0 :(得分:2)

那将是HTML。 First learn HTML,尤指HTML forms

您想要使用HTML表单。创建一个JSP文件,该文件应该将此HTML提供给Web浏览器。它看起来像是:

<!DOCTYPE html>
<html lang="en">
    <head><title>Hello World</title></head>
    <body>
        <form action="servleturl" method="post">
            <p>Empid: <input name="Empid">
            <p>Name: <input name="Name">
            <p>Age: <input name="Age">
            <p>Salary: <input name="Salary">
            <p><input type="submit">
        </form>
    </body>
</html>

您只需要更改form action值以匹配<url-pattern>中映射的servlet的web.xml

另见:


这说明与实际问题无关,您的JDBC代码对SQL injection attacks很敏感。一直使用PreparedStatementPrepare here。然后我还没有谈到连接泄漏的风险。