在servlet中使用dopost()

时间:2018-02-17 15:21:02

标签: servlets jdbc

我试图通过从JSP获取params并通过java代码返回并传递给servlet来向db插入值。 以下是我的代码

CreateProject.java

/ **      * Servlet实现类CreateBug      * /     @WebServlet( “/ projectForm”)

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

      int projectId =Integer.parseInt(request.getParameter("projectId"));
      String projectName = request.getParameter("projectName");  
      Project proj = new Project(projectName,projectId);
      proj.setProjectId(projectId);
      proj.setProjectName(projectName);
      System.out.println("Insideservlet"+"-----------"+projectId+"----"+projectName);

      DBConnection db1 =new DBConnection();
      try {
        db1.createProjects(request);
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
      request.getRequestDispatcher("projectForm.jsp").forward(request, response);

     }
} 

DBCOnnection.java

    public Boolean createProjects(HttpServletRequest request) throws SQLException {
            try {


                Class.forName("oracle.jdbc.driver.OracleDriver");
                Connection myConnection = DriverManager.getConnection(dbURL,strUserID, strPassword);
                myConnection =DriverManager.getConnection(dbURL,strUserID,strPassword);
                PreparedStatement pst =(PreparedStatement) myConnection.prepareStatement("insert into 'shilshet'.'projects'(projectName,projectId) values(?,?)");  

                pst.setString(1,this.request.getParameter("projectName")); 
                pst.setInt(2, Integer.parseInt(this.request.getParameter("projectId")));

                int i = pst.executeUpdate();

                String msg=" ";
                if(i!=0){  
                    msg="Record has been inserted";
                }  
                else{  
                    msg="failed to insert the data";
                }  
                pst.close();
                myConnection.close();
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return false;

            }       
            return true;

        }

0 个答案:

没有答案