我正在读这本书,Murach的Java Servlets和JSP第二版。 他提供了一个通过.bat文件自动安装的数据库。
我尝试了他的例子并且工作正常。
现在我正在尝试使用他的数据库创建我的应用程序,但没有任何事情发生。以下是代码:
JSP:
<%--
Document : index
Created on : 27/01/2012, 9:20:02 AM
Author : Camus
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Form</title>
</head>
<body>
<h1>Type your information here!</h1>
<form action="addToEmailList" method="get">
<input type="text" name="firstName">First Name<br>
<input type="text" name="lastName"> Last Name<br>
<input type="text" name="emailAddress"> email
<input type="submit" value="Submit">
</form>
</body>
</html>
的Servlet
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
/**
*
* @author Camus
*/
public class addToEmailList extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String emailAddress = request.getParameter("emailAddress");
User user = new User();
user.setFirstName(firstName);
user.setLastName(lastName);
user.setEmailAddress(emailAddress);
String query ="DELETE FROM user WHERE FirstName = 'Diogo'";
try {
String dbURL="jdbc:mysql://localhost:3306/murach";
String username ="root";
String password = "sesame";
Connection connection = DriverManager.getConnection(dbURL, username, password);
Statement statement = connection.createStatement();
statement.executeUpdate(query);
connection.close();
}
catch (Exception e) {
e.printStackTrace();
}
String URL = "/result.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(URL);
dispatcher.forward(request, response);
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* 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 {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</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 doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
我已经尝试了很多东西,当我检查数据库时,没有发生任何事情。我尝试了不同的查询,但没有更新任何内容。你们是否知道我做错了什么?
请帮帮我。我认为它应该是一个基本的错误,但是因为我正在学习并且真的不知道发生了什么。
提前致谢。
答案 0 :(得分:4)
我想知道你提交表单时为什么要使用DELETE查询?我认为这应该是一个INSERT。
我认为你在一个问题上遇到了太多问题。您正在一次性学习JSP,servlet和数据库。发生了太多事情。
计算机科学就是分解:通过将复杂问题分解为更小,更易于管理的问题来解决复杂问题。
您不需要servlet或JSP来获取数据库。让它先工作。
以下是我推荐的内容:从Person类开始。
package model;
public class Person {
private String firstName;
private String lastName;
private String email;
// Add constructors, getters, equals, hashcode, etc.
}
然后从持久性接口开始:
package persistence;
public interface PersonDao {
List<Person> find(String lastName, String firstName);
List<Person> find();
void save(Person p);
void update(Person p);
void delete(Person p);
}
然后实现DAO接口:
package persistence;
public class PersonDaoImpl implements PersonDao {
private Connection connection;
public PersonDaoImpl(Connection connection) {
this.connection = connection;
}
// Implement all the JDBC methods here.
}
像这样的实用程序类可能会对您有所帮助。使用它来查看您是否可以成功连接到数据库并执行某些操作:
package persistence;
import java.sql.*;
import java.util.*;
/**
* util.DatabaseUtils
* User: Michael
* Date: Aug 17, 2010
* Time: 7:58:02 PM
*/
public class DatabaseUtils
{
private static final String DEFAULT_DRIVER = "oracle.jdbc.driver.OracleDriver";
private static final String DEFAULT_URL = "jdbc:oracle:thin:@host:1521:database";
private static final String DEFAULT_USERNAME = "username";
private static final String DEFAULT_PASSWORD = "password";
/*
private static final String DEFAULT_DRIVER = "org.postgresql.Driver";
private static final String DEFAULT_URL = "jdbc:postgresql://localhost:5432/party";
private static final String DEFAULT_USERNAME = "pgsuper";
private static final String DEFAULT_PASSWORD = "pgsuper";
*/
/*
private static final String DEFAULT_DRIVER = "com.mysql.jdbc.Driver";
private static final String DEFAULT_URL = "jdbc:mysql://localhost:3306/party";
private static final String DEFAULT_USERNAME = "party";
private static final String DEFAULT_PASSWORD = "party";
*/
public static void main(String[] args)
{
long begTime = System.currentTimeMillis();
String driver = ((args.length > 0) ? args[0] : DEFAULT_DRIVER);
String url = ((args.length > 1) ? args[1] : DEFAULT_URL);
String username = ((args.length > 2) ? args[2] : DEFAULT_USERNAME);
String password = ((args.length > 3) ? args[3] : DEFAULT_PASSWORD);
Connection connection = null;
try
{
connection = createConnection(driver, url, username, password);
DatabaseMetaData meta = connection.getMetaData();
System.out.println(meta.getDatabaseProductName());
System.out.println(meta.getDatabaseProductVersion());
String sqlQuery = "SELECT PERSON_ID, FIRST_NAME, LAST_NAME FROM PERSON ORDER BY LAST_NAME";
System.out.println("before insert: " + query(connection, sqlQuery, Collections.EMPTY_LIST));
connection.setAutoCommit(false);
String sqlUpdate = "INSERT INTO PERSON(FIRST_NAME, LAST_NAME) VALUES(?,?)";
List parameters = Arrays.asList( "Foo", "Bar" );
int numRowsUpdated = update(connection, sqlUpdate, parameters);
connection.commit();
System.out.println("# rows inserted: " + numRowsUpdated);
System.out.println("after insert: " + query(connection, sqlQuery, Collections.EMPTY_LIST));
}
catch (Exception e)
{
rollback(connection);
e.printStackTrace();
}
finally
{
close(connection);
long endTime = System.currentTimeMillis();
System.out.println("wall time: " + (endTime - begTime) + " ms");
}
}
public static Connection createConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException
{
Class.forName(driver);
if ((username == null) || (password == null) || (username.trim().length() == 0) || (password.trim().length() == 0))
{
return DriverManager.getConnection(url);
}
else
{
return DriverManager.getConnection(url, username, password);
}
}
public static void close(Connection connection)
{
try
{
if (connection != null)
{
connection.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void close(Statement st)
{
try
{
if (st != null)
{
st.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void close(ResultSet rs)
{
try
{
if (rs != null)
{
rs.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void rollback(Connection connection)
{
try
{
if (connection != null)
{
connection.rollback();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static List<Map<String, Object>> map(ResultSet rs) throws SQLException
{
List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
try
{
if (rs != null)
{
ResultSetMetaData meta = rs.getMetaData();
int numColumns = meta.getColumnCount();
while (rs.next())
{
Map<String, Object> row = new HashMap<String, Object>();
for (int i = 1; i <= numColumns; ++i)
{
String name = meta.getColumnName(i);
Object value = rs.getObject(i);
row.put(name, value);
}
results.add(row);
}
}
}
finally
{
close(rs);
}
return results;
}
public static List<Map<String, Object>> query(Connection connection, String sql, List<Object> parameters) throws SQLException
{
List<Map<String, Object>> results = null;
PreparedStatement ps = null;
ResultSet rs = null;
try
{
ps = connection.prepareStatement(sql);
int i = 0;
for (Object parameter : parameters)
{
ps.setObject(++i, parameter);
}
rs = ps.executeQuery();
results = map(rs);
}
finally
{
close(rs);
close(ps);
}
return results;
}
public static int update(Connection connection, String sql, List<Object> parameters) throws SQLException
{
int numRowsUpdated = 0;
PreparedStatement ps = null;
try
{
ps = connection.prepareStatement(sql);
int i = 0;
for (Object parameter : parameters)
{
ps.setObject(++i, parameter);
}
numRowsUpdated = ps.executeUpdate();
}
finally
{
close(ps);
}
return numRowsUpdated;
}
}