23.servlet to insert data


package p1;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class serv_directory extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ClassNotFoundException, SQLException {
response.setContentType(“text/html;charset=UTF-8”);
String s=request.getParameter(“name”);
String phone=request.getParameter(“phone”);
try (PrintWriter out = response.getWriter()) {
Class.forName(“com.mysql.jdbc.Driver”);
Connection con=DriverManager.getConnection(“jdbc:mysql://localhost:3307/try”,”root”,””);
Statement st = con.createStatement();
// ResultSet rs=st.executeQuery(“select * from directory”);
PreparedStatement pst;
pst= con.prepareStatement(“insert into directory values(?,?)”);
pst.setString(1,s);
pst.setString(2, phone);
pst.executeUpdate();
out.println(“records inserted successfully”);
ResultSet rs=st.executeQuery(“select * from directory”);
while(rs.next())
{
out.println(rs.getString(“name”)+” “+rs.getString(“phone”));
out.println();
}

}
}
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (ClassNotFoundException ex) {
Logger.getLogger(serv_directory.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(serv_directory.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (ClassNotFoundException ex) {
Logger.getLogger(serv_directory.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(serv_directory.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public String getServletInfo() {
return “Short description”;
}// </editor-fold>

}