public class HelloServlet extends HttpServlet {
private static final long serialVersionUID=1L;
Connection conn=null;
public void init(){
String url="jdbc:mysql://localhost:3306/test?useSSL=true";
String user="root";
String pwd="123456";
try{
Class.forName("com.mysql.cj.jdbc.Driver");
conn= DriverManager.getConnection(url,user,pwd);
}catch (ClassNotFoundException e1)
{
System.out.println(e1);
getServletContext().log("驱动程序类找不到!");
}catch (SQLException e2)
{
System.out.println(e2);
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
ArrayList<product>prolist=null;
prolist=new ArrayList<product>();
try
{
String sql="SELECT * FROM products";
PreparedStatement statement=conn.prepareStatement(sql);
ResultSet result=statement.executeQuery();
while(result.next())
{
product pro=new product();
pro.setId(result.getInt("id"));
pro.setPname(result.getString("pname"));
pro.setBrand(result.getString("brand"));
pro.setPrice(result.getFloat("price"));
pro.setStock(result.getInt("stock"));
prolist.add(pro);
}
if(!prolist.isEmpty())
{
request.getSession().setAttribute("prolist",prolist);
response.sendRedirect("/displayAll.jsp");
}
else
{
response.sendRedirect("/error.jsp");
}
}catch (SQLException e)
{
e.printStackTrace();
}
}
idea Cannot invoke "java.sql.Connection.prepareStatement(String)" because "this.conn" is null
为什么会出现这个错误呢