java的空指针问题,各位大佬帮帮忙啊?

AdminDao代码

package com.dao;

import com.bean.AdminBean;
import com.db.DBHelper;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class AdminDao {
    //验证登录
    public String CheckLogin(String username,String password){
        String id = null;
        String sql = "select * from Admin where Admin_Username ='"+username+"'and Admin_Password='"+password+"'";
        ResultSet rs = null;

        try{
            Connection conn = new DBHelper().getConn();
            System.out.println(conn);
            Statement stat = conn.createStatement();
            rs = stat.executeQuery(sql);
            while(rs.next()) {
                id = rs.getString("Admin_ID");
            }
        }
        catch (SQLException ex){
            ex.printStackTrace();
        }
        return id;
    }
    //验证密码
    public boolean CheckPassword(String id , String password){
        boolean ps= false;
        String sql = "select * from Admin_ID = '"+id+"'and Admin_Password='"+password+"'";
        Statement stat = null;
        ResultSet rs = null;
        Connection conn = new DBHelper().getConn();
        try{
            stat = conn.createStatement();
            rs =stat.executeQuery(sql);
            while (rs.next()){
                ps=true;
            }
        }
        catch (SQLException es){}
        return ps;
    }
    //获取列表
    public List<AdminBean> GetList(String strwhere, String strorder){
        String sql = "select * from Admin";
        if (!(isInvalid(strwhere))){
            sql+="where"+strwhere;
        }if (!(isInvalid(strorder))){
            sql+="order by"+strorder;
        }
        Statement stat = null;
        ResultSet rs = null;
        Connection conn = new DBHelper().getConn();
        List<AdminBean> list = new ArrayList<AdminBean>();
        try{
            stat = conn.createStatement();
            rs = stat.executeQuery(sql);
            while(rs.next()){
                AdminBean cnbean = new AdminBean();
                cnbean.setAdmin_ID(rs.getInt("Admin_ID"));
                cnbean.setAdmin_Username(rs.getString("Admin_Username"));
                cnbean.setAdmin_Password(rs.getString("Admin_Password"));
                cnbean.setAdmin_Name(rs.getString("Admin_name"));
                cnbean.setAdmin_Sex(rs.getString("Admin_Sex"));
                cnbean.setAdmin_Tel(rs.getString("Admin_Tel"));
                list.add(cnbean);
            }
            }catch (SQLException e){
            e.printStackTrace();
        }finally {
            try{
               if (conn != null)
                    conn.close();
               if(stat != null)
                   stat.close();
               if(rs!=null)
                   rs.close();
               }catch (SQLException e){
                e.printStackTrace();
            }
                }
        return list;
    }
    public AdminBean GetBean(int id){
        String sql = "select * from Admin where Admin_ID="+id;
        Statement stat = null;
        ResultSet rs = null;
        Connection conn = new DBHelper().getConn();
        AdminBean cnbean = new AdminBean();
        try{
            stat = conn.createStatement();
            rs = stat.executeQuery(sql);
            while(rs.next()){
                cnbean.setAdmin_ID(rs.getInt("Admin_ID"));
                cnbean.setAdmin_Username(rs.getString("Admin_Username"));
                cnbean.setAdmin_Password(rs.getString("Admin_Password"));
                cnbean.setAdmin_Name(rs.getString("Admin_Name"));
                cnbean.setAdmin_Sex(rs.getString("Admin_Sex"));
                cnbean.setAdmin_Tel(rs.getString("Admin_Tel"));
            }
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            try {
                if (conn != null)
                    conn.close();
                if (stat != null)
                    stat.close();
                if (rs != null)
                    rs.close();
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
        return cnbean;
    }
    //添加
    public void Add(AdminBean cnbean){
        String sql = "insert into Admin(";
        sql+= "Admin_Username,Admin_Password,Admin_Name,Admin_Sex,Admin_Tel";
        sql+=")values(";
        sql+="'"+cnbean.getAdmin_Username()+"','"+cnbean.getAdmin_Password()+"','"+cnbean.getAdmin_Name()+"','"+cnbean.getAdmin_Sex()+"','"+cnbean.getAdmin_Tel()+"'";
        sql+=")";
        Statement stat = null;
        ResultSet rs = null;
        Connection conn = new DBHelper().getConn();
        try{
            stat = conn.createStatement();
            stat.executeUpdate(sql);
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            try{
                if (conn != null)
                    conn.close();
                if (stat != null)
                    stat.close();
                if (rs   != null)
                    rs.close();
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
    }
    //修改
    public void Update(AdminBean cnbean){
        String sql = "update Admin set";
        sql+="Admin_Username='"+cnbean.getAdmin_Username()+"','";
        sql+="Admin_Password'"+cnbean.getAdmin_Password()+"','";
        sql+="Admin_Name'"+cnbean.getAdmin_Name()+"','";
        sql+="Admin_Sex'"+cnbean.getAdmin_Sex()+"','";
        sql+="Admin_Tel'"+cnbean.getAdmin_Tel()+"','";
        sql+="where Admin_ID'"+cnbean.getAdmin_ID()+"'";

        Statement stat = null;
        ResultSet rs = null ;
        Connection conn = new DBHelper().getConn();
        try{
            stat = conn.createStatement();
            stat.executeUpdate(sql);
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            try{
                if (conn != null)
                    conn.close();
                if (stat != null)
                    stat.close();
                if (rs != null)
                    rs.close();
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
    }
    //删除
    public void Delete(String strwhere){
        String sql = "delete Admin where ";
        sql+=strwhere;
        Statement stat = null;
        ResultSet rs = null;
        Connection conn = new DBHelper().getConn();
        try{
            stat = conn.createStatement();
            stat.executeUpdate(sql);
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            try{
                if (conn != null)
                    conn.close();
                if (stat != null)
                    stat.close();
                if (rs   != null)
                    rs.close();
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
    }
    //判断是否为空值
    private boolean isInvalid(String value){
        return (value == null || value.length()==0);
    }



}

GoLogin代码

package com.action;

import com.dao.AdminDao;
import com.dao.StudentDao;
import com.dao.TeacherDao;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpSession;

public class GoLogin extends ActionSupport {

    //下面是Action内用于封装用户请求参数的属性
    private String Type;
    private String Username;
    private String Password;
    private String Msg;
    public String getType() {
        return Type;
    }
    public void setType(String type) {
        Type = type;
    }
    public String getUsername() {
        return Username;
    }
    public void setUsername(String username) {
        Username = username;
    }
    public String getPassword() {
        return Password;
    }
    public void setPassword(String password) {
        Password = password;
    }
    public String getMsg() {
        return Msg;
    }
    public void setMsg(String msg) {
        Msg = msg;
    }
    //处理用户请求的execute方法
    public String execute() throws Exception {
        if(Type.equals("系统管理员"))
        {
            if (null == new AdminDao().CheckLogin(Username, Password)) {
                Msg = "用户名或者密码错误";
                return INPUT;
            }
            else
            {
                //获取ID
                String Admin_ID=new AdminDao().CheckLogin(Username, Password);
                //创建session
                HttpSession session = ServletActionContext.getRequest().getSession();
                session.setAttribute("id", Admin_ID);
                session.setAttribute("type", "1");
                return SUCCESS;
            }
        }
        else if(Type.equals("楼宇管理员"))
        {
            if (null == new TeacherDao().CheckLogin(Username, Password)) {
                Msg = "用户名或者密码错误";
                return INPUT;
            }
            else
            {
                //获取ID
                String Teacher_ID=new TeacherDao().CheckLogin(Username, Password);
                //创建session
                HttpSession session = ServletActionContext.getRequest().getSession();
                session.setAttribute("id", Teacher_ID);
                session.setAttribute("type", "2");

                return SUCCESS;
            }
        }
        else if(Type.equals("学生"))
        {
            if (null == new StudentDao().CheckLogin(Username, Password)) {
                Msg = "用户名或者密码错误";
                return INPUT;
            }
            else
            {
                //获取ID
                String Student_ID=new StudentDao().CheckLogin(Username, Password);
                //创建session
                HttpSession session = ServletActionContext.getRequest().getSession();
                session.setAttribute("id", Student_ID);
                session.setAttribute("type", "3");
                return SUCCESS;
            }
        }
        else
        {
            Msg = "身份类型错误";
            return INPUT;
        }

    }
    private boolean isInvalid(String value) {
        return (value == null || value.length() == 0);
    }
}

DBHelper代码

ackage com.db;

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

public class DBHelper {
    private String dbUrl = "jdbc:mysql://localhost:3306/sushe";
    private String dbUser= "root";
    private String dbPassword = "admin";
    private String jdbcName = "com.mysql.jdbc.Driver";


    //连接数据库
    public Connection getConn() {
        Connection conn = null;
        try {
            Class.forName(jdbcName);
        } catch (Exception e) {
        }
        try {
            conn = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
        } catch (SQLException ex) {
        }

        return conn;
    }
}

JSP代码

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
  <base href="<%=basePath%>"> 
  <title>校园宿舍管理系统</title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <link href="Style/Style.css" rel="stylesheet" type="text/css" />
</head>
<script language="JavaScript">

function mycheck(){
   if(isNull(form1.Type.value)){  
   alert("请选择身份!"); 
   return false;
   }
   if(isNull(form1.Username.value)){  
   alert("请输入用户名!"); 
   return false;
   }
   if(isNull(form1.Password.value)){
   alert("请输入密码!");
   return false;
   }

}

function isNull(str){
if ( str == "" ) return true;
var regu = "^[ ]+$";
var re = new RegExp(regu);
return re.test(str);
}


</script>
<body>
<center>
  <br><br><br><br><br>
  <table width="684" border="0" cellspacing="0" cellpadding="0">
    <tr>
      <td height="292" align="center" valign="top" background="Images/LoginBg.jpg">
      <table width="350" height="201" border="0" cellpadding="0" cellspacing="0">
        <tr>
          <td height="72" align="center"><h3>校园宿舍管理系统</h3></td>
        </tr>
        <tr>
          <td align="center" valign="top">
             <form name="form1" action="GoLogin.action" method="post" onSubmit="return mycheck()">
              <table width="100%" border="0" cellspacing="0" cellpadding="0">
                <tr>
                  <td height="30" colspan="2" align="center" class="STYLE2"><span style="color:red;">
                    <%if(request.getAttribute("Msg")!=null){%>
                    <%=request.getAttribute("Msg")%>
                    <%}%>
                  </span></td>
                  </tr>
                <tr>
                  <td height="30" align="right" class="STYLE2">身份:</td>
                  <td align="left"><select name="Type" id="Type">
                    <option value="">请选择</option>
                    <option value="系统管理员">系统管理员</option>
                    <option value="楼宇管理员">楼宇管理员</option>
                    <option value="学生">学生</option>
                  </select></td>
                  </tr>
                <tr>
                  <td width="37%" height="30" align="right" class="STYLE2">用户名:</td>
                  <td width="300" align="left"><input type="text" name="Username" id="Username" class="text1" /></td>
                  </tr>
                <tr>
                  <td height="30" align="right" class="STYLE2">密码:</td>
                  <td align="left"><input type="password" name="Password" id="Password" class="text1" /></td>
                  </tr>
                <tr>
                  <td height="30" colspan="2" align="center"><label>
                    <input type="submit" name="button" id="button" value="登录">
                  </label></td>
                  </tr>
              </table>
              </form>

          </td>
        </tr>
      </table></td>
    </tr>
  </table>


</center>
</body>
</html>

异常是这样的
图片说明

2个回答

String sql = "select * from Admin where Admin_Username ='"+username+"'and Admin_Password='"+password+"'";
这里的username password变量有没有值

Connection conn = new DBHelper().getConn();
这里连接有没有获取,如果没有,检查数据库驱动、账户、连接字符串、数据库配置

id = rs.getString("Admin_ID");
数据库是否有Admin_ID这个字段,是否是字符串类型,是否查到有记录

wjh1104720242
YaChao30 昨晚尝试输出conn,结果是null
10 个月之前 回复

空针位置1:你的DBHelper中,在创建Connection对象时,捕获了异常,没有做处理。并且你在后面的代码中使用其的时候,也未作null判断,所以,这里才为后面空指针埋下了伏笔。
空针位置2:ResultSet executeQuery()的使用问题。

官方解释:
Executes the SQL query in this PreparedStatement objectand returns the ResultSet object generated by the query.

Returns:___a ResultSet object that contains the data produced by thequery; never null

看斜体字的解释,就是没有数据的时候,返回的为null。意思就是你在使用resultSet的时候,必须得判断是否为null。

以上,希望对你能有帮助。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!