我想实现一个servlet来从浏览器获取参数并使用http post而不是http get插入到db中。
servlet 将从诸如http://localhost:8080/NewServlet?firstname=me&middlename=you&lastName=secret&location=here之类的 url 接收参数 ,并插入到数据库中,但就像我无法正确完成一样。
这是我试图运行的一段代码
public class NewServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String firstName = request.getParameter("firstname");
String middleName = request.getParameter("middlename");
String lastName = request.getParameter("lastname");
String location = request.getParameter("location");
String result;
java.sql.Connection connDB = null;
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
}
try {
connDB = DriverManager.getConnection("jdbc:postgresql://" + "localhost" + ":" + 5432 + "/" + "mydb", "username", "secret");
connDB.setAutoCommit(false);
System.out.println("Connection established : [" + connDB.toString() + "]");
java.sql.Statement bankStmt = connDB.createStatement();
java.sql.Statement stt = connDB.createStatement();
bankStmt.execute("INSERT INTO full_names(firstname, secondname, lastname) VALUES('"+firstName+"', '"+middleName+"', '"+lastName+"' )");
java.sql.Statement bnk =connDB.createStatement();
bnk.execute("INSERT INTO employee_details(location) VALUES('"+location+"')");
}
connDB.commit();
} catch (SQLException ex) {
ex.printStackTrace();
try {
connDB.rollback();
} catch (SQLException ex1) {
ex1.printStackTrace();
Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex1);
}
Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
}
out.println("<b><font color='blue'>Your FirstName is :</font></b>"
+ "<b>"+ firstName +"</b>" + "<br>");
out.println("<b><font color='blue'>Your Middle Name is :</font></b>"
+ "<b>"+ middleName +"</b>" + "<br>");
out.println("<b><font color='blue'>Your Last Name is :</font></b>"
+ "<b>"+ lastName +"</b>");
}
}
当我尝试使用 url http://localhost:8080/NewServlet?firstname=me&middlename=you&lastName=secret&location=here运行代码时
我收到以下错误:
HTTP 状态 405 - 此 URL 不支持 HTTP 方法 GET
类型状态报告
此 URL 不支持消息 HTTP 方法 GET
描述 请求的资源不允许指定的 HTTP 方法(此 URL 不支持 HTTP 方法 GET)。