我的代码在Servlet中没有工作,但是当从另一个类进行相同的调用时工作正常。
index.java它的servlet
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.*;
import java.util.ListIterator;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Index extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter pri=response.getWriter();
JdbcConnection jdbc=new JdbcConnection();
try {
ArrayList<String> rs = jdbc.getData();
ListIterator<String> itr=rs.listIterator();
while(itr.hasNext()){
pri.print(itr.next());
}
} catch (SQLException e) {
e.printStackTrace();
}
pri.close();
}
}
JdbcConnection.java
import java.sql.*;
import java.util.ArrayList;
public class JdbcConnection {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3309/shopping";
static final String USER = "root";
static final String PASS = "sukh";
public ArrayList<String> getData() throws SQLException{
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
conn = DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement();
ArrayList<String> list=new ArrayList<String>();
String sql;
sql = "select * from users";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
String s=rs.getString("name");
list.add(s);
}
return list;
}
}