servlet无法保存到数据库

时间:2015-03-23 11:53:46

标签: java mysql database jsp servlets

我正在编写一个简单的servlet程序,我试图将Web表单数据(jsp)保存到mySQL数据库。我获得了http状态404。 这是我的代码

我的FirstServlet.java文件是

package first;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.sql.*;

公共类FirstServlet扩展了HttpServlet {     private static final long serialVersionUID = 1L;

/**
 * @see HttpServlet#HttpServlet()
 */
public FirstServlet() {
    super();
    // TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse      response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse     response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Employee Management form";
 String docType =
 "<!doctype html public \"-//w3c//dtd html 4.0 " +
 "transitional//en\">\n";
 out.println(docType +
           "<html>\n" +
           "<head><title>" + title + "</title></head>\n" +
           "<body bgcolor=\"#f0f0c0\">\n" +
           "<h1 align=\"center\">" + title + "</h1>\n" +
           "<ul>\n" +
           "  <li><b>First Name</b>: "
           + request.getParameter("first_name") + "\n" +
           "  <li><b>Last Name</b>: "
           + request.getParameter("last_name") + "\n" +
           "</ul>\n" +
           "</body></html>");

 try {

 Connection myConn =     DriverManager.getConnection("jdbc:mysql://localhost:3306/world", "root" , "password");
 System.out.println("Loading driver...");
 Class.forName("com.mysql.jdbc.Driver");
 System.out.println("Driver loaded!");

Statement myStmt = myConn.createStatement();
//ResultSet myRs = myStmt.executeQuery("select * from countrylanguage");
String sql = "insert into countrylanguage"
+ " (CountryCode, Language, IsOfficial, Percentage)"
+ " VALUES ('dvi', 'engli', 'T', '9.3')";

myStmt.executeUpdate(sql);

}
catch (Exception exc) {
exc.printStackTrace();
 }
}
// Method to handle POST method request.
public void doPost(HttpServletRequest request,
                HttpServletResponse response)
 throws ServletException, IOException {
doGet(request, response);
 }
}

index.jsp文件是

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"     "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<H1>Welcome to Employee Management Project</H1>
<form action="FirstServlet" method="GET">
    First Name: <input type="text" name="first_name"> <br /> 
    Last Name: <input type="text" name="last_name" /> <br /> <br />
    <input type="checkbox" name="add" /> Add <input type="checkbox"    name="search" /> Search <input
        type="checkbox" name="delete" /> Delete  <input type="checkbox"
        name="update" /> Update <br /> <br />
        <input type="submit" value="Submit" />
 </form>
</body>
</html>

web.xml文件是

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">

<display-name>HelloServlet2</display-name>

<servlet>
    <servlet-name>FirstServlet</servlet-name>
    <servlet-class>first.FirstServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>FirstServlet</servlet-name>
    <url-pattern>/FirstServlet</url-pattern>
</servlet-mapping>

</web-app>

以下是文件夹的层次结构

HelloSevrvlet2
 Java Resources
  src
   first
    FirstServlet.java
 Libraries
  Apache Tomcat v7.0
  EAR Libraries
  JRE System Library
  Web App Libraries
 WebContent
  WEB-INF
   Lib
   web.xml
 index.jsp

3 个答案:

答案 0 :(得分:1)

jsp文件中的form语句中有拼写错误。 你有:          “HelloServlet2”被错误地拼写为HelloSevrvlet2。一旦你纠正了这个问题,你的代码应该可以正常工作。我亲自使用Glassfish服务器测试了您的代码。

答案 1 :(得分:0)

在web.xml中,以下行必须如下:

<servlet-class>first.FirstServlet</servlet-class>

并在jsp文件中,您的操作必须是:

action="/FirstServlet"

答案 2 :(得分:0)

以下是从JSP获取值并存储在数据库表中的方法:
1.在数据库中创建表

   create table emp(
      emp_id Integer primary key,
      first_name varchar(25),
      last_name varchar(25)
   )

上面提到的'create table'语句适用于与Glassfish服务器捆绑在一起的JavaDB数据库。但是你可以调整create语句,以便它可以在你选择的数据库上运行。

  1. Java Servlet代码(我刚刚为数据库添加了try / catch块 相互作用。 servlet代码的其他部分与之前发布的相同。)

    // You do not need to load the driver class as JDBC now  
    // loads the required driver class automatically based on the   
    // connect string you specify in the getConnection() method.  
    Connection myConn = null;  
    try {  
        int emp_id = Integer.parseInt(request.getParameter("emp_id"));  
        String first_name = (String) request.getParameter("first_name");  
        String last_name = (String) request.getParameter("last_name");  
        myConn = DriverManager.getConnection
        ("jdbc:derby://localhost:1527/sun-appserv-samples", "app", "app");  
        String sql = "INSERT INTO emp"  
                   + " (emp_id, first_name, last_name)"  
                   + " VALUES (?,?,?)";  
        PreparedStatement myStmt = myConn.prepareStatement(sql);  
        myStmt.setInt(1, emp_id);  
        myStmt.setString(2, first_name);  
        myStmt.setString(3, last_name);  
        int status = myStmt.executeUpdate();  
        out.println(status + " rows inserted");  
        myConn.commit();  
        myConn.close();  
    } catch (Exception exc) {  
        exc.printStackTrace();  
        out.println(exc.getMessage());  
    }
    
  2. 一旦您了解了Hibernate / JPA / JTA / JPQL等技术,您会发现这些API提供了非常强大的功能,可以与数据库进行交互。使用这些技术,您不必直接与JDBC交互。目前,我上面给出的解决方案应该足够了。