gpt4 book ai didi

java - 使用jsp时出现空指针异常:usebean

转载 作者:行者123 更新时间:2023-12-01 13:32:07 25 4
gpt4 key购买 nike

我在使用 <jsp:usebean> 创建的对象时遇到空指针异常。该对象已正确实例化,( <jsp:getproperty> 运行良好)。但是当我在 Register 的静态方法中传递此创建的对象时类,它抛出空指针异常。

NewFile.htm

    <!DOCTYPE html>
<html>
<form action="NewFile.jsp">
Name<input type="text" name="textbox1"/>
<br>
ID<input type="text" name="textbox2"/>
<br><select name="select1">
<option>India</option>
<option>France</option>
<option>Japan</option>

</select>
<br>
<input type="submit"/>

</form>
</body>
</html>

NewFile.jsp

<%@ page import="com.psl.Register" %>
<jsp:useBean id="emp" class="com.psl.Employee"/>
<jsp:setProperty property="name" name="emp" param="textbox1"/>
<jsp:setProperty property="country" name="emp" param="select1"/>
<jsp:setProperty property="id" name="emp" param="textbox2"/>
<jsp:getProperty property="country" name="emp"/>
<%Register.register(emp);%>

注册.java

package com.psl;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Register {
public static void register (Employee obj)
{

try {
PreparedStatement stm = DBConnection.establishConnection().prepareStatement("insert into Person values (?,?,?)");
stm.setString(1,obj.getName() );
stm.setInt(2, obj.getId());
stm.setString(3, obj.getCountry());
stm.execute();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

员工.java

package com.psl;

import java.util.Arrays;

public class Employee {



@Override
public String toString() {
return "Employee [name=" + name + ", id=" + id + ", country=" + country
+ "]";
}

private String name;
private int id;
private String country;


public Employee() {
// TODO Auto-generated constructor stub
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getCountry() {
return country;
}

public void setCountry(String country) {
this.country = country;
}


}

DBConnection.java

public class DBConnection {

private static Connection con ;
public static Connection establishConnection()
{try {

Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/database","root","root");
} catch (Exception e) {
// TODO: handle exception
}
return con;

}

}

最佳答案

这就是你的问题。

Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/database","root","root");
} catch (Exception e) {
// TODO: handle exception
}

Exception 可能会被抛出,而你正在吞下它,即。 不处理con 仍为 null,但您将其返回。

DBConnection.establishConnection()

因此返回null

您尝试调用

prepareStatement("insert into Person values (?,?,?)");

null上。

<小时/>

Don't use scriptlets.

关于java - 使用jsp时出现空指针异常:usebean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21513879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com