tags:

views:

67

answers:

1
  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();

I want to get the values and add it in a database using this program, but I don't know what error there is. What should I do next to create a corresponding webpage to enter the values and add it to the table?

+2  A: 

That'll be HTML. First learn HTML, especially HTML forms.

You want to use a HTML form. Create a JSP file which should serve this HTML to the webbrowser. It'll look something like:

<!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>

You only need to change the form action value to match the <url-pattern> of the servlet as mapped in the web.xml.

See also:


That said and unrelated to the actual question, your JDBC code is sensitive to SQL injection attacks. Use PreparedStatement all the way. Prepare here. Then I don't talk about the connection leak risks yet.

BalusC
Shouldn't you close that `p` and `input` tags?
Willi
@Willi: It's HTML, not XHTML.
BalusC
Ok, valid point, but... just because you can doesn't mean you should.
Willi
@Willi: if you aren't using a XML based view technology like JSPX or Facelets, using HTML shorttags is perfectly valid. It was just a kickoff example, it saves extra typing :)
BalusC