sun_li_qian
sun_li_qian
采纳率0%
2017-08-26 12:19 阅读 1.3k

servlet调用数据库封装类提示,无法获取Connection对象!!!

servlet调用数据库封装类进行查询时,提示ps = conn.preparedStatement(sql);语句是NUllPOINTEREXCEPTION,但在main方法中测试数据库正常连接

我把有问题的代码提炼成一个新的模板,因为我查了很多,都是说Connection conn对象获取异常。网上说的一些解决办法,我都试过了,如提升Tomcat版本,还是不行。下面的代码中无法获取conn对象,跟我的demo问题一摸一样,不知道如何解决!!!

index.jsp文件源码

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<!DOCTYPE HTML>


My JSP 'index.jsp' starting page


<%
String temp =(String) request.getAttribute("info");
if(temp != null){
out.print(temp);

}
%>
<h1>index.jsp页面!!!</h1>
<hr>
<form action = "ConnectionServlet" method="post">
    <input type ="submit" value = "提交"/>
</form>


ConnectionServlet.java源码

import java.io.IOException;
import java.sql.Connection;

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

public class ConnectionServlet extends HttpServlet{

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Connection conn = ConnectionClass.getConnection();
    if(conn != null){
        request.setAttribute("info", conn);         
    } else {
        request.setAttribute("info", "conn为空!!!");
    }
    request.getRequestDispatcher("index.jsp").forward(request, response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    this.doGet(request, response);
}

}

ConnectionClass.java源码

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionClass {
public static Connection getConnection(){
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/user","root","sunliqian");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1"
metadata-complete="true">

ConnectionServlet
ConnectionServlet


ConnectionServlet
/ConnectionServlet

求大佬解决!!! 没有金币。。。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • Small_Mouse0 鼠小 2017-08-26 14:08

    main方法这句话能跑?

     Class.forName("com.mysql.jdbc.Driver");
    conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/user","root","sunliqian");
    

    你可能是把mysql的驱动jar没放到tomcat上,,,apache-tomcat-7.0.57\lib,,,tomcat下面有个lib包,,把mysql的jar放进去就行了。。

    main运行和tomcat运行不是一个平台

    点赞 2 评论 复制链接分享

相关推荐